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
module Main where import Network.Wai.Handler.Warp (run) import System.Environment (getArgs) import qualified NumberStreamServer import qualified EchoServer -- | Testing the echo server: -- -- > curl -XPOST http://localhost:8081/session/new -- > curl -XPOST http://localhost:8081/session/0/echo -H "Content-Type: application/json" -d '{"msgText": "World"}' -- -- To subscribe to the events use: -- -- > curl http://localhost:8081/session/0/events -- main :: IO () main = do args <- getArgs case args of ["stream"] -> run 8081 NumberStreamServer.app ["sse"] -> do env <- EchoServer.newEnv run 8081 (EchoServer.app env) _ -> putStrLn "Usage: streaming-endpoints-exe (stream | sse)"
capitanbatata/sandbox
streaming-endpoints/app/Main.hs
gpl-3.0
780
0
15
189
131
74
57
16
3
{-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE TypeOperators #-} module Data.Tuple.Operator ((:-), pattern (:-)) where type a :- b = (a, b) pattern a :- b = (a, b) infixr 1 :-
cblp/stack-offline
tuple-operator/Data/Tuple/Operator.hs
gpl-3.0
178
0
6
34
60
40
20
6
0
{-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fdefer-typed-holes #-} module Documentator.Parser where import Preprocessor import Documentator.Descriptors import Documentator.Types import Documentator.Utils import Language.Haskell.Exts import Language.Haskell.Exts.Parser import Language.Haskell.Exts.Fixity import Control.Exception import Control.Lens import Data.List myParse :: FilePath -> IO (Either String (Located Module)) myParse f = fmap associateHaddock . unwrapParseOk . parseFileContentsWithComments parseMode <$> preprocessFile f where parseMode = defaultParseMode { fixities = Nothing , extensions = defaultExtensions } -- The parser may fail for the absence of the right extensions. A common trick, -- used for example by hlint at -- https://github.com/ndmitchell/hlint/blob/e1c22030721999d4505eb14b19e6f8560a87507a/src/Util.hs -- is to import all possible reasonable extensions by default. This might be -- changed in a future version. defaultExtensions :: [Extension] defaultExtensions = [e | e@EnableExtension{} <- knownExtensions] \\ map EnableExtension badExtensions badExtensions = [ Arrows -- steals proc , TransformListComp -- steals the group keyword , XmlSyntax, RegularPatterns -- steals a-b , UnboxedTuples -- breaks (#) lens operator , QuasiQuotes -- breaks [x| ...], making whitespace free list comps break , DoRec, RecursiveDo -- breaks rec ] -- -- g is a convenience function to use in ghci -- g :: Extractor a -> IO a -- g e = do -- lensFilePath <- lensFileExample -- e <$> myParse lensFilePath -- pRaw :: (Show a) => Extractor [a] -> IO () -- pRaw e = g e >>= mapM_ (\a -> print a >> putStrLn "\n") -- p :: (Pretty a) => Extractor [a] -> IO () -- p e = g e >>= mapM_ (putStrLn . prettyPrint) isTypeSig :: Decl (SrcSpanInfo, [Comment]) -> Bool isTypeSig (TypeSig _ _ _) = True isTypeSig _ = False ---------------------------------------------------------------- Extractors typeSignaturesExtractor :: Extractor [Located Decl] typeSignaturesExtractor = filter isTypeSig . declarations where declarations :: Module t -> [Decl t] declarations (Module _ _ _ _ ds) = ds typesExtractor :: Extractor [Located Type] typesExtractor = map getType . filter isTypeSig . typeSignaturesExtractor where getType (TypeSig _ _ t) = t instance {-# OVERLAPPING #-} Ord (Located Type) where compare t1 t2 = compare (fmap (const ()) t1) (fmap (const ()) t2) instance {-# OVERLAPPING #-} Eq (Located Type) where t1 == t2 = (fmap (const ()) t1) == (fmap (const ()) t2) instance {-# OVERLAPPING #-} Ord (Located QName) where compare qn1 qn2 = compare (fmap (const ()) qn1) (fmap (const ()) qn2) tyConExtractor :: Extractor [Located QName] tyConExtractor = ordNub . sort . concatMap allTyCon . ordNub . typesExtractor allTypesExtractor :: Extractor [Type ()] allTypesExtractor = concatMap (allTypes . clean) . typesExtractor typeUsages :: Extractor [(Type (), Int)] typeUsages = count . allTypesExtractor -- showTypeUsages :: Extractor [(Located Type, Int)] -> IO () -- showTypeUsages e = g e >>= mapM_ (putStrLn . str) -- where -- str (t, num) = (prettyPrint (fmap fst t)) ++ " " ++ show num resultTypeExtractor :: Extractor [Located Type] resultTypeExtractor = map resultTyCon . ordNub . typesExtractor inputTypesExtractor :: Extractor [Located Type] inputTypesExtractor = ordNub . concatMap argumentsTyCon . ordNub . typesExtractor instance {-# OVERLAPPING #-} SrcInfo (SrcSpanInfo, [Comment]) where toSrcInfo a b c = (toSrcInfo a b c, []) fromSrcInfo a = (fromSrcInfo a, []) getPointLoc = getPointLoc . fst fileName = fileName . fst startLine = startLine . fst startColumn = startColumn . fst typeFromString :: String -> Either String (Type ()) typeFromString s = case parseType s of ParseOk annType -> Right $ fmap (const ()) annType ParseFailed _ err -> Left err
Arguggi/documentator
src/Documentator/Parser.hs
gpl-3.0
3,973
0
12
759
930
500
430
63
2
class X a where f :: a -> Int g :: a -> Char g = primChr . f f = primOrd . g instance X Int where f = id instance X Char where g = id main = show (f 3) ++ show (f 'a')
Helium4Haskell/helium
test/typeClasses/ClassInstance2.hs
gpl-3.0
194
0
8
73
99
51
48
10
1
{-# LANGUAGE CPP #-} module Hledger.Web.WebOptions where import Prelude import Data.Default #if !MIN_VERSION_base(4,8,0) import Data.Functor.Compat ((<$>)) #endif import Data.Maybe import System.Environment import Hledger.Cli hiding (progname,version,prognameandversion) import Settings progname, version :: String progname = "hledger-web" #ifdef VERSION version = VERSION #else version = "" #endif prognameandversion :: String prognameandversion = progname ++ " " ++ version :: String webflags :: [Flag [([Char], [Char])]] webflags = [ flagNone ["serve","server"] (setboolopt "serve") ("serve and log requests, don't browse or auto-exit") ,flagReq ["host"] (\s opts -> Right $ setopt "host" s opts) "IPADDR" ("listen on this IP address (default: "++defhost++")") ,flagReq ["port"] (\s opts -> Right $ setopt "port" s opts) "PORT" ("listen on this TCP port (default: "++show defport++")") ,flagReq ["base-url"] (\s opts -> Right $ setopt "base-url" s opts) "BASEURL" ("set the base url (default: http://IPADDR:PORT)") ,flagReq ["file-url"] (\s opts -> Right $ setopt "file-url" s opts) "FILEURL" ("set the static files url (default: BASEURL/static)") ] webmode :: Mode [([Char], [Char])] webmode = (mode "hledger-web" [("command","web")] "start serving the hledger web interface" (argsFlag "[PATTERNS]") []){ modeGroupFlags = Group { groupUnnamed = webflags ,groupHidden = [flagNone ["binary-filename"] (setboolopt "binary-filename") "show the download filename for this executable, and exit"] ,groupNamed = [generalflagsgroup1] } ,modeHelpSuffix=[ -- "Reads your ~/.hledger.journal file, or another specified by $LEDGER_FILE or -f, and starts the full-window curses ui." ] } -- hledger-web options, used in hledger-web and above data WebOpts = WebOpts { serve_ :: Bool ,host_ :: String ,port_ :: Int ,base_url_ :: String ,file_url_ :: Maybe String ,cliopts_ :: CliOpts } deriving (Show) defwebopts :: WebOpts defwebopts = WebOpts def def def def def def -- instance Default WebOpts where def = defwebopts rawOptsToWebOpts :: RawOpts -> IO WebOpts rawOptsToWebOpts rawopts = checkWebOpts <$> do cliopts <- rawOptsToCliOpts rawopts let h = fromMaybe defhost $ maybestringopt "host" rawopts p = fromMaybe defport $ maybeintopt "port" rawopts b = maybe (defbaseurl h p) stripTrailingSlash $ maybestringopt "base-url" rawopts return defwebopts { serve_ = boolopt "serve" rawopts ,host_ = h ,port_ = p ,base_url_ = b ,file_url_ = stripTrailingSlash <$> maybestringopt "file-url" rawopts ,cliopts_ = cliopts } where stripTrailingSlash = reverse . dropWhile (=='/') . reverse -- yesod don't like it checkWebOpts :: WebOpts -> WebOpts checkWebOpts wopts = either usageError (const wopts) $ do let h = host_ wopts if any (not . (`elem` ".0123456789")) h then Left $ "--host requires an IP address, not "++show h else Right () getHledgerWebOpts :: IO WebOpts --getHledgerWebOpts = processArgs webmode >>= return . decodeRawOpts >>= rawOptsToWebOpts getHledgerWebOpts = do args <- getArgs >>= expandArgsAt let args' = replaceNumericFlags args let cmdargopts = either usageError id $ process webmode args' rawOptsToWebOpts $ decodeRawOpts cmdargopts
ony/hledger
hledger-web/Hledger/Web/WebOptions.hs
gpl-3.0
3,601
0
14
905
870
480
390
74
2
-- | This monad transformer adds the ability to accumulate errors from several ErrorT computations -- and report them all at once. module Boogie.ErrorAccum where import Control.Monad import Control.Monad.Trans import Control.Monad.Trans.Except -- | Error accumulator: -- used in combination with ErrorT to store intermediate computation results, -- when errors should be accumulated rather than reported immediately newtype ErrorAccumT e m a = ErrorAccumT { runErrorAccumT :: m ([e], a) } instance (Monad m) => Functor (ErrorAccumT e m) where fmap = liftM instance (Monad m) => Applicative (ErrorAccumT e m) where -- | Attach an empty list of errors to a succesful computation pure x = ErrorAccumT $ return ([], x) -- | The bind strategy is to concatenate error lists (<*>) = ap instance (Monad m) => Monad (ErrorAccumT e m) where -- | Attach an empty list of errors to a succesful computation return = pure -- | The bind strategy is to concatenate error lists m >>= k = ErrorAccumT $ do (errs, res) <- runErrorAccumT m (errs', res') <- runErrorAccumT $ k res return (errs ++ errs', res') instance MonadTrans (ErrorAccumT e) where lift m = ErrorAccumT $ do a <- m return ([], a) -- | transform an error computation and default value into an error accumlator accum :: (Monad m) => ExceptT [e] m a -> a -> ErrorAccumT e m a accum c def = ErrorAccumT (errToAccum def `liftM` runExceptT c) where errToAccum def (Left errs) = (errs, def) errToAccum def (Right x) = ([], x) -- | Transform an error accumlator back into a regular error computation report :: (Monad m) => ErrorAccumT e m a -> ExceptT [e] m a report accum = ExceptT (accumToErr `liftM` runErrorAccumT accum) where accumToErr ([], x) = Right x accumToErr (es, _) = Left es -- | 'mapAccum' @f def xs@ : -- Apply @f@ to all @xs@, accumulating errors and reporting them at the end mapAccum :: (Monad m) => (a -> ExceptT [e] m b) -> b -> [a] -> ExceptT [e] m [b] mapAccum f def xs = report $ mapM (acc f) xs where acc f x = accum (f x) def -- | 'mapAccumA_' @f xs@ : -- Apply @f@ to all @xs@ throwing away the result, accumulating errors mapAccumA_ :: (Monad m) => (a -> ExceptT [e] m ()) -> [a] -> ErrorAccumT e m () mapAccumA_ f xs = mapM_ (acc f) xs where acc f x = accum (f x) () -- | Same as 'mapAccumA_', but reporting errors at the end mapAccum_ :: (Monad m) => (a -> ExceptT [e] m ()) -> [a] -> ExceptT [e] m () mapAccum_ f xs = report $ mapAccumA_ f xs -- | 'zipWithAccum_' @f xs ys@ : -- Apply type checking @f@ to all @xs@ and @ys@ throwing away the result, -- accumulating errors and reporting them at the end zipWithAccum_ :: (Monad m) => (a -> b -> ExceptT [e] m ()) -> [a] -> [b] -> ExceptT [e] m () zipWithAccum_ f xs ys = report $ zipWithM_ (acc f) xs ys where acc f x y = accum (f x y) ()
emptylambda/BLT
src/Boogie/ErrorAccum.hs
gpl-3.0
2,905
0
11
672
919
491
428
39
2
module Dep where import Helpers import Ticket dep :: Ticket -> [String] -> IO () dep from totitles = do fs <- mapM expandTicketGlob totitles ticks <- checkAllRight fs usagemsg putStrLn $ "Dep from " ++ (title from) ++ " to " ++ (show ticks) ++ "." saveTicket (modDeps (ticks ++) from) usagemsg = "Usage: dep ticketname depends-on ..." handleDep args = paramList dep args "dep" usagemsg
anttisalonen/nix
src/Dep.hs
gpl-3.0
399
0
12
80
140
70
70
11
1
module Lambda.TestEngine where import Test.HUnit import qualified Data.Set as Set import Lambda.Variable import Lambda.Engine import Lambda.Parser tests :: Test tests = test [ assertEqual "Test uguaglianza Term 1" True (parseRaw "λz.x" == parseRaw "λk.x") , assertEqual "Test uguaglianza Term 2" False (parseRaw "λa.λb.a" == parseRaw "λa.λb.b") , assertEqual "Test uguaglianza Term 3" True (parseRaw "λa.λb.b" == parseRaw "λc.λc.c") , assertEqual "Test uguaglianza Term 4" True (parseRaw "λb.λb.b" == parseRaw "λc.λc.c") , assertEqual "Test uguaglianza Term 5" False (parseRaw "λx.x(y)" == parseRaw "λy.y(y)") , assertEqual "Test substitute" (parseRaw "λa.a(λz.x)") (substitute (parseRaw "λx.x(y)") (Variable "y") (parseRaw "λz.x")) , assertEqual "Test allVar 1" (Set.fromList [Variable "a", Variable "x", Variable "z"]) (allVar (parseRaw "λa.a(λz.x)")) , assertEqual "Test allVar 2" (Set.fromList [Variable "x", Variable "y"]) (allVar (parseRaw "λx.λy.x")) , assertEqual "Test betaReduce" (Just (parseRaw "a")) (betaReduce (parseRaw "(λb.a)(x)")) , assertEqual "Test betaReduce" (Just (parseRaw "(λret.λa.ret)(y2)(z3)")) (betaReduce (parseRaw "(λb.λret.λa.ret)(x1)(y2)(z3)")) , assertEqual "Test reduceAll" (parseRaw "x") (reduceAll (parseRaw "(λy.y)(x)")) , assertEqual "Test applyArgs" (parseRaw "f(x1)(x2)(x3)") (applyArgs (parseRaw "f") [parseRaw "x1", parseRaw "x2", parseRaw "x3"]) , assertEqual "Test lambdaVars" (parseRaw "λx1.λx2.λx3.m") (lambdaVars [Variable "x1", Variable "x2", Variable "x3"] (parseRaw "m")) ]
fpoli/lambda
test/Lambda/TestEngine.hs
gpl-3.0
2,413
0
11
1,038
488
247
241
71
1
module HelloWorld where { import Prelude hiding (head, span, div, map); import WASH.CGI.CGI; mainCGI :: CGI (); mainCGI = standardQuery "Hello World" empty}
ckaestne/CIDE
CIDE_Language_Haskell/test/WSP/scripts/HelloWorld.hs
gpl-3.0
167
0
6
33
53
34
19
5
1
{-# 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.IAM.UpdateAccountPasswordPolicy -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Updates the password policy settings for the AWS account. -- -- This action does not support partial updates. No parameters are -- required, but if you do not specify a parameter, that parameter\'s value -- reverts to its default value. See the __Request Parameters__ section for -- each parameter\'s default value. -- -- For more information about using a password policy, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/Using_ManagingPasswordPolicies.html Managing an IAM Password Policy> -- in the /Using IAM/ guide. -- -- /See:/ <http://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccountPasswordPolicy.html AWS API Reference> for UpdateAccountPasswordPolicy. module Network.AWS.IAM.UpdateAccountPasswordPolicy ( -- * Creating a Request updateAccountPasswordPolicy , UpdateAccountPasswordPolicy -- * Request Lenses , uappMinimumPasswordLength , uappRequireNumbers , uappPasswordReusePrevention , uappRequireLowercaseCharacters , uappMaxPasswordAge , uappHardExpiry , uappRequireSymbols , uappRequireUppercaseCharacters , uappAllowUsersToChangePassword -- * Destructuring the Response , updateAccountPasswordPolicyResponse , UpdateAccountPasswordPolicyResponse ) where import Network.AWS.IAM.Types import Network.AWS.IAM.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'updateAccountPasswordPolicy' smart constructor. data UpdateAccountPasswordPolicy = UpdateAccountPasswordPolicy' { _uappMinimumPasswordLength :: !(Maybe Nat) , _uappRequireNumbers :: !(Maybe Bool) , _uappPasswordReusePrevention :: !(Maybe Nat) , _uappRequireLowercaseCharacters :: !(Maybe Bool) , _uappMaxPasswordAge :: !(Maybe Nat) , _uappHardExpiry :: !(Maybe Bool) , _uappRequireSymbols :: !(Maybe Bool) , _uappRequireUppercaseCharacters :: !(Maybe Bool) , _uappAllowUsersToChangePassword :: !(Maybe Bool) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateAccountPasswordPolicy' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'uappMinimumPasswordLength' -- -- * 'uappRequireNumbers' -- -- * 'uappPasswordReusePrevention' -- -- * 'uappRequireLowercaseCharacters' -- -- * 'uappMaxPasswordAge' -- -- * 'uappHardExpiry' -- -- * 'uappRequireSymbols' -- -- * 'uappRequireUppercaseCharacters' -- -- * 'uappAllowUsersToChangePassword' updateAccountPasswordPolicy :: UpdateAccountPasswordPolicy updateAccountPasswordPolicy = UpdateAccountPasswordPolicy' { _uappMinimumPasswordLength = Nothing , _uappRequireNumbers = Nothing , _uappPasswordReusePrevention = Nothing , _uappRequireLowercaseCharacters = Nothing , _uappMaxPasswordAge = Nothing , _uappHardExpiry = Nothing , _uappRequireSymbols = Nothing , _uappRequireUppercaseCharacters = Nothing , _uappAllowUsersToChangePassword = Nothing } -- | The minimum number of characters allowed in an IAM user password. -- -- Default value: 6 uappMinimumPasswordLength :: Lens' UpdateAccountPasswordPolicy (Maybe Natural) uappMinimumPasswordLength = lens _uappMinimumPasswordLength (\ s a -> s{_uappMinimumPasswordLength = a}) . mapping _Nat; -- | Specifies whether IAM user passwords must contain at least one numeric -- character (0 to 9). -- -- Default value: false uappRequireNumbers :: Lens' UpdateAccountPasswordPolicy (Maybe Bool) uappRequireNumbers = lens _uappRequireNumbers (\ s a -> s{_uappRequireNumbers = a}); -- | Specifies the number of previous passwords that IAM users are prevented -- from reusing. The default value of 0 means IAM users are not prevented -- from reusing previous passwords. -- -- Default value: 0 uappPasswordReusePrevention :: Lens' UpdateAccountPasswordPolicy (Maybe Natural) uappPasswordReusePrevention = lens _uappPasswordReusePrevention (\ s a -> s{_uappPasswordReusePrevention = a}) . mapping _Nat; -- | Specifies whether IAM user passwords must contain at least one lowercase -- character from the ISO basic Latin alphabet (a to z). -- -- Default value: false uappRequireLowercaseCharacters :: Lens' UpdateAccountPasswordPolicy (Maybe Bool) uappRequireLowercaseCharacters = lens _uappRequireLowercaseCharacters (\ s a -> s{_uappRequireLowercaseCharacters = a}); -- | The number of days that an IAM user password is valid. The default value -- of 0 means IAM user passwords never expire. -- -- Default value: 0 uappMaxPasswordAge :: Lens' UpdateAccountPasswordPolicy (Maybe Natural) uappMaxPasswordAge = lens _uappMaxPasswordAge (\ s a -> s{_uappMaxPasswordAge = a}) . mapping _Nat; -- | Prevents IAM users from setting a new password after their password has -- expired. -- -- Default value: false uappHardExpiry :: Lens' UpdateAccountPasswordPolicy (Maybe Bool) uappHardExpiry = lens _uappHardExpiry (\ s a -> s{_uappHardExpiry = a}); -- | Specifies whether IAM user passwords must contain at least one of the -- following non-alphanumeric characters: -- -- ! \' # $ % ^ &amp; * ( ) _ + - = [ ] { } | \' -- -- Default value: false uappRequireSymbols :: Lens' UpdateAccountPasswordPolicy (Maybe Bool) uappRequireSymbols = lens _uappRequireSymbols (\ s a -> s{_uappRequireSymbols = a}); -- | Specifies whether IAM user passwords must contain at least one uppercase -- character from the ISO basic Latin alphabet (A to Z). -- -- Default value: false uappRequireUppercaseCharacters :: Lens' UpdateAccountPasswordPolicy (Maybe Bool) uappRequireUppercaseCharacters = lens _uappRequireUppercaseCharacters (\ s a -> s{_uappRequireUppercaseCharacters = a}); -- | Allows all IAM users in your account to use the AWS Management Console -- to change their own passwords. For more information, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/HowToPwdIAMUser.html Letting IAM Users Change Their Own Passwords> -- in the /Using IAM/ guide. -- -- Default value: false uappAllowUsersToChangePassword :: Lens' UpdateAccountPasswordPolicy (Maybe Bool) uappAllowUsersToChangePassword = lens _uappAllowUsersToChangePassword (\ s a -> s{_uappAllowUsersToChangePassword = a}); instance AWSRequest UpdateAccountPasswordPolicy where type Rs UpdateAccountPasswordPolicy = UpdateAccountPasswordPolicyResponse request = postQuery iAM response = receiveNull UpdateAccountPasswordPolicyResponse' instance ToHeaders UpdateAccountPasswordPolicy where toHeaders = const mempty instance ToPath UpdateAccountPasswordPolicy where toPath = const "/" instance ToQuery UpdateAccountPasswordPolicy where toQuery UpdateAccountPasswordPolicy'{..} = mconcat ["Action" =: ("UpdateAccountPasswordPolicy" :: ByteString), "Version" =: ("2010-05-08" :: ByteString), "MinimumPasswordLength" =: _uappMinimumPasswordLength, "RequireNumbers" =: _uappRequireNumbers, "PasswordReusePrevention" =: _uappPasswordReusePrevention, "RequireLowercaseCharacters" =: _uappRequireLowercaseCharacters, "MaxPasswordAge" =: _uappMaxPasswordAge, "HardExpiry" =: _uappHardExpiry, "RequireSymbols" =: _uappRequireSymbols, "RequireUppercaseCharacters" =: _uappRequireUppercaseCharacters, "AllowUsersToChangePassword" =: _uappAllowUsersToChangePassword] -- | /See:/ 'updateAccountPasswordPolicyResponse' smart constructor. data UpdateAccountPasswordPolicyResponse = UpdateAccountPasswordPolicyResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'UpdateAccountPasswordPolicyResponse' with the minimum fields required to make a request. -- updateAccountPasswordPolicyResponse :: UpdateAccountPasswordPolicyResponse updateAccountPasswordPolicyResponse = UpdateAccountPasswordPolicyResponse'
fmapfmapfmap/amazonka
amazonka-iam/gen/Network/AWS/IAM/UpdateAccountPasswordPolicy.hs
mpl-2.0
8,834
0
11
1,622
1,047
633
414
124
1
-- | Traverse the AST to find any traits referenced module GatherTraits(GatherTraits(traits)) where import Scoped(Label) import Command as Comm(Command(ActivateTitle, AddTrait,RemoveTrait, Random,RandomList, SetFlag,ClrFlag, SpawnUnit, VarOpLit,VarOpVar,VarOpScope, Concrete, Scoped, Break,If, BestFitCharacterForTitle, BooleanCommand, BuildHolding, ChangeTech, ClearWealth, CreateTitle, Death, GainSettlementsUnderTitle, NumericCommand, OpinionModifier, ReligionAuthority, RemoveOpinion, ScopedModifier, SetAllowViceRoyalties, StringCommand, TriggerEvent, War), Modifier(..)) import qualified Command (Command(CreateCharacter),traits) import qualified Condition as Cond(Condition(..),Scope(..),ScopeType(..),Value(..)) import Event as E(Event(..),Option(..)) import Decision(Decision(..)) import Data.Monoid((<>)) import qualified Data.Set as S -- | Any type that can contain a reference to a trait should belong to this class. class GatherTraits t where traits :: t → [Label] instance GatherTraits () where traits _ = [] instance GatherTraits Double where traits _ = [] instance (GatherTraits a, GatherTraits b) ⇒ GatherTraits (a,b) where traits (a,b) = traits a <> traits b instance (GatherTraits a, GatherTraits b, GatherTraits c) ⇒ GatherTraits (a,b,c) where traits (a,b,c) = traits a <> traits b <> traits c instance GatherTraits a ⇒ GatherTraits [a] where traits = mconcat . map traits instance GatherTraits a ⇒ GatherTraits (Maybe a) where traits Nothing = [] traits (Just a) = traits a instance (GatherTraits a, GatherTraits b) ⇒ GatherTraits (Either a b) where traits (Left a) = traits a traits (Right b) = traits b instance GatherTraits a => GatherTraits (S.Set a) where traits s = traits $ S.toList s instance GatherTraits Command where traits (AddTrait t) = [t] traits (BooleanCommand _ _) = mempty traits (ClearWealth _) = mempty traits (NumericCommand _ _) = mempty traits (RemoveTrait t) = [t] traits (If conds comms) = traits conds <> traits comms traits Break = [] traits (Random _ _ comms) = traits comms traits (RandomList os) = traits os traits (SetAllowViceRoyalties _) = mempty traits (Comm.Scoped s) = traits s traits (SetFlag _ _) = [] -- Flags never are localised traits (ClrFlag _ _) = [] traits SpawnUnit {} = [] traits VarOpLit {} = [] traits VarOpVar {} = [] traits VarOpScope {} = [] traits (Concrete _ _) = [] traits (Command.CreateCharacter { traits = t }) = t traits (ActivateTitle t _) = [t] traits (BestFitCharacterForTitle title perspective _ title') = traits title <> traits perspective <> traits title' traits BuildHolding {} = mempty traits (ChangeTech _ _) = mempty traits TriggerEvent {} = mempty traits (CreateTitle _ _ _ _ titleCulture _ holder _ _ _) = traits titleCulture <> traits holder traits (Death _ _) = mempty traits (GainSettlementsUnderTitle title enemy) = traits title <> traits enemy traits (OpinionModifier _ who _ _) = traits who traits (ReligionAuthority _) = mempty traits (RemoveOpinion _ scope _) = traits scope traits (ScopedModifier _ _) = mempty traits (StringCommand _ _) = mempty traits War {} = mempty instance GatherTraits Modifier where traits (Modifier _ _) = [] instance GatherTraits Cond.Condition where traits (Cond.Trait t) = [t] traits _ = [] instance GatherTraits c => GatherTraits (Cond.Value c) where traits _ = [] instance GatherTraits Cond.ScopeType where traits _ = [] instance GatherTraits c => GatherTraits (Cond.Scope c) where traits (Cond.Scope _ limit cont) = traits cont <> traits limit instance GatherTraits Event where traits Event { options, trigger, immediate } = traits options <> traits trigger <> traits immediate instance GatherTraits E.Option where traits E.Option { optionTrigger, action, aiChance } = traits optionTrigger <> traits action <> traits aiChance instance GatherTraits Decision where traits Decision { potential, allow, effect, aiWillDo } = traits potential <> traits allow <> traits effect <> traits aiWillDo
joelwilliamson/validator
GatherTraits.hs
agpl-3.0
5,015
0
10
1,657
1,508
810
698
-1
-1
module MetaTests where import Graphics.UI.InterfaceDescription import Test.Hspec main :: IO () main = hspec $ do describe "Validate haqify function" $ do it "just should compile" $ do let (InterfaceDescription () (FrameConfiguration Frame elems)) = test in elems `shouldBe` [Label "Class1" "SomeTextLabel", Button "Class2" "OkButton"] test :: InterfaceDescription () test = do label "Class1" "SomeTextLabel" button "Class2" "OkButton"
kchugalinskiy/shiny-head
MetaTests.hs
lgpl-3.0
451
0
21
74
140
69
71
12
1
{- Copyright 2019 The CodeWorld Authors. 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. -} import CodeWorld main = drawingOf (codeWorldLogo)
alphalambda/codeworld
codeworld-compiler/test/testcases/haskellInCodeWorld/source.hs
apache-2.0
662
0
6
123
16
9
7
2
1
{-# LANGUAGE OverloadedLists #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} module BarthPar.Scrape where import Control.Arrow ((&&&)) import Control.Error import Control.Monad import Data.Function import qualified Data.List as L import Data.Monoid import Data.Ord import qualified Data.Text as T import Network.URI import Prelude hiding (div) import System.FilePath import System.IO import Text.XML.Cursor import qualified BarthPar.Scrape.Chunks as Chunks import BarthPar.Scrape.Network import BarthPar.Scrape.Output import BarthPar.Scrape.Read import BarthPar.Scrape.Types import BarthPar.Scrape.Utils import BarthPar.Scrape.XML scrape :: Bool -- ^ Print debugging output? -> Bool -- ^ Clean out the output directory first? -> MetadataTarget -- ^ How to output the metadata. -> Chunking -- ^ How to chunk the output. -> FilePath -- ^ The output directory. -> Either FilePath String -- ^ The input. -> Script () scrape debug clean mdata chunkings outputDir inputRoot = toScript debug mdata $ do when clean $ cleanOutputs outputDir input <- case fmap parseURI inputRoot of Right (Just uri) -> return $ Right uri Left filePath -> return $ Left filePath Right Nothing -> throwS "Invalid root URL." outputs <- Chunks.chunk chunkings mdata <$> (dumpHtml "CORPUS" =<< scrapeTOC input) mapM_ (writeOutput outputDir) outputs when (mdata == TargetCSV) $ writeCsv (outputDir </> "corpus.csv") $ mapMaybe _outputCsv outputs scrapeTOC :: InputSource -> Scrape (Corpus ContentBlock) scrapeTOC input = fmap (Corpus . wrapVolume . concat) . smapConcurrently (uncurry scrapePartPage) =<< scrapeTOCPage input "Table of Contents" (T.isPrefixOf "CD ") scrapeTOCPage :: InputSource -- ^ The ToC's URI to download -> T.Text -- ^ The content of A tags to look for. -> (T.Text -> Bool) -- ^ A predicate to find which links to move to next. -> Scrape [(T.Text, InputSource)] -- ^ A list of A tag contents and @hrefs. scrapeTOCPage input title f = mapMaybe (sequenceA . fmap (appendInput input)) . filter (f . fst) . ($// tocEntries >=> tocPair title) . fromDocument <$> dl (Just $ "TOC: " <> title) input scrapePartPage :: T.Text -> InputSource -> Scrape [Part ContentBlock] scrapePartPage volName input = fmap groupParts . smapConcurrently (uncurry (scrapePage volName)) =<< scrapeTOCPage input "View Text" (T.isPrefixOf "§ ") scrapePage :: Title -> T.Text -> InputSource -> Scrape (Chapter ContentBlock) scrapePage volName pageName input = do doc <- dl (Just $ "PAGE: " <> volName <> " | " <> pageName) input dumpPage "page" doc >>= scrapeIO . maybe (return ()) (hPutStrLn stderr . (">>> " ++)) . fst let nds = fromDocument doc $// tinyurl >=> followingSibling >=> div io $ makeChapter volName pageName nds wrapVolume :: Eq a => [Part a] -> [Volume a] wrapVolume = mapMaybe volume . L.groupBy ((==) `on` (_headerN . _partVolume)) . L.sortBy (comparing (_headerN . _partVolume)) where volume :: Eq a => [Part a] -> Maybe (Volume a) volume ps@(Part{_partVolume=(Header vn vt)}:_) = Just . Volume vn vt $ L.sort ps volume _ = Nothing groupParts :: Eq a => [Chapter a] -> [Part a] groupParts = mapMaybe part . L.groupBy ((==) `on` _chapterPart) . L.sortBy (comparing (_chapterVolume &&& _chapterPart)) where part :: Eq a => [Chapter a] -> Maybe (Part a) part cs@(Chapter{_chapterVolume=v,_chapterPart=pt}:_) = Just . Part v pt $ L.sort cs part _ = Nothing
erochest/barth-scrape
src/BarthPar/Scrape.hs
apache-2.0
4,188
0
15
1,347
1,151
596
555
85
3
module Data.Discrimination.Class ( Discriminating(..) -- * Joins , joining , inner , outer , leftOuter , rightOuter ) where import Control.Applicative import Control.Arrow import Data.Functor.Contravariant.Divisible import Data.Discrimination.Grouping import Data.Discrimination.Internal import Data.Discrimination.Sorting import Data.Maybe (catMaybes) class Decidable f => Discriminating f where disc :: f a -> [(a, b)] -> [[b]] instance Discriminating Sort where disc = runSort instance Discriminating Group where disc = runGroup -------------------------------------------------------------------------------- -- * Joins -------------------------------------------------------------------------------- -- | /O(n)/. Perform a full outer join while explicit merging of the two result tables a table at a time. -- -- The results are grouped by the discriminator. joining :: Discriminating f => f d -- ^ the discriminator to use -> ([a] -> [b] -> c) -- ^ how to join two tables -> (a -> d) -- ^ selector for the left table -> (b -> d) -- ^ selector for the right table -> [a] -- ^ left table -> [b] -- ^ right table -> [c] joining m abc ad bd as bs = spanEither abc <$> disc m (((ad &&& Left) <$> as) ++ ((bd &&& Right) <$> bs)) {-# INLINE joining #-} -- | /O(n)/. Perform an inner join, with operations defined one row at a time. -- -- The results are grouped by the discriminator. -- -- This takes operation time linear in both the input and result sets. inner :: Discriminating f => f d -- ^ the discriminator to use -> (a -> b -> c) -- ^ how to join two rows -> (a -> d) -- ^ selector for the left table -> (b -> d) -- ^ selector for the right table -> [a] -- ^ left table -> [b] -- ^ right table -> [[c]] inner m abc ad bd as bs = catMaybes $ joining m go ad bd as bs where go ap bp | Prelude.null ap || Prelude.null bp = Nothing | otherwise = Just (liftA2 abc ap bp) -- | /O(n)/. Perform a full outer join with operations defined one row at a time. -- -- The results are grouped by the discriminator. -- -- This takes operation time linear in both the input and result sets. outer :: Discriminating f => f d -- ^ the discriminator to use -> (a -> b -> c) -- ^ how to join two rows -> (a -> c) -- ^ row present on the left, missing on the right -> (b -> c) -- ^ row present on the right, missing on the left -> (a -> d) -- ^ selector for the left table -> (b -> d) -- ^ selector for the right table -> [a] -- ^ left table -> [b] -- ^ right table -> [[c]] outer m abc ac bc ad bd as bs = joining m go ad bd as bs where go ap bp | Prelude.null ap = bc <$> bp | Prelude.null bp = ac <$> ap | otherwise = liftA2 abc ap bp -- | /O(n)/. Perform a left outer join with operations defined one row at a time. -- -- The results are grouped by the discriminator. -- -- This takes operation time linear in both the input and result sets. leftOuter :: Discriminating f => f d -- ^ the discriminator to use -> (a -> b -> c) -- ^ how to join two rows -> (a -> c) -- ^ row present on the left, missing on the right -> (a -> d) -- ^ selector for the left table -> (b -> d) -- ^ selector for the right table -> [a] -- ^ left table -> [b] -- ^ right table -> [[c]] leftOuter m abc ac ad bd as bs = catMaybes $ joining m go ad bd as bs where go ap bp | Prelude.null ap = Nothing | Prelude.null bp = Just (ac <$> ap) | otherwise = Just (liftA2 abc ap bp) -- | /O(n)/. Perform a right outer join with operations defined one row at a time. -- -- The results are grouped by the discriminator. -- -- This takes operation time linear in both the input and result sets. rightOuter :: Discriminating f => f d -- ^ the discriminator to use -> (a -> b -> c) -- ^ how to join two rows -> (b -> c) -- ^ row present on the right, missing on the left -> (a -> d) -- ^ selector for the left table -> (b -> d) -- ^ selector for the right table -> [a] -- ^ left table -> [b] -- ^ right table -> [[c]] rightOuter m abc bc ad bd as bs = catMaybes $ joining m go ad bd as bs where go ap bp | Prelude.null bp = Nothing | Prelude.null ap = Just (bc <$> bp) | otherwise = Just (liftA2 abc ap bp)
markus1189/discrimination
src/Data/Discrimination/Class.hs
bsd-2-clause
4,478
0
15
1,238
1,100
599
501
90
1
module Fold where import CLaSH.Prelude topEntity :: Vec 8 Int -> Int topEntity = fold (+) testInput :: Signal (Vec 8 Int) testInput = pure (1:>2:>3:>4:>5:>6:>7:>8:>Nil) expectedOutput :: Signal Int -> Signal Bool expectedOutput = outputVerifier (36 :> Nil)
ggreif/clash-compiler
tests/shouldwork/Vector/Fold.hs
bsd-2-clause
261
0
14
43
122
64
58
-1
-1
{-# LANGUAGE TupleSections #-} {-# LANGUAGE TemplateHaskell #-} module JvmTypeQuery ( Connection -- Hide data constructors , withConnection , definedClass , definedConstructor , findMethodReturnType , findFieldType , getModuleInfo , extractModuleInfo , ModuleInfo(..) ) where import JavaUtils (ClassName, MethodName, FieldName, ModuleName) import RuntimeProcessManager (withRuntimeProcess) import Src (Type, PackageName) import StringUtils import Control.Exception import Data.Char (isSpace, toLower) import Data.Either import Data.List import Data.List.Split import Data.Maybe (listToMaybe) import System.Directory import System.FilePath import System.IO import System.Process.Extra (system_) data Connection = Connection { -- private _toHandle :: Handle , _fromHandle :: Handle } data ModuleInfo = ModuleInfo { minfoName :: String, -- source name minfoGname :: String, -- java variable name minfoSignature :: Type } deriving (Show) withConnection :: (Connection -> IO a) -> Bool -- True for loading prelude -> IO a withConnection action = withRuntimeProcess "TypeServer" NoBuffering (\(toHandle, fromHandle) -> action Connection { _toHandle = toHandle, _fromHandle = fromHandle } ) sendRecv :: Connection -> [String] -> IO String sendRecv conn args = do hPutStrLn (_toHandle conn) (unwords args) hGetLine (_fromHandle conn) fixRet :: String -> IO (Maybe String) fixRet "$" = return Nothing fixRet str = return (Just str) isTrue :: String -> Bool isTrue s = (map toLower . filter (not . isSpace)) s == "true" definedClass :: Connection -> ClassName -> IO Bool definedClass conn c = isTrue <$> sendRecv conn ["qType", c] definedConstructor :: Connection -> ClassName -> [ClassName] -> IO Bool definedConstructor conn c params = isTrue <$> sendRecv conn (["qConstructor", c] ++ params) findMethodReturnType :: Connection -> ClassName -> (Bool, MethodName) -- True <=> static method -> [ClassName] -- Class of the arguments -> IO (Maybe ClassName) findMethodReturnType conn c (is_static, m) args = sendRecv conn ([tag, c, m] ++ args) >>= fixRet where tag = if is_static then "qStaticMethod" else "qMethod" findFieldType :: Connection -> ClassName -> (Bool, FieldName) -- True <=> static field -> IO (Maybe ClassName) findFieldType conn c (is_static, f) = sendRecv conn [tag, c, f] >>= fixRet where tag = if is_static then "qStaticField" else "qField" getModuleInfo :: Connection -> (Maybe Src.PackageName, ModuleName) -> IO (Maybe ([ModuleInfo], ModuleName)) getModuleInfo h (p, m) = do s <- sendRecv h ["qModuleInfo", ((maybe "" (++ ".") p) ++ capitalize m)] >>= fixRet case s of Nothing -> return Nothing Just xs -> return $ (maybe Nothing (Just . (,m)) (listToModuleInfo (splitOn "$" (init xs)))) where maybeRead = fmap fst . listToMaybe . reads listToModuleInfo [] = return [] listToModuleInfo (x:y:z:xs) = do xs' <- listToModuleInfo xs ty' <- maybeRead z :: Maybe Type return $ ModuleInfo x y ty' : xs' listToModuleInfo _ = Nothing extractModuleInfo :: Connection -> String -> (Maybe Src.PackageName, ModuleName) -> IO (Maybe ([ModuleInfo], ModuleName)) -- Compile imported modules if not compiled already extractModuleInfo h methods (p, m) = do currDir <- getCurrentDirectory maybeExistClass <- getModuleInfo h (p, m) case maybeExistClass of Nothing -> do let moduleDir = maybe "" (\name -> currDir </> intercalate [pathSeparator] (splitOn "." name)) p res <- (try . system_ $ "f2j" ++ methods ++ " --compile --silent " ++ moduleDir </> m ++ ".sf") :: IO (Either SomeException ()) either (const (return Nothing)) (const (getModuleInfo h (p, m))) res _ -> return maybeExistClass -- Tests inteneded to be run by `runhaskell` main :: IO () main = withConnection (\conn -> do definedClass conn "java.lang.String" >>= print definedClass conn "java.lang.Foo" >>= print definedConstructor conn "java.lang.String" [] >>= print definedConstructor conn "java.lang.String" ["java.lang.String"] >>= print definedConstructor conn "java.lang.String" ["Foo"] >>= print findMethodReturnType conn "java.lang.String" (False, "concat") ["java.lang.String"] >>= print findMethodReturnType conn "java.lang.String" (False, "length") [] >>= print findMethodReturnType conn "java.lang.String" (True, "valueOf") ["java.lang.Integer"] >>= print findMethodReturnType conn "java.lang.String" (True, "valueOf") ["Foo"] >>= print ) False
bixuanzju/fcore
lib/JvmTypeQuery.hs
bsd-2-clause
4,728
0
21
1,024
1,450
771
679
114
4
-- -- testing program for attoparsec and sax hoodle parser -- import Control.Monad import Data.Attoparsec import qualified Data.ByteString as B import System.Environment -- import Data.Hoodle.Simple -- import Text.Hoodle.Parse.Attoparsec -- import Text.Hoodle.Parse.Conduit import Graphics.Hoodle.Render import Graphics.Hoodle.Render.Type import Graphics.Rendering.Cairo -- | main :: IO () main = do args <- getArgs when (length args /= 3) $ error "parsertest mode filename (mode = atto/sax) outputfile" if args !! 0 == "atto" then attoparsec (args !! 1) (args !! 2) else return () -- sax (args !! 1) -- | using attoparsec without any built-in xml support attoparsec :: FilePath -> FilePath -> IO () attoparsec fp ofp = do bstr <- B.readFile fp let r = parse hoodle bstr case r of Done _ h -> renderjob h ofp -- print (length (hoodle_pages h)) _ -> print r -- | renderjob :: Hoodle -> FilePath -> IO () renderjob h ofp = do let p = head (hoodle_pages h) let Dim width height = page_dim p withPDFSurface ofp width height $ \s -> renderWith s $ (sequence1_ showPage . map renderPage . hoodle_pages) h -- | interleaving a monadic action between each pair of subsequent actions sequence1_ :: (Monad m) => m () -> [m ()] -> m () sequence1_ _ [] = return () sequence1_ _ [a] = a sequence1_ i (a:as) = a >> i >> sequence1_ i as {- -- | using sax (from xml-conduit) sax :: FilePath -> IO () sax fp = do r <- parseHoodleFile fp case r of Left err -> print err Right h -> print (length (hoodle_pages h)) -}
wavewave/hoodle-parser
examples/parsetest.hs
bsd-2-clause
1,641
0
14
410
453
232
221
33
2
module Language.Haskell.GhcMod.Utils where -- dropWhileEnd is not provided prior to base 4.5.0.0. dropWhileEnd :: (a -> Bool) -> [a] -> [a] dropWhileEnd p = foldr (\x xs -> if p x && null xs then [] else x : xs) []
carlohamalainen/ghc-mod
Language/Haskell/GhcMod/Utils.hs
bsd-3-clause
216
0
10
42
84
47
37
3
2
------------------------------------------------------------------------------- -- -- | Main API for compiling plain Haskell source code. -- -- This module implements compilation of a Haskell source. It is -- /not/ concerned with preprocessing of source files; this is handled -- in "DriverPipeline". -- -- There are various entry points depending on what mode we're in: -- "batch" mode (@--make@), "one-shot" mode (@-c@, @-S@ etc.), and -- "interactive" mode (GHCi). There are also entry points for -- individual passes: parsing, typechecking/renaming, desugaring, and -- simplification. -- -- All the functions here take an 'HscEnv' as a parameter, but none of -- them return a new one: 'HscEnv' is treated as an immutable value -- from here on in (although it has mutable components, for the -- caches). -- -- Warning messages are dealt with consistently throughout this API: -- during compilation warnings are collected, and before any function -- in @HscMain@ returns, the warnings are either printed, or turned -- into a real compialtion error if the @-Werror@ flag is enabled. -- -- (c) The GRASP/AQUA Project, Glasgow University, 1993-2000 -- ------------------------------------------------------------------------------- module HscMain ( -- * Making an HscEnv newHscEnv -- * Compiling complete source files , Compiler , HscStatus' (..) , InteractiveStatus, HscStatus , hscCompileOneShot , hscCompileBatch , hscCompileNothing , hscCompileInteractive , hscCompileCmmFile , hscCompileCore -- * Running passes separately , hscParse , hscTypecheckRename , hscDesugar , makeSimpleIface , makeSimpleDetails , hscSimplify -- ToDo, shouldn't really export this -- ** Backends , hscOneShotBackendOnly , hscBatchBackendOnly , hscNothingBackendOnly , hscInteractiveBackendOnly -- * Support for interactive evaluation , hscParseIdentifier , hscTcRcLookupName , hscTcRnGetInfo , hscCheckSafe #ifdef GHCI , hscGetModuleInterface , hscRnImportDecls , hscTcRnLookupRdrName , hscStmt, hscStmtWithLocation , hscDecls, hscDeclsWithLocation , hscTcExpr, hscImport, hscKcType , hscCompileCoreExpr #endif ) where #ifdef GHCI import ByteCodeGen ( byteCodeGen, coreExprToBCOs ) import Linker import CoreTidy ( tidyExpr ) import Type ( Type ) import PrelNames import {- Kind parts of -} Type ( Kind ) import CoreLint ( lintUnfolding ) import DsMeta ( templateHaskellNames ) import VarSet import VarEnv ( emptyTidyEnv ) import Panic #endif import Id import Module import Packages import RdrName import HsSyn import CoreSyn import StringBuffer import Parser import Lexer hiding (getDynFlags) import SrcLoc import TcRnDriver import TcIface ( typecheckIface ) import TcRnMonad import IfaceEnv ( initNameCache ) import LoadIface ( ifaceStats, initExternalPackageState ) import PrelInfo import MkIface import Desugar import SimplCore import TidyPgm import CorePrep import CoreToStg ( coreToStg ) import qualified StgCmm ( codeGen ) import StgSyn import CostCentre import ProfInit import TyCon import Name import SimplStg ( stg2stg ) import CodeGen ( codeGen ) import OldCmm as Old ( CmmGroup ) import PprCmm ( pprCmms ) import CmmParse ( parseCmmFile ) import CmmBuildInfoTables import CmmPipeline import CmmInfo import OptimizationFuel ( initOptFuelState ) import CmmCvt import CodeOutput import NameEnv ( emptyNameEnv ) import NameSet ( emptyNameSet ) import InstEnv import FamInstEnv import Fingerprint ( Fingerprint ) import DynFlags import ErrUtils import UniqSupply ( mkSplitUniqSupply ) import Outputable import HscStats ( ppSourceStats ) import HscTypes import MkExternalCore ( emitExternalCore ) import FastString import UniqFM ( emptyUFM ) import UniqSupply ( initUs_ ) import Bag import Exception import Data.List import Control.Monad import Data.Maybe import Data.IORef import System.FilePath as FilePath import System.Directory #include "HsVersions.h" {- ********************************************************************** %* * Initialisation %* * %********************************************************************* -} newHscEnv :: DynFlags -> IO HscEnv newHscEnv dflags = do eps_var <- newIORef initExternalPackageState us <- mkSplitUniqSupply 'r' nc_var <- newIORef (initNameCache us knownKeyNames) fc_var <- newIORef emptyUFM mlc_var <- newIORef emptyModuleEnv optFuel <- initOptFuelState return HscEnv { hsc_dflags = dflags, hsc_targets = [], hsc_mod_graph = [], hsc_IC = emptyInteractiveContext, hsc_HPT = emptyHomePackageTable, hsc_EPS = eps_var, hsc_NC = nc_var, hsc_FC = fc_var, hsc_MLC = mlc_var, hsc_OptFuel = optFuel, hsc_type_env_var = Nothing } knownKeyNames :: [Name] -- Put here to avoid loops involving DsMeta, knownKeyNames = -- where templateHaskellNames are defined map getName wiredInThings ++ basicKnownKeyNames #ifdef GHCI ++ templateHaskellNames #endif -- ----------------------------------------------------------------------------- -- The Hsc monad: Passing an enviornment and warning state newtype Hsc a = Hsc (HscEnv -> WarningMessages -> IO (a, WarningMessages)) instance Monad Hsc where return a = Hsc $ \_ w -> return (a, w) Hsc m >>= k = Hsc $ \e w -> do (a, w1) <- m e w case k a of Hsc k' -> k' e w1 instance MonadIO Hsc where liftIO io = Hsc $ \_ w -> do a <- io; return (a, w) runHsc :: HscEnv -> Hsc a -> IO a runHsc hsc_env (Hsc hsc) = do (a, w) <- hsc hsc_env emptyBag printOrThrowWarnings (hsc_dflags hsc_env) w return a getWarnings :: Hsc WarningMessages getWarnings = Hsc $ \_ w -> return (w, w) clearWarnings :: Hsc () clearWarnings = Hsc $ \_ _ -> return ((), emptyBag) logWarnings :: WarningMessages -> Hsc () logWarnings w = Hsc $ \_ w0 -> return ((), w0 `unionBags` w) getHscEnv :: Hsc HscEnv getHscEnv = Hsc $ \e w -> return (e, w) getDynFlags :: Hsc DynFlags getDynFlags = Hsc $ \e w -> return (hsc_dflags e, w) handleWarnings :: Hsc () handleWarnings = do dflags <- getDynFlags w <- getWarnings liftIO $ printOrThrowWarnings dflags w clearWarnings -- | log warning in the monad, and if there are errors then -- throw a SourceError exception. logWarningsReportErrors :: Messages -> Hsc () logWarningsReportErrors (warns,errs) = do logWarnings warns when (not $ isEmptyBag errs) $ throwErrors errs -- | Throw some errors. throwErrors :: ErrorMessages -> Hsc a throwErrors = liftIO . throwIO . mkSrcErr -- | Deal with errors and warnings returned by a compilation step -- -- In order to reduce dependencies to other parts of the compiler, functions -- outside the "main" parts of GHC return warnings and errors as a parameter -- and signal success via by wrapping the result in a 'Maybe' type. This -- function logs the returned warnings and propagates errors as exceptions -- (of type 'SourceError'). -- -- This function assumes the following invariants: -- -- 1. If the second result indicates success (is of the form 'Just x'), -- there must be no error messages in the first result. -- -- 2. If there are no error messages, but the second result indicates failure -- there should be warnings in the first result. That is, if the action -- failed, it must have been due to the warnings (i.e., @-Werror@). ioMsgMaybe :: IO (Messages, Maybe a) -> Hsc a ioMsgMaybe ioA = do ((warns,errs), mb_r) <- liftIO $ ioA logWarnings warns case mb_r of Nothing -> throwErrors errs Just r -> ASSERT( isEmptyBag errs ) return r -- | like ioMsgMaybe, except that we ignore error messages and return -- 'Nothing' instead. ioMsgMaybe' :: IO (Messages, Maybe a) -> Hsc (Maybe a) ioMsgMaybe' ioA = do ((warns,_errs), mb_r) <- liftIO $ ioA logWarnings warns return mb_r -- ----------------------------------------------------------------------------- -- | Lookup things in the compiler's environment #ifdef GHCI hscTcRnLookupRdrName :: HscEnv -> RdrName -> IO [Name] hscTcRnLookupRdrName hsc_env rdr_name = runHsc hsc_env $ ioMsgMaybe $ tcRnLookupRdrName hsc_env rdr_name #endif hscTcRcLookupName :: HscEnv -> Name -> IO (Maybe TyThing) hscTcRcLookupName hsc_env name = runHsc hsc_env $ ioMsgMaybe' $ tcRnLookupName hsc_env name -- ignore errors: the only error we're likely to get is -- "name not found", and the Maybe in the return type -- is used to indicate that. hscTcRnGetInfo :: HscEnv -> Name -> IO (Maybe (TyThing, Fixity, [Instance])) hscTcRnGetInfo hsc_env name = runHsc hsc_env $ ioMsgMaybe' $ tcRnGetInfo hsc_env name #ifdef GHCI hscGetModuleInterface :: HscEnv -> Module -> IO ModIface hscGetModuleInterface hsc_env mod = runHsc hsc_env $ ioMsgMaybe $ getModuleInterface hsc_env mod -- ----------------------------------------------------------------------------- -- | Rename some import declarations hscRnImportDecls :: HscEnv -> [LImportDecl RdrName] -> IO GlobalRdrEnv hscRnImportDecls hsc_env import_decls = runHsc hsc_env $ ioMsgMaybe $ tcRnImportDecls hsc_env import_decls #endif -- ----------------------------------------------------------------------------- -- | parse a file, returning the abstract syntax hscParse :: HscEnv -> ModSummary -> IO HsParsedModule hscParse hsc_env mod_summary = runHsc hsc_env $ hscParse' mod_summary -- internal version, that doesn't fail due to -Werror hscParse' :: ModSummary -> Hsc HsParsedModule hscParse' mod_summary = do dflags <- getDynFlags let src_filename = ms_hspp_file mod_summary maybe_src_buf = ms_hspp_buf mod_summary -------------------------- Parser ---------------- liftIO $ showPass dflags "Parser" {-# SCC "Parser" #-} do -- sometimes we already have the buffer in memory, perhaps -- because we needed to parse the imports out of it, or get the -- module name. buf <- case maybe_src_buf of Just b -> return b Nothing -> liftIO $ hGetStringBuffer src_filename let loc = mkRealSrcLoc (mkFastString src_filename) 1 1 case unP parseModule (mkPState dflags buf loc) of PFailed span err -> liftIO $ throwOneError (mkPlainErrMsg span err) POk pst rdr_module -> do logWarningsReportErrors (getMessages pst) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" $ ppr rdr_module liftIO $ dumpIfSet_dyn dflags Opt_D_source_stats "Source Statistics" $ ppSourceStats False rdr_module -- To get the list of extra source files, we take the list -- that the parser gave us, -- - eliminate files beginning with '<'. gcc likes to use -- pseudo-filenames like "<built-in>" and "<command-line>" -- - normalise them (elimiante differences between ./f and f) -- - filter out the preprocessed source file -- - filter out anything beginning with tmpdir -- - remove duplicates -- - filter out the .hs/.lhs source filename if we have one -- let n_hspp = FilePath.normalise src_filename srcs0 = nub $ filter (not . (tmpDir dflags `isPrefixOf`)) $ filter (not . (== n_hspp)) $ map FilePath.normalise $ filter (not . (== '<') . head) $ map unpackFS $ srcfiles pst srcs1 = case ml_hs_file (ms_location mod_summary) of Just f -> filter (/= FilePath.normalise f) srcs0 Nothing -> srcs0 -- sometimes we see source files from earlier -- preprocessing stages that cannot be found, so just -- filter them out: srcs2 <- liftIO $ filterM doesFileExist srcs1 return HsParsedModule { hpm_module = rdr_module, hpm_src_files = srcs2 } -- XXX: should this really be a Maybe X? Check under which circumstances this -- can become a Nothing and decide whether this should instead throw an -- exception/signal an error. type RenamedStuff = (Maybe (HsGroup Name, [LImportDecl Name], Maybe [LIE Name], Maybe LHsDocString)) -- | Rename and typecheck a module, additionally returning the renamed syntax hscTypecheckRename :: HscEnv -> ModSummary -> HsParsedModule -> IO (TcGblEnv, RenamedStuff) hscTypecheckRename hsc_env mod_summary rdr_module = runHsc hsc_env $ do tc_result <- tcRnModule' hsc_env mod_summary True rdr_module -- This 'do' is in the Maybe monad! let rn_info = do decl <- tcg_rn_decls tc_result let imports = tcg_rn_imports tc_result exports = tcg_rn_exports tc_result doc_hdr = tcg_doc_hdr tc_result return (decl,imports,exports,doc_hdr) return (tc_result, rn_info) -- wrapper around tcRnModule to handle safe haskell extras tcRnModule' :: HscEnv -> ModSummary -> Bool -> HsParsedModule -> Hsc TcGblEnv tcRnModule' hsc_env sum save_rn_syntax mod = do tcg_res <- {-# SCC "Typecheck-Rename" #-} ioMsgMaybe $ tcRnModule hsc_env (ms_hsc_src sum) save_rn_syntax mod tcSafeOK <- liftIO $ readIORef (tcg_safeInfer tcg_res) dflags <- getDynFlags -- end of the Safe Haskell line, how to respond to user? if not (safeHaskellOn dflags) || (safeInferOn dflags && not tcSafeOK) -- if safe haskell off or safe infer failed, wipe trust then wipeTrust tcg_res emptyBag -- module safe, throw warning if needed else do tcg_res' <- hscCheckSafeImports tcg_res safe <- liftIO $ readIORef (tcg_safeInfer tcg_res') when (safe && wopt Opt_WarnSafe dflags) (logWarnings $ unitBag $ mkPlainWarnMsg (warnSafeOnLoc dflags) $ errSafe tcg_res') return tcg_res' where pprMod t = ppr $ moduleName $ tcg_mod t errSafe t = text "Warning:" <+> quotes (pprMod t) <+> text "has been infered as safe!" -- | Convert a typechecked module to Core hscDesugar :: HscEnv -> ModSummary -> TcGblEnv -> IO ModGuts hscDesugar hsc_env mod_summary tc_result = runHsc hsc_env $ hscDesugar' (ms_location mod_summary) tc_result hscDesugar' :: ModLocation -> TcGblEnv -> Hsc ModGuts hscDesugar' mod_location tc_result = do hsc_env <- getHscEnv r <- ioMsgMaybe $ {-# SCC "deSugar" #-} deSugar hsc_env mod_location tc_result -- always check -Werror after desugaring, this is the last opportunity for -- warnings to arise before the backend. handleWarnings return r -- | Make a 'ModIface' from the results of typechecking. Used when -- not optimising, and the interface doesn't need to contain any -- unfoldings or other cross-module optimisation info. -- ToDo: the old interface is only needed to get the version numbers, -- we should use fingerprint versions instead. makeSimpleIface :: HscEnv -> Maybe ModIface -> TcGblEnv -> ModDetails -> IO (ModIface,Bool) makeSimpleIface hsc_env maybe_old_iface tc_result details = runHsc hsc_env $ do safe_mode <- hscGetSafeMode tc_result ioMsgMaybe $ do mkIfaceTc hsc_env (fmap mi_iface_hash maybe_old_iface) safe_mode details tc_result -- | Make a 'ModDetails' from the results of typechecking. Used when -- typechecking only, as opposed to full compilation. makeSimpleDetails :: HscEnv -> TcGblEnv -> IO ModDetails makeSimpleDetails hsc_env tc_result = mkBootModDetailsTc hsc_env tc_result {- ********************************************************************** %* * The main compiler pipeline %* * %********************************************************************* -} {- -------------------------------- The compilation proper -------------------------------- It's the task of the compilation proper to compile Haskell, hs-boot and core files to either byte-code, hard-code (C, asm, LLVM, ect) or to nothing at all (the module is still parsed and type-checked. This feature is mostly used by IDE's and the likes). Compilation can happen in either 'one-shot', 'batch', 'nothing', or 'interactive' mode. 'One-shot' mode targets hard-code, 'batch' mode targets hard-code, 'nothing' mode targets nothing and 'interactive' mode targets byte-code. The modes are kept separate because of their different types and meanings: * In 'one-shot' mode, we're only compiling a single file and can therefore discard the new ModIface and ModDetails. This is also the reason it only targets hard-code; compiling to byte-code or nothing doesn't make sense when we discard the result. * 'Batch' mode is like 'one-shot' except that we keep the resulting ModIface and ModDetails. 'Batch' mode doesn't target byte-code since that require us to return the newly compiled byte-code. * 'Nothing' mode has exactly the same type as 'batch' mode but they're still kept separate. This is because compiling to nothing is fairly special: We don't output any interface files, we don't run the simplifier and we don't generate any code. * 'Interactive' mode is similar to 'batch' mode except that we return the compiled byte-code together with the ModIface and ModDetails. Trying to compile a hs-boot file to byte-code will result in a run-time error. This is the only thing that isn't caught by the type-system. -} -- | Status of a compilation to hard-code or nothing. data HscStatus' a = HscNoRecomp | HscRecomp (Maybe FilePath) -- Has stub files. This is a hack. We can't compile -- C files here since it's done in DriverPipeline. -- For now we just return True if we want the caller -- to compile them for us. a -- This is a bit ugly. Since we use a typeclass below and would like to avoid -- functional dependencies, we have to parameterise the typeclass over the -- result type. Therefore we need to artificially distinguish some types. We do -- this by adding type tags which will simply be ignored by the caller. type HscStatus = HscStatus' () type InteractiveStatus = HscStatus' (Maybe (CompiledByteCode, ModBreaks)) -- INVARIANT: result is @Nothing@ <=> input was a boot file type OneShotResult = HscStatus type BatchResult = (HscStatus, ModIface, ModDetails) type NothingResult = (HscStatus, ModIface, ModDetails) type InteractiveResult = (InteractiveStatus, ModIface, ModDetails) -- ToDo: The old interface and module index are only using in 'batch' and -- 'interactive' mode. They should be removed from 'oneshot' mode. type Compiler result = HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -- Old interface, if available -> Maybe (Int,Int) -- Just (i,n) <=> module i of n (for msgs) -> IO result data HsCompiler a = HsCompiler { -- | Called when no recompilation is necessary. hscNoRecomp :: ModIface -> Hsc a, -- | Called to recompile the module. hscRecompile :: ModSummary -> Maybe Fingerprint -> Hsc a, hscBackend :: TcGblEnv -> ModSummary -> Maybe Fingerprint -> Hsc a, -- | Code generation for Boot modules. hscGenBootOutput :: TcGblEnv -> ModSummary -> Maybe Fingerprint -> Hsc a, -- | Code generation for normal modules. hscGenOutput :: ModGuts -> ModSummary -> Maybe Fingerprint -> Hsc a } genericHscCompile :: HsCompiler a -> (HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO ()) -> HscEnv -> ModSummary -> SourceModified -> Maybe ModIface -> Maybe (Int, Int) -> IO a genericHscCompile compiler hscMessage hsc_env mod_summary source_modified mb_old_iface0 mb_mod_index = do (recomp_reqd, mb_checked_iface) <- {-# SCC "checkOldIface" #-} checkOldIface hsc_env mod_summary source_modified mb_old_iface0 -- save the interface that comes back from checkOldIface. -- In one-shot mode we don't have the old iface until this -- point, when checkOldIface reads it from the disk. let mb_old_hash = fmap mi_iface_hash mb_checked_iface let skip iface = do hscMessage hsc_env mb_mod_index RecompNotRequired mod_summary runHsc hsc_env $ hscNoRecomp compiler iface compile reason = do hscMessage hsc_env mb_mod_index reason mod_summary runHsc hsc_env $ hscRecompile compiler mod_summary mb_old_hash stable = case source_modified of SourceUnmodifiedAndStable -> True _ -> False -- If the module used TH splices when it was last compiled, -- then the recompilation check is not accurate enough (#481) -- and we must ignore it. However, if the module is stable -- (none of the modules it depends on, directly or indirectly, -- changed), then we *can* skip recompilation. This is why -- the SourceModified type contains SourceUnmodifiedAndStable, -- and it's pretty important: otherwise ghc --make would -- always recompile TH modules, even if nothing at all has -- changed. Stability is just the same check that make is -- doing for us in one-shot mode. case mb_checked_iface of Just iface | not recomp_reqd -> if mi_used_th iface && not stable then compile RecompForcedByTH else skip iface _otherwise -> compile RecompRequired hscCheckRecompBackend :: HsCompiler a -> TcGblEnv -> Compiler a hscCheckRecompBackend compiler tc_result hsc_env mod_summary source_modified mb_old_iface _m_of_n = do (recomp_reqd, mb_checked_iface) <- {-# SCC "checkOldIface" #-} checkOldIface hsc_env mod_summary source_modified mb_old_iface let mb_old_hash = fmap mi_iface_hash mb_checked_iface case mb_checked_iface of Just iface | not recomp_reqd -> runHsc hsc_env $ hscNoRecomp compiler iface{ mi_globals = Just (tcg_rdr_env tc_result) } _otherwise -> runHsc hsc_env $ hscBackend compiler tc_result mod_summary mb_old_hash genericHscRecompile :: HsCompiler a -> ModSummary -> Maybe Fingerprint -> Hsc a genericHscRecompile compiler mod_summary mb_old_hash | ExtCoreFile <- ms_hsc_src mod_summary = panic "GHC does not currently support reading External Core files" | otherwise = do tc_result <- hscFileFrontEnd mod_summary hscBackend compiler tc_result mod_summary mb_old_hash genericHscBackend :: HsCompiler a -> TcGblEnv -> ModSummary -> Maybe Fingerprint -> Hsc a genericHscBackend compiler tc_result mod_summary mb_old_hash | HsBootFile <- ms_hsc_src mod_summary = hscGenBootOutput compiler tc_result mod_summary mb_old_hash | otherwise = do guts <- hscDesugar' (ms_location mod_summary) tc_result hscGenOutput compiler guts mod_summary mb_old_hash compilerBackend :: HsCompiler a -> TcGblEnv -> Compiler a compilerBackend comp tcg hsc_env ms' _ _mb_old_iface _ = runHsc hsc_env $ hscBackend comp tcg ms' Nothing -------------------------------------------------------------- -- Compilers -------------------------------------------------------------- hscOneShotCompiler :: HsCompiler OneShotResult hscOneShotCompiler = HsCompiler { hscNoRecomp = \_old_iface -> do hsc_env <- getHscEnv liftIO $ dumpIfaceStats hsc_env return HscNoRecomp , hscRecompile = genericHscRecompile hscOneShotCompiler , hscBackend = \tc_result mod_summary mb_old_hash -> do dflags <- getDynFlags case hscTarget dflags of HscNothing -> return (HscRecomp Nothing ()) _otherw -> genericHscBackend hscOneShotCompiler tc_result mod_summary mb_old_hash , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do (iface, changed, _) <- hscSimpleIface tc_result mb_old_iface hscWriteIface iface changed mod_summary return (HscRecomp Nothing ()) , hscGenOutput = \guts0 mod_summary mb_old_iface -> do guts <- hscSimplify' guts0 (iface, changed, _details, cgguts) <- hscNormalIface guts mb_old_iface hscWriteIface iface changed mod_summary hasStub <- hscGenHardCode cgguts mod_summary return (HscRecomp hasStub ()) } -- Compile Haskell, boot and extCore in OneShot mode. hscCompileOneShot :: Compiler OneShotResult hscCompileOneShot hsc_env mod_summary src_changed mb_old_iface mb_i_of_n = do -- One-shot mode needs a knot-tying mutable variable for interface -- files. See TcRnTypes.TcGblEnv.tcg_type_env_var. type_env_var <- newIORef emptyNameEnv let mod = ms_mod mod_summary hsc_env' = hsc_env{ hsc_type_env_var = Just (mod, type_env_var) } genericHscCompile hscOneShotCompiler oneShotMsg hsc_env' mod_summary src_changed mb_old_iface mb_i_of_n hscOneShotBackendOnly :: TcGblEnv -> Compiler OneShotResult hscOneShotBackendOnly = compilerBackend hscOneShotCompiler -------------------------------------------------------------- hscBatchCompiler :: HsCompiler BatchResult hscBatchCompiler = HsCompiler { hscNoRecomp = \iface -> do details <- genModDetails iface return (HscNoRecomp, iface, details) , hscRecompile = genericHscRecompile hscBatchCompiler , hscBackend = genericHscBackend hscBatchCompiler , hscGenBootOutput = \tc_result mod_summary mb_old_iface -> do (iface, changed, details) <- hscSimpleIface tc_result mb_old_iface hscWriteIface iface changed mod_summary return (HscRecomp Nothing (), iface, details) , hscGenOutput = \guts0 mod_summary mb_old_iface -> do guts <- hscSimplify' guts0 (iface, changed, details, cgguts) <- hscNormalIface guts mb_old_iface hscWriteIface iface changed mod_summary hasStub <- hscGenHardCode cgguts mod_summary return (HscRecomp hasStub (), iface, details) } -- | Compile Haskell, boot and extCore in batch mode. hscCompileBatch :: Compiler (HscStatus, ModIface, ModDetails) hscCompileBatch = genericHscCompile hscBatchCompiler batchMsg hscBatchBackendOnly :: TcGblEnv -> Compiler BatchResult hscBatchBackendOnly = hscCheckRecompBackend hscBatchCompiler -------------------------------------------------------------- hscInteractiveCompiler :: HsCompiler InteractiveResult hscInteractiveCompiler = HsCompiler { hscNoRecomp = \iface -> do details <- genModDetails iface return (HscNoRecomp, iface, details) , hscRecompile = genericHscRecompile hscInteractiveCompiler , hscBackend = genericHscBackend hscInteractiveCompiler , hscGenBootOutput = \tc_result _mod_summary mb_old_iface -> do (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface return (HscRecomp Nothing Nothing, iface, details) , hscGenOutput = \guts0 mod_summary mb_old_iface -> do guts <- hscSimplify' guts0 (iface, _changed, details, cgguts) <- hscNormalIface guts mb_old_iface hscInteractive (iface, details, cgguts) mod_summary } -- Compile Haskell, extCore to bytecode. hscCompileInteractive :: Compiler (InteractiveStatus, ModIface, ModDetails) hscCompileInteractive = genericHscCompile hscInteractiveCompiler batchMsg hscInteractiveBackendOnly :: TcGblEnv -> Compiler InteractiveResult hscInteractiveBackendOnly = compilerBackend hscInteractiveCompiler -------------------------------------------------------------- hscNothingCompiler :: HsCompiler NothingResult hscNothingCompiler = HsCompiler { hscNoRecomp = \iface -> do details <- genModDetails iface return (HscNoRecomp, iface, details) , hscRecompile = genericHscRecompile hscNothingCompiler , hscBackend = \tc_result _mod_summary mb_old_iface -> do handleWarnings (iface, _changed, details) <- hscSimpleIface tc_result mb_old_iface return (HscRecomp Nothing (), iface, details) , hscGenBootOutput = \_ _ _ -> panic "hscCompileNothing: hscGenBootOutput should not be called" , hscGenOutput = \_ _ _ -> panic "hscCompileNothing: hscGenOutput should not be called" } -- Type-check Haskell and .hs-boot only (no external core) hscCompileNothing :: Compiler (HscStatus, ModIface, ModDetails) hscCompileNothing = genericHscCompile hscNothingCompiler batchMsg hscNothingBackendOnly :: TcGblEnv -> Compiler NothingResult hscNothingBackendOnly = compilerBackend hscNothingCompiler -------------------------------------------------------------- -- NoRecomp handlers -------------------------------------------------------------- genModDetails :: ModIface -> Hsc ModDetails genModDetails old_iface = do hsc_env <- getHscEnv new_details <- {-# SCC "tcRnIface" #-} liftIO $ initIfaceCheck hsc_env (typecheckIface old_iface) liftIO $ dumpIfaceStats hsc_env return new_details -------------------------------------------------------------- -- Progress displayers. -------------------------------------------------------------- data RecompReason = RecompNotRequired | RecompRequired | RecompForcedByTH deriving Eq oneShotMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO () oneShotMsg hsc_env _mb_mod_index recomp _mod_summary = case recomp of RecompNotRequired -> compilationProgressMsg (hsc_dflags hsc_env) $ "compilation IS NOT required" _other -> return () batchMsg :: HscEnv -> Maybe (Int,Int) -> RecompReason -> ModSummary -> IO () batchMsg hsc_env mb_mod_index recomp mod_summary = case recomp of RecompRequired -> showMsg "Compiling " RecompNotRequired | verbosity (hsc_dflags hsc_env) >= 2 -> showMsg "Skipping " | otherwise -> return () RecompForcedByTH -> showMsg "Compiling [TH] " where showMsg msg = compilationProgressMsg (hsc_dflags hsc_env) $ (showModuleIndex mb_mod_index ++ msg ++ showModMsg (hscTarget (hsc_dflags hsc_env)) (recomp == RecompRequired) mod_summary) -------------------------------------------------------------- -- FrontEnds -------------------------------------------------------------- hscFileFrontEnd :: ModSummary -> Hsc TcGblEnv hscFileFrontEnd mod_summary = do hpm <- hscParse' mod_summary hsc_env <- getHscEnv tcg_env <- tcRnModule' hsc_env mod_summary False hpm return tcg_env -------------------------------------------------------------- -- Safe Haskell -------------------------------------------------------------- -- Note [Safe Haskell Trust Check] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell checks that an import is trusted according to the following -- rules for an import of module M that resides in Package P: -- -- * If M is recorded as Safe and all its trust dependencies are OK -- then M is considered safe. -- * If M is recorded as Trustworthy and P is considered trusted and -- all M's trust dependencies are OK then M is considered safe. -- -- By trust dependencies we mean that the check is transitive. So if -- a module M that is Safe relies on a module N that is trustworthy, -- importing module M will first check (according to the second case) -- that N is trusted before checking M is trusted. -- -- This is a minimal description, so please refer to the user guide -- for more details. The user guide is also considered the authoritative -- source in this matter, not the comments or code. -- Note [Safe Haskell Inference] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- Safe Haskell does Safe inference on modules that don't have any specific -- safe haskell mode flag. The basic aproach to this is: -- * When deciding if we need to do a Safe language check, treat -- an unmarked module as having -XSafe mode specified. -- * For checks, don't throw errors but return them to the caller. -- * Caller checks if there are errors: -- * For modules explicitly marked -XSafe, we throw the errors. -- * For unmarked modules (inference mode), we drop the errors -- and mark the module as being Unsafe. -- | Check that the safe imports of the module being compiled are valid. -- If not we either issue a compilation error if the module is explicitly -- using Safe Haskell, or mark the module as unsafe if we're in safe -- inference mode. hscCheckSafeImports :: TcGblEnv -> Hsc TcGblEnv hscCheckSafeImports tcg_env = do dflags <- getDynFlags tcg_env' <- checkSafeImports dflags tcg_env case safeLanguageOn dflags of True -> do -- we nuke user written RULES in -XSafe logWarnings $ warns (tcg_rules tcg_env') return tcg_env' { tcg_rules = [] } False -- user defined RULES, so not safe or already unsafe | safeInferOn dflags && not (null $ tcg_rules tcg_env') || safeHaskell dflags == Sf_None -> wipeTrust tcg_env' $ warns (tcg_rules tcg_env') -- trustworthy OR safe infered with no RULES | otherwise -> return tcg_env' where warns rules = listToBag $ map warnRules rules warnRules (L loc (HsRule n _ _ _ _ _ _)) = mkPlainWarnMsg loc $ text "Rule \"" <> ftext n <> text "\" ignored" $+$ text "User defined rules are disabled under Safe Haskell" -- | Validate that safe imported modules are actually safe. For modules in the -- HomePackage (the package the module we are compiling in resides) this just -- involves checking its trust type is 'Safe' or 'Trustworthy'. For modules -- that reside in another package we also must check that the external pacakge -- is trusted. See the Note [Safe Haskell Trust Check] above for more -- information. -- -- The code for this is quite tricky as the whole algorithm is done in a few -- distinct phases in different parts of the code base. See -- RnNames.rnImportDecl for where package trust dependencies for a module are -- collected and unioned. Specifically see the Note [RnNames . Tracking Trust -- Transitively] and the Note [RnNames . Trust Own Package]. checkSafeImports :: DynFlags -> TcGblEnv -> Hsc TcGblEnv checkSafeImports dflags tcg_env = do -- We want to use the warning state specifically for detecting if safe -- inference has failed, so store and clear any existing warnings. oldErrs <- getWarnings clearWarnings imps <- mapM condense imports' pkgs <- mapM checkSafe imps -- grab any safe haskell specific errors and restore old warnings errs <- getWarnings clearWarnings logWarnings oldErrs -- See the Note [Safe Haskell Inference] case (not $ isEmptyBag errs) of -- We have errors! True -> -- did we fail safe inference or fail -XSafe? case safeInferOn dflags of True -> wipeTrust tcg_env errs False -> liftIO . throwIO . mkSrcErr $ errs -- All good matey! False -> do when (packageTrustOn dflags) $ checkPkgTrust dflags pkg_reqs -- add in trusted package requirements for this module let new_trust = emptyImportAvails { imp_trust_pkgs = catMaybes pkgs } return tcg_env { tcg_imports = imp_info `plusImportAvails` new_trust } where imp_info = tcg_imports tcg_env -- ImportAvails imports = imp_mods imp_info -- ImportedMods imports' = moduleEnvToList imports -- (Module, [ImportedModsVal]) pkg_reqs = imp_trust_pkgs imp_info -- [PackageId] condense :: (Module, [ImportedModsVal]) -> Hsc (Module, SrcSpan, IsSafeImport) condense (_, []) = panic "HscMain.condense: Pattern match failure!" condense (m, x:xs) = do (_,_,l,s) <- foldlM cond' x xs -- we turn all imports into safe ones when -- inference mode is on. let s' = if safeInferOn dflags then True else s return (m, l, s') -- ImportedModsVal = (ModuleName, Bool, SrcSpan, IsSafeImport) cond' :: ImportedModsVal -> ImportedModsVal -> Hsc ImportedModsVal cond' v1@(m1,_,l1,s1) (_,_,_,s2) | s1 /= s2 = throwErrors $ unitBag $ mkPlainErrMsg l1 (text "Module" <+> ppr m1 <+> (text $ "is imported both as a safe and unsafe import!")) | otherwise = return v1 -- easier interface to work with checkSafe (_, _, False) = return Nothing checkSafe (m, l, True ) = hscCheckSafe' dflags m l -- | Check that a module is safe to import. -- -- We return a package id if the safe import is OK and a Nothing otherwise -- with the reason for the failure printed out. hscCheckSafe :: HscEnv -> Module -> SrcSpan -> IO (Maybe PackageId) hscCheckSafe hsc_env m l = runHsc hsc_env $ do dflags <- getDynFlags hscCheckSafe' dflags m l hscCheckSafe' :: DynFlags -> Module -> SrcSpan -> Hsc (Maybe PackageId) hscCheckSafe' dflags m l = do tw <- isModSafe m l case tw of False -> return Nothing True | isHomePkg m -> return Nothing | otherwise -> return $ Just $ modulePackageId m where -- Is a module trusted? Return Nothing if True, or a String if it isn't, -- containing the reason it isn't. Also return if the module trustworthy -- (true) or safe (false) so we know if we should check if the package -- itself is trusted in the future. isModSafe :: Module -> SrcSpan -> Hsc (Bool) isModSafe m l = do iface <- lookup' m case iface of -- can't load iface to check trust! Nothing -> throwErrors $ unitBag $ mkPlainErrMsg l $ text "Can't load the interface file for" <+> ppr m <> text ", to check that it can be safely imported" -- got iface, check trust Just iface' -> do let trust = getSafeMode $ mi_trust iface' trust_own_pkg = mi_trust_pkg iface' -- check module is trusted safeM = trust `elem` [Sf_SafeInfered, Sf_Safe, Sf_Trustworthy] -- check package is trusted safeP = packageTrusted trust trust_own_pkg m case (safeM, safeP) of -- General errors we throw but Safe errors we log (True, True ) -> return $ trust == Sf_Trustworthy (True, False) -> liftIO . throwIO $ pkgTrustErr (False, _ ) -> logWarnings modTrustErr >> return (trust == Sf_Trustworthy) where pkgTrustErr = mkSrcErr $ unitBag $ mkPlainErrMsg l $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The package (" <> ppr (modulePackageId m) <> text ") the module resides in isn't trusted." ] modTrustErr = unitBag $ mkPlainErrMsg l $ sep [ ppr (moduleName m) <> text ": Can't be safely imported!" , text "The module itself isn't safe." ] -- | Check the package a module resides in is trusted. Safe compiled -- modules are trusted without requiring that their package is trusted. For -- trustworthy modules, modules in the home package are trusted but -- otherwise we check the package trust flag. packageTrusted :: SafeHaskellMode -> Bool -> Module -> Bool packageTrusted _ _ _ | not (packageTrustOn dflags) = True packageTrusted Sf_Safe False _ = True packageTrusted Sf_SafeInfered False _ = True packageTrusted _ _ m | isHomePkg m = True | otherwise = trusted $ getPackageDetails (pkgState dflags) (modulePackageId m) lookup' :: Module -> Hsc (Maybe ModIface) lookup' m = do hsc_env <- getHscEnv hsc_eps <- liftIO $ hscEPS hsc_env let pkgIfaceT = eps_PIT hsc_eps homePkgT = hsc_HPT hsc_env iface = lookupIfaceByModule dflags homePkgT pkgIfaceT m return iface isHomePkg :: Module -> Bool isHomePkg m | thisPackage dflags == modulePackageId m = True | otherwise = False -- | Check the list of packages are trusted. checkPkgTrust :: DynFlags -> [PackageId] -> Hsc () checkPkgTrust dflags pkgs = case errors of [] -> return () _ -> (liftIO . throwIO . mkSrcErr . listToBag) errors where errors = catMaybes $ map go pkgs go pkg | trusted $ getPackageDetails (pkgState dflags) pkg = Nothing | otherwise = Just $ mkPlainErrMsg noSrcSpan $ text "The package (" <> ppr pkg <> text ") is required" <> text " to be trusted but it isn't!" -- | Set module to unsafe and wipe trust information. -- -- Make sure to call this method to set a module to infered unsafe, -- it should be a central and single failure method. wipeTrust :: TcGblEnv -> WarningMessages -> Hsc TcGblEnv wipeTrust tcg_env whyUnsafe = do dflags <- getDynFlags when (wopt Opt_WarnUnsafe dflags) (logWarnings $ unitBag $ mkPlainWarnMsg (warnUnsafeOnLoc dflags) (whyUnsafe' dflags)) liftIO $ writeIORef (tcg_safeInfer tcg_env) False return $ tcg_env { tcg_imports = wiped_trust } where wiped_trust = (tcg_imports tcg_env) { imp_trust_pkgs = [] } pprMod = ppr $ moduleName $ tcg_mod tcg_env whyUnsafe' df = vcat [ text "Warning:" <+> quotes pprMod <+> text "has been infered as unsafe!" , text "Reason:" , nest 4 $ (vcat $ badFlags df) $+$ (vcat $ pprErrMsgBagWithLoc whyUnsafe) ] badFlags df = concat $ map (badFlag df) unsafeFlags badFlag df (str,loc,on,_) | on df = [mkLocMessage (loc df) $ text str <+> text "is not allowed in Safe Haskell"] | otherwise = [] -- | Figure out the final correct safe haskell mode hscGetSafeMode :: TcGblEnv -> Hsc SafeHaskellMode hscGetSafeMode tcg_env = do dflags <- getDynFlags liftIO $ finalSafeMode dflags tcg_env -------------------------------------------------------------- -- Simplifiers -------------------------------------------------------------- hscSimplify :: HscEnv -> ModGuts -> IO ModGuts hscSimplify hsc_env modguts = runHsc hsc_env $ hscSimplify' modguts hscSimplify' :: ModGuts -> Hsc ModGuts hscSimplify' ds_result = do hsc_env <- getHscEnv {-# SCC "Core2Core" #-} liftIO $ core2core hsc_env ds_result -------------------------------------------------------------- -- Interface generators -------------------------------------------------------------- hscSimpleIface :: TcGblEnv -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails) hscSimpleIface tc_result mb_old_iface = do hsc_env <- getHscEnv details <- liftIO $ mkBootModDetailsTc hsc_env tc_result safe_mode <- hscGetSafeMode tc_result (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} ioMsgMaybe $ mkIfaceTc hsc_env mb_old_iface safe_mode details tc_result -- And the answer is ... liftIO $ dumpIfaceStats hsc_env return (new_iface, no_change, details) hscNormalIface :: ModGuts -> Maybe Fingerprint -> Hsc (ModIface, Bool, ModDetails, CgGuts) hscNormalIface simpl_result mb_old_iface = do hsc_env <- getHscEnv (cg_guts, details) <- {-# SCC "CoreTidy" #-} liftIO $ tidyProgram hsc_env simpl_result -- BUILD THE NEW ModIface and ModDetails -- and emit external core if necessary -- This has to happen *after* code gen so that the back-end -- info has been set. Not yet clear if it matters waiting -- until after code output (new_iface, no_change) <- {-# SCC "MkFinalIface" #-} ioMsgMaybe $ mkIface hsc_env mb_old_iface details simpl_result -- Emit external core -- This should definitely be here and not after CorePrep, -- because CorePrep produces unqualified constructor wrapper declarations, -- so its output isn't valid External Core (without some preprocessing). liftIO $ emitExternalCore (hsc_dflags hsc_env) cg_guts liftIO $ dumpIfaceStats hsc_env -- Return the prepared code. return (new_iface, no_change, details, cg_guts) -------------------------------------------------------------- -- BackEnd combinators -------------------------------------------------------------- hscWriteIface :: ModIface -> Bool -> ModSummary -> Hsc () hscWriteIface iface no_change mod_summary = do dflags <- getDynFlags unless no_change $ {-# SCC "writeIface" #-} liftIO $ writeIfaceFile dflags (ms_location mod_summary) iface -- | Compile to hard-code. hscGenHardCode :: CgGuts -> ModSummary -> Hsc (Maybe FilePath) -- ^ @Just f@ <=> _stub.c is f hscGenHardCode cgguts mod_summary = do hsc_env <- getHscEnv liftIO $ do let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs0, cg_dep_pkgs = dependencies, cg_hpc_info = hpc_info } = cgguts dflags = hsc_dflags hsc_env platform = targetPlatform dflags location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} corePrepPgm dflags core_binds data_tycons ; ----------------- Convert to STG ------------------ (stg_binds, cost_centre_info) <- {-# SCC "CoreToStg" #-} myCoreToStg dflags this_mod prepd_binds let prof_init = profilingInitCode platform this_mod cost_centre_info foreign_stubs = foreign_stubs0 `appendStubC` prof_init ------------------ Code generation ------------------ cmms <- if dopt Opt_TryNewCodeGen dflags then {-# SCC "NewCodeGen" #-} tryNewCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info else {-# SCC "CodeGen" #-} codeGen dflags this_mod data_tycons cost_centre_info stg_binds hpc_info ------------------ Code output ----------------------- rawcmms <- {-# SCC "cmmToRawCmm" #-} cmmToRawCmm platform cmms dumpIfSet_dyn dflags Opt_D_dump_raw_cmm "Raw Cmm" (pprPlatform platform rawcmms) (_stub_h_exists, stub_c_exists) <- {-# SCC "codeOutput" #-} codeOutput dflags this_mod location foreign_stubs dependencies rawcmms return stub_c_exists hscInteractive :: (ModIface, ModDetails, CgGuts) -> ModSummary -> Hsc (InteractiveStatus, ModIface, ModDetails) #ifdef GHCI hscInteractive (iface, details, cgguts) mod_summary = do dflags <- getDynFlags let CgGuts{ -- This is the last use of the ModGuts in a compilation. -- From now on, we just use the bits we need. cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_foreign = foreign_stubs, cg_modBreaks = mod_breaks } = cgguts location = ms_location mod_summary data_tycons = filter isDataTyCon tycons -- cg_tycons includes newtypes, for the benefit of External Core, -- but we don't generate any code for newtypes ------------------- -- PREPARE FOR CODE GENERATION -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} liftIO $ corePrepPgm dflags core_binds data_tycons ; ----------------- Generate byte code ------------------ comp_bc <- liftIO $ byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks ------------------ Create f-x-dynamic C-side stuff --- (_istub_h_exists, istub_c_exists) <- liftIO $ outputForeignStubs dflags this_mod location foreign_stubs return (HscRecomp istub_c_exists (Just (comp_bc, mod_breaks)) , iface, details) #else hscInteractive _ _ = panic "GHC not compiled with interpreter" #endif ------------------------------ hscCompileCmmFile :: HscEnv -> FilePath -> IO () hscCompileCmmFile hsc_env filename = runHsc hsc_env $ do let dflags = hsc_dflags hsc_env cmm <- ioMsgMaybe $ parseCmmFile dflags filename liftIO $ do rawCmms <- cmmToRawCmm (targetPlatform dflags) [cmm] _ <- codeOutput dflags no_mod no_loc NoStubs [] rawCmms return () where no_mod = panic "hscCmmFile: no_mod" no_loc = ModLocation{ ml_hs_file = Just filename, ml_hi_file = panic "hscCmmFile: no hi file", ml_obj_file = panic "hscCmmFile: no obj file" } -------------------- Stuff for new code gen --------------------- tryNewCodeGen :: HscEnv -> Module -> [TyCon] -> CollectedCCs -> [(StgBinding,[(Id,[Id])])] -> HpcInfo -> IO [Old.CmmGroup] tryNewCodeGen hsc_env this_mod data_tycons cost_centre_info stg_binds hpc_info = do let dflags = hsc_dflags hsc_env platform = targetPlatform dflags prog <- StgCmm.codeGen dflags this_mod data_tycons cost_centre_info stg_binds hpc_info dumpIfSet_dyn dflags Opt_D_dump_cmmz "Cmm produced by new codegen" (pprCmms platform prog) -- We are building a single SRT for the entire module, so -- we must thread it through all the procedures as we cps-convert them. us <- mkSplitUniqSupply 'S' let initTopSRT = initUs_ us emptySRT (topSRT, prog) <- foldM (cmmPipeline hsc_env) (initTopSRT, []) prog let prog' = map cmmOfZgraph (srtToData topSRT : prog) dumpIfSet_dyn dflags Opt_D_dump_cmmz "Output Cmm" (pprPlatform platform prog') return prog' myCoreToStg :: DynFlags -> Module -> CoreProgram -> IO ( [(StgBinding,[(Id,[Id])])] -- output program , CollectedCCs) -- cost centre info (declared and used) myCoreToStg dflags this_mod prepd_binds = do stg_binds <- {-# SCC "Core2Stg" #-} coreToStg dflags prepd_binds (stg_binds2, cost_centre_info) <- {-# SCC "Stg2Stg" #-} stg2stg dflags this_mod stg_binds return (stg_binds2, cost_centre_info) {- ********************************************************************** %* * \subsection{Compiling a do-statement} %* * %********************************************************************* -} {- When the UnlinkedBCOExpr is linked you get an HValue of type IO [HValue] When you run it you get a list of HValues that should be the same length as the list of names; add them to the ClosureEnv. A naked expression returns a singleton Name [it]. What you type The IO [HValue] that hscStmt returns ------------- ------------------------------------ let pat = expr ==> let pat = expr in return [coerce HVal x, coerce HVal y, ...] bindings: [x,y,...] pat <- expr ==> expr >>= \ pat -> return [coerce HVal x, coerce HVal y, ...] bindings: [x,y,...] expr (of IO type) ==> expr >>= \ v -> return [v] [NB: result not printed] bindings: [it] expr (of non-IO type, result showable) ==> let v = expr in print v >> return [v] bindings: [it] expr (of non-IO type, result not showable) ==> error -} #ifdef GHCI -- | Compile a stmt all the way to an HValue, but don't run it hscStmt :: HscEnv -> String -- ^ The statement -> IO (Maybe ([Id], HValue)) -- ^ 'Nothing' <==> empty statement -- (or comment only), but no parse error hscStmt hsc_env stmt = hscStmtWithLocation hsc_env stmt "<interactive>" 1 -- | Compile a stmt all the way to an HValue, but don't run it hscStmtWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO (Maybe ([Id], HValue)) -- ^ 'Nothing' <==> empty statement -- (or comment only), but no parse error hscStmtWithLocation hsc_env stmt source linenumber = runHsc hsc_env $ do maybe_stmt <- hscParseStmtWithLocation source linenumber stmt case maybe_stmt of Nothing -> return Nothing -- The real stuff Just parsed_stmt -> do -- Rename and typecheck it let icontext = hsc_IC hsc_env (ids, tc_expr) <- ioMsgMaybe $ tcRnStmt hsc_env icontext parsed_stmt -- Desugar it let rdr_env = ic_rn_gbl_env icontext type_env = mkTypeEnvWithImplicits (ic_tythings icontext) ds_expr <- ioMsgMaybe $ deSugarExpr hsc_env iNTERACTIVE rdr_env type_env tc_expr handleWarnings -- Then code-gen, and link it let src_span = srcLocSpan interactiveSrcLoc hsc_env <- getHscEnv hval <- liftIO $ hscCompileCoreExpr hsc_env src_span ds_expr return $ Just (ids, hval) -- | Compile a decls hscDecls :: HscEnv -> String -- ^ The statement -> IO ([TyThing], InteractiveContext) hscDecls hsc_env str = hscDeclsWithLocation hsc_env str "<interactive>" 1 -- | Compile a decls hscDeclsWithLocation :: HscEnv -> String -- ^ The statement -> String -- ^ The source -> Int -- ^ Starting line -> IO ([TyThing], InteractiveContext) hscDeclsWithLocation hsc_env str source linenumber = runHsc hsc_env $ do L _ (HsModule{ hsmodDecls = decls }) <- hscParseThingWithLocation source linenumber parseModule str {- Rename and typecheck it -} let icontext = hsc_IC hsc_env tc_gblenv <- ioMsgMaybe $ tcRnDeclsi hsc_env icontext decls {- Grab the new instances -} -- We grab the whole environment because of the overlapping that may have -- been done. See the notes at the definition of InteractiveContext -- (ic_instances) for more details. let finsts = famInstEnvElts $ tcg_fam_inst_env tc_gblenv insts = instEnvElts $ tcg_inst_env tc_gblenv {- Desugar it -} -- We use a basically null location for iNTERACTIVE let iNTERACTIVELoc = ModLocation{ ml_hs_file = Nothing, ml_hi_file = undefined, ml_obj_file = undefined} ds_result <- hscDesugar' iNTERACTIVELoc tc_gblenv {- Simplify -} simpl_mg <- liftIO $ hscSimplify hsc_env ds_result {- Tidy -} (tidy_cg, _mod_details) <- liftIO $ tidyProgram hsc_env simpl_mg let dflags = hsc_dflags hsc_env !CgGuts{ cg_module = this_mod, cg_binds = core_binds, cg_tycons = tycons, cg_modBreaks = mod_breaks } = tidy_cg data_tycons = filter isDataTyCon tycons {- Prepare For Code Generation -} -- Do saturation and convert to A-normal form prepd_binds <- {-# SCC "CorePrep" #-} liftIO $ corePrepPgm dflags core_binds data_tycons {- Generate byte code -} cbc <- liftIO $ byteCodeGen dflags this_mod prepd_binds data_tycons mod_breaks let src_span = srcLocSpan interactiveSrcLoc hsc_env <- getHscEnv liftIO $ linkDecls hsc_env src_span cbc let tcs = filter (not . isImplicitTyCon) $ (mg_tcs simpl_mg) ext_vars = filter (isExternalName . idName) $ bindersOfBinds core_binds (sys_vars, user_vars) = partition is_sys_var ext_vars is_sys_var id = isDFunId id || isRecordSelector id || isJust (isClassOpId_maybe id) -- we only need to keep around the external bindings -- (as decided by TidyPgm), since those are the only ones -- that might be referenced elsewhere. tythings = map AnId user_vars ++ map ATyCon tcs let ictxt1 = extendInteractiveContext icontext tythings ictxt = ictxt1 { ic_sys_vars = sys_vars ++ ic_sys_vars ictxt1, ic_instances = (insts, finsts) } return (tythings, ictxt) hscImport :: HscEnv -> String -> IO (ImportDecl RdrName) hscImport hsc_env str = runHsc hsc_env $ do (L _ (HsModule{hsmodImports=is})) <- hscParseThing parseModule str case is of [i] -> return (unLoc i) _ -> liftIO $ throwOneError $ mkPlainErrMsg noSrcSpan $ ptext (sLit "parse error in import declaration") -- | Typecheck an expression (but don't run it) hscTcExpr :: HscEnv -> String -- ^ The expression -> IO Type hscTcExpr hsc_env expr = runHsc hsc_env $ do maybe_stmt <- hscParseStmt expr case maybe_stmt of Just (L _ (ExprStmt expr _ _ _)) -> ioMsgMaybe $ tcRnExpr hsc_env (hsc_IC hsc_env) expr _ -> throwErrors $ unitBag $ mkPlainErrMsg noSrcSpan (text "not an expression:" <+> quotes (text expr)) -- | Find the kind of a type hscKcType :: HscEnv -> Bool -- ^ Normalise the type -> String -- ^ The type as a string -> IO (Type, Kind) -- ^ Resulting type (possibly normalised) and kind hscKcType hsc_env normalise str = runHsc hsc_env $ do ty <- hscParseType str ioMsgMaybe $ tcRnType hsc_env (hsc_IC hsc_env) normalise ty hscParseStmt :: String -> Hsc (Maybe (LStmt RdrName)) hscParseStmt = hscParseThing parseStmt hscParseStmtWithLocation :: String -> Int -> String -> Hsc (Maybe (LStmt RdrName)) hscParseStmtWithLocation source linenumber stmt = hscParseThingWithLocation source linenumber parseStmt stmt hscParseType :: String -> Hsc (LHsType RdrName) hscParseType = hscParseThing parseType #endif hscParseIdentifier :: HscEnv -> String -> IO (Located RdrName) hscParseIdentifier hsc_env str = runHsc hsc_env $ hscParseThing parseIdentifier str hscParseThing :: (Outputable thing) => Lexer.P thing -> String -> Hsc thing hscParseThing = hscParseThingWithLocation "<interactive>" 1 hscParseThingWithLocation :: (Outputable thing) => String -> Int -> Lexer.P thing -> String -> Hsc thing hscParseThingWithLocation source linenumber parser str = {-# SCC "Parser" #-} do dflags <- getDynFlags liftIO $ showPass dflags "Parser" let buf = stringToStringBuffer str loc = mkRealSrcLoc (fsLit source) linenumber 1 case unP parser (mkPState dflags buf loc) of PFailed span err -> do let msg = mkPlainErrMsg span err throwErrors $ unitBag msg POk pst thing -> do logWarningsReportErrors (getMessages pst) liftIO $ dumpIfSet_dyn dflags Opt_D_dump_parsed "Parser" (ppr thing) return thing hscCompileCore :: HscEnv -> Bool -> SafeHaskellMode -> ModSummary -> CoreProgram -> IO () hscCompileCore hsc_env simplify safe_mode mod_summary binds = runHsc hsc_env $ do guts <- maybe_simplify (mkModGuts (ms_mod mod_summary) safe_mode binds) (iface, changed, _details, cgguts) <- hscNormalIface guts Nothing hscWriteIface iface changed mod_summary _ <- hscGenHardCode cgguts mod_summary return () where maybe_simplify mod_guts | simplify = hscSimplify' mod_guts | otherwise = return mod_guts -- Makes a "vanilla" ModGuts. mkModGuts :: Module -> SafeHaskellMode -> CoreProgram -> ModGuts mkModGuts mod safe binds = ModGuts { mg_module = mod, mg_boot = False, mg_exports = [], mg_deps = noDependencies, mg_dir_imps = emptyModuleEnv, mg_used_names = emptyNameSet, mg_used_th = False, mg_rdr_env = emptyGlobalRdrEnv, mg_fix_env = emptyFixityEnv, mg_tcs = [], mg_insts = [], mg_fam_insts = [], mg_rules = [], mg_vect_decls = [], mg_binds = binds, mg_foreign = NoStubs, mg_warns = NoWarnings, mg_anns = [], mg_hpc_info = emptyHpcInfo False, mg_modBreaks = emptyModBreaks, mg_vect_info = noVectInfo, mg_inst_env = emptyInstEnv, mg_fam_inst_env = emptyFamInstEnv, mg_safe_haskell = safe, mg_trust_pkg = False, mg_dependent_files = [] } {- ********************************************************************** %* * Desugar, simplify, convert to bytecode, and link an expression %* * %********************************************************************* -} #ifdef GHCI hscCompileCoreExpr :: HscEnv -> SrcSpan -> CoreExpr -> IO HValue hscCompileCoreExpr hsc_env srcspan ds_expr | rtsIsProfiled = throwIO (InstallationError "You can't call hscCompileCoreExpr in a profiled compiler") -- Otherwise you get a seg-fault when you run it | otherwise = do let dflags = hsc_dflags hsc_env let lint_on = dopt Opt_DoCoreLinting dflags {- Simplify it -} simpl_expr <- simplifyExpr dflags ds_expr {- Tidy it (temporary, until coreSat does cloning) -} let tidy_expr = tidyExpr emptyTidyEnv simpl_expr {- Prepare for codegen -} prepd_expr <- corePrepExpr dflags tidy_expr {- Lint if necessary -} -- ToDo: improve SrcLoc when lint_on $ let ictxt = hsc_IC hsc_env te = mkTypeEnvWithImplicits (ic_tythings ictxt ++ map AnId (ic_sys_vars ictxt)) tyvars = varSetElems $ tyThingsTyVars $ typeEnvElts $ te vars = typeEnvIds te in case lintUnfolding noSrcLoc (tyvars ++ vars) prepd_expr of Just err -> pprPanic "hscCompileCoreExpr" err Nothing -> return () {- Convert to BCOs -} bcos <- coreExprToBCOs dflags iNTERACTIVE prepd_expr {- link it -} hval <- linkExpr hsc_env srcspan bcos return hval #endif {- ********************************************************************** %* * Statistics on reading interfaces %* * %********************************************************************* -} dumpIfaceStats :: HscEnv -> IO () dumpIfaceStats hsc_env = do eps <- readIORef (hsc_EPS hsc_env) dumpIfSet (dump_if_trace || dump_rn_stats) "Interface statistics" (ifaceStats eps) where dflags = hsc_dflags hsc_env dump_rn_stats = dopt Opt_D_dump_rn_stats dflags dump_if_trace = dopt Opt_D_dump_if_trace dflags {- ********************************************************************** %* * Progress Messages: Module i of n %* * %********************************************************************* -} showModuleIndex :: Maybe (Int, Int) -> String showModuleIndex Nothing = "" showModuleIndex (Just (i,n)) = "[" ++ padded ++ " of " ++ n_str ++ "] " where n_str = show n i_str = show i padded = replicate (length n_str - length i_str) ' ' ++ i_str
ilyasergey/GHC-XAppFix
compiler/main/HscMain.hs
bsd-3-clause
67,236
0
27
19,553
11,579
5,967
5,612
-1
-1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Data.Tree.Diff where import Control.Monad.State import Data.Bifunctor import Data.List as L import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import Data.Monoid import Data.Vector (Vector) import qualified Data.Vector as V import Data.Tree -- * Flattened Trees -- $ The algorithm assigns a number to each node in the tree in -- left-to-right post-order traversal and uses these to select -- sub-forests as the sub-problems. Throughout what follows we'll call -- this number the /index/. newtype Idx = Idx { fromIdx :: Int } deriving (Eq, Ord, Num, Enum) instance Show Idx where show = show . fromIdx instance Read Idx where readsPrec i = map (first Idx) . filter (\(a,r) -> a >= 0) . readsPrec i data FNode l = N { label :: l , index :: Idx , leftMostChild :: Idx , parent :: Idx } deriving (Show) -- | An array stored ascending by index. -- -- The root of the tree is the last node. newtype Flattened l = F (Vector (FNode l)) deriving (Show) -- | Find the root node root :: Flattened l -> FNode l root (F v) = V.last v -- | Find the span of the sub-tree rooted at a node. tree :: Flattened l -> Idx -> (Idx, Idx) tree t id = (leftMostChild $ t `node` id, id) -- | We'll flatten the tree in a left-right post-order traversal. flattenTree :: Tree l -> Flattened l flattenTree tree = let flat = flip evalState 0 . fmap fst . go $ tree root = V.last flat root' = root{parent = index root} in F $ V.init flat `V.snoc` root' where go :: Tree l -> State Idx (Vector (FNode l), Idx) go (Node l (Forest cs)) = do cs' <- V.mapM go cs next <- state (\next -> (next, next + 1)) let left = maybe next snd $ cs' V.!? 0 return (V.concatMap (fixup next) cs' `V.snoc` N l next left (-1), left) -- I should probably figure out how to tie this knot correctly. fixup :: Idx -> (Vector (FNode l), Idx) -> Vector (FNode l) fixup p = V.map (\n -> if parent n < 0 then n{parent = p} else n) . fst -- | We access the elements of a flattened tree safely. -- -- If we ever get a Nothing: 1) our program is wrong, 2) the answer -- will be wrong, 3) screw you guys, I'm going home. node :: Flattened l -> Idx -> FNode l node (F v) (Idx n) = fromMaybe (error $ "Cannot get node " <> show n <> " from tree with " <> show (V.length v) <> " nodes") (v V.!? n) -- | The key to this algorithm (and the newer better algorithms in the -- same class) is in identifying the subset of sub-trees in that we -- must process. This allows us to prune the search space considerably. -- -- keyRoots(T) := { k | there is k' > k such that l(k) = l(k') } -- -- i.e. k is either the root of T or it has a left-sibling (i.e. it's -- own left-most child is different from it's parent's). keyRoots :: Flattened l -> [Idx] keyRoots tree@(F v) = map index . filter isKeyroot . V.toList $ v where isKeyroot :: FNode l -> Bool isKeyroot n = isRoot n || isKey n isRoot :: FNode l -> Bool isRoot node = index node == (index . root $ tree) isKey :: FNode l -> Bool isKey k = let lk = leftMostChild k lpk = leftMostChild (tree `node` parent k) in lk /= lpk -- * Tree Distance -- $ The algorithm proceeds by building a series of tableaux of -- solutions to two types of sub-problems: -- -- 1. a tableaux of sub-tree vs sub-tree distances; and -- -- 2. a series of tableaux of sub-forest vs sub-forest distances. -- -- | The edit operations. -- -- These could be enhanced with a path to produce not just an optimal -- edit distance but also a diff. data Op l = Ins l | Del l | Rep l l -- | We evaluate the cost of an operation. -- -- We assign equal costs to each operation and we don't use the labels -- in determining the cost of an operation. It would be entirely -- sensible for us to use the label information cost :: Eq l => Op l -> Int cost (Ins _) = 1 cost (Del _) = 1 cost (Rep f t) | f == t = 0 | otherwise = 1 treeDist in1 in2 = let t1 = flattenTree in1 t2 = flattenTree in2 kr1 = keyRoots t1 kr2 = keyRoots t2 -- | We'll describe the sub-problems to be evaluated from each -- pair of key roots. We can calculate these descriptions easily -- but we'll need to normalise them to have a single -- representation of the "empty" span. dep (l@(li, i), r@(lj, j), c) = let l' = if i < li then (li, -1) else l r' = if j < lj then (lj, -1) else r in (l', r', c) -- Solve a forest vs forest sub-problem. trees prev (i, j) = let li = leftMostChild $ t1 `node` i lj = leftMostChild $ t2 `node` j zeros = [ ((li, -1), (lj, -1), []) ] deletes = [ ((li, m), (lj, -1), [ dep ((li, m-1), (lj, -1), cost (Del v1)) ]) | m <- [ li .. i ] , let v1 = label (t1 `node` m) ] inserts = [ ((li, -1), (lj, n), [ dep ((li, -1), (lj, n-1), cost (Ins v2)) ]) | n <- [ lj .. j ] , let v2 = label (t2 `node` n) ] changes = [ ((li, m), (lj, n), if leftIsAWholeTree && rightIsAWholeTree then [ dep ((li, m-1), (lj, n ), cost (Del v1)), dep ((li, m ), (lj, n-1), cost (Ins v2)), dep ((li, m-1), (lj, n-1), cost (Rep v1 v2)) ] else [ dep ((li, m-1 ), (lj, n ), cost (Del v1)), dep ((li, m ), (lj, n-1 ), cost (Ins v2)), dep ((li, li1-1), (lj, lj1-1), treedist prev m n) ] ) | m <- [ li .. i ] , n <- [ lj .. j ] , let li1 = leftMostChild (t1 `node` m) lj1 = leftMostChild (t2 `node` n) leftIsAWholeTree = li1 == li rightIsAWholeTree = lj1 == lj v1 = label (t1 `node` m) v2 = label (t2 `node` n) ] in foldl (forests i j) prev $ zeros <> deletes <> inserts <> changes treedist prev i1 j1 = let key = (tree t1 i1, tree t2 j1) in fromMaybe (error $ "Cannot find previous subtree: " <> show key) (M.lookup key prev) forests i j prev subproblem@((li, i1), (lj, j1), cs) | i1 == -1 && j1 == -1 = M.insert ((li, -1), (lj, -1)) 0 prev | L.null cs = error $ "Expected to compute minimum but not children given: " <> show subproblem | otherwise = let f (from, to, c') = case M.lookup (from, to) prev of Just c -> c + c' Nothing -> error $ "Missing subproblem: " <> show (from, to) in M.insert ((li, i1), (lj, j1)) (minimum $ map f cs) prev -- The forest vs forest sub-problems. ftabs = [ (r1, r2) | r1 <- kr1, r2 <- kr2 ] in foldl trees mempty ftabs n :: l -> [Tree l] -> Tree l n l cs = Node l (Forest $ V.fromList cs) t1 = n 'f' [ n 'd' [ n 'a' [] , n 'c' [ n 'b' [] ] ] , n 'e' [] ] t2 = n 'f' [ n 'c' [ n 'd' [ n 'a' [] , n 'b' [] ] ] , n 'e' [] ]
thsutton/arborism
lib/Data/Tree/Diff.hs
bsd-3-clause
7,797
0
21
2,895
2,504
1,375
1,129
140
5
module Board (Board, Point, buildB, putB, getB) where import Tile (Tile(..)) type Point = (Int, Int) type Board = [(Point, Char)] buildB :: [String] -> Board buildB lns = buildAccB lns 0 buildAccB :: [String] -> Int -> Board buildAccB [] _ = [] buildAccB (ln:lns) row = foldr step [] ln ++ buildAccB lns (row + 1) where step c acc = ((row, col acc), c) : acc col acc = length ln - length acc - 1 putB :: Point -> Char -> Board -> Board putB findpt newc bd = foldr step [] bd where step (pt, oldc) acc | pt == findpt = (pt, newc) : acc | otherwise = (pt, oldc) : acc getB :: Point -> Board -> Maybe Char getB findpt bd = lookup findpt bd tilB :: Point -> Board -> Tile tilB findpt bd = read $ case getB findpt bd of Nothing -> show OutBounds Just a -> [a]
eamsden/icfp-contest-14
code/simulation/Board.hs
bsd-3-clause
925
0
10
329
393
209
184
21
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Text.Md.MdParser ( readMd , writeMd , parseMd , parseMdFormat , parseMdWith , parseMdFile , parseMdFileFormat , parseMdFileWith ) where import Control.Monad import qualified Data.Map as M import Data.Maybe (fromMaybe) import Debug.Trace import System.IO import qualified Text.HTML.TagSoup as TS import Text.Md.HtmlParser import Text.Md.HtmlTags import Text.Md.MdParserDef import Text.Md.ParseUtils import Text.Parsec (Parsec, ParsecT, Stream, (<?>), (<|>)) import qualified Text.Parsec as P import qualified Text.ParserCombinators.Parsec as P hiding (runParser, try) instance ReadMarkDown Document where parser = do blocks <- P.manyTill parser P.eof meta <- metadata <$> P.getState return $ Document blocks meta {- Block elements -} instance ReadMarkDown Block where parser = P.choice [ pHeader , pHtmlBlock , pHorizontalRule , pListBlock , pReference , pCodeBlock , pBlockQuote , pParagraph ] <?> "block" -- | Parse newlines between blocks. Expect more than one newlines. blanklineBetweenBlock = blankline *> P.many (P.try blankline) -- | Parse newlines between blocks. Expect more than two newlines. blanklinesBetweenBlock = blankline *> blankline *> P.many (P.try blankline) ----- Header ----- -- | Parse a header. -- Accept only the 'Atx' form without closing hashes, not the 'Setext' form. pHeader = P.try $ do level <- length <$> P.many1 (P.char '#') skipSpaces inlines <- P.many1 (P.notFollowedBy blanklines >> parser) blanklinesBetweenBlock return $ Header level inlines ----- Header ----- ----- Html Block ----- -- | Parse a html block. Text inside html tags are escaped, but markdown literals are not processed. pHtmlBlock = P.try $ do let htmlParseContext = HtmlParseContext pStrWithHtmlEscape pBlockElement htmlParseContext <* skipSpaces <* blanklinesBetweenBlock ----- Html Block ----- ----- Horizontal rule ----- -- | Parse a horizontal rule. Accept three kinds of symbols ('-', '*', and '_'). pHorizontalRule = P.try $ P.choice [pBorder '-', pBorder '*', pBorder '_'] pBorder char = P.try $ do chars <- P.many1 (P.char char <* skipSpaces) blanklinesBetweenBlock guard $ length chars >= 3 return HorizontalRule ----- Horizontal rule ----- ----- List ----- -- | Parse a list. Three kinds of symbols ('-', '*', and '+') can be handled as items of unordered lists. -- List items can be converted to paragraphs if each one is separated by blanklines. -- An item can consist of multiple paragraphs. pListBlock = P.try $ P.choice [pList '-', pList '*', pList '+'] pListIndent = P.try (P.count 4 (P.char ' ')) <|> P.string "\t" insertL 0 val node@(ListLineItem l v cs) = ListLineItem l v (cs ++ [ ListLineItem (l+1) val [] ]) insertL level val node@(ListLineItem l v cs) = ListLineItem l v newCs where (formers, lastC) = splitAt (length cs - 1) cs newCs = formers ++ fmap (insertL (level-1) val) lastC insertP 0 val node@(ListParaItem l v cs) = ListParaItem l v (cs ++ [ ListParaItem (l+1) val [] ]) insertP level val node@(ListParaItem l v cs) = ListParaItem l v newCs where (formers, lastC) = splitAt (length cs - 1) cs newCs = formers ++ fmap (insertP (level-1) val) lastC toListL items = foldl summarize (ListLineItem 0 [NullL] []) items where summarize node (ListLineItem l v cs) = insertL (l-1) v node toListP items = foldl summarize (ListParaItem 0 [NullB] []) items where summarize node (ListParaItem l v cs) = insertP (l-1) v node -- TODO: summarize L and P pList char = P.try $ do let pItem = P.try (pListLineItem char <* P.notFollowedBy (P.try (blankline *> P.string [char]) <|> (blankline *> P.many1 spaceChar))) <|> pListParaItem char firstItem <- pItem case firstItem of ListLineItem {} -> do items <- P.many (pListLineItem char) P.optional blanklines return $ List (toListL (firstItem:items)) ListParaItem {} -> do items <- P.many (pListParaItem char) P.optional blanklines return $ List (toListP (firstItem:items)) pListLineItem char = P.try $ do indents <- P.many pListIndent P.char char spaceSep <- P.many1 (P.char ' ') guard $ length spaceSep <= 3 inlines <- P.many1 (P.notFollowedBy (blankline *> P.optional (P.many pListIndent) *> P.char char) >> parser) blankline return $ ListLineItem (length indents + 1) inlines [] pListParaItem char = P.try $ do indents <- P.many pListIndent P.char char spaceSep <- P.many1 (P.char ' ') guard $ length spaceSep <= 3 let pIndent = P.count (length indents) pListIndent pSpaceSep = P.count (length spaceSep + 1) (P.char ' ') firstContent <- pParagraph followingContent <- P.many (P.notFollowedBy (P.many pListIndent *> P.char char) *> pIndent *> pSpaceSep *> P.notFollowedBy (P.char char) *> pParagraph) return $ ListParaItem (length indents + 1) (firstContent : followingContent) [] ----- List ----- ----- Reference ----- addRef (refId, refLink, refTitle) state = state { metadata = newMeta } where oldMeta = metadata state newMeta = oldMeta { references = newRefs } originalRefs = references . metadata $ state newRefs = M.insert refId (refLink, refTitle) originalRefs -- | Parse a pair or label and link for reference links. pReference = P.try $ do let pOneRef = do refId <- pEnclosed "[" "]" P.char ':' skipSpaces refLink <- P.many1 (P.notFollowedBy (spaceChar <|> blankline) >> P.anyChar) refTitle <- P.optionMaybe $ skipSpaces *> pEnclosed "\"" "\"" blankline return (refId, refLink, refTitle) refs <- P.many1 pOneRef blanklineBetweenBlock mapM_ (P.updateState . addRef) refs return NullB ----- Reference ----- ----- Code block ----- -- | Parse a code block. Escape any '<', '>', '"', '&' characters inside blocks. pCodeBlock = P.try $ do P.string "```" >> newlineQuote xs <- P.many (P.notFollowedBy (newlineQuote >> P.string "```") >> pStrWithHtmlEscapeForce) newlineQuote >> P.string "```" blanklinesBetweenBlock return $ CodeBlock xs ----- Code block ----- ----- Block quote ----- -- | Parse a blockquote. Blockquotes can contain other kinds of blocks including blockquotes. pBlockQuote = P.try $ do let plusQuoteLevel context = context { quoteLevel = quoteLevel context + 1 } minusQuoteLevel context = context { quoteLevel = quoteLevel context - 1 } let updateLineStart c context = context { lineStart = c } let pFollowingBlock = do b <- isLastNewLineQuoted <$> P.getState guard b parser P.char '>' >> skipSpaces originalChar <- lineStart <$> P.getState P.modifyState plusQuoteLevel P.modifyState (updateLineStart '>') firstBlock <- parser followingBlocks <- P.many pFollowingBlock P.modifyState minusQuoteLevel P.modifyState (updateLineStart originalChar) level <- quoteLevel <$> P.getState when (level > 0) (P.modifyState (\context -> context { isLastNewLineQuoted = True })) return $ BlockQuote (firstBlock : followingBlocks) ----- Block quote ----- ----- Paragraph ----- -- | Parse a paragraph. -- All blocks which are not parsed as other kinds of blocks will be handled as paragraphs. pParagraph = P.try $ do inlines <- P.many1 parser blanklinesBetweenBlock return $ Paragraph inlines ----- Paragraph ----- {- Inline elements -} instance ReadMarkDown Inline where parser = P.choice [ pLineBreak , pSoftBreak , pSpace , pStrong , pEmphasis , pInlineLink , pInlineCode , pInlineHtml , pReferenceLink , pStr , pHtmlEscape , pMark ] <?> "inline" ----- Line break ----- -- | Parse more than two spaces at the end of line. pLineBreak = P.try $ do P.count 2 (P.char ' ') >> blankline return LineBreak ----- Line break ----- ----- Soft break ----- -- | Parse soft break('\n') pSoftBreak = P.try $ do blankline >> skipSpaces >> P.notFollowedBy P.newline return SoftBreak ----- Soft break ----- ----- Space ----- -- | Parse more than one spaces and treats as only one space. pSpace = P.try $ do spaceChar >> skipSpaces return Space ----- Space ----- ----- Strong and emphasis ----- -- | Parse a strong framed by two '*' or '_'. pStrong = P.try (P.choice [parserStrong "**", parserStrong "__"]) where parserStrong s = Strong <$> pEnclosedInline s s -- | Parse a emphasis framed by one '*' or '_'. pEmphasis = P.try (P.choice [parserEmphasis "*", parserEmphasis "_"]) where parserEmphasis s = Emphasis <$> pEnclosedInline s s ----- Strong and emphasis ----- ----- Link ----- -- | Parse a inline link such as '[foo](https://foobar.com "foo")'. pInlineLink = P.try $ do let pText = P.many1 (P.notFollowedBy (P.char ']') >> P.anyChar) pLinkAndTitle = do text <- P.many1 (P.notFollowedBy (P.oneOf " )") >> P.anyChar) skipSpaces title <- P.optionMaybe $ P.char '"' *> P.many (P.notFollowedBy (P.char '"') >> P.anyChar) <* P.char '"' return (text, title) text <- P.between (P.char '[') (P.char ']') pText (link, title) <- P.between (P.char '(') (P.char ')') pLinkAndTitle return $ InlineLink text link title -- | Parse a reference link such as '[foo][1]'. -- There must be a corresponding link with the label anywhere in the document. pReferenceLink = P.try $ do text <- pEnclosed "[" "]" P.optional spaceChar refId <- pEnclosed "[" "]" return $ ReferenceLink text refId pEnclosed begin end = pEnclosedP begin end pNones where pNones = P.noneOf (begin ++ end) pEnclosedInline begin end = pEnclosedP begin end parser pEnclosedP begin end parser = do P.string begin ps <- P.many1 (P.notFollowedBy (P.string end) >> parser) P.string end return ps ----- Link ----- ----- Str ----- -- | Parse a string consisting of any alphabets and digits. pStr = P.try $ do str <- P.many1 P.alphaNum return $ Str str -- FIXME: Summarize `pStrWithHtmlEscape` and `pStrWithHtmlEscapeForce` -- | Parse a string. Accept any marks as well as alphanums and perform html-escaping. pStrWithHtmlEscape = P.try pHtmlEscape <|> P.try pStr <|> P.try pNewlineQuote <|> pSingleStr where pNewlineQuote = newlineQuote >>= (\x -> return $ Str [x]) pSingleStr = P.anyChar >>= (\x -> return $ Str [x]) -- | Parse a string. Accept any marks as well as alphanums and perform html-escaping. pStrWithHtmlEscapeForce = P.try pHtmlEscapeForce <|> P.try pStr <|> P.try pNewlineQuote <|> pSingleStr where pNewlineQuote = newlineQuote >>= (\x -> return $ Str [x]) pSingleStr = P.anyChar >>= (\x -> return $ Str [x]) ----- Str ----- ----- Inline code ----- -- | Parse a inline code. pInlineCode = P.try $ do start <- P.many1 $ P.try (P.char '`') codes <- P.manyTill pStrWithHtmlEscapeForce (P.try (P.string start)) return $ InlineCode codes ----- Inline code ----- ----- Inline html ----- -- | Parse inline html. Inline markdown literals and html escaping are active. pInlineHtml = P.try $ do let context = HtmlParseContext parser :: HtmlParseContext Inline pInlineElement context ----- Inline html ----- ----- Str with marks ----- -- | Parse a mark. Escape markdown literals if necssary. pMark = P.try $ do P.notFollowedBy $ P.choice [spaceChar, blankline] let toStr = flip (:) [] str <- toStr <$> P.try (P.char '\\' *> P.oneOf mdSymbols) <|> toStr <$> P.anyChar return $ Str str mdSymbols = ['\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '#', '+', '-', '.', '!'] ----- Str with marks ----- {- Implementation of WriteMd -} instance WriteMarkDown Document where writeMarkDown (Document blocks meta) _ = case doesFormatHtml meta of True -> hDiv True $ concatMapMdFormat meta blocksNoNull False -> hDiv False $ concatMapMd meta blocksNoNull where blocksNoNull = filter (NullB /=) blocks instance WriteMarkDown Block where writeMarkDown (Header level inlines) meta = hHead level $ concatMapMd meta inlines writeMarkDown (BlockHtml inlines) meta = concatMapMd meta inlines writeMarkDown (List item@(ListLineItem {})) meta = toStrL item where toStrL node = toLinesL node toLinesL node@(ListLineItem 0 _ cs) = "<ul>" ++ concatMap toLinesL cs ++ "</ul>" toLinesL node@(ListLineItem l v []) = "<li>" ++ toLineL node ++ "</li>" toLinesL node@(ListLineItem l v cs) = "<li>" ++ toLineL node ++ "<ul>" ++ concatMap toLinesL cs ++ "</ul>" ++ "</li>" toLineL node@(ListLineItem l v cs) = concatMapMd meta v writeMarkDown (List item@(ListParaItem {})) meta = toStrP item where toStrP node = toLinesP node toLinesP node@(ListParaItem 0 _ cs) = "<ul>" ++ concatMap toLinesP cs ++ "</ul>" toLinesP node@(ListParaItem l v []) = "<li>" ++ toLineP node ++ "</li>" toLinesP node@(ListParaItem l v cs) = "<li>" ++ toLineP node ++ "<ul>" ++ concatMap toLinesP cs ++ "</ul>" ++ "</li>" toLineP node@(ListParaItem l v cs) = concatMapMd meta v writeMarkDown HorizontalRule meta = hBorder writeMarkDown (CodeBlock inlines) meta = hCodeBlock $ concatMapMd meta inlines writeMarkDown (BlockQuote blocks) meta = hQuote $ concatMapMd meta blocks writeMarkDown (Paragraph inlines) meta = hParagraph $ concatMapMd meta inlines writeMarkDown NullB meta = "" instance WriteMarkDown Inline where writeMarkDown LineBreak meta = hLineBreak writeMarkDown SoftBreak meta = " " writeMarkDown Space meta = " " writeMarkDown (Strong inlines) meta = hStrong $ concatMapMd meta inlines writeMarkDown (Emphasis inlines) meta = hEmphasis $ concatMapMd meta inlines writeMarkDown (ReferenceLink text linkId) meta = case M.lookup linkId (references meta) of Just (link, title) -> hLink text link title Nothing -> hLink text "" Nothing writeMarkDown (InlineLink text link title) meta = hLink text link title writeMarkDown (InlineCode inlines) meta = hCode $ trim $ concatMapMd meta inlines writeMarkDown (InlineHtml inlines) meta = concatMapMd meta inlines writeMarkDown (Str str) meta = str writeMarkDown NullL meta = "" concatMapMd meta wms = concatMap (`writeMarkDown` meta) wms concatMapMdFormat meta [] = [] concatMapMdFormat meta [w] = writeMarkDown w meta concatMapMdFormat meta (w:ws) = writeMarkDown w meta ++ "\n" ++ concatMapMdFormat meta ws {- functions to handle conversion of markdown -} -- | Convert markdown to document. readMd :: ParseContext -> String -> Document readMd context md = case P.runParser parser context "" (md ++ "\n\n") of -- dirty way to parse... Left e -> error (show e) Right s -> s -- | Convert document to html. writeMd :: Document -> String writeMd doc@(Document _ meta) = writeMarkDown doc meta -- | Parse and convert markdown to html. parseMd :: String -> String parseMd = writeMd . readMd defContext -- | Parse and convert markdown to formatted html. parseMdFormat :: String -> String parseMdFormat md = writeMd $ readMd context md where context = defContext { metadata = defMetaData { doesFormatHtml = True } } -- | Parse and convert markdown to html with the passed context. parseMdWith :: ParseContext -> String -> String parseMdWith context md = writeMd $ readMd context md -- | Parse and convert markdown to html. Accept a path to the markdown file. parseMdFile :: FilePath -> IO String parseMdFile path = do content <- readFile path return $ parseMd content -- | Parse and convert markdown to formatted html. Accept a path to the markdown file. parseMdFileFormat :: FilePath -> IO String parseMdFileFormat path = do content <- readFile path let context = defContext { metadata = defMetaData { doesFormatHtml = True } } return $ writeMd $ readMd context content -- | Parse and convert markdown to html with the passed context. Accept a path to the markdown file parseMdFileWith :: ParseContext -> FilePath -> IO String parseMdFileWith context path = do content <- readFile path return $ writeMd $ readMd context content
tiqwab/md-parser
src/Text/Md/MdParser.hs
bsd-3-clause
17,434
0
22
4,678
4,789
2,402
2,387
285
2
-- | Core module for Haskoop Configurations module Haskoop.Configuration where import Haskoop.Configuration.Types import Control.Monad(liftM) import Control.Monad.State -- | A Configuration is a State Monad type Configuration a = State JobConfiguration a -- | Getter and Setters for the State getInputs :: Configuration [String] getInputs = get >>= liftM input
jejansse/Haskoop
src/Haskoop/Configuration/Configuration.hs
bsd-3-clause
364
0
6
52
66
40
26
7
1
module System.Build.Access.Subpackages where class Subpackages r where subpackages :: [String] -> r -> r getSubpackages :: r -> [String]
tonymorris/lastik
System/Build/Access/Subpackages.hs
bsd-3-clause
167
0
8
49
45
26
19
9
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExtendedDefaultRules #-} module Lucid.Foundation.Navigation.Breadcrumbs where import Lucid.Base import Lucid.Html5 import qualified Data.Text as T import Data.Monoid breadcrumbs_ :: T.Text breadcrumbs_ = " breadcrumbs " unavailable_ :: T.Text unavailable_ = " unavailable " current_ :: T.Text current_ = " current "
athanclark/lucid-foundation
src/Lucid/Foundation/Navigation/Breadcrumbs.hs
bsd-3-clause
371
0
5
53
69
44
25
13
1
module Database.Algebra.Dag ( -- * The DAG data structure AlgebraDag , Operator(..) , dmap , nodeMap , rootNodes , refCountMap , mkDag , emptyDag , addRootNodes -- * Query functions for topological and operator information , parents -- FIXME is topological sorting still necessary? , topsort , hasPath , reachable , reachableNodesFrom , operator -- * DAG modification functions , insert , insertNoShare , replaceChild , replaceRoot , collect ) where import Control.Exception.Base import Data.Aeson import qualified Data.Graph.Inductive.Graph as G import Data.Graph.Inductive.PatriciaTree import qualified Data.Graph.Inductive.Query.DFS as DFS import qualified Data.IntMap as IM import qualified Data.List as L import qualified Data.Map as M import qualified Data.Set as S import Database.Algebra.Dag.Common data AlgebraDag a = AlgebraDag { nodeMap :: NodeMap a -- ^ Return the nodemap of a DAG , opMap :: M.Map a AlgNode -- ^ reverse index from operators to nodeids , nextNodeID :: AlgNode -- ^ the next node id to be used when inserting a node , graph :: UGr -- ^ Auxilliary representation for topological information , rootNodes :: [AlgNode] -- ^ Return the (possibly modified) list of root nodes from a DAG , refCountMap :: NodeMap Int -- ^ A map storing the number of parents for each node. } -- | Map a function over the DAG algebra operators. dmap :: Ord b => (a -> b) -> AlgebraDag a -> AlgebraDag b dmap f d = d { nodeMap = fmap f (nodeMap d) , opMap = M.mapKeys f (opMap d) } instance ToJSON a => ToJSON (AlgebraDag a) where toJSON dag = toJSON (nodeMap dag, rootNodes dag) instance (FromJSON a, Operator a) => FromJSON (AlgebraDag a) where parseJSON v = do (nm, rs) <- parseJSON v return $ mkDag nm rs -- For every node, count the number of parents (or list of edges to the node). -- We don't consider the graph a multi-graph, so an edge (u, v) is only counted -- once. initRefCount :: Operator o => [AlgNode] -> NodeMap o -> NodeMap Int initRefCount rs nm = addRoots $ IM.foldr' insertEdge IM.empty nm where insertEdge op rm = L.foldl' incParents rm (L.nub $ opChildren op) incParents rm n = IM.insert n ((IM.findWithDefault 0 n rm) + 1) rm addRoots rm = L.foldl' (\rm' r -> IM.insertWith (\_ o -> o) r 0 rm') rm rs initOpMap :: Ord o => NodeMap o -> M.Map o AlgNode initOpMap nm = IM.foldrWithKey (\n o om -> M.insert o n om) M.empty nm -- | Create a DAG from a node map of algebra operators and a list of -- root nodes. Nodes which are not reachable from the root nodes -- provided will be pruned! mkDag :: Operator a => NodeMap a -> [AlgNode] -> AlgebraDag a mkDag m rs = AlgebraDag { nodeMap = mNormalized , graph = g , rootNodes = rs , refCountMap = initRefCount rs mNormalized , opMap = initOpMap mNormalized , nextNodeID = 1 + (fst $ IM.findMax mNormalized) } where mNormalized = normalizeMap rs m g = uncurry G.mkUGraph $ IM.foldrWithKey aux ([], []) mNormalized aux n op (allNodes, allEdges) = (n : allNodes, es ++ allEdges) where es = map (\v -> (n, v)) $ opChildren op -- | Construct an empty DAG with no root nodes. Beware: before any -- collections are performed, root nodes must be added. Otherwise, all -- nodes will be considered unreachable. emptyDag :: AlgebraDag a emptyDag = AlgebraDag { nodeMap = IM.empty , opMap = M.empty , nextNodeID = 1 , graph = G.mkUGraph [] [] , rootNodes = [] , refCountMap = IM.empty } -- | Add a list of root nodes to a DAG, all of which must be present -- in the DAG. The node map is normalized by removing all nodes which -- are not reachable from the root nodes. -- FIXME re-use graph, opmap etc, only remove pruned nodes. addRootNodes :: Operator a => AlgebraDag a -> [AlgNode] -> AlgebraDag a addRootNodes d rs = assert (all (\n -> IM.member n $ nodeMap d) rs) $ d { rootNodes = rs , nodeMap = mNormalized , refCountMap = initRefCount rs mNormalized , opMap = initOpMap mNormalized , graph = uncurry G.mkUGraph $ IM.foldrWithKey aux ([], []) mNormalized } where mNormalized = normalizeMap rs (nodeMap d) aux n op (allNodes, allEdges) = (n : allNodes, es ++ allEdges) where es = map (\v -> (n, v)) $ opChildren op reachable :: Operator a => NodeMap a -> [AlgNode] -> S.Set AlgNode reachable m rs = L.foldl' traverseDag S.empty rs where traverseDag :: S.Set AlgNode -> AlgNode -> S.Set AlgNode traverseDag s n = if S.member n s then s else L.foldl' traverseDag (S.insert n s) (opChildren $ lookupOp n) lookupOp n = case IM.lookup n m of Just op -> op Nothing -> error $ "node not present in map: " ++ (show n) normalizeMap :: Operator a => [AlgNode] -> NodeMap a -> NodeMap a normalizeMap rs m = let reachableNodes = reachable m rs in IM.filterWithKey (\n _ -> S.member n reachableNodes) m -- Utility functions to maintain the reference counter map and eliminate no -- longer referenced nodes. lookupRefCount :: AlgNode -> AlgebraDag a -> Int lookupRefCount n d = case IM.lookup n (refCountMap d) of Just c -> c Nothing -> error $ "no refcount value for node " ++ (show n) decrRefCount :: AlgebraDag a -> AlgNode -> AlgebraDag a decrRefCount d n = let refCount = lookupRefCount n d refCount' = assert (refCount /= 0) $ refCount - 1 in d { refCountMap = IM.insert n refCount' (refCountMap d) } -- | Delete a node from the node map and the aux graph -- Beware: this leaves the DAG in an inconsistent state, because -- reference counters have to be updated. delete' :: Operator a => AlgNode -> AlgebraDag a -> AlgebraDag a delete' n d = let op = operator n d g' = G.delNode n $ graph d m' = IM.delete n $ nodeMap d rc' = IM.delete n $ refCountMap d opMap' = case M.lookup op $ opMap d of Just n' | n == n' -> M.delete op $ opMap d _ -> opMap d in d { nodeMap = m', graph = g', refCountMap = rc', opMap = opMap' } refCountSafe :: AlgNode -> AlgebraDag o -> Maybe Int refCountSafe n d = IM.lookup n $ refCountMap d collect :: Operator o => S.Set AlgNode -> AlgebraDag o -> AlgebraDag o collect collectNodes d = S.foldl' tryCollectNode d collectNodes where tryCollectNode :: Operator o => AlgebraDag o -> AlgNode -> AlgebraDag o tryCollectNode di n = case refCountSafe n di of -- node is unreferenced -> collect it Just rc | rc == 0 && n `notElem` (rootNodes di) -> let cs = L.nub $ opChildren $ operator n di d' = delete' n di in L.foldl' cutEdge d' cs | otherwise -> di Nothing -> error $ "Dag.collect: no reference counting entry for node " ++ show n -- Cut an edge to a node reference counting wise. -- If the ref count becomes zero, the node is deleted and the children are -- traversed. cutEdge :: Operator a => AlgebraDag a -> AlgNode -> AlgebraDag a cutEdge d edgeTarget = let d' = decrRefCount d edgeTarget newRefCount = lookupRefCount edgeTarget d' in if newRefCount == 0 && edgeTarget `notElem` rootNodes d then let cs = L.nub $ opChildren $ operator edgeTarget d' d'' = delete' edgeTarget d' in L.foldl' cutEdge d'' cs else d' addRefTo :: AlgebraDag a -> AlgNode -> AlgebraDag a addRefTo d n = let refCount = lookupRefCount n d in d { refCountMap = IM.insert n (refCount + 1) (refCountMap d) } -- | Replace an entry in the list of root nodes with a new node. The root node -- must be present in the DAG. replaceRoot :: AlgebraDag a -> AlgNode -> AlgNode -> AlgebraDag a replaceRoot d old new = let rs' = map doReplace $ rootNodes d doReplace r = if r == old then new else r in d { rootNodes = rs' } -- | Insert a new node into the DAG. insert :: Operator a => a -> AlgebraDag a -> (AlgNode, AlgebraDag a) insert op d = -- check if an equivalent operator is already present case M.lookup op $ opMap d of Just n -> (n, d) -- no operator can be reused, insert a new one Nothing -> insertNoShare op d -- | Insert an operator without checking if an equivalent operator is -- already present. insertNoShare :: Operator a => a -> AlgebraDag a -> (AlgNode, AlgebraDag a) insertNoShare op d = let cs = L.nub $ opChildren op n = nextNodeID d g' = G.insEdges (map (\c -> (n, c, ())) cs) $ G.insNode (n, ()) $ graph d m' = IM.insert n op $ nodeMap d rc' = IM.insert n 0 $ refCountMap d opMap' = M.insert op n $ opMap d d' = d { nodeMap = m' , graph = g' , refCountMap = rc' , opMap = opMap' , nextNodeID = n + 1 } in (n, L.foldl' addRefTo d' cs) -- | Return the list of parents of a node. parents :: AlgNode -> AlgebraDag a -> [AlgNode] parents n d = G.pre (graph d) n -- | 'replaceChild n old new' replaces all links from node n to node old with links to node new. replaceChild :: Operator a => AlgNode -> AlgNode -> AlgNode -> AlgebraDag a -> AlgebraDag a replaceChild parent old new d = let op = operator parent d in if old `elem` opChildren op && old /= new then let op' = replaceOpChild op old new m' = IM.insert parent op' $ nodeMap d om' = M.insert op' parent $ M.delete op $ opMap d g' = G.insEdge (parent, new, ()) $ G.delEdge (parent, old) $ graph d d' = d { nodeMap = m', graph = g', opMap = om' } -- Update reference counters if nodes are not simply -- inserted or deleted but edges are replaced by other -- edges. We must not delete nodes before the new edges -- have been taken into account. Only after that can we -- certainly say that a node is no longer referenced -- (edges might be replaced by themselves). -- First, decrement refcounters for the old child d'' = decrRefCount d' old in -- Then, increment refcounters for the new child if the link was -- not already present (we do not count multi-edges separately) if new `elem` G.suc (graph d) parent then d'' else addRefTo d'' new else d -- | Returns the operator for a node. operator :: Operator a => AlgNode -> AlgebraDag a -> a operator n d = case IM.lookup n $ nodeMap d of Just op -> op Nothing -> error $ "AlgebraDag.operator: lookup failed for " ++ (show n) ++ "\n" ++ (show $ map fst $ IM.toList $ nodeMap d) -- | Return a topological ordering of all nodes which are reachable from the root nodes. topsort :: AlgebraDag a -> [AlgNode] topsort d = DFS.topsort $ graph d -- | Return all nodes that are reachable from one node. reachableNodesFrom :: AlgNode -> AlgebraDag a -> S.Set AlgNode reachableNodesFrom n d = S.fromList $ DFS.reachable n $ graph d -- | Tests wether there is a path from the first to the second node. hasPath :: AlgNode -> AlgNode -> AlgebraDag a -> Bool hasPath a b d = b `S.member` (reachableNodesFrom a d)
ulricha/algebra-dag
src/Database/Algebra/Dag.hs
bsd-3-clause
12,010
0
17
3,776
3,217
1,678
1,539
193
3
module ContM (HasCont(..), runCont, ContM) where import MT import Monad newtype ContM o i = C { ($$) :: (i -> o) -> o } runCont :: ContM i i -> i runCont m = m $$ id instance Monad (ContM o) where return x = C (\k -> k x) C m >>= f = C (\k -> m (\i -> f i $$ k)) C m >> C n = C (m . const . n) instance HasBaseMonad (ContM o) (ContM o) where inBase = id instance HasCont (ContM o) where callcc f = C (\k -> f (\a -> C (\d -> k a)) $$ k) shift :: ((a -> ContM b b) -> ContM b b) -> ContM b a shift f = C (\k -> runCont $ f (\a -> C (\k' -> k' (k a)))) reset :: ContM a a -> ContM a a reset m = return (runCont m) {- test1 = do x <- reset $ do y <- shift (\f -> do z <- f "100" f z) return ("10 + " ++ y) return $ "1 + " ++ x test2 = liftM ("1 + " ++) $ reset $ liftM ("10 + " ++) $ shift (\f -> return "100") test3 = liftM ("1 + " ++) $ reset $ liftM ("10 + " ++) $ shift $ \f -> liftM2 (\x y -> x ++ " + " ++ y) (f "100") (f "1000") -}
forste/haReFork
tools/base/lib/Monads/ContM.hs
bsd-3-clause
1,171
35
15
482
398
213
185
-1
-1
module FunctionWithLet where printInc2 n = let plusTwo = n + 2 in print plusTwo
dsaenztagarro/haskellbook
src/chapter2/FunctionWithLet.hs
bsd-3-clause
96
0
9
31
30
15
15
3
1
{-# LANGUAGE GADTs #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE ScopedTypeVariables #-} module Data.Array.Accelerate.Apart.Acc ( OpenAccWithName(..), OpenExpWithName, OpenFunWithName, accToApart, accGen ) where import Control.Monad.State import Data.List import qualified Text.PrettyPrint.Mainland as C import qualified Language.C as C import Language.C.Quote.C as C import Data.Array.Accelerate.AST hiding (Val (..), prj) import Data.Array.Accelerate.Array.Sugar import Data.Array.Accelerate.Trafo.Sharing as Sharing import Data.Array.Accelerate.Tuple import Data.Array.Accelerate.Apart.Base import Data.Array.Accelerate.Apart.Exp import Data.Array.Accelerate.Apart.Type import Data.List data OpenAccWithName aenv t = OpenAccWithName Name (PreOpenAcc OpenAccWithName aenv t) type OpenExpWithName = PreOpenExp OpenAccWithName type OpenFunWithName = PreOpenFun OpenAccWithName type UserVal = (String, String) data UserFun = UserFun { usrName :: String , usrParams :: [UserVal] , usrCode :: String , usrRet :: [UserVal] } showParams :: [UserVal] -> String showParams [v] = "\"" ++ (snd v) ++ "\"" showParams vs = "Array(" ++ (intercalate "," $ map quoteNames vs) ++ ")" where quoteNames (_,n) = "\"" ++ n ++ "\"" showParamType :: [UserVal] -> String showParamType [v] = fst v showParamType vs = "Seq(" ++ (intercalate "," $ map fst vs) ++ ")" showRetType :: [UserVal] -> String showRetType [v] = snd v showRetType vs = "TupleType(" ++ (intercalate "," $ map snd vs) ++ ")" instance Show UserFun where show u = "val " ++ (usrName u) ++ " = UserFunDef(\"" ++ (usrName u) ++ "\", " ++ (showParams $ usrParams u) ++ ", \"{" ++ (usrCode u) ++ "}\", " ++ (showParamType $ usrParams u) ++ ", " ++ (showRetType $ usrRet u) ++ ")" data ArrayFun = ArrayFun { arrName :: String , arrCode :: String } deriving (Show) data GenState = GenState { unique :: Int , scalarDefs :: [UserFun] , arrayDefs :: [ArrayFun] } type Gen = State GenState accToApart :: forall arrs aenv. Arrays arrs => Env aenv -> OpenAcc aenv arrs -> (String, String, OpenAccWithName aenv arrs) accToApart aenv acc = let (acc', state) = runState (accGen aenv acc) $ GenState 0 [] [] userFuns = concat $ map show (scalarDefs state) arrayFuns = concat $ map show (arrayDefs state) in (userFuns, arrayFuns, acc') incUnique :: Gen () incUnique = state $ \s -> ((), s { unique = (unique s) + 1 }) gensym :: Gen String gensym = do s <- get let i = unique s incUnique return $ "gensym" ++ (show i) addScalarDef :: UserFun -> Gen () addScalarDef def = state $ \s -> ((), s { scalarDefs = (scalarDefs s) ++ [def] }) addArrayDef :: ArrayFun -> Gen () addArrayDef def = state $ \s -> ((), s { arrayDefs = (arrayDefs s) ++ [def] }) makeReturnStmt :: [String] -> String makeReturnStmt [] = "return;" makeReturnStmt [x] = "return " ++ x ++ ";" makeReturnStmt _ = undefined accGen :: forall arrs aenv. Arrays arrs => Env aenv -> OpenAcc aenv arrs -> Gen (OpenAccWithName aenv arrs) accGen aenv' (OpenAcc (Alet bnd body)) = do bnd' <- accGen aenv' bnd body' <- accGen (snd $ pushAccEnv aenv' bnd) body return $ OpenAccWithName noName (Alet bnd' body') accGen aenv' (OpenAcc (Avar ix)) = return $ OpenAccWithName noName (Avar ix) accGen aenv' (OpenAcc (Use arr)) = return $ OpenAccWithName noName (Use arr) accGen aenv' acc@(OpenAcc (Map f arr)) = do arr' <- accGen aenv' arr funName <- gensym arrName <- gensym lambName <- gensym let cresTys = accTypeToC acc cresNames = accNames "res" [length cresTys - 1] cargTys = accTypeToC arr cargNames = accNames "arg" [length cargTys - 1] (bnds, es) = fun1ToC aenv' f retNames <- forM es $ \_ -> do name <- gensym return name let retStmt = makeReturnStmt retNames funStmts = map ((++ "; ") . show . C.ppr) es funCode = (++ retStmt) $ concat $ zipWith (\t s -> (init $ show $ C.ppr t) ++ " " ++ s) (tail cresTys) $ zipWith (\n s -> n ++ " = " ++ s) retNames funStmts params = map (\(t,n) -> (show $ C.ppr $ t,n)) bnds fun = UserFun { usrName = funName, usrParams = params, usrCode = funCode, usrRet = zip retNames $ map (init . show . C.ppr) $ tail cresTys } apartArr = ArrayFun { arrName = arrName, arrCode = "(fun " ++ showParamType params ++ ", " ++ lambName ++ " => Map(" ++ funName ++ ") $ " ++ lambName ++ ")" } addScalarDef fun addArrayDef apartArr return $ OpenAccWithName funName (Map (adaptFun f) arr') accGen _aenv _ = error "Not implemented." adaptFun :: OpenFun env aenv t -> OpenFunWithName env aenv t adaptFun (Body e) = Body $ adaptExp e adaptFun (Lam f) = Lam $ adaptFun f adaptExp :: OpenExp env aenv t -> OpenExpWithName env aenv t adaptExp e = case e of Var ix -> Var ix Let bnd body -> Let (adaptExp bnd) (adaptExp body) Const c -> Const c PrimConst c -> PrimConst c PrimApp f x -> PrimApp f (adaptExp x) Tuple t -> Tuple (adaptTuple t) Prj ix e -> Prj ix (adaptExp e) Cond p t e -> Cond (adaptExp p) (adaptExp t) (adaptExp e) IndexAny -> IndexAny IndexNil -> IndexNil IndexCons sh sz -> IndexCons (adaptExp sh) (adaptExp sz) IndexHead sh -> IndexHead (adaptExp sh) IndexTail sh -> IndexTail (adaptExp sh) IndexSlice ix slix sh -> IndexSlice ix (adaptExp slix) (adaptExp sh) IndexFull ix slix sl -> IndexFull ix (adaptExp slix) (adaptExp sl) ToIndex sh ix -> ToIndex (adaptExp sh) (adaptExp ix) FromIndex sh ix -> FromIndex (adaptExp sh) (adaptExp ix) Intersect sh1 sh2 -> Intersect (adaptExp sh1) (adaptExp sh2) ShapeSize sh -> ShapeSize (adaptExp sh) Shape acc -> Shape (adaptAcc acc) Index acc ix -> Index (adaptAcc acc) (adaptExp ix) LinearIndex acc ix -> LinearIndex (adaptAcc acc) (adaptExp ix) Foreign fo f x -> Foreign fo (adaptFun f) (adaptExp x) where adaptTuple :: Tuple (OpenExp env aenv) t -> Tuple (OpenExpWithName env aenv) t adaptTuple NilTup = NilTup adaptTuple (t `SnocTup` e) = adaptTuple t `SnocTup` adaptExp e adaptAcc (OpenAcc (Avar ix)) = OpenAccWithName noName (Avar ix) adaptAcc _ = error "D.A.A.C: unlifted array computation"
vollmerm/accelerate-apart
Data/Array/Accelerate/Apart/Acc.hs
bsd-3-clause
7,061
0
20
2,177
2,479
1,280
1,199
145
25
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} module Definitions where -- We define the data types and generate the TH in a separate module -- because we want to ensure that no external names are required to be -- imported. import Data.Profunctor.Product.TH (makeAdaptorAndInstance, makeAdaptorAndInstance') data Data2 a b = Data2 a b data Data3 a b c = Data3 a b c data Record2 a b = Record2 { a2 :: a, b2 :: b } data Record3 a b c = Record3 { a3 :: a, b3 :: b, c3 :: c } data RecordDefaultName x y = RecordDefaultName { x :: x, y :: y } $(makeAdaptorAndInstance "pData2" ''Data2) $(makeAdaptorAndInstance "pData3" ''Data3) $(makeAdaptorAndInstance "pRecord2" ''Record2) $(makeAdaptorAndInstance "pRecord3" ''Record3) makeAdaptorAndInstance' ''RecordDefaultName
karamaan/product-profunctors
Test/Definitions.hs
bsd-3-clause
831
0
8
134
194
114
80
15
0
{-| Restricted monads are a subset of indexed monads where the return value is restricted to a single index. They build on top of 'IMonad' using the (':=') type constructor which restricts the index of the return value. -} {-# LANGUAGE TypeOperators, GADTs, Rank2Types, CPP #-} #if MIN_VERSION_base(4,6,0) {-# LANGUAGE PolyKinds #-} #endif module Control.IMonad.Restrict ( -- * Restriction -- $restrict (:=)(..), R, returnR, (!>=), -- * Functions -- $functions fmapR, (<!>), (<.>), (=<!), (!>), (>!>), (<!<), joinR, voidR, foreverR, mapMR, mapMR_, forMR, forMR_, replicateMR, replicateMR_, sequenceR, sequenceR_, whenR, unlessR, -- * Interoperability -- $interop U(..), u, D(..) ) where import Control.Category ((<<<), (>>>)) import Control.IMonad.Core import Control.Monad (liftM, ap) import Control.Applicative (Applicative (..)) -- Just copying the fixities from Control.Monad infixr 1 =<!, <!<, >!> infixl 1 !>, !>= {- $restrict The (':=') type constructor restricts the index that the return value inhabits. 'returnR' and ('!>=') provide the restricted operations corresponding to 'returnI' and ('?>='). If 'returnI' and ('?>=') satisfy the monad laws, then so will 'returnR' and ('!>='): > returnR >!> f = f > > f >!> returnR = f > > (f >!> g) >!> h = f >!> (g >!> h) The type synonym 'R' rearranges the type variables of the restricted monad to match conventional notation. -} {-| @(a := i)@ represents a locked value of type @a@ that you can only access at the index @i@. 'V' seals values of type @a@, restricting them to a single index @i@. -} data (a := i) j where V :: a -> (a := i) i -- | An indexed monad where the final index, @j@, is \'R\'estricted type R m i j a = m (a := j) i -- | A 'returnI' that restricts the final index returnR :: (IMonad m) => a -> m (a := i) i returnR = returnI . V {-| A flipped 'bindI' that restricts the intermediate and final index. Called \"angelic bind\" in Conor McBride's paper. The type of this function has the following specialization: @(!>=) :: IMonad m => m (a := j) i -> (a -> m (b := k) j) -> m (b := k) i@ -} (!>=) :: (IMonad m) => m (a := j) i -> (a -> m b j) -> m b i m !>= f = bindI (\(V a) -> f a) m {- $functions Functions derived from 'returnR' and ('!>=') -} -- | All restricted monads are ordinary functors fmapR :: (IMonad m) => (a -> b) -> m (a := j) i -> m (b := j) i fmapR f m = m !>= returnR . f -- | Infix 'fmapR' (<!>) :: (IMonad m) => (a -> b) -> m (a := j) i -> m (b := j) i (<!>) = fmapR -- | All restricted monads are restricted applicatives (<.>) :: (IMonad m) => m ((a -> b) := j) i -> m (a := k) j -> m (b := k) i mf <.> mx = mf !>= \f -> f <!> mx {-| A 'bindI' that restricts the intermediate and final index. The type of this function has the following specialization: @(=\<!) :: IMonad m => (a -> m (b := k) j) -> m (a := j) i -> m (b := k) i@ -} (=<!) :: (IMonad m) => (a -> m b j) -> m (a := j) i -> m b i (=<!) = flip (!>=) {-| Sequence two indexed monads. The type of this function has the following specialization: @(!>) :: IMonad m => m (a := j) i -> m (b := k) j -> m (b := k) i@ -} (!>) :: (IMonad m) => m (a := j) i -> m b j -> m b i m1 !> m2 = m1 !>= \_ -> m2 {-| Composition of restricted Kleisli arrows This is equivalent to ('>>>') from @Control.Category@. The type of this function has the following specialization: @IMonad m => (a -> m (b:= j) i) -> (b -> m (c := k) j) -> (a -> m (c := k) i)@ -} (>!>) :: (IMonad m) => (a -> m (b := j) i) -> (b -> m c j) -> (a -> m c i) f >!> g = \x -> f x !>= g {-| Composition of restricted Kleisli arrows This is equivalent to ('<<<') from @Control.Category@. The type of this function has the following specialization: @(\<!\<) :: IMonad m => (b -> m (c := k) j) -> (a -> m (b := j) i) -> a -> m (c := k) i@ -} (<!<) :: (IMonad m) => (b -> m c j) -> (a -> m (b := j) i) -> (a -> m c i) f <!< g = \x -> f =<! g x {-| 'joinR' joins two monad layers into one. The type of this function has the following specialization: @joinR :: IMonad m => m (m (a := k) j := j) i -> m (a := k) i@ -} joinR :: (IMonad m) => m (m a j := j) i -> m a i joinR m = m !>= id -- | Discard the result of evaluation voidR :: (IMonad m) => m (a := i) i -> m (() := i) i voidR m = m !> returnR () -- | 'foreverR' repeats the action indefinitely foreverR :: (IMonad m) => m (a := i) i -> m (b := j) i foreverR m = let r = m !> r in r -- | \"@mapMR f@\" is equivalent to \"@sequenceR . map f@\" mapMR :: (IMonad m) => (a -> m (b := i) i) -> [a] -> m ([b] := i) i {-# INLINE mapMR #-} mapMR f as = sequenceR (map f as) -- | \"@mapMR_ f@\" is equivalent to \"@sequenceR_ . map f@\" mapMR_ :: (IMonad m) => (a -> m (b := i) i) -> [a] -> m (() := i) i {-# INLINE mapMR_ #-} mapMR_ f as = sequenceR_ (map f as) -- | 'mapMR' with its arguments flipped forMR :: (IMonad m) => [a] -> (a -> m (b := i) i) -> m ([b] := i) i {-# INLINE forMR #-} forMR = flip mapMR -- | 'mapMR_' with its arguments flipped forMR_ :: (IMonad m) => [a] -> (a -> m (b := i) i) -> m (() := i) i {-# INLINE forMR_ #-} forMR_ = flip mapMR_ -- | \"@replicateMR n m@\" performs @m@ @n@ times and collects the results replicateMR :: (IMonad m) => Int -> m (a := i) i -> m ([a] := i) i replicateMR n x = sequenceR (replicate n x) -- | \"@replicateMR_ n m@\" performs @m@ @n@ times and ignores the results replicateMR_ :: (IMonad m) => Int -> m (a := i) i -> m (() := i) i replicateMR_ n x = sequenceR_ (replicate n x) -- | Evaluate each action from left to right and collect the results sequenceR :: (IMonad m) => [m (a := i) i] -> m ([a] := i) i {-# INLINE sequenceR #-} sequenceR ms = foldr k (returnR []) ms where k m m' = m !>= \x -> m' !>= \xs -> returnR (x:xs) -- | Evaluate each action from left to right and ignore the results sequenceR_ :: (IMonad m) => [m (a := i) i] -> m (() := i) i {-# INLINE sequenceR_ #-} sequenceR_ ms = foldr (!>) (returnR ()) ms -- | \"@whenR p m@\" executes @m@ if @p@ is 'True' whenR :: (IMonad m) => Bool -> m (() := i) i -> m (() := i) i whenR p s = if p then s else returnR () -- | \"@unlessR p m@\" executes @m@ if @p@ is 'False' unlessR :: (IMonad m) => Bool -> m (() := i) i -> m (() := i) i unlessR p s = if p then returnR () else s {- $interop The following types and functions convert between ordinary monads and restricted monads. Use 'u' to convert an ordinary monad to a restricted monad so that it can be used within an indexed @do@ block like so: > -- Both do blocks are indexed, using syntax rebinding from Control.IMonad.Do > do x <- indexedAction > lift $ do > y <- u $ ordinaryAction1 x > u $ ordinaryAction2 x y Use 'D' to convert an index-preserving restricted monad into an ordinary monad so that it can be used within a normal @do@ block. > -- An ordinary do block (i.e. without syntax rebinding from Control.IMonad.Do) > do x <- D $ indexPreservingAction > D $ anotherIndexPreservingAction x -} -- | The 'U' type \'U\'pgrades ordinary monads to restricted monads data U m a i where U :: { unU :: m (a i) } -> U m a i instance (Monad m) => IFunctor (U m) where fmapI f m = m ?>= (returnI . f) instance (Monad m) => IMonad (U m) where returnI = U . return bindI f (U m) = U (m >>= (unU . f)) -- | 'u' transforms an ordinary monad into a restricted monad u :: (Monad m) => m a -> (U m) (a := i) i u x = U (liftM V x) {-| The 'D' type \'D\'owngrades index-preserving restricted monads to ordinary monads -} data D i m r = D { unD :: m (r := i) i } instance (IMonad m) => Monad (D i m) where return = D . returnR (D m) >>= f = D (m !>= (unD . f)) instance (IMonad m) => Applicative (D i m) where pure = return (<*>) = ap instance (IMonad m) => Functor (D i m) where fmap f (D m) = D (fmapR f m)
Gabriel439/Haskell-Index-Core-Library
Control/IMonad/Restrict.hs
bsd-3-clause
8,073
24
13
2,110
2,234
1,247
987
110
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Lasca.Modules where import Data.Maybe import qualified Data.Text as T import qualified Data.Text.IO as TIO import Text.Printf import Control.Monad.State import Control.Lens hiding ((<.>)) import Data.List import Data.IntMap.Strict ( IntMap ) import qualified Data.IntMap.Strict as IntMap import Data.Map.Strict ( Map ) import qualified Data.Map.Strict as Map import System.Environment import System.Exit import System.Directory import System.FilePath import Debug.Trace as Debug import qualified Text.Megaparsec as Megaparsec import Lasca.Syntax import Lasca.Parser import Lasca.Type data LascaModule = LascaModule { imports :: [LascaModule], moduleExprs :: [Expr], modName :: Name } instance Show LascaModule where show m = show (modName m) instance Eq LascaModule where lhs == rhs = modName lhs == modName rhs instance Ord LascaModule where compare lhs rhs = compare (modName lhs) (modName rhs) data Dependencies = Dependencies { _modsByLevel :: IntMap [LascaModule], _modLevel :: Map LascaModule Int } deriving (Show) makeLenses 'Dependencies calcModulesDependencies :: LascaModule -> Dependencies calcModulesDependencies lascaModule = execState (getMaxLevel lascaModule) (Dependencies {_modsByLevel = IntMap.empty, _modLevel = Map.empty}) where getMaxLevel :: LascaModule -> State Dependencies Int getMaxLevel m = do s <- get case Map.lookup m (s ^. modLevel) of Just l -> return l Nothing -> do let mods = imports m levels <- forM mods getMaxLevel let level = case levels of [] -> 0 levels -> 1 + maximum levels modLevel %= Map.insert m level modsByLevel %= IntMap.alter (joinModules m) level return level where joinModules new Nothing = Just [new] joinModules new (Just mods) = Just $ new : mods linearizeIncludes :: LascaModule -> [LascaModule] linearizeIncludes lascaModule = do let all = calcModulesDependencies lascaModule let pathes = snd <$> IntMap.toList (all ^. modsByLevel) foldr (\mods path -> sort mods ++ path) [] pathes fixModuleAndImportPrelude :: FilePath -> [Expr] -> IO [Expr] fixModuleAndImportPrelude filename exprs = case exprs of (mod@(Module _ name): exprs) -> do when (takeBaseName filename /= T.unpack (last $ nameToList name)) $ die $ printf "Wrong module name in file %s. Module name should match file name, but was %s)" filename (show name) return $ mod : insertImportPrelude name exprs _ -> do let name = Name $ T.pack $ takeBaseName filename let mod = Module emptyMeta name return $ mod : insertImportPrelude name exprs insertImportPrelude :: Name -> [Expr] -> [Expr] insertImportPrelude name exprs = if name == Name "Prelude" then exprs else Import emptyMeta "Prelude" : exprs moduleSearchPaths :: IO [FilePath] moduleSearchPaths = do dir <- getCurrentDirectory lascaPathEnv <- lookupEnv "LASCAPATH" let lascaPaths = splitSearchPath $ fromMaybe "" lascaPathEnv absPaths <- mapM canonicalizePath lascaPaths existingPaths <- filterM doesDirectoryExist absPaths -- TODO add XDB paths return $ nub $ dir : existingPaths findModulePath :: [FilePath] -> Name -> IO FilePath findModulePath searchPaths name = do let relPath = path name <.> "lasca" result <- findFile searchPaths relPath case result of Just file -> return file Nothing -> error $ printf "Couldn't find module %s. Search path: %s" (show name) (show $ intercalate "," searchPaths) where path (Name n) = T.unpack n path (NS prefix n) = path prefix </> path n type Mapping = Map Name LascaModule loadModule :: [FilePath] -> Mapping -> [Name] -> FilePath -> Name -> IO (Mapping, LascaModule) loadModule searchPaths imported importPath absoluteFilePath name = do file <- TIO.readFile absoluteFilePath case parseToplevelFilename absoluteFilePath file of Left err -> die $ Megaparsec.parseErrorPretty err Right exprs -> do canonizedExprs <- fixModuleAndImportPrelude absoluteFilePath exprs let imports = getImports canonizedExprs (newImported, modules) <- loadImports searchPaths imported (name : importPath) imports let thisModule = LascaModule { modName = name, imports = modules, moduleExprs = canonizedExprs } return (Map.insert name thisModule newImported, thisModule) loadImports :: [FilePath] -> Mapping -> [Name] -> [Name] -> IO (Mapping, [LascaModule]) loadImports searchPaths imported importPath imports = do -- Debug.traceM $ printf "loadImports %s %s %s" (show imported) (show importPath) (show $ imports) foldM (\(imported, modules) name -> do (newImported, lascaModule) <- loadImport searchPaths imported importPath name return (Map.union imported newImported, lascaModule : modules) ) (imported, []) imports loadImport :: [FilePath] -> Mapping -> [Name] -> Name -> IO (Mapping, LascaModule) loadImport searchPaths imported importPath name = do -- Debug.traceM $ printf "loadImport %s %s %s" (show imported) (show importPath) (show name) when (name `elem` importPath) $ die (printf "Circular dependency in %s -> %s" (show importPath) (show name)) case name `Map.lookup` imported of Just lascaModule -> return (imported, lascaModule) Nothing -> do absoluteFilePath <- findModulePath searchPaths name loadModule searchPaths imported importPath absoluteFilePath name getImports :: [Expr] -> [Name] getImports exprs = foldl' folder [] exprs where folder imports (Import _ name) = name : imports folder imports _ = imports
nau/lasca-compiler
src/lib/Lasca/Modules.hs
bsd-3-clause
6,015
0
21
1,477
1,733
886
847
122
4
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} module Network.Sock.Types.Handler ( Handler(..) ) where ------------------------------------------------------------------------------ import qualified Data.ByteString.Lazy as BL (ByteString) import Data.Proxy ------------------------------------------------------------------------------ import qualified Network.HTTP.Types as H (ResponseHeaders) import qualified Network.HTTP.Types.Response as H (IsResponse(..)) import qualified Network.HTTP.Types.Request as H (IsRequest(..)) ------------------------------------------------------------------------------ import Network.Sock.Types.Frame import Network.Sock.Types.Server import Network.Sock.Types.Request ------------------------------------------------------------------------------ -- | Handler class Handler tag where handleReuqest :: H.IsResponse res => Proxy tag -> Request -> Server res -- | Formats the Frame (different protocols may format frames differently). format :: H.IsRequest req => Proxy tag -> req -> Frame -> BL.ByteString -- | Used to create a response (headers might be transport & request dependent). headers :: Proxy tag -> Request -> H.ResponseHeaders
Palmik/wai-sockjs
src/Network/Sock/Types/Handler.hs
bsd-3-clause
1,394
0
11
312
204
128
76
25
0
{-# LANGUAGE OverloadedStrings #-} -- | This module contains all the web framework independent code for parsing and verifying -- JSON Web Tokens. module JwtAuth where import Control.Monad ((<=<)) import qualified Data.Aeson as Aeson import qualified Data.Aeson.Types as Aeson import Data.Bifunctor (first) import qualified Data.ByteString as SBS import qualified Data.Map.Strict as Map import qualified Data.Text.Encoding as Text import Data.Time.Clock.POSIX (POSIXTime) import Web.JWT (JWT, UnverifiedJWT, VerifiedJWT) import qualified Web.JWT as JWT import AccessControl -- * Token verification data VerificationError = TokenUsedTooEarly | TokenExpired | TokenInvalid | TokenNotFound | TokenSignatureInvalid deriving (Show, Eq) -- | Check that a token is valid at the given time for the given secret. verifyToken :: POSIXTime -> JWT.Signer -> SBS.ByteString -> Either VerificationError (JWT VerifiedJWT) verifyToken now secret = verifyNotBefore now <=< verifyExpiry now <=< verifySignature secret <=< decodeToken -- | Verify that the token is not used before it was issued. verifyNotBefore :: POSIXTime -> JWT VerifiedJWT -> Either VerificationError (JWT VerifiedJWT) verifyNotBefore now token = case JWT.nbf . JWT.claims $ token of Nothing -> Right token Just notBefore -> if now <= JWT.secondsSinceEpoch notBefore then Left TokenUsedTooEarly else Right token -- | Verify that the token is not used after is has expired. verifyExpiry :: POSIXTime -> JWT VerifiedJWT -> Either VerificationError (JWT VerifiedJWT) verifyExpiry now token = case JWT.exp . JWT.claims $ token of Nothing -> Right token Just expiry -> if now > JWT.secondsSinceEpoch expiry then Left TokenExpired else Right token -- | Verify that the token contains a valid signature. verifySignature :: JWT.Signer -> JWT UnverifiedJWT -> Either VerificationError (JWT VerifiedJWT) verifySignature secret token = case JWT.verify secret token of Nothing -> Left TokenSignatureInvalid Just token' -> Right token' decodeToken :: SBS.ByteString -> Either VerificationError (JWT UnverifiedJWT) decodeToken bytes = case JWT.decode (Text.decodeUtf8 bytes) of Nothing -> Left TokenInvalid Just token -> Right token -- * Claim parsing data TokenError = VerificationError VerificationError -- ^ JWT could not be verified. | ClaimError String -- ^ The claims do not fit the schema. deriving (Show, Eq) -- | Verify the token and extract the icepeak claim from it. extractClaim :: POSIXTime -> JWT.Signer -> SBS.ByteString -> Either TokenError IcepeakClaim extractClaim now secret tokenBytes = do jwt <- first VerificationError $ verifyToken now secret tokenBytes claim <- first ClaimError $ getIcepeakClaim jwt pure claim -- | Extract the icepeak claim from the token without verifying it. extractClaimUnverified :: SBS.ByteString -> Either TokenError IcepeakClaim extractClaimUnverified tokenBytes = do jwt <- first VerificationError $ decodeToken tokenBytes claim <- first ClaimError $ getIcepeakClaim jwt pure claim getIcepeakClaim :: JWT r -> Either String IcepeakClaim getIcepeakClaim token = do let (JWT.ClaimsMap claimsMap) = JWT.unregisteredClaims $ JWT.claims token maybeClaim = Map.lookup "icepeak" claimsMap claimJson <- maybe (Left "Icepeak claim missing.") Right maybeClaim Aeson.parseEither Aeson.parseJSON claimJson -- * Token generation -- | Add the icepeak claim to a set of JWT claims. addIcepeakClaim :: IcepeakClaim -> JWT.JWTClaimsSet -> JWT.JWTClaimsSet addIcepeakClaim claim claims = claims { JWT.unregisteredClaims = newClaimsMap <> JWT.unregisteredClaims claims } where newClaimsMap = JWT.ClaimsMap $ Map.fromList [("icepeak", Aeson.toJSON claim)]
channable/icepeak
server/src/JwtAuth.hs
bsd-3-clause
3,977
0
12
855
890
459
431
75
3
{-# LANGUAGE OverloadedStrings #-} -------------------------------------------------------------------- -- | -- Module : Text.Atom.Feed.Import -- Copyright : (c) Galois, Inc. 2007-2008 -- License : BSD3 -- -- Maintainer: Sigbjorn Finne <sof@galois.com> -- Stability : provisional -- Description: Convert from XML to Atom -- -------------------------------------------------------------------- module Text.Atom.Feed.Import where import Control.Monad (guard,mplus) import Data.Maybe (listToMaybe, mapMaybe, isJust) import Data.List (find) import Data.Text (Text,unpack) import Text.Feed.Util import Text.Atom.Feed import Text.Atom.Feed.Export (atomName, atomThreadName) import Text.XML as XML pNodes :: Text -> [XML.Element] -> [XML.Element] pNodes x es = filter ((atomName x ==) . elementName) es pQNodes :: Name -> [XML.Element] -> [XML.Element] pQNodes x es = filter ((x==) . elementName) es pNode :: Text -> [XML.Element] -> Maybe XML.Element pNode x es = listToMaybe (pNodes x es) pQNode :: Name -> [XML.Element] -> Maybe XML.Element pQNode x es = listToMaybe (pQNodes x es) pLeaf :: Text -> [XML.Element] -> Maybe Text pLeaf x es = strContent `fmap` pNode x es pQLeaf :: Name -> [XML.Element] -> Maybe Text pQLeaf x es = strContent `fmap` pQNode x es pAttr :: Text -> XML.Element -> Maybe Text pAttr x e = fmap snd $ find sameAttr [ (k,v) | (k, v) <- elementAttributes e ] where ax = atomName x sameAttr (k,_) = k == ax || (not (isJust (nameNamespace k)) && nameLocalName k == x) pAttrs :: Text -> XML.Element -> [Text] pAttrs x e = [ v | (k, v) <- elementAttributes e, k == atomName x ] pQAttr :: Name -> XML.Element -> Maybe Text pQAttr x e = lookup x [ (k,v) | (k, v) <- elementAttributes e ] pMany :: Text -> (XML.Element -> Maybe a) -> [XML.Element] -> [a] pMany p f es = mapMaybe f (pNodes p es) children :: XML.Element -> [XML.Element] children e = onlyElems (elementNodes e) elementFeed :: XML.Element -> Maybe Feed elementFeed e = do guard (elementName e == atomName "feed") let es = children e i <- pLeaf "id" es t <- pTextContent "title" es `mplus` return (TextText "<no-title>") u <- pLeaf "updated" es return Feed { feedId = i , feedTitle = t , feedSubtitle = pTextContent "subtitle" es , feedUpdated = u , feedAuthors = pMany "author" pPerson es , feedContributors = pMany "contributor" pPerson es , feedCategories = pMany "category" pCategory es , feedGenerator = pGenerator `fmap` pNode "generator" es , feedIcon = pLeaf "icon" es , feedLogo = pLeaf "logo" es , feedRights = pTextContent "rights" es , feedLinks = pMany "link" pLink es , feedEntries = pMany "entry" pEntry es , feedOther = other_es es , feedAttrs = other_as (elementAttributes e) } where other_es es = filter (\ el -> not (elementName el `elem` known_elts)) es other_as as = filter (\ (k,_) -> not (k `elem` known_attrs)) as -- let's have them all (including xml:base and xml:lang + xmlns: stuff) known_attrs = [] known_elts = map atomName [ "author" , "category" , "contributor" , "generator" , "icon" , "id" , "link" , "logo" , "rights" , "subtitle" , "title" , "updated" , "entry" ] pTextContent :: Text -> [XML.Element] -> Maybe TextContent pTextContent tag es = do e <- pNode tag es case pAttr "type" e of Nothing -> return (TextText (strContent e)) Just "text" -> return (TextText (strContent e)) Just "html" -> return (HTMLText (strContent e)) Just "xhtml" -> case children e of -- hmm... [c] -> return (XHTMLText c) _ -> Nothing -- Multiple XHTML children. _ -> Nothing -- Unknown text content type. pPerson :: XML.Element -> Maybe Person pPerson e = do let es = children e name <- pLeaf "name" es -- or missing "name" return Person { personName = name , personURI = pLeaf "uri" es , personEmail = pLeaf "email" es , personOther = [] -- XXX? } pCategory :: XML.Element -> Maybe Category pCategory e = do term <- pAttr "term" e -- or missing "term" attribute return Category { catTerm = term , catScheme = pAttr "scheme" e , catLabel = pAttr "label" e , catOther = [] -- XXX? } pGenerator :: XML.Element -> Generator pGenerator e = Generator { genURI = pAttr "href" e , genVersion = pAttr "version" e , genText = strContent e } pSource :: XML.Element -> Source pSource e = let es = children e in Source { sourceAuthors = pMany "author" pPerson es , sourceCategories = pMany "category" pCategory es , sourceGenerator = pGenerator `fmap` pNode "generator" es , sourceIcon = pLeaf "icon" es , sourceId = pLeaf "id" es , sourceLinks = pMany "link" pLink es , sourceLogo = pLeaf "logo" es , sourceRights = pTextContent "rights" es , sourceSubtitle = pTextContent "subtitle" es , sourceTitle = pTextContent "title" es , sourceUpdated = pLeaf "updated" es , sourceOther = [] -- XXX ? } pLink :: XML.Element -> Maybe Link pLink e = do uri <- pAttr "href" e return Link { linkHref = uri , linkRel = Right `fmap` pAttr "rel" e , linkType = pAttr "type" e , linkHrefLang = pAttr "hreflang" e , linkTitle = pAttr "title" e , linkLength = pAttr "length" e , linkAttrs = other_as (elementAttributes e) , linkOther = [] } where other_as as = filter (\ (k,_) -> not (k `elem` known_attrs)) as known_attrs = map atomName [ "href", "rel", "type", "hreflang", "title", "length"] pEntry :: XML.Element -> Maybe Entry pEntry e = do let es = children e i <- pLeaf "id" es t <- pTextContent "title" es u <- pLeaf "updated" es `mplus` pLeaf "published" es return Entry { entryId = i , entryTitle = t , entryUpdated = u , entryAuthors = pMany "author" pPerson es , entryContributor = pMany "contributor" pPerson es , entryCategories = pMany "category" pCategory es , entryContent = pContent =<< pNode "content" es , entryLinks = pMany "link" pLink es , entryPublished = pLeaf "published" es , entryRights = pTextContent "rights" es , entrySource = pSource `fmap` pNode "source" es , entrySummary = pTextContent "summary" es , entryInReplyTo = pInReplyTo es , entryInReplyTotal = pInReplyTotal es , entryAttrs = other_as (elementAttributes e) , entryOther = [] -- ? } where other_as as = filter (\ (k,_) -> not (k `elem` known_attrs)) as -- let's have them all (including xml:base and xml:lang + xmlns: stuff) known_attrs = [] pContent :: XML.Element -> Maybe EntryContent pContent e = case pAttr "type" e of Nothing -> return (TextContent (strContent e)) Just "text" -> return (TextContent (strContent e)) Just "html" -> return (HTMLContent (strContent e)) Just "xhtml" -> case children e of [] -> return (TextContent "") [c] -> return (XHTMLContent c) _ -> Nothing Just ty -> case pAttr "src" e of Nothing -> return (MixedContent (Just ty) (elementNodes e)) Just uri -> return (ExternalContent (Just ty) uri) pInReplyTotal :: [XML.Element] -> Maybe InReplyTotal pInReplyTotal es = do t <- pQLeaf (atomThreadName "total") es case reads $ unpack t of ((x,_):_) -> do n <- pQNode (atomThreadName "total") es return InReplyTotal { replyToTotal = x , replyToTotalOther = elementAttributes n } _ -> fail "no parse" pInReplyTo :: [XML.Element] -> Maybe InReplyTo pInReplyTo es = do t <- pQNode (atomThreadName "reply-to") es case pQAttr (atomThreadName "ref") t of Just ref -> return InReplyTo { replyToRef = ref , replyToHRef = pQAttr (atomThreadName "href") t , replyToType = pQAttr (atomThreadName "type") t , replyToSource = pQAttr (atomThreadName "source") t , replyToOther = elementAttributes t -- ToDo: snip out matched ones. , replyToContent = elementNodes t } _ -> fail "no parse"
haskell-pkg-janitors/feed
Text/Atom/Feed/Import.hs
bsd-3-clause
8,838
8
15
2,723
2,744
1,443
1,301
205
8
-- A script for parsing the Haskell keywords out of the Haskell wiki page -- and producing a database. import Text.HTML.TagSoup import Data.List.Extra import Data.Char import System.Environment import System.IO.Extra import Numeric main :: IO () main = do [input,output] <- getArgs writeFileBinary output . translateKeywords =<< readFile' input translateKeywords :: String -> String translateKeywords src = unlines $ keywordPrefix ++ items where items = concatMap keywordFormat $ partitions (~== "<span class='mw-headline' id>") $ takeWhile (~/= "<div class=printfooter>") $ parseTags src keywordPrefix = ["-- Hoogle documentation, generated by Hoogle" ,"-- From https://wiki.haskell.org/Keywords" ,"-- See Hoogle, https://hoogle.haskell.org/" ,"" ,"-- | Haskell keywords, always available" ,"@url https://wiki.haskell.org/Keywords" ,"@package keyword" ] keywordFormat x = concat ["" : docs ++ ["@url #" ++ concatMap g n, "@entry keyword " ++ noUnderscore n] | n <- name] where noUnderscore "_" = "_" noUnderscore xs = map (\x -> if x == '_' then ' ' else x) xs name = words $ f $ fromAttrib "id" (head x) docs = zipWith (++) ("-- | " : repeat "-- ") $ intercalate [""] $ map docFormat $ partitions isBlock x g x | isAlpha x || x `elem` "_-:" = [x] | otherwise = '.' : upper (showHex (ord x) "") isBlock (TagOpen x _) = x `elem` ["p","pre","ul"] isBlock _ = False f ('.':'2':'C':'_':xs) = ' ' : f xs f ('.':a:b:xs) = chr res : f xs where [(res,"")] = readHex [a,b] f (x:xs) = x : f xs f [] = [] docFormat :: [Tag String] -> [String] docFormat (TagOpen "pre" _:xs) = ["<pre>"] ++ map (drop n) ys ++ ["</pre>"] where ys = lines $ trimEnd $ innerText xs n = minimum $ map (length . takeWhile isSpace) ys docFormat (TagOpen "p" _:xs) = g 0 [] $ words $ f xs where g n acc [] = [unwords $ reverse acc | acc /= []] g n acc (x:xs) | nx+1+n > 70 = g n acc [] ++ g nx [x] xs | otherwise = g (n+nx+1) (x:acc) xs where nx = length x f (TagOpen "code" _:xs) = "<tt>" ++ innerText a ++ "</tt>" ++ f (drop1 b) where (a,b) = break (~== "</code>") xs f (x:xs) = h x ++ f xs f [] = [] h (TagText x) = unwords (lines x) h _ = "" docFormat (TagOpen "ul" _:xs) = ["<ul><li>"] ++ intercalate ["</li><li>"] [docFormat (TagOpen "p" []:x) | x <- partitions (~== "<li>") xs] ++ ["</li></ul>"]
ndmitchell/hoogle
misc/Keywords.hs
bsd-3-clause
2,641
0
13
783
1,059
544
515
56
7
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE MultiParamTypeClasses #-} module Numeric.Sparse.Internal where import Data.IntMap import GHC.TypeLits type Index = Key type DIM = KnownNat -- | Shifts (re-enumerates) keys of IntMap by given number shiftKeys :: Int -> IntMap a -> IntMap a shiftKeys k m = fromAscList [ (i+k,x) | (i,x) <- toAscList m ] natInt :: (KnownNat n) => proxy n -> Int natInt = fromIntegral . natVal
mnick/hsparse
src/Numeric/Sparse/Internal.hs
bsd-3-clause
445
0
9
94
124
70
54
11
1
{- | Copyright: 2002, Simon Marlow. Copyright: 2006, Bjorn Bringert. Copyright: 2009, Henning Thielemann. Show @index.html@ or another configured file whenever the URI path is a directory. However, this module gets only active if the directory path is terminated with a slash. Without a slash the relative paths will not be processed correct by the web clients (they will consider relative paths as relative to the superdirectory). See also "Network.MoHWS.Part.AddSlash". -} module Network.MoHWS.Part.Index (Configuration, desc, ) where import qualified Network.MoHWS.Module as Module import qualified Network.MoHWS.Module.Description as ModuleDesc import qualified Network.MoHWS.Server.Request as ServerRequest import qualified Network.MoHWS.Server.Context as ServerContext import Network.MoHWS.Logger.Error (debug, ) import qualified Network.MoHWS.Configuration as Config import qualified Network.MoHWS.Configuration.Accessor as ConfigA import qualified Network.MoHWS.Configuration.Parser as ConfigParser import qualified Data.Accessor.Basic as Accessor import Data.Accessor.Basic ((.>)) import Network.MoHWS.Utility (statFile, hasTrailingSlash, ) import Data.Maybe (fromMaybe, ) import Control.Monad.Trans.Maybe (MaybeT, runMaybeT, ) import Control.Monad.Trans.Class (lift, ) import Control.Monad (guard, ) import qualified System.FilePath as FilePath import System.Posix (isDirectory, ) desc :: ModuleDesc.T body Configuration desc = ModuleDesc.empty { ModuleDesc.name = "index", ModuleDesc.load = return . funs, ModuleDesc.configParser = parser, ModuleDesc.setDefltConfig = const defltConfig } data Configuration = Configuration { index_ :: String } defltConfig :: Configuration defltConfig = Configuration { index_ = "index.html" } index :: Accessor.T Configuration String index = Accessor.fromSetGet (\x c -> c{index_ = x}) index_ parser :: ConfigParser.T st Configuration parser = ConfigParser.field "directoryindex" p_index p_index :: ConfigParser.T st Configuration p_index = ConfigParser.set (ConfigA.extension .> index) $ ConfigParser.stringLiteral funs :: ServerContext.T Configuration -> Module.T body funs st = Module.empty { Module.tweakRequest = tweakRequest st } tweakRequest :: ServerContext.T Configuration -> ServerRequest.T body -> IO (ServerRequest.T body) tweakRequest = Module.tweakFilename fixPath fixPath :: ServerContext.T Configuration -> FilePath -> IO FilePath fixPath st filename = let conf = ServerContext.config st in fmap (fromMaybe filename) $ runMaybeT $ do guard (hasTrailingSlash filename) stat <- statFile filename guard (isDirectory stat) let indexFilename = FilePath.combine filename $ index_ $ Config.extension conf lift $ debug st $ "indexFilename = " ++ show indexFilename _ <- statFile indexFilename -- check whether file exists return indexFilename
xpika/mohws
src/Network/MoHWS/Part/Index.hs
bsd-3-clause
2,958
0
16
500
651
371
280
59
1
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE RankNTypes #-} -- | Blockchain listener for Explorer. -- Callbacks on application and rollback. module Pos.Explorer.BListener ( runExplorerBListener , ExplorerBListener -- * Instances -- ** MonadBListener (ExplorerBListener m) -- * Required for tests , epochPagedBlocksMap -- * Required for migration , findEpochMaxPages -- * Required for test util , createPagedHeaderHashesPair ) where import Universum hiding (keys) import Control.Lens (at, non) import Control.Monad.Trans.Identity (IdentityT (..)) import Data.Coerce (coerce) import Data.List ((\\)) import qualified Data.List.NonEmpty as NE import qualified Data.Map as M import qualified Ether import UnliftIO (MonadUnliftIO) import Pos.Chain.Block (Block, Blund, HeaderHash, MainBlock, headerHash, mainBlockSlot, mainBlockTxPayload) import Pos.Chain.Txp (Tx, topsortTxs, txpTxs) import Pos.Core (LocalSlotIndex (..), SlotId (..), difficultyL, epochIndexL, getChainDifficulty) import Pos.Core.Chrono (NE, NewestFirst (..), OldestFirst (..), toNewestFirst) import Pos.Crypto (withHash) import Pos.DB.BatchOp (SomeBatchOp (..)) import Pos.DB.Block (MonadBListener (..)) import Pos.DB.Class (MonadDBRead) import Pos.Explorer.DB (Epoch, EpochPagedBlocksKey, Page, defaultPageSize, findEpochMaxPages, numOfLastTxs) import qualified Pos.Explorer.DB as DB import Pos.Util.AssertMode (inAssertMode) import Pos.Util.Wlog (WithLogger) ---------------------------------------------------------------------------- -- Declarations ---------------------------------------------------------------------------- data ExplorerBListenerTag type ExplorerBListener = Ether.TaggedTrans ExplorerBListenerTag IdentityT -- Unwrap the @BListener@. runExplorerBListener :: ExplorerBListener m a -> m a runExplorerBListener = coerce -- Type alias, remove duplication type MonadBListenerT m = ( WithLogger m , MonadCatch m , MonadDBRead m , MonadUnliftIO m ) -- Explorer implementation for usual node. Combines the operations. instance ( MonadDBRead m , MonadUnliftIO m , MonadCatch m , WithLogger m ) => MonadBListener (ExplorerBListener m) where onApplyBlocks _nm blunds = onApplyCallGeneral blunds onRollbackBlocks _nm _pc blunds = onRollbackCallGeneral blunds ---------------------------------------------------------------------------- -- General calls ---------------------------------------------------------------------------- onApplyCallGeneral :: MonadBListenerT m => OldestFirst NE Blund -> m SomeBatchOp onApplyCallGeneral blunds = do epochBlocks <- onApplyEpochBlocksExplorer blunds pageBlocks <- onApplyPageBlocksExplorer blunds lastTxs <- onApplyLastTxsExplorer blunds inAssertMode DB.sanityCheckBalances pure $ SomeBatchOp [epochBlocks, pageBlocks, lastTxs] onRollbackCallGeneral :: MonadBListenerT m => NewestFirst NE Blund -> m SomeBatchOp onRollbackCallGeneral blunds = do epochBlocks <- onRollbackEpochBlocksExplorer blunds pageBlocks <- onRollbackPageBlocksExplorer blunds lastTxs <- onRollbackLastTxsExplorer blunds inAssertMode DB.sanityCheckBalances pure $ SomeBatchOp [epochBlocks, pageBlocks, lastTxs] ---------------------------------------------------------------------------- -- Function calls ---------------------------------------------------------------------------- -- For @EpochBlocks@ onApplyEpochBlocksExplorer :: MonadBListenerT m => OldestFirst NE Blund -> m SomeBatchOp onApplyEpochBlocksExplorer blunds = onApplyEpochPagedBlocks blunds -- For @PageBlocks@ onApplyPageBlocksExplorer :: MonadBListenerT m => OldestFirst NE Blund -> m SomeBatchOp onApplyPageBlocksExplorer blunds = onApplyKeyBlocksGeneral blunds pageBlocksMap -- For last transactions, @Tx@ onApplyLastTxsExplorer :: MonadBListenerT m => OldestFirst NE Blund -> m SomeBatchOp onApplyLastTxsExplorer blunds = generalLastTxsExplorer blocksNE getTopTxsDiff where -- Get the top transactions by pulling the old top transactions and adding -- new transactions. After we append them, take the last N transactions and -- we have our top transactions. getTopTxsDiff :: OldTxs -> NewTxs -> [Tx] getTopTxsDiff oldTxs newTxs = take numOfLastTxs reversedCombined where reversedCombined :: [Tx] reversedCombined = reverse $ getOldTxs oldTxs ++ getNewTxs newTxs blocksNE :: NE Block blocksNE = fst <$> getOldestFirst blunds ---------------------------------------------------------------------------- -- Rollback ---------------------------------------------------------------------------- -- For @EpochBlocks@ onRollbackEpochBlocksExplorer :: MonadBListenerT m => NewestFirst NE Blund -> m SomeBatchOp onRollbackEpochBlocksExplorer blunds = onRollbackEpochPagedBlocks blunds -- For @PageBlocks@ onRollbackPageBlocksExplorer :: MonadBListenerT m => NewestFirst NE Blund -> m SomeBatchOp onRollbackPageBlocksExplorer blunds = onRollbackGeneralBlocks blunds pageBlocksMap -- For last transactions, @Tx@ onRollbackLastTxsExplorer :: MonadBListenerT m => NewestFirst NE Blund -> m SomeBatchOp onRollbackLastTxsExplorer blunds = generalLastTxsExplorer blocksNE getTopTxsDiff where -- Get the top transactions by pulling the old top transactions and removing -- new transactions. After we remove them, what remains are the new top -- transactions. getTopTxsDiff :: OldTxs -> NewTxs -> [Tx] getTopTxsDiff oldTxs newTxs = getOldTxs oldTxs \\ getNewTxs newTxs blocksNE :: NE Block blocksNE = fst <$> getNewestFirst blunds ---------------------------------------------------------------------------- -- Common ---------------------------------------------------------------------------- -- Return a map from @Page@ to @HeaderHash@es for all non-empty blocks. pageBlocksMap :: NE Block -> M.Map Page [HeaderHash] pageBlocksMap neBlocks = blocksPages where -- | Finally, create a map from @Page@ to a list of @HeaderHash@. In other words, -- group all blocks @HeaderHash@ to corresponding @Page@. blocksPages :: M.Map Page [HeaderHash] blocksPages = M.fromListWith (++) [ (k, [v]) | (k, v) <- createPagedHeaderHashesPair blocks] where -- | Get blocks as list. blocks :: [Block] blocks = NE.toList neBlocks -- | Creates paged @HeaderHash@es @SlotId@ pair. -- TODO(ks): Yes, we can extract both these functions in one common function for paging. createPagedHeaderHashesSlotIdPair :: [Block] -> [(Page, HeaderHash)] createPagedHeaderHashesSlotIdPair blocks = blockIndexBlock where -- Zip the @Page@ number with the @HeaderHash@ we can use to retrieve block. blockIndexBlock :: [(Page, HeaderHash)] blockIndexBlock = blockPages `zip` blocksHHs where blocksHHs :: [HeaderHash] blocksHHs = headerHash <$> blocks -- | Calculate which block index goes into which page blockPages :: [Page] blockPages = getCurrentPage <$> blockIndexes where -- | Get the page the index belongs to. getCurrentPage :: Int -> Page getCurrentPage blockIndex = ((blockIndex - 1) `div` defaultPageSize) + 1 -- | Get the blocks index numbers. blockIndexes :: [Int] blockIndexes = getBlockIndex <$> blocks where -- | Get the block index number. We start with the the index 1 for the -- genesis block and add 1 for the main blocks since they start with 1 -- as well. getBlockIndex :: Block -> Int getBlockIndex (Left _) = 1 getBlockIndex (Right block) = fromIntegral $ (+1) $ getSlotIndex $ siSlot $ block ^. mainBlockSlot -- | Creates paged @HeaderHash@es pair. -- TODO(ks): Yes, we can extract both these functions in one common function for paging. createPagedHeaderHashesPair :: [Block] -> [(Page, HeaderHash)] createPagedHeaderHashesPair blocks = blockIndexBlock where -- Zip the @Page@ number with the @HeaderHash@ we can use to retrieve block. blockIndexBlock :: [(Page, HeaderHash)] blockIndexBlock = blockPages `zip` blocksHHs where blocksHHs :: [HeaderHash] blocksHHs = headerHash <$> blocks -- | Calculate which block index goes into which page blockPages :: [Page] blockPages = getCurrentPage <$> blockIndexes where -- | Get the page the index belongs to. getCurrentPage :: Int -> Page getCurrentPage blockIndex = ((blockIndex - 1) `div` defaultPageSize) + 1 -- | Get the blocks index numbers. blockIndexes :: [Int] blockIndexes = getBlockIndex <$> blocks where -- | Get the block index number. getBlockIndex :: Block -> Int getBlockIndex block = fromIntegral $ getChainDifficulty $ block ^. difficultyL -- So the parameters can be type checked. newtype PrevKBlocks k = PrevKBlocks { getPrevKBlocks :: M.Map k [HeaderHash] } newtype NewKBlocks k = NewKBlocks { getNewKBlocks :: M.Map k [HeaderHash] } -- The result is the map that contains diffed blocks from the keys. rollbackedBlocks :: forall a . (Ord a) => [a] -> PrevKBlocks a -> NewKBlocks a -> M.Map a [HeaderHash] rollbackedBlocks keys' oldMap' newMap' = M.unions rolledbackKeyMaps where rolledbackKeyMaps = [ rollbackedKey key oldMap' newMap' | key <- keys' ] -- From a single key, retrieve blocks and return their difference rollbackedKey :: a -> PrevKBlocks a -> NewKBlocks a -> M.Map a [HeaderHash] rollbackedKey key oldMap newMap = elementsExist where newBlocks' :: [HeaderHash] newBlocks' = getNewKBlocks newMap ^. at key . non [] existingBlocks :: [HeaderHash] existingBlocks = getPrevKBlocks oldMap ^. at key . non [] elementsExist :: M.Map a [HeaderHash] elementsExist = M.singleton key finalBlocks where -- Rollback the new blocks, remove them from the collection finalBlocks :: [HeaderHash] finalBlocks = existingBlocks \\ newBlocks' -- The repetitions can be extracted class (Ord k) => KeyBlocksOperation k where putKeyBlocksF :: (k -> [HeaderHash] -> DB.ExplorerOp) getKeyBlocksF :: (MonadDBRead m) => (k -> m (Maybe [HeaderHash])) instance KeyBlocksOperation (Epoch, Page) where putKeyBlocksF (epoch, page) = DB.PutEpochBlocks epoch page getKeyBlocksF (epoch, page) = DB.getEpochBlocks epoch page instance KeyBlocksOperation Page where putKeyBlocksF = DB.PutPageBlocks getKeyBlocksF = DB.getPageBlocks -- For each (k, [v]) pair, create a database operation. putKeysBlocks :: forall k . (KeyBlocksOperation k) => M.Map k [HeaderHash] -> [DB.ExplorerOp] putKeysBlocks keysBlocks = putKeyBlocks <$> M.toList keysBlocks where putKeyBlocks :: (k, [HeaderHash]) -> DB.ExplorerOp putKeyBlocks keyBlocks = putKeyBlocksF key uniqueBlocks where key = keyBlocks ^. _1 blocks = keyBlocks ^. _2 uniqueBlocks = ordNub blocks -- Get exisiting key blocks paired with the key. getExistingBlocks :: forall k m. (MonadDBRead m, KeyBlocksOperation k) => [k] -> m (M.Map k [HeaderHash]) getExistingBlocks keys = do keyBlocks <- traverse getExistingKeyBlocks keys pure $ M.unions keyBlocks where -- Get exisiting key blocks paired with the key. If there are no -- saved blocks on the key return an empty list. getExistingKeyBlocks :: k -> m (M.Map k [HeaderHash]) getExistingKeyBlocks key = do mKeyBlocks <- getKeyBlocksF key let keyBlocks = fromMaybe [] mKeyBlocks pure $ M.singleton key keyBlocks -- A general @Key@ @Block@ database application for the apply call. {-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-} onApplyKeyBlocksGeneral :: forall k m. (MonadBListenerT m, KeyBlocksOperation k) => OldestFirst NE Blund -> (NE Block -> M.Map k [HeaderHash]) -> m SomeBatchOp onApplyKeyBlocksGeneral blunds newBlocksMapF = do -- Get existing @HeaderHash@es from the keys so we can merge them. existingBlocks <- getExistingBlocks keys -- Merge the new and the old let mergedBlocksMap = M.unionWith (<>) existingBlocks newBlocks -- Create database operation let mergedBlocks = putKeysBlocks mergedBlocksMap -- In the end make sure we place this under @SomeBatchOp@ in order to -- preserve atomicity. pure $ SomeBatchOp mergedBlocks where keys :: [k] keys = M.keys newBlocks newBlocks :: M.Map k [HeaderHash] newBlocks = newBlocksMapF blocksNE blocksNE :: NE Block blocksNE = fst <$> getNewestFirst blocksNewF blocksNewF :: NewestFirst NE Blund blocksNewF = toNewestFirst blunds -- A general @Key@ @Block@ database application for the rollback call. {-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-} onRollbackGeneralBlocks :: forall k m. (MonadBListenerT m, KeyBlocksOperation k) => NewestFirst NE Blund -> (NE Block -> M.Map k [HeaderHash]) -> m SomeBatchOp onRollbackGeneralBlocks blunds newBlocksMapF = do -- Get existing @HeaderHash@es from the keys so we can merge them. existingBlocks <- getExistingBlocks keys let prevKeyBlocks = PrevKBlocks existingBlocks let newKeyBlocks = NewKBlocks newBlocks -- Diffrence between the new and the old let mergedBlocksMap = rollbackedBlocks keys prevKeyBlocks newKeyBlocks -- Create database operation let mergedBlocks = putKeysBlocks mergedBlocksMap -- In the end make sure we place this under @SomeBatchOp@ in order to -- preserve atomicity. pure $ SomeBatchOp mergedBlocks where keys :: [k] keys = M.keys newBlocks newBlocks :: M.Map k [HeaderHash] newBlocks = newBlocksMapF blocksNE blocksNE :: NE Block blocksNE = fst <$> getNewestFirst blunds -- Wrappers so I don't mess up the parameter order newtype OldTxs = OldTxs { getOldTxs :: [Tx] } newtype NewTxs = NewTxs { getNewTxs :: [Tx] } -- If you give me non-empty blocks that contain transactions and a way to -- combine old and new transactions I will return you an -- atomic database operation. generalLastTxsExplorer :: MonadBListenerT m => NE Block -> (OldTxs -> NewTxs -> [Tx]) -> m SomeBatchOp generalLastTxsExplorer blocksNE getTopTxsDiff = do let newTxs = NewTxs mainBlocksTxs mPrevTopTxs <- DB.getLastTransactions let prevTopTxs = OldTxs $ fromMaybe [] mPrevTopTxs let newTopTxs = getTopTxsDiff prevTopTxs newTxs -- Create database operation let mergedTopTxs = DB.PutLastTxs newTopTxs -- In the end make sure we place this under @SomeBatchOp@ in order to -- preserve atomicity. pure $ SomeBatchOp mergedTopTxs where mainBlocksTxs :: [Tx] mainBlocksTxs = concat $ catMaybes mMainBlocksTxs mMainBlocksTxs :: [Maybe [Tx]] mMainBlocksTxs = blockTxs <$> mainBlocks blockTxs :: MainBlock -> Maybe [Tx] blockTxs mb = topsortTxs withHash $ toList $ mb ^. mainBlockTxPayload . txpTxs mainBlocks :: [MainBlock] mainBlocks = rights blocks blocks :: [Block] blocks = NE.toList blocksNE ---------------------------------------------------------------------------- -- Epoch paged map -- TODO(ks): I know, I know, it could be more general, but let's worry about -- that when we have more time. ---------------------------------------------------------------------------- -- Return a map from @Epoch@ to @HeaderHash@es for all non-empty blocks. epochPagedBlocksMap :: NE (Block) -> M.Map EpochPagedBlocksKey [HeaderHash] epochPagedBlocksMap neBlocks = getPagedEpochHeaderHashesMap where -- | Get a map from the "composite key" of @Epoch@ and @Page@ that return a list of -- @HeaderHash@es on that @Page@ in that @Epoch@. getPagedEpochHeaderHashesMap :: M.Map EpochPagedBlocksKey [HeaderHash] getPagedEpochHeaderHashesMap = M.fromListWith (++) [ (k, [v]) | (k, v) <- epochPagedHeaderHashes] where epochPagedHeaderHashes :: [(EpochPagedBlocksKey, HeaderHash)] epochPagedHeaderHashes = concat $ createEpochPagedHeaderHashes <$> getAllEpochs where getAllEpochs :: [Epoch] getAllEpochs = M.keys blocksEpochs createEpochPagedHeaderHashes :: Epoch -> [(EpochPagedBlocksKey, HeaderHash)] createEpochPagedHeaderHashes epoch = createEpochPageHHAssoc epoch <$> pageBlocks where -- | Get @HeaderHash@es grouped by @Page@ inside an @Epoch@. pageBlocks :: [(Page, HeaderHash)] pageBlocks = createPagedHeaderHashesSlotIdPair $ getEpochHeaderHashes epoch where getEpochHeaderHashes :: Epoch -> [Block] getEpochHeaderHashes epochKey = case blocksEpochs ^. at epochKey of Nothing -> [] Just blocks' -> blocks' -- | Just add @Epoch@ to the @(Page, HeaderHash)@ pair, so we can group -- @Epoch@ and @Page@ and reuse it like a composite key. createEpochPageHHAssoc :: Epoch -> (Page, HeaderHash) -> (EpochPagedBlocksKey, HeaderHash) createEpochPageHHAssoc epoch' pageBlock = ((epoch', pageBlock ^. _1), pageBlock ^. _2) -- | Finally, create a map from @Epoch@ to a list of @HeaderHash@. In other words, -- group all blocks @HeaderHash@ to corresponding @Epoch@. blocksEpochs :: M.Map Epoch [Block] blocksEpochs = M.fromListWith (++) [ (k, [v]) | (k, v) <- blockEpochs] where blockEpochs :: [(Epoch, Block)] blockEpochs = getBlockEpoch <$> blocks where getBlockEpoch :: Block -> (Epoch, Block) getBlockEpoch block = (block ^. epochIndexL, block) -- | Get blocks as list. blocks :: [Block] blocks = NE.toList neBlocks -- A general @Key@ @Block@ database application for the apply call. {-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-} onApplyEpochPagedBlocks :: forall m. ( MonadBListenerT m ) => OldestFirst NE (Blund) -> m SomeBatchOp onApplyEpochPagedBlocks blunds = do -- Get existing @HeaderHash@es from the keys so we can merge them. existingBlocks <- getExistingBlocks keys -- Merge the new and the old let mergedBlocksMap = M.unionWith (<>) existingBlocks newBlocks -- Find the maximum page number for each @Epoch@. let maxPagesEpochBlocks = findEpochMaxPages mergedBlocksMap let epochMaxPages = [ DB.PutEpochPages epoch maxPageNumber | (epoch, maxPageNumber) <- maxPagesEpochBlocks] -- Create database operation let mergedBlocks = putKeysBlocks mergedBlocksMap -- In the end make sure we place this under @SomeBatchOp@ in order to -- preserve atomicity. pure $ SomeBatchOp [mergedBlocks, epochMaxPages] where keys :: [EpochPagedBlocksKey] keys = M.keys newBlocks newBlocks :: M.Map EpochPagedBlocksKey [HeaderHash] newBlocks = epochPagedBlocksMap blocksNE blocksNE :: NE (Block) blocksNE = fst <$> getNewestFirst blocksNewF blocksNewF :: NewestFirst NE (Blund) blocksNewF = toNewestFirst blunds -- A general @Key@ @Block@ database application for the rollback call. {-# ANN module ("HLint: ignore Reduce duplication" :: Text) #-} onRollbackEpochPagedBlocks :: forall m. ( MonadBListenerT m ) => NewestFirst NE (Blund) -> m SomeBatchOp onRollbackEpochPagedBlocks blunds = do -- Get existing @HeaderHash@es from the keys so we can merge them. existingBlocks <- getExistingBlocks keys let prevKeyBlocks = PrevKBlocks existingBlocks let newKeyBlocks = NewKBlocks newBlocks -- Diffrence between the new and the old let mergedBlocksMap = rollbackedBlocks keys prevKeyBlocks newKeyBlocks -- Create database operation let mergedBlocks = putKeysBlocks mergedBlocksMap -- In the end make sure we place this under @SomeBatchOp@ in order to -- preserve atomicity. pure $ SomeBatchOp mergedBlocks where keys :: [EpochPagedBlocksKey] keys = M.keys newBlocks newBlocks :: M.Map EpochPagedBlocksKey [HeaderHash] newBlocks = epochPagedBlocksMap blocksNE blocksNE :: NE (Block) blocksNE = fst <$> getNewestFirst blunds
input-output-hk/pos-haskell-prototype
explorer/src/Pos/Explorer/BListener.hs
mit
21,239
0
18
5,172
3,882
2,114
1,768
-1
-1
-- | -- Description : Lower-level registry access wrappers -- Copyright : (c) 2015 Egor Tensin <Egor.Tensin@gmail.com> -- License : MIT -- Maintainer : Egor.Tensin@gmail.com -- Stability : experimental -- Portability : Windows-only -- -- Lower-level functions for reading and writing registry values. {-# LANGUAGE CPP #-} module WindowsEnv.Registry ( IsKeyPath(..) , RootKey(..) , KeyPath(..) , ValueName , ValueType(..) , Value , StringValue , openKey , closeKey , deleteValue , queryValue , queryValueType , getValue , GetValueFlag(..) , getValueType , getStringValue , setValue , setStringValue ) where import Control.Exception (bracket) import Control.Monad.Trans.Except (ExceptT(..)) import Data.Bits ((.|.)) import qualified Data.ByteString as B import Data.List (intercalate) import Data.Maybe (fromJust) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf16LE, encodeUtf16LE) import Data.Tuple (swap) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Marshal.Alloc (alloca, allocaBytes) import Foreign.Marshal.Array (peekArray, pokeArray) import Foreign.Storable (peek, poke) import System.IO.Error (tryIOError) import qualified System.Win32.Types as WinAPI import qualified System.Win32.Registry as WinAPI type Handle = WinAPI.HKEY class IsKeyPath a where openKeyUnsafe :: a -> IO Handle closeKey :: Handle -> IO () closeKey = WinAPI.regCloseKey openKey :: IsKeyPath a => a -> IO (Either IOError Handle) openKey keyPath = tryIOError $ openKeyUnsafe keyPath withHandle :: IsKeyPath a => a -> (Handle -> IO b) -> ExceptT IOError IO b withHandle keyPath f = ExceptT $ tryIOError doWithHandle where doWithHandle = bracket (openKeyUnsafe keyPath) closeKey f data RootKey = CurrentUser | LocalMachine deriving (Eq) instance IsKeyPath RootKey where openKeyUnsafe CurrentUser = return WinAPI.hKEY_CURRENT_USER openKeyUnsafe LocalMachine = return WinAPI.hKEY_LOCAL_MACHINE instance Show RootKey where show CurrentUser = "HKCU" show LocalMachine = "HKLM" data KeyPath = KeyPath RootKey [String] keyPathSep :: String keyPathSep = "\\" instance IsKeyPath KeyPath where openKeyUnsafe (KeyPath root path) = do rootHandle <- openKeyUnsafe root WinAPI.regOpenKey rootHandle $ intercalate keyPathSep path instance Show KeyPath where show (KeyPath root path) = intercalate keyPathSep $ show root : path type ValueName = String data ValueType = TypeNone | TypeBinary | TypeDWord | TypeDWordBE | TypeQWord | TypeString | TypeMultiString | TypeExpandableString | TypeLink deriving (Eq, Show) instance Enum ValueType where fromEnum = fromJust . flip lookup valueTypeNumbers toEnum = fromJust . flip lookup (map swap valueTypeNumbers) valueTypeNumbers :: [(ValueType, Int)] valueTypeNumbers = [ (TypeNone, 0) , (TypeBinary, 3) , (TypeDWord, 4) , (TypeDWordBE, 5) , (TypeQWord, 11) , (TypeString, 1) , (TypeMultiString, 7) , (TypeExpandableString, 2) , (TypeLink, 6) ] type Value = (ValueType, B.ByteString) type StringValue = (ValueType, String) encodeString :: StringValue -> Value encodeString (valueType, valueData) = (valueType, encodeUtf16LE addLastZero) where addLastZero | T.null text = text | T.last text == '\0' = text | otherwise = T.snoc text '\0' text = T.pack valueData decodeString :: Value -> StringValue decodeString (valueType, valueData) = (valueType, T.unpack dropLastZero) where dropLastZero | T.null text = text | otherwise = T.takeWhile (/= '\0') text text = decodeUtf16LE valueData #include "windows_cconv.h" -- These aren't provided by Win32 (as of version 2.4.0.0). foreign import WINDOWS_CCONV unsafe "Windows.h RegQueryValueExW" c_RegQueryValueEx :: WinAPI.PKEY -> WinAPI.LPCTSTR -> WinAPI.LPDWORD -> WinAPI.LPDWORD -> WinAPI.LPBYTE -> WinAPI.LPDWORD -> IO WinAPI.ErrCode foreign import WINDOWS_CCONV unsafe "Windows.h RegSetValueExW" c_RegSetValueEx :: WinAPI.PKEY -> WinAPI.LPCTSTR -> WinAPI.DWORD -> WinAPI.DWORD -> WinAPI.LPBYTE -> WinAPI.DWORD -> IO WinAPI.ErrCode foreign import WINDOWS_CCONV unsafe "Windows.h RegGetValueW" c_RegGetValue :: WinAPI.PKEY -> WinAPI.LPCTSTR -> WinAPI.LPCTSTR -> WinAPI.DWORD -> WinAPI.LPDWORD -> WinAPI.LPBYTE -> WinAPI.LPDWORD -> IO WinAPI.ErrCode queryValue :: IsKeyPath a => a -> ValueName -> ExceptT IOError IO Value queryValue keyPath valueName = withHandle keyPath $ \keyHandle -> withForeignPtr keyHandle $ \keyHandlePtr -> WinAPI.withTString valueName $ \valueNamePtr -> alloca $ \valueSizePtr -> do poke valueSizePtr 0 WinAPI.failUnlessSuccess "RegQueryValueExW" $ c_RegQueryValueEx keyHandlePtr valueNamePtr WinAPI.nullPtr WinAPI.nullPtr WinAPI.nullPtr valueSizePtr valueSize <- fromIntegral <$> peek valueSizePtr alloca $ \valueTypePtr -> allocaBytes valueSize $ \bufferPtr -> do WinAPI.failUnlessSuccess "RegQueryValueExW" $ c_RegQueryValueEx keyHandlePtr valueNamePtr WinAPI.nullPtr valueTypePtr bufferPtr valueSizePtr buffer <- B.pack <$> peekArray valueSize bufferPtr valueType <- toEnum . fromIntegral <$> peek valueTypePtr return (valueType, buffer) queryValueType :: IsKeyPath a => a -> ValueName -> ExceptT IOError IO ValueType queryValueType keyPath valueName = withHandle keyPath $ \keyHandle -> withForeignPtr keyHandle $ \keyHandlePtr -> WinAPI.withTString valueName $ \valueNamePtr -> alloca $ \valueTypePtr -> do WinAPI.failUnlessSuccess "RegQueryValueExW" $ c_RegQueryValueEx keyHandlePtr valueNamePtr WinAPI.nullPtr valueTypePtr WinAPI.nullPtr WinAPI.nullPtr toEnum . fromIntegral <$> peek valueTypePtr data GetValueFlag = RestrictAny | RestrictNone | RestrictBinary | RestrictDWord | RestrictQWord | RestrictString | RestrictMultiString | RestrictExpandableString | DoNotExpand deriving (Eq, Show) instance Enum GetValueFlag where fromEnum = fromJust . flip lookup getValueFlagNumbers toEnum = fromJust . flip lookup (map swap getValueFlagNumbers) getValueFlagNumbers :: [(GetValueFlag, Int)] getValueFlagNumbers = [ (RestrictAny, 0x0000ffff) , (RestrictNone, 0x00000001) , (RestrictBinary, 0x00000008) , (RestrictDWord, 0x00000010) , (RestrictQWord, 0x00000040) , (RestrictString, 0x00000002) , (RestrictMultiString, 0x00000020) , (RestrictExpandableString, 0x00000004) , (DoNotExpand, 0x10000000) ] collapseGetValueFlags :: Num a => [GetValueFlag] -> a collapseGetValueFlags = fromIntegral . foldr ((.|.) . fromEnum) 0 getValue :: IsKeyPath a => a -> ValueName -> [GetValueFlag] -> ExceptT IOError IO Value getValue keyPath valueName flags = withHandle keyPath $ \keyHandle -> withForeignPtr keyHandle $ \keyHandlePtr -> WinAPI.withTString valueName $ \valueNamePtr -> alloca $ \valueSizePtr -> do poke valueSizePtr 0 WinAPI.failUnlessSuccess "RegGetValueW" $ c_RegGetValue keyHandlePtr WinAPI.nullPtr valueNamePtr collapsedFlags WinAPI.nullPtr WinAPI.nullPtr valueSizePtr bufferCapacity <- fromIntegral <$> peek valueSizePtr alloca $ \valueTypePtr -> allocaBytes bufferCapacity $ \bufferPtr -> do WinAPI.failUnlessSuccess "RegGetValueW" $ c_RegGetValue keyHandlePtr WinAPI.nullPtr valueNamePtr collapsedFlags valueTypePtr bufferPtr valueSizePtr bufferSize <- fromIntegral <$> peek valueSizePtr buffer <- B.pack <$> peekArray bufferSize bufferPtr valueType <- toEnum . fromIntegral <$> peek valueTypePtr return (valueType, buffer) where collapsedFlags = collapseGetValueFlags $ DoNotExpand : flags getValueType :: IsKeyPath a => a -> ValueName -> [GetValueFlag] -> ExceptT IOError IO ValueType getValueType keyPath valueName flags = withHandle keyPath $ \keyHandle -> withForeignPtr keyHandle $ \keyHandlePtr -> WinAPI.withTString valueName $ \valueNamePtr -> alloca $ \valueTypePtr -> do WinAPI.failUnlessSuccess "RegGetValueW" $ c_RegGetValue keyHandlePtr WinAPI.nullPtr valueNamePtr collapsedFlags valueTypePtr WinAPI.nullPtr WinAPI.nullPtr toEnum . fromIntegral <$> peek valueTypePtr where collapsedFlags = collapseGetValueFlags $ DoNotExpand : flags getStringValue :: IsKeyPath a => a -> ValueName -> ExceptT IOError IO StringValue getStringValue keyPath valueName = decodeString <$> getValue keyPath valueName [RestrictExpandableString, RestrictString] setValue :: IsKeyPath a => a -> ValueName -> Value -> ExceptT IOError IO () setValue keyPath valueName (valueType, valueData) = withHandle keyPath $ \keyHandle -> withForeignPtr keyHandle $ \keyHandlePtr -> WinAPI.withTString valueName $ \valueNamePtr -> allocaBytes bufferSize $ \bufferPtr -> do pokeArray bufferPtr buffer WinAPI.failUnlessSuccess "RegSetValueExW" $ c_RegSetValueEx keyHandlePtr valueNamePtr 0 rawValueType bufferPtr (fromIntegral bufferSize) where rawValueType = fromIntegral $ fromEnum valueType buffer = B.unpack valueData bufferSize = B.length valueData setStringValue :: IsKeyPath a => a -> ValueName -> StringValue -> ExceptT IOError IO () setStringValue keyPath valueName value = setValue keyPath valueName $ encodeString value deleteValue :: IsKeyPath a => a -> ValueName -> ExceptT IOError IO () deleteValue keyPath valueName = withHandle keyPath $ \keyHandle -> withForeignPtr keyHandle $ \keyHandlePtr -> WinAPI.withTString valueName $ \valueNamePtr -> WinAPI.failUnlessSuccess "RegDeleteValueW" $ WinAPI.c_RegDeleteValue keyHandlePtr valueNamePtr
egor-tensin/windows-env
src/WindowsEnv/Registry.hs
mit
10,476
17
23
2,552
2,597
1,371
1,226
-1
-1
{-# 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.CloudWatchLogs.CreateLogStream -- Copyright : (c) 2013-2015 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a new log stream in the specified log group. The name of the log -- stream must be unique within the log group. There is no limit on the -- number of log streams that can exist in a log group. -- -- You must use the following guidelines when naming a log stream: -- -- - Log stream names can be between 1 and 512 characters long. -- - The \':\' colon character is not allowed. -- -- /See:/ <http://docs.aws.amazon.com/AmazonCloudWatchLogs/latest/APIReference/API_CreateLogStream.html AWS API Reference> for CreateLogStream. module Network.AWS.CloudWatchLogs.CreateLogStream ( -- * Creating a Request createLogStream , CreateLogStream -- * Request Lenses , clsLogGroupName , clsLogStreamName -- * Destructuring the Response , createLogStreamResponse , CreateLogStreamResponse ) where import Network.AWS.CloudWatchLogs.Types import Network.AWS.CloudWatchLogs.Types.Product import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response -- | /See:/ 'createLogStream' smart constructor. data CreateLogStream = CreateLogStream' { _clsLogGroupName :: !Text , _clsLogStreamName :: !Text } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateLogStream' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'clsLogGroupName' -- -- * 'clsLogStreamName' createLogStream :: Text -- ^ 'clsLogGroupName' -> Text -- ^ 'clsLogStreamName' -> CreateLogStream createLogStream pLogGroupName_ pLogStreamName_ = CreateLogStream' { _clsLogGroupName = pLogGroupName_ , _clsLogStreamName = pLogStreamName_ } -- | The name of the log group under which the log stream is to be created. clsLogGroupName :: Lens' CreateLogStream Text clsLogGroupName = lens _clsLogGroupName (\ s a -> s{_clsLogGroupName = a}); -- | The name of the log stream to create. clsLogStreamName :: Lens' CreateLogStream Text clsLogStreamName = lens _clsLogStreamName (\ s a -> s{_clsLogStreamName = a}); instance AWSRequest CreateLogStream where type Rs CreateLogStream = CreateLogStreamResponse request = postJSON cloudWatchLogs response = receiveNull CreateLogStreamResponse' instance ToHeaders CreateLogStream where toHeaders = const (mconcat ["X-Amz-Target" =# ("Logs_20140328.CreateLogStream" :: ByteString), "Content-Type" =# ("application/x-amz-json-1.1" :: ByteString)]) instance ToJSON CreateLogStream where toJSON CreateLogStream'{..} = object (catMaybes [Just ("logGroupName" .= _clsLogGroupName), Just ("logStreamName" .= _clsLogStreamName)]) instance ToPath CreateLogStream where toPath = const "/" instance ToQuery CreateLogStream where toQuery = const mempty -- | /See:/ 'createLogStreamResponse' smart constructor. data CreateLogStreamResponse = CreateLogStreamResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'CreateLogStreamResponse' with the minimum fields required to make a request. -- createLogStreamResponse :: CreateLogStreamResponse createLogStreamResponse = CreateLogStreamResponse'
olorin/amazonka
amazonka-cloudwatch-logs/gen/Network/AWS/CloudWatchLogs/CreateLogStream.hs
mpl-2.0
4,082
0
12
870
485
292
193
69
1
module Haskus.Tests.Format where import Test.Tasty testsFormat :: TestTree testsFormat = testGroup "Format" [ ]
hsyl20/ViperVM
haskus-system/src/tests/Haskus/Tests/Format.hs
bsd-3-clause
120
0
6
22
29
17
12
5
1
import Database.DSH
ulricha/dsh
Test.hs
bsd-3-clause
21
0
4
3
6
3
3
1
0
module Chap11 where import Data.Char import Data.List computeShift :: Char -> Int computeShift c = ord c - ord 'A' encodeChar :: Char -> Char -> Char encodeChar ' ' _ = ' ' encodeChar c e = chr (ord(c) + shift) where shift = computeShift e encode :: String -> String encode = map (\x -> x) -- foo :: String -> String -> String -- foo s cipher = foldr () "" s -- cipher = "ALLY" -- isSubsequenceOf :: (Eq a) => [a] -> [a] -> Bool -- isSubsequenceOf [] _ = True -- isSubsequenceOf _ [] = False -- isSubsequenceOf x'@(x:xs) (y:ys) = case x == y of -- True -> isSubsequenceOf xs ys -- False -> isSubsequenceOf x' ys capitalizeWord :: String -> String capitalizeWord (x:xs) = toUpper(x):xs capitalizeWords :: String -> [(String, String)] capitalizeWords s = map (\x -> (x,capitalizeWord x)) $ words s capitalizeParagraph :: String -> String capitalizeParagraph p = unwords $ map capitalizeWord $ words p type PhoneDigit = Char type PhoneChar = Char data Key = Key PhoneDigit [PhoneChar] deriving(Eq, Show) data DaPhone = DaPhone [Key] deriving (Eq, Show) phone = DaPhone [(Key '1' ""), (Key '2' "abc"), (Key '3' "def"), (Key '4' "ghi"), (Key '5' "jkl"), (Key '6' "mno"), (Key '7' "pqrs"), (Key '8' "tuv"), (Key '9' "wxyz"), (Key '*' "^"), (Key '0' " +"), (Key '#' ".,")] type Digit = Char -- Valid presses: 1 and up type Presses = Int -- findKey phone 'A' -> [('2', 1)] findKey :: DaPhone -> Char -> Key findKey (DaPhone (theKey@(Key digit vals):ks)) k = case digit == k of True -> theKey False -> findKey (DaPhone ks) k findDigitPresses :: DaPhone -> Char -> [(Digit, Presses)] findDigitPresses phone@(DaPhone (theKey@(Key digit vals):ks)) k = case isUpper k of True -> [('*', 1)] ++ findDigitPresses phone (toLower k) False -> case (elemIndex k vals) of Just(idx) -> [(digit, idx + 1)] Nothing -> findDigitPresses (DaPhone ks) k reverseTaps :: DaPhone -> Char -> [(Digit, Presses)] reverseTaps phone c = findDigitPresses phone c convo :: [String] convo = ["Wanna play 20 questions", "Ya", "U 1st haha", "Lol ok. Have u ever tasted alcohol lol", "Lol ya", "Wow ur cool haha. Ur turn", "Ok. Do u think I am pretty Lol", "Lol ya", "Haha thanks just making sure rofl ur turn"] flatten = foldr (\x y -> x ++ y) [] cellPhonesDead :: DaPhone -> String -> [(Digit, Presses)] cellPhonesDead phone w = flatten $ map (reverseTaps phone) w fingerTaps :: [(Digit, Presses)] -> Presses fingerTaps [] = 0 fingerTaps ((digit, presses):r) = presses + fingerTaps r -- mostPopularLetters :: String -> Char data Expr = Lit Integer | Add Expr Expr eval :: Expr -> Integer eval (Lit i) = i eval (Add e1 e2) = (eval e1) + (eval e2) printExpr :: Expr -> String printExpr (Lit i) = show i printExpr (Add e1 e2) = (printExpr e1) ++ " + " ++ (printExpr e2)
punitrathore/haskell-first-principles
src/Chap11.hs
bsd-3-clause
3,053
0
13
819
1,040
566
474
71
3
{-# LANGUAGE NoImplicitPrelude, TemplateHaskell, TypeFamilies, DeriveDataTypeable, FlexibleInstances, UndecidableInstances #-} import Math.Combinatorics.Species import Math.Combinatorics.Species.Types import Math.Combinatorics.Species.AST import Math.Combinatorics.Species.AST.Instances import Data.Typeable import NumericPrelude data Tree2C = Tree2C deriving (Typeable, Show) type instance Interp Tree2C self = Sum Unit (Prod self (Prod Id self)) data Tree2 a = Leaf2 | Node2 (Tree2 a) a (Tree2 a) deriving Show instance ASTFunctor Tree2C where apply _ self = annI TOne :+: annI (annI self :*: annI (annI TX :*: annI self)) instance Show a => Show (Mu Tree2C a) where show = show . unMu instance Enumerable Tree2 where type StructTy Tree2 = Mu Tree2C iso (Mu (Inl _)) = Leaf2 iso (Mu (Inr (Prod l (Prod (Id a) r)))) = Node2 (iso l) a (iso r) tree2 :: Species s => s tree2 = rec Tree2C main = do print $ (enumerate tree2 [1,2] :: [Tree2 Int])
timsears/species
test/TreeTest.hs
bsd-3-clause
1,034
0
16
234
363
191
172
29
1
{-# LANGUAGE ExistentialQuantification #-} module Data.Generics.Any where import Control.Exception import Control.Monad.Trans.State import qualified Data.Data as D import Data.Data hiding (toConstr, typeOf, dataTypeOf, isAlgType) import Data.List import Data.Maybe import qualified Data.Typeable.Internal as I import System.IO.Unsafe type CtorName = String type FieldName = String readTupleType :: String -> Maybe Int readTupleType x | "(" `isPrefixOf` x && ")" `isSuffixOf` x && all (== ',') y = Just $ length y | otherwise = Nothing where y = init $ tail x try1 :: a -> Either SomeException a try1 = unsafePerformIO . try . evaluate --------------------------------------------------------------------- -- BASIC TYPES -- | Any value, with a Data dictionary. data Any = forall a . Data a => Any a type AnyT t = Any instance Show Any where show = show . typeOf fromAny :: Typeable a => Any -> a fromAny (Any x) = case D.cast x of Just y -> y ~(Just y) -> error $ "Data.Generics.Any.fromAny: Failed to extract any, got " ++ show (D.typeOf x) ++ ", wanted " ++ show (D.typeOf y) cast :: Typeable a => Any -> Maybe a cast (Any x) = D.cast x --------------------------------------------------------------------- -- SYB COMPATIBILITY toConstr :: Any -> Constr toConstr (Any x) = D.toConstr x typeOf :: Any -> TypeRep typeOf (Any x) = D.typeOf x dataTypeOf :: Any -> DataType dataTypeOf (Any x) = D.dataTypeOf x isAlgType :: Any -> Bool isAlgType = D.isAlgType . dataTypeOf --------------------------------------------------------------------- -- TYPE STUFF typeShell :: Any -> String typeShell = tyconUQname . typeShellFull typeShellFull :: Any -> String typeShellFull = I.tyConName . typeRepTyCon . typeOf typeName :: Any -> String typeName = show . typeOf --------------------------------------------------------------------- -- ANY PRIMITIVES ctor :: Any -> CtorName ctor = showConstr . toConstr fields :: Any -> [String] fields = constrFields . toConstr children :: Any -> [Any] children (Any x) = gmapQ Any x compose0 :: Any -> CtorName -> Any compose0 x c | either (const False) (== c) $ try1 $ ctor x = x compose0 (Any x) c = Any $ fromConstrB err y `asTypeOf` x where Just y = readConstr (D.dataTypeOf x) c err = error $ "Data.Generics.Any: Undefined field inside compose0, " ++ c ++ " :: " ++ show (Any x) recompose :: Any -> [Any] -> Any recompose (Any x) cs | null s = Any $ res `asTypeOf` x | otherwise = err where (res,s) = runState (fromConstrM field $ D.toConstr x) cs field :: Data d => State [Any] d field = do cs <- get if null cs then err else do put $ tail cs return $ fromAny $ head cs err = error $ "Data.Generics.Any.recompose: Incorrect number of children to recompose, " ++ ctor (Any x) ++ " :: " ++ show (Any x) ++ ", expected " ++ show (arity $ Any x) ++ ", got " ++ show (length cs) ctors :: Any -> [CtorName] ctors = map showConstr . dataTypeConstrs . dataTypeOf --------------------------------------------------------------------- -- DERIVED FUNCTIONS decompose :: Any -> (CtorName,[Any]) decompose x = (ctor x, children x) arity = length . children compose :: Any -> CtorName -> [Any] -> Any compose t c xs = recompose (compose0 t c) xs --------------------------------------------------------------------- -- FIELD UTILITIES getField :: FieldName -> Any -> Any getField lbl x = fromMaybe (error $ "getField: Could not find field " ++ show lbl) $ lookup lbl $ zip (fields x) (children x) setField :: (FieldName,Any) -> Any -> Any setField (lbl,child) parent | lbl `notElem` fs = error $ "setField: Could not find field " ++ show lbl | otherwise = recompose parent $ zipWith (\f c -> if f == lbl then child else c) fs cs where fs = fields parent cs = children parent
copland/cmdargs
Data/Generics/Any.hs
bsd-3-clause
4,014
0
16
943
1,316
688
628
82
2
module Data.CExtraChan where import Control.Applicative import Data.IORef import qualified Data.Sequence as S data ExtraChan a = ExtraChan { chan :: IORef (S.Seq a) , minEver :: IORef a , maxEver :: IORef a , lLength :: IORef Int } newExtraChan :: (Bounded a) => IO (ExtraChan a) newExtraChan = ExtraChan <$> newIORef S.empty <*> newIORef maxBound <*> newIORef minBound <*> newIORef 0 writeExtraChan :: (Ord a) => ExtraChan a -> a -> IO () writeExtraChan c a = do modifyIORef (chan c) (S.|> a) modifyIORef (minEver c) $ \oldMin -> min a oldMin modifyIORef (maxEver c) $ \oldMax -> max a oldMax modifyIORef (lLength c) $ (+1) readExtraChan :: ExtraChan a -> IO (Maybe a) readExtraChan c = do v <- S.viewl <$> readIORef (chan c) a <- case v of (a S.:< as) -> do writeIORef (chan c) as modifyIORef (lLength c) pred return $ Just a S.EmptyL -> return Nothing return a extraChanLength :: (Show a) => ExtraChan a -> IO Int extraChanLength = readIORef . lLength describe :: (Show a) => ExtraChan a -> IO String describe s = do c <- readIORef (chan s) min' <- readIORef (minEver s) max' <- readIORef (maxEver s) len' <- readIORef (lLength s) return $ unwords ["Chan:", show c ,"min':", show min' ,"max':", show max' ,"len':", show len' ]
imalsogreg/stm-demo
Data/CExtraChan.hs
bsd-3-clause
1,546
0
15
535
575
283
292
42
2
{-# LANGUAGE RankNTypes #-} {-# OPTIONS_GHC -fno-warn-missing-methods #-} {-| You can think of `Shell` as @[]@ + `IO` + `Managed`. In fact, you can embed all three of them within a `Shell`: > select :: [a] -> Shell a > liftIO :: IO a -> Shell a > using :: Managed a -> Shell a Those three embeddings obey these laws: > do { x <- select m; select (f x) } = select (do { x <- m; f x }) > do { x <- liftIO m; liftIO (f x) } = liftIO (do { x <- m; f x }) > do { x <- with m; using (f x) } = using (do { x <- m; f x }) > > select (return x) = return x > liftIO (return x) = return x > using (return x) = return x ... and `select` obeys these additional laws: > select xs <|> select ys = select (xs <|> ys) > select empty = empty You typically won't build `Shell`s using the `Shell` constructor. Instead, use these functions to generate primitive `Shell`s: * `empty`, to create a `Shell` that outputs nothing * `return`, to create a `Shell` that outputs a single value * `select`, to range over a list of values within a `Shell` * `liftIO`, to embed an `IO` action within a `Shell` * `using`, to acquire a `Managed` resource within a `Shell` Then use these classes to combine those primitive `Shell`s into larger `Shell`s: * `Alternative`, to concatenate `Shell` outputs using (`<|>`) * `Monad`, to build `Shell` comprehensions using @do@ notation If you still insist on building your own `Shell` from scratch, then the `Shell` you build must satisfy this law: > -- For every shell `s`: > _foldIO s (FoldM step begin done) = do > x <- begin > x' <- _foldIO s (FoldM step (return x) return) > done x' ... which is a fancy way of saying that your `Shell` must call @\'begin\'@ exactly once when it begins and call @\'done\'@ exactly once when it ends. -} module Turtle.Shell ( -- * Shell Shell(..) , foldIO , fold , sh , view -- * Embeddings , select , liftIO , using ) where import Control.Applicative (Applicative(..), Alternative(..), liftA2) import Control.Monad (MonadPlus(..), ap) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Managed (Managed, with) import Control.Foldl (Fold(..), FoldM(..)) import qualified Control.Foldl as Foldl import Data.Monoid (Monoid(..), (<>)) import Data.String (IsString(..)) -- | A @(Shell a)@ is a protected stream of @a@'s with side effects newtype Shell a = Shell { _foldIO :: forall r . FoldM IO a r -> IO r } -- | Use a @`FoldM` `IO`@ to reduce the stream of @a@'s produced by a `Shell` foldIO :: MonadIO io => Shell a -> FoldM IO a r -> io r foldIO s f = liftIO (_foldIO s f) -- | Use a `Fold` to reduce the stream of @a@'s produced by a `Shell` fold :: MonadIO io => Shell a -> Fold a b -> io b fold s f = foldIO s (Foldl.generalize f) -- | Run a `Shell` to completion, discarding any unused values sh :: MonadIO io => Shell a -> io () sh s = fold s (pure ()) -- | Run a `Shell` to completion, `print`ing any unused values view :: (MonadIO io, Show a) => Shell a -> io () view s = sh (do x <- s liftIO (print x) ) instance Functor Shell where fmap f s = Shell (\(FoldM step begin done) -> let step' x a = step x (f a) in _foldIO s (FoldM step' begin done) ) instance Applicative Shell where pure = return (<*>) = ap instance Monad Shell where return a = Shell (\(FoldM step begin done) -> do x <- begin x' <- step x a done x' ) m >>= f = Shell (\(FoldM step0 begin0 done0) -> do let step1 x a = _foldIO (f a) (FoldM step0 (return x) return) _foldIO m (FoldM step1 begin0 done0) ) fail _ = mzero instance Alternative Shell where empty = Shell (\(FoldM _ begin done) -> do x <- begin done x ) s1 <|> s2 = Shell (\(FoldM step begin done) -> do x <- _foldIO s1 (FoldM step begin return) _foldIO s2 (FoldM step (return x) done) ) instance MonadPlus Shell where mzero = empty mplus = (<|>) instance MonadIO Shell where liftIO io = Shell (\(FoldM step begin done) -> do x <- begin a <- io x' <- step x a done x' ) instance Monoid a => Monoid (Shell a) where mempty = pure mempty mappend = liftA2 mappend -- | Shell forms a semiring, this is the closest approximation instance Monoid a => Num (Shell a) where fromInteger n = select (replicate (fromInteger n) mempty) (+) = (<|>) (*) = (<>) instance IsString a => IsString (Shell a) where fromString str = pure (fromString str) -- | Convert a list to a `Shell` that emits each element of the list select :: [a] -> Shell a select as = Shell (\(FoldM step begin done) -> do x0 <- begin let step' a k x = do x' <- step x a k $! x' foldr step' done as $! x0 ) -- | Acquire a `Managed` resource within a `Shell` in an exception-safe way using :: Managed a -> Shell a using resource = Shell (\(FoldM step begin done) -> do x <- begin x' <- with resource (step x) done x' )
rpglover64/Haskell-Turtle-Library
src/Turtle/Shell.hs
bsd-3-clause
5,110
0
18
1,370
1,223
632
591
83
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE ScopedTypeVariables#-} module Main where import OpenCog.AtomSpace import OpenCog.Lojban import Control.Concurrent import Control.Monad import Control.Monad.IO.Class import Control.Exception import System.Process main :: IO () main = do (parser,printer) <- initParserPrinter mainloop parser printer mainloop parser printer = do putStrLn "Please Input some Lojban to Translate" input <- getLine let res = parser input case res of Right (Just x) -> printAtom x Right (Nothing) -> putStrLn "Empty parse no Error" Left e -> putStrLn e putStrLn "" mainloop parser printer
ngeiswei/opencog
opencog/nlp/lojban/HaskellLib/app/Main.hs
agpl-3.0
826
0
12
202
184
93
91
28
3
import qualified Data.Vector.Unboxed as U main = print ((==) (U.replicate 100000000 True) (U.replicate 100000000 True))
dolio/vector
old-testsuite/microsuite/eq.hs
bsd-3-clause
142
0
10
37
48
27
21
3
1
module Case2 where data T a = C1 a | C3 Int | C2 Float addedC3 = error "added C3 Int to T" addedC2 = error "added C2 Float to T" -- f (C1 x) = x f :: T a -> Int f (C3 a) = addedC3 f x = case g of (C1 x) -> x (C3 a) -> addedC3 where g = C1 42
kmate/HaRe
old/testing/addCon/Case_TokOut.hs
bsd-3-clause
277
0
9
102
113
60
53
10
2
module ShouldFail where -- !!! Testing recursive type synonyms type T1 = (Int,T2) type T2 = (Int,T1)
hferreiro/replay
testsuite/tests/module/mod27.hs
bsd-3-clause
101
0
5
17
29
20
9
3
0
{-# LANGUAGE FlexibleInstances , TypeSynonymInstances #-} module System.Expression ( Type(..) , Expression(..) , Relation(..) , Formula(..) , VariableName , VariableVersion , int , constValue , varType , varName , varVersion , var , var' , var0 , varAt , intVar , intVar' , intVar0 , intVarAt , vars , types , substitute , Predicate , extractPredicates , and , or , not , atoms , literals ) where import Prelude hiding (and, or, not) import Data.Map (Map) import Data.Monoid import qualified Data.List as L import qualified Data.List.Ordered as O import qualified Data.Map as M import Utils.Canonical import Utils.Versioned type VariableName = String type VariableVersion = Int class WithSubstitutableExpression v where vars :: v -> [Expression] substitute :: Map Expression Expression -> v -> v class Typed v where types :: v -> [Type] data Type = Integer | Container Type deriving (Eq, Ord, Show, Read) int :: Type int = Integer data Expression = Var !Type !VariableName !VariableVersion | Const !Int | Add [Expression] | Mul [Expression] deriving (Eq, Ord, Show, Read) constValue :: Expression -> Int constValue (Const c) = c varType :: Expression -> Type varType (Var t _ _) = t varName :: Expression -> VariableName varName (Var _ v _) = v varVersion :: Expression -> VariableVersion varVersion (Var _ _ n) = n var :: Type -> VariableName -> Expression var t n = Var t n 0 var' :: Type -> VariableName -> Expression var' t n = Var t n 1 var0 :: Type -> VariableName -> Expression var0 t = var t . (++ "0") varAt :: Type -> VariableVersion -> VariableName -> Expression varAt t = flip (Var t) intVar :: VariableName -> Expression intVar = var int intVar' :: VariableName -> Expression intVar' = var' int intVar0 :: VariableName -> Expression intVar0 = var0 int intVarAt :: VariableVersion -> VariableName -> Expression intVarAt = varAt int instance WithSubstitutableExpression Expression where vars v@Var {} = [v] vars (Add as) = L.nub $ concatMap vars as vars (Mul ms) = L.nub $ concatMap vars ms vars _ = [] substitute m e = M.findWithDefault d e m where d = case e of v@Var {} -> v c@(Const _) -> c (Add as) -> Add $ map (substitute m) as (Mul ms) -> Mul $ map (substitute m) ms instance Typed Expression where types (Const c) = [Integer] types (Var t _ _) = [t] types (Add as) = concatMap types as types (Mul ms) = concatMap types ms instance Normal Expression where normalise c@(Const _) = c normalise v@Var {} = v normalise (Add as) = inline1 . Add . L.sort . constants 0 . inline . map normalise $ as where inline :: [Expression] -> [Expression] inline as = inline' as [] inline' :: [Expression] -> [Expression] -> [Expression] inline' [] out = out inline' (Add as' : as) out = inline' as $ inline' as' out inline' (a : as) out = inline' as $ a : out inline1 :: Expression -> Expression inline1 (Add []) = Const 0 inline1 (Add [a]) = a inline1 a@(Add _) = a inline1 _ = error "unexpected expression" constants :: Int -> [Expression] -> [Expression] constants c [] | c == 0 = [] | otherwise = [Const c] constants c (Const c' : es) = constants (c + c') es constants c (e : es) = e : constants c es normalise (Mul ms) = inline1 . Mul . L.sort . constants 1 . inline . map normalise $ ms where inline :: [Expression] -> [Expression] inline ms = inline' ms [] inline' :: [Expression] -> [Expression] -> [Expression] inline' [] out = out inline' (Mul ms' : ms) out = inline' ms $ inline' ms' out inline' (m : ms) out = inline' ms $ m : out inline1 :: Expression -> Expression inline1 (Mul []) = Const 1 inline1 (Mul [m]) = m inline1 m@(Mul _) = m inline1 _ = error "unexpected expression" constants :: Int -> [Expression] -> [Expression] constants c [] | c == 1 = [] | otherwise = [Const c] constants c (Const c' : es) = constants (c * c') es constants c (e : es) = e : constants c es instance Canonical Expression where canonicalise (Var t v _) = var t v canonicalise e = normalise e instance Versioned Expression where bumped (Const _) = fromVersions 0 [] bumped (Var _ v n) = fromVersions 0 [(v, n)] bumped (Add as) = mergeVersionsWith max 0 . map bumped $ as bumped (Mul ms) = mergeVersionsWith max 0 . map bumped $ ms bumped1 (Const _) = fromVersions 0 [] bumped1 (Var _ v _) = fromVersions 0 [(v, 1)] bumped1 (Add as) = mergeVersionsWith max 0 . map bumped $ as bumped1 (Mul ms) = mergeVersionsWith max 0 . map bumped $ ms bump _ c@(Const _) = c bump m (Var t v n) = Var t v $ n + getVersion m v bump m (Add as) = Add $ map (bump m) as bump m (Mul ms) = Mul $ map (bump m) ms invert _ c@(Const _) = c invert m (Var t v n) = Var t v $ max (getVersion m v) n - n invert m (Add as) = Add $ map (invert m) as invert m (Mul ms) = Mul $ map (invert m) ms reset c@(Const _) = c reset (Var t v _) = var t v reset (Add as) = Add $ map reset as reset (Mul ms) = Mul $ map reset ms data Relation = Eq | Ne | Gt | Ge | Lt | Le deriving (Eq, Ord, Show, Read) data Formula = Atom Expression !Relation Expression | Not Formula | And [Formula] | Or [Formula] deriving (Eq, Show, Read) atoms :: Formula -> [Formula] atoms f = normalise $ atoms' f [] where atoms' a@Atom {} as = a : as atoms' (Not f) as = atoms' f as atoms' (And fs) as = foldr atoms' as fs atoms' (Or fs) as = foldr atoms' as fs literals :: Formula -> [Formula] literals f = normalise $ literals' f [] where literals' a@Atom {} as = a : as literals' n@(Not Atom {}) as = n : as literals' (Not f) as = literals' f as literals' (And fs) as = foldr literals' as fs literals' (Or fs) as = foldr literals' as fs instance WithSubstitutableExpression Formula where vars (Atom a _ b) = L.nub $ vars a ++ vars b vars (Not f) = vars f vars (And as) = L.nub $ concatMap vars as vars (Or os) = L.nub $ concatMap vars os substitute m (Atom a p b) = Atom (substitute m a) p (substitute m b) substitute m (Not f) = Not $ substitute m f substitute m (And as) = And $ map (substitute m) as substitute m (Or os) = Or $ map (substitute m) os instance Typed Formula where types (Atom a _ b) = types a ++ types b types (Not f) = types f types (And as) = concatMap types as types (Or os) = concatMap types os instance Ord Formula where (Not f1) `compare` (Not f2) = f1 `compare` f2 <> EQ f1 `compare` (Not f2) = f1 `compare` f2 <> LT (Not f1) `compare` f2 = f1 `compare` f2 <> GT (Atom a b c) `compare` (Atom d e f) = a `compare` d <> b `compare` e <> c `compare` f Atom {} `compare` _ = LT _ `compare` Atom {} = GT (And a1) `compare` (And a2) = a1 `compare` a2 (And _) `compare` _ = LT _ `compare` (And _) = GT (Or o1) `compare` (Or o2) = o1 `compare` o2 type Predicate = Formula -- can be put into equivalent normal form instance Normal Formula where normalise (Atom a Eq b) = let (a', b') = normalise (a, b) in Atom a' Eq b' normalise (Atom a Ne b) = normalise (Atom a Eq b) normalise (Atom a Gt b) = simplify $ Atom (normalise b) Lt (normalise a) normalise (Atom a Ge b) = Not . simplify $ Atom (normalise a) Lt (normalise b) normalise (Atom a Lt b) = simplify $ Atom (normalise a) Lt (normalise b) normalise (Atom a Le b) = Not . simplify $ Atom (normalise b) Lt (normalise a) normalise (Not f) = case normalise f of Not f' -> f' And [] -> Or [] Or [] -> And [] f' -> propagateNot . Not $ f' normalise (And as) = inlineAnd1 . And . O.nub . L.sort . mergeEq . inlineAnd . map normalise $ as normalise (Or os) = inlineOr1 . Or . O.nub . L.sort . inlineOr . map normalise $ os -- can be put into canonical form, phase can change instance Canonical Formula where canonicalise (Atom a Eq b) = let (a', b') = canonicalise (a, b) in Atom a' Eq b' canonicalise (Atom a Ne b) = canonicalise (Atom a Eq b) canonicalise (Atom a Gt b) = simplify $ Atom (canonicalise b) Lt (canonicalise a) canonicalise (Atom a Ge b) = simplify $ Atom (canonicalise a) Lt (canonicalise b) canonicalise (Atom a Lt b) = simplify $ Atom (canonicalise a) Lt (canonicalise b) canonicalise (Atom a Le b) = simplify $ Atom (canonicalise b) Lt (canonicalise a) canonicalise (Not f) = canonicalise f canonicalise (And [a]) = canonicalise a canonicalise (And as) = inlineAnd1 . And . O.nub . L.sort . inlineAnd . map canonicalise $ as canonicalise (Or [o]) = canonicalise o canonicalise (Or os) = inlineOr1 . Or . O.nub . L.sort . inlineOr . map canonicalise $ os instance Versioned Formula where bumped (Atom a p b) = mergeVersionsWith max 0 [bumped a, bumped b] bumped (Not f) = bumped f bumped (And as) = mergeVersionsWith max 0 . map bumped $ as bumped (Or os) = mergeVersionsWith max 0 . map bumped $ os bumped1 (Atom a p b) = mergeVersionsWith max 0 [bumped1 a, bumped1 b] bumped1 (Not f) = bumped1 f bumped1 (And as) = mergeVersionsWith max 0 . map bumped1 $ as bumped1 (Or os) = mergeVersionsWith max 0 . map bumped1 $ os bump m (Atom a p b) = Atom (bump m a) p (bump m b) bump m (Not f) = Not (bump m f) bump m (And as) = And . map (bump m) $ as bump m (Or os) = Or . map (bump m) $ os invert m (Atom a p b) = Atom (invert m a) p (invert m b) invert m (Not f) = Not (invert m f) invert m (And as) = And . map (invert m) $ as invert m (Or os) = Or . map (invert m) $ os reset (Atom a p b) = Atom (reset a) p (reset b) reset (Not f) = Not (reset f) reset (And as) = And . map reset $ as reset (Or os) = Or . map reset $ os inlineAnd :: [Formula] -> [Formula] inlineAnd as = inline' as [] where inline' :: [Formula] -> [Formula] -> [Formula] inline' [] out = out inline' (Or [] : _ ) _ = [Or []] inline' (And as' : as) out = inline' as $ inline' as' out inline' (a : as) out = inline' as $ a : out inlineAnd1 :: Formula -> Formula inlineAnd1 (And [a]) = a inlineAnd1 a@(And _) = a inlineAnd1 _ = error "unexpected formula" mergeEq :: [Formula] -> [Formula] mergeEq as = m as as where m [] _ = [] m (a@(Not (Atom x Lt y)) : as) bs = let r = m as bs e = normalise (Atom x Eq y) in if Not (Atom y Lt x) `elem` bs then e : r else a : r m (a : as) bs = a : m as bs inlineOr :: [Formula] -> [Formula] inlineOr os = inline' os [] where inline' :: [Formula] -> [Formula] -> [Formula] inline' [] out = out inline' (And [] : _ ) _ = [And []] inline' (Or os' : os) out = inline' os $ inline' os' out inline' (o : os) out = inline' os $ o : out inlineOr1 :: Formula -> Formula inlineOr1 (Or [o]) = o inlineOr1 o@(Or _) = o inlineOr1 _ = error "unexpected formula" simplify :: Formula -> Formula simplify (Atom (Add as1) p (Add as2)) = let (ns1, ps1) = L.partition isNeg as1 (ns2, ps2) = L.partition isNeg as2 in Atom (normalise . Add $ ps1 ++ map neg ns2) p (normalise . Add $ ps2 ++ map neg ns1) simplify (Atom a p (Add as)) = let (ns, ps) = L.partition isNeg as in Atom (normalise . Add $ a : map neg ns) p (normalise $ Add ps) simplify (Atom (Add as) p b) = let (ns, ps) = L.partition isNeg as in Atom (normalise $ Add ps) p (normalise . Add $ b : map neg ns) simplify (Atom a p b) | isNeg a = Atom (Const 0) p (normalise $ Add [neg a, b]) simplify (Atom a p b) | isNeg b = Atom (normalise $ Add [a, neg b]) p (Const 0) simplify f = f neg :: Expression -> Expression neg e = Mul [Const (-1), e] isNeg :: Expression -> Bool isNeg (Mul [Const (-1), _]) = True isNeg (Mul [_, Const (-1)]) = True isNeg _ = False and :: Formula -> Formula -> Formula and a b = normalise $ And [a, b] or :: Formula -> Formula -> Formula or a b = normalise $ Or [a, b] not :: Formula -> Formula not a = normalise $ Not a extractPredicates :: Formula -> [Predicate] extractPredicates f = map reset $ extractPredicates' f [] where extractPredicates' :: Formula -> [Predicate] -> [Predicate] extractPredicates' a@Atom {} ps = canonicalise a : ps extractPredicates' (Not f) ps = extractPredicates' f ps extractPredicates' (And as) ps = foldr extractPredicates' ps as extractPredicates' (Or os) ps = foldr extractPredicates' ps os propagateNot :: Formula -> Formula propagateNot a@Atom {} = a propagateNot (Not (Not f)) = propagateNot f propagateNot n@(Not Atom {}) = n propagateNot (Not (And as)) = Or $ map (propagateNot . Not) as propagateNot (Not (Or os)) = And $ map (propagateNot . Not) os propagateNot (And as) = And $ map propagateNot as propagateNot (Or os) = Or $ map propagateNot os
d3sformal/bacon-core
src/System/Expression.hs
mit
15,312
0
14
5,772
6,304
3,192
3,112
371
5
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE TypeSynonymInstances #-} module IHaskell.Display.Widgets.Button ( -- * The Button Widget Button, -- * Create a new button mkButton) where -- To keep `cabal repl` happy when running from the ihaskell repo import Prelude import Control.Monad (when) import Data.Aeson import Data.HashMap.Strict as HM import Data.IORef (newIORef) import Data.Text (Text) import Data.Vinyl (Rec(..), (<+>)) import IHaskell.Display import IHaskell.Eval.Widgets import IHaskell.IPython.Message.UUID as U import IHaskell.Display.Widgets.Types import IHaskell.Display.Widgets.Common -- | A 'Button' represents a Button from IPython.html.widgets. type Button = IPythonWidget ButtonType -- | Create a new button mkButton :: IO Button mkButton = do -- Default properties, with a random uuid uuid <- U.random let dom = defaultDOMWidget "ButtonView" "ButtonModel" but = (Description =:: "") :& (Tooltip =:: "") :& (Disabled =:: False) :& (Icon =:: "") :& (ButtonStyle =:: DefaultButton) :& (ClickHandler =:: return ()) :& RNil buttonState = WidgetState (dom <+> but) stateIO <- newIORef buttonState let button = IPythonWidget uuid stateIO -- Open a comm for this widget, and store it in the kernel state widgetSendOpen button $ toJSON buttonState -- Return the button widget return button instance IHaskellDisplay Button where display b = do widgetSendView b return $ Display [] instance IHaskellWidget Button where getCommUUID = uuid comm widget (Object dict1) _ = do let key1 = "content" :: Text key2 = "event" :: Text Just (Object dict2) = HM.lookup key1 dict1 Just (String event) = HM.lookup key2 dict2 when (event == "click") $ triggerClick widget
sumitsahrawat/IHaskell
ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Button.hs
mit
2,032
0
17
550
455
248
207
48
1
{-| Module : Database.Orville.PostgreSQL.Expr Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} module Database.Orville.PostgreSQL.Expr ( RawExpr , rawSql , GenerateSql(..) , Expr , rawSqlExpr , expr , NameExpr , NameForm , unescapedName , SelectExpr , SelectForm(..) , selectColumn , qualified , aliased ) where import Database.Orville.PostgreSQL.Internal.Expr
flipstone/orville
orville-postgresql/src/Database/Orville/PostgreSQL/Expr.hs
mit
417
0
5
84
69
48
21
16
0
{-# LANGUAGE Haskell2010 , DeriveDataTypeable #-} {-# OPTIONS -Wall -fno-warn-unused-do-bind -fno-warn-name-shadowing #-} module Text.Nicify ( nicify, X (..), parseX, printX, printX' ) where import Data.Data import Data.Functor.Identity import Text.Parsec data X = XString String | XCurly [X] | XBrackets [X] | XAnything String | XSep deriving (Show, Read, Eq, Data, Typeable) nicify :: String -> String nicify = printX . parseX type Parser a = ParsecT String () Identity a parseX :: String -> [X] parseX = either (const []) id . runParser (many rData) () "-" printX :: [X] -> String printX = printX' "" printX' :: String -> [X] -> String printX' indent = (indent ++) . concatMap (prettify indent) prettify :: String -> X -> String prettify indent x = case x of XAnything s -> s XString s -> '\"' : foldr stringify "\"" s XSep -> ",\n" ++ indent XCurly [] -> "{}" XBrackets [] -> "[]" XCurly x -> "{\n" ++ indent' ++ foldr (++) ('\n' : indent ++ "}") (map (prettify indent') x) XBrackets x -> "[\n" ++ indent' ++ foldr (++) ('\n' : indent ++ "]") (map (prettify indent') x) where indent' = indent ++ " " stringify c cs = case c of '\"' -> "\\\"" ++ cs '\\' -> "\\\\" ++ cs char -> char : cs rData, rSep, rAnything, rCurly, rBrackets, rString :: Parser X rData = rString <|> rCurly <|> rBrackets <|> rSep <|> rAnything rSep = do char ',' spaces return XSep rAnything = do str <- many1 (noneOf "\"{}[],") return $ XAnything str rCurly = do char '{' str <- many rData char '}' return $ XCurly str rBrackets = do char '[' str <- many rData char ']' return $ XBrackets str rString = do char '\"' str <- many (noneOf "\\\"" <|> escape) char '\"' return $ XString str escape :: Parser Char escape = do char '\\' c <- anyChar case c of 'n' -> return '\n' 'r' -> return '\r' 't' -> return '\t' any -> return any
scravy/nicify-lib
src/Text/Nicify.hs
mit
2,073
0
13
606
772
390
382
74
9
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.Path2D (js_newPath2D, newPath2D, js_newPath2D', newPath2D', js_newPath2D'', newPath2D'', js_addPath, addPath, js_closePath, closePath, js_moveTo, moveTo, js_lineTo, lineTo, js_quadraticCurveTo, quadraticCurveTo, js_bezierCurveTo, bezierCurveTo, js_arcTo, arcTo, js_rect, rect, js_arc, arc, Path2D, castToPath2D, gTypePath2D) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "new window[\"Path2D\"]()" js_newPath2D :: IO Path2D -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D Mozilla Path2D documentation> newPath2D :: (MonadIO m) => m Path2D newPath2D = liftIO (js_newPath2D) foreign import javascript unsafe "new window[\"Path2D\"]($1)" js_newPath2D' :: Nullable Path2D -> IO Path2D -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D Mozilla Path2D documentation> newPath2D' :: (MonadIO m) => Maybe Path2D -> m Path2D newPath2D' path = liftIO (js_newPath2D' (maybeToNullable path)) foreign import javascript unsafe "new window[\"Path2D\"]($1)" js_newPath2D'' :: JSString -> IO Path2D -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D Mozilla Path2D documentation> newPath2D'' :: (MonadIO m, ToJSString text) => text -> m Path2D newPath2D'' text = liftIO (js_newPath2D'' (toJSString text)) foreign import javascript unsafe "$1[\"addPath\"]($2, $3)" js_addPath :: Path2D -> Nullable Path2D -> Nullable SVGMatrix -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.addPath Mozilla Path2D.addPath documentation> addPath :: (MonadIO m) => Path2D -> Maybe Path2D -> Maybe SVGMatrix -> m () addPath self path transform = liftIO (js_addPath (self) (maybeToNullable path) (maybeToNullable transform)) foreign import javascript unsafe "$1[\"closePath\"]()" js_closePath :: Path2D -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.closePath Mozilla Path2D.closePath documentation> closePath :: (MonadIO m) => Path2D -> m () closePath self = liftIO (js_closePath (self)) foreign import javascript unsafe "$1[\"moveTo\"]($2, $3)" js_moveTo :: Path2D -> Float -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.moveTo Mozilla Path2D.moveTo documentation> moveTo :: (MonadIO m) => Path2D -> Float -> Float -> m () moveTo self x y = liftIO (js_moveTo (self) x y) foreign import javascript unsafe "$1[\"lineTo\"]($2, $3)" js_lineTo :: Path2D -> Float -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.lineTo Mozilla Path2D.lineTo documentation> lineTo :: (MonadIO m) => Path2D -> Float -> Float -> m () lineTo self x y = liftIO (js_lineTo (self) x y) foreign import javascript unsafe "$1[\"quadraticCurveTo\"]($2, $3,\n$4, $5)" js_quadraticCurveTo :: Path2D -> Float -> Float -> Float -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.quadraticCurveTo Mozilla Path2D.quadraticCurveTo documentation> quadraticCurveTo :: (MonadIO m) => Path2D -> Float -> Float -> Float -> Float -> m () quadraticCurveTo self cpx cpy x y = liftIO (js_quadraticCurveTo (self) cpx cpy x y) foreign import javascript unsafe "$1[\"bezierCurveTo\"]($2, $3, $4,\n$5, $6, $7)" js_bezierCurveTo :: Path2D -> Float -> Float -> Float -> Float -> Float -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.bezierCurveTo Mozilla Path2D.bezierCurveTo documentation> bezierCurveTo :: (MonadIO m) => Path2D -> Float -> Float -> Float -> Float -> Float -> Float -> m () bezierCurveTo self cp1x cp1y cp2x cp2y x y = liftIO (js_bezierCurveTo (self) cp1x cp1y cp2x cp2y x y) foreign import javascript unsafe "$1[\"arcTo\"]($2, $3, $4, $5, $6)" js_arcTo :: Path2D -> Float -> Float -> Float -> Float -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.arcTo Mozilla Path2D.arcTo documentation> arcTo :: (MonadIO m) => Path2D -> Float -> Float -> Float -> Float -> Float -> m () arcTo self x1 y1 x2 y2 radius = liftIO (js_arcTo (self) x1 y1 x2 y2 radius) foreign import javascript unsafe "$1[\"rect\"]($2, $3, $4, $5)" js_rect :: Path2D -> Float -> Float -> Float -> Float -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.rect Mozilla Path2D.rect documentation> rect :: (MonadIO m) => Path2D -> Float -> Float -> Float -> Float -> m () rect self x y width height = liftIO (js_rect (self) x y width height) foreign import javascript unsafe "$1[\"arc\"]($2, $3, $4, $5, $6,\n$7)" js_arc :: Path2D -> Float -> Float -> Float -> Float -> Float -> Bool -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/Path2D.arc Mozilla Path2D.arc documentation> arc :: (MonadIO m) => Path2D -> Float -> Float -> Float -> Float -> Float -> Bool -> m () arc self x y radius startAngle endAngle anticlockwise = liftIO (js_arc (self) x y radius startAngle endAngle anticlockwise)
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Path2D.hs
mit
6,003
132
9
1,103
1,550
846
704
96
1
-- | This module provides Cabal integration. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} module Distribution.HaskellSuite.Cabal ( main, customMain ) where import Control.Exception import Control.Monad import Control.Monad.Trans.Except import Data.Foldable (asum) import Data.List import Data.Monoid import Data.Proxy import Data.Typeable import qualified Distribution.HaskellSuite.Compiler as Compiler import Distribution.HaskellSuite.Packages import Distribution.InstalledPackageInfo (parseInstalledPackageInfo, showInstalledPackageInfo) import Distribution.ModuleName hiding (main) import Distribution.Package import Distribution.ParseUtils import Distribution.Simple.Compiler import Distribution.Text import Distribution.Version import Language.Haskell.Exts.Extension import Options.Applicative import Options.Applicative.Types import Paths_haskell_packages as Our (version) import System.Directory import System.FilePath import Text.Printf -- It is actually important that we import 'defaultCpphsOptions' from -- hse-cpp and not from cpphs, because they are different. hse-cpp version -- provides the defaults more compatible with haskell-src-exts. import Language.Haskell.Exts.CPP main :: forall c . Compiler.Is c => c -> IO () main = customMain empty customMain :: forall c . Compiler.Is c => Parser (IO ()) -> c -> IO () customMain additionalActions t = join $ customExecParser (prefs noBacktrack) $ info (helper <*> optParser) idm where optParser = asum [ version , compilerVersion , hspkgVersion , supportedLanguages , supportedExtensions , hsubparser $ pkgCommand <> compilerCommand , additionalActions ] versionStr = showVersion $ Compiler.version t ourVersionStr = showVersion (mkVersion' Our.version) compilerVersion = flag' (printf "%s %s\n" (Compiler.name t) versionStr) (long "compiler-version") hspkgVersion = flag' (putStrLn ourVersionStr) (long "hspkg-version") supportedLanguages = flag' (mapM_ (putStrLn . prettyLanguage) $ Compiler.languages t) (long "supported-languages") supportedExtensions = flag' (mapM_ (putStrLn . prettyExtension) $ Compiler.languageExtensions t) (long "supported-extensions") version = flag' (printf "%s %s\nBased on haskell-packages version %s\n" (Compiler.name t) versionStr ourVersionStr) (long "version") pkgCommand = command "pkg" (info (hsubparser pkgSubcommands) idm) pkgSubcommands = mconcat [ pkgDump , pkgInstallLib , pkgUpdate , pkgUnregister , pkgList , pkgInit ] pkgDump = command "dump" $ info (doDump <$> pkgDbStackParser) idm where doDump dbs = do pkgs <- fmap concat $ forM dbs $ \db -> getInstalledPackages (Proxy :: Proxy (Compiler.DB c)) db putStr $ intercalate "---\n" $ map showInstalledPackageInfo pkgs pkgInstallLib = command "install-library" $ flip info idm $ Compiler.installLib t <$> strOption (long "build-dir" <> metavar "PATH") <*> strOption (long "target-dir" <> metavar "PATH") <*> optional (strOption (long "dynlib-target-dir" <> metavar "PATH")) <*> option (simpleParseM "package-id") (long "package-id" <> metavar "ID") <*> many (argument (simpleParseM "module") (metavar "MODULE")) pkgUpdate = command "update" $ flip info idm $ doRegister <$> pkgDbParser doRegister d = do pi <- parseInstalledPackageInfo <$> getContents case pi of ParseOk _ a -> Compiler.register t d a ParseFailed e -> putStrLn $ snd $ locatedErrorMsg e pkgUnregister = command "unregister" $ flip info idm $ Compiler.unregister t <$> pkgDbParser <*> pkgIdParser pkgInit = command "init" $ flip info idm $ initDB <$> argument str (metavar "PATH") pkgList = command "list" $ flip info idm $ Compiler.list t <$> pkgDbParser compilerCommand = command "compile" (info compiler idm) compiler = (\srcDirs buildDir lang exts cppOpts pkg dbStack deps mods -> Compiler.compile t buildDir lang exts cppOpts pkg dbStack deps =<< findModules srcDirs mods) <$> many (strOption (short 'i' <> metavar "PATH")) <*> (strOption (long "build-dir" <> metavar "PATH") <|> pure ".") <*> optional (classifyLanguage <$> strOption (short 'G' <> metavar "language")) <*> many (parseExtension <$> strOption (short 'X' <> metavar "extension")) <*> cppOptsParser <*> option (simpleParseM "package name") (long "package-name" <> metavar "NAME-VERSION") <*> pkgDbStackParser <*> many (mkUnitId <$> strOption (long "package-id")) <*> many (argument str (metavar "MODULE")) newtype ModuleNotFound = ModuleNotFound String deriving Typeable instance Show ModuleNotFound where show (ModuleNotFound mod) = printf "Module %s not found" mod instance Exception ModuleNotFound findModules :: [FilePath] -> [String] -> IO [FilePath] findModules srcDirs = mapM (findModule srcDirs) findModule :: [FilePath] -> String -> IO FilePath findModule srcDirs mod = do r <- runExceptT $ sequence_ (checkInDir <$> srcDirs <*> exts) case r of Left found -> return found Right {} -> throwIO $ ModuleNotFound mod where exts = ["hs", "lhs"] checkInDir dir ext = ExceptT $ do let file = dir </> toFilePath (fromString mod) <.> ext found <- doesFileExist file return $ if found then Left file else Right () pkgDbParser :: Parser PackageDB pkgDbParser = flag' GlobalPackageDB (long "global") <|> flag' UserPackageDB (long "user") <|> (SpecificPackageDB <$> strOption (long "package-db" <> metavar "PATH")) pkgIdParser :: Parser PackageId pkgIdParser = argument (simpleParseM "package-id") (metavar "PACKAGE") pkgDbStackParser :: Parser PackageDBStack pkgDbStackParser = (\fs -> if null fs then [GlobalPackageDB] else fs) <$> many pkgDbParser cppOptsParser :: Parser CpphsOptions cppOptsParser = appEndo <$> allMod <*> pure defaultCpphsOptions where allMod = fmap mconcat $ many $ define <|> includeDir define = flip fmap (strOption (short 'D' <> metavar "sym[=var]")) $ \str -> let def :: (String, String) def = case span (/= '=') str of (_, []) -> (str, "1") (sym, _:var) -> (sym, var) in Endo $ \opts -> opts { defines = def : defines opts } includeDir = flip fmap (strOption (short 'I' <> metavar "PATH")) $ \str -> Endo $ \opts -> opts { includes = str : includes opts } -- | 'simpleParse' is defined in "Distribution.Text" with type -- -- >simpleParse :: Text a => String -> Maybe a -- -- (It is similar to 'read'.) -- -- 'simpleParseM' wraps it as a 'ReadM' value to be used for parsing -- command-line options simpleParseM :: Text a => String -> ReadM a simpleParseM entityName = do str <- readerAsk case simpleParse str of Just thing -> return thing Nothing -> readerError $ "could not parse " ++ entityName ++ " '" ++ str ++ "'"
haskell-suite/haskell-packages
src/Distribution/HaskellSuite/Cabal.hs
mit
7,543
0
21
1,978
2,036
1,040
996
183
3
module Phantom.Config ( Context , alphabet , size , repeats , path , defaultConfig ) where import Control.Applicative ((<$>)) import System.Directory (getHomeDirectory) import System.FilePath ((</>)) data Context = Context { alphabet :: !String -- Password alphabet. , size :: !Int -- Password length. , repeats :: !Int -- Number of repeated hashes. , path :: IO FilePath -- Path to password entry file. } defaultConfig :: Context defaultConfig = Context { alphabet = ['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] , size = 12 , repeats = 1000 , path = (</> ".phantoms") <$> getHomeDirectory }
slyrz/phantom
src/Phantom/Config.hs
mit
663
0
9
171
170
106
64
28
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- | A Bandwidth document for relays module Onionhoo.Bandwidth.Relay (Relay) where import Onionhoo.History.Graph import Data.Text (Text) import Data.Aeson import Data.Aeson.TH import Data.Aeson.Types -- | Contains Bandwidth information for a relay data Relay = Relay {fingerprint :: Text ,writeHistory :: Maybe Object ,readHistory :: Maybe Object } deriving (Show) $(deriveFromJSON defaultOptions {fieldLabelModifier = camelTo2 '_'} ''Relay)
baumanno/onionhoo
src/Onionhoo/Bandwidth/Relay.hs
mit
560
0
10
113
114
68
46
15
0
module Carbs.Pasta.Vongole.Test where import Test.Framework (testGroup, Test) import Test.Framework.Providers.QuickCheck2 (testProperty) import Carbs.Pasta.Vongole vongoleSuite :: Test vongoleSuite = testGroup "Vongole" [ testProperty "calory count >= 100" prop_minimumCalories ] prop_minimumCalories :: [Int] -> Bool prop_minimumCalories list = calories list >= 100
elisehuard/hs-pasta
test/Carbs/Pasta/Vongole/Test.hs
mit
375
0
7
47
89
52
37
9
1
{-| Description : Evaluate Uroboro Define the operational semantics and reduce terms. -} module Uroboro.Interpreter ( eval , pmatch ) where import Control.Monad (zipWithM) import Data.Either (rights) import Uroboro.Tree ( Identifier , Rule , Rules , TExp(..) , TP(..) , TQ(..) , Type(..) ) -- |Evaluation contexts. data E = EApp Type [TExp] | EDes Type Identifier [TExp] E deriving (Show, Eq) -- |Result of a pattern match. type Substitution = [(Identifier, TExp)] -- |Pattern matching. pmatch :: TExp -> TP -> Either String Substitution pmatch (TVar _ _) _ = error "Substitute variables before trying to match" pmatch term (TPVar r x) | returnType term /= r = Left "Type Mismatch" | otherwise = return [(x, term)] where returnType (TVar t _) = t returnType (TApp t _ _) = t returnType (TCon t _ _) = t returnType (TDes t _ _ _) = t pmatch (TCon r c ts) (TPCon r' c' ps) | r /= r' = Left "Type Mismatch" | c /= c' = Left $ "Name Mismatch: constructor " ++ c' ++ " doesn't match pattern " ++ c | length ts /= length ps = Left "Argument Length Mismatch" | otherwise = zipWithM pmatch ts ps >>= return . concat pmatch _ _ = Left "Not Comparable" -- |Copattern matching. qmatch :: E -> TQ -> Either String Substitution qmatch (EApp r as) (TQApp r' _ ps) | r /= r' = error "Type checker guarantees hole type" | length as /= length ps = Left "Argument Length Mismatch" | otherwise = zipWithM pmatch as ps >>= return . concat qmatch (EDes r d as inner) (TQDes r' d' ps inner') | r /= r' = Left "Type Mismatch" | d /= d' = Left "Name Mismatch" | length as /= length ps = Left "Argument Length Mismatch" | otherwise = do is <- qmatch inner inner' ss <- zipWithM pmatch as ps return $ is ++ (concat ss) qmatch _ _ = Left "Not Comparable" -- |Substitute all occurences. subst :: TExp -> (Identifier, TExp) -> TExp subst t@(TVar _ n') (n, term) | n == n' = term | otherwise = t subst (TApp t n as) s = TApp t n $ map (flip subst s) as subst (TCon t n as) s = TCon t n $ map (flip subst s) as subst (TDes t n as inner) s = TDes t n (map (flip subst s) as) (subst inner s) -- |If context matches rule, apply it. contract :: E -> Rule -> Either String TExp contract context (pattern, term) = do s <- qmatch context pattern return $ foldl subst term s -- |Find hole. reducible :: TExp -> Either String (E, Identifier) -- Could be Maybe. reducible (TApp r f args) = return (EApp r args, f) reducible (TDes r d args inner) = do (inner', f) <- reducible inner return (EDes r d args inner', f) reducible t = Left $ "Not a redex: " ++ show t -- |Star reduction. eval :: Rules -> TExp -> TExp eval _ e@(TVar _ _) = e eval r (TCon t c as) = TCon t c $ map (eval r) as eval r (TApp t f as) = case lookup f r of Nothing -> error "Did you type-check?" Just rf -> case rights $ map (contract con) rf of (e':_) -> eval r e' _ -> es where as' = map (eval r) as es = TApp t f as' con = EApp t as' eval r (TDes t n args inner) = case reducible es of -- TODO factor out. Left _ -> error "Did you type-check?" Right (con, f) -> case lookup f r of Nothing -> error "Did you type-check?" Just rf -> case rights $ map (contract con) rf of (e':_) -> eval r e' _ -> es where args' = map (eval r) args inner' = eval r inner es = TDes t n args' inner'
lordxist/uroboro
src/Uroboro/Interpreter.hs
mit
3,758
0
15
1,212
1,461
726
735
86
6
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ViewPatterns #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.Neural.HMatrix.Recurrent where -- import qualified Data.Neural.Types as N import Control.DeepSeq import Control.Monad.Random as R import Control.Monad.State import Data.Foldable import Data.MonoTraversable import Data.Neural.HMatrix.FLayer import Data.Neural.HMatrix.Utility import Data.Neural.Types (KnownNet, NeuralActs(..)) import Data.Proxy import Data.Reflection import GHC.Generics (Generic) import GHC.TypeLits import GHC.TypeLits.List import Numeric.LinearAlgebra.Static import qualified Data.Binary as B import qualified Data.Neural.Recurrent as N import qualified Data.Vector as V import qualified Data.Vector.Generic as VG import qualified Linear.V as L import qualified Numeric.LinearAlgebra as H data RLayer :: Nat -> Nat -> * where RLayer :: { rLayerBiases :: !(R o) , rLayerIWeights :: !(L o i) , rLayerSWeights :: !(L o o) , rLayerState :: !(R o) } -> RLayer i o deriving (Show, Generic) data Network :: Nat -> [Nat] -> Nat -> * where NetOL :: !(FLayer i o) -> Network i '[] o NetIL :: (KnownNat j, KnownNats hs) => !(RLayer i j) -> !(Network j hs o) -> Network i (j ': hs) o infixr 5 `NetIL` data NetActs :: Nat -> [Nat] -> Nat -> * where NetAOL :: !(R o) -> NetActs i hs o NetAIL :: (KnownNat j, KnownNats hs) => !(R j) -> !(NetActs j hs o) -> NetActs i (j ': js) o infixr 5 `NetAIL` data SomeNet :: * where SomeNet :: KnownNet i hs o => Network i hs o -> SomeNet data OpaqueNet :: Nat -> Nat -> * where OpaqueNet :: KnownNats hs => Network i hs o -> OpaqueNet i o deriving instance KnownNet i hs o => Show (Network i hs o) deriving instance KnownNet i hs o => Show (NetActs i hs o) deriving instance Show SomeNet deriving instance (KnownNat i, KnownNat o) => Show (OpaqueNet i o) type instance Element (RLayer i o) = Double instance (KnownNat i, KnownNat o) => MonoFunctor (RLayer i o) where omap f (RLayer b wI wS s) = RLayer (dvmap f b) (dmmap f wI) (dmmap f wS) (dvmap f s) konstRLayer :: (KnownNat i, KnownNat o) => Double -> RLayer i o konstRLayer = RLayer <$> konst <*> konst <*> konst <*> konst instance (KnownNat i, KnownNat o) => Num (RLayer i o) where RLayer b1 wI1 wS1 s1 + RLayer b2 wI2 wS2 s2 = RLayer (b1 + b2) (wI1 + wI2) (wS1 + wS2) (s1 + s2) RLayer b1 wI1 wS1 s1 * RLayer b2 wI2 wS2 s2 = RLayer (b1 * b2) (wI1 * wI2) (wS1 * wS2) (s1 * s2) RLayer b1 wI1 wS1 s1 - RLayer b2 wI2 wS2 s2 = RLayer (b1 - b2) (wI1 - wI2) (wS1 - wS2) (s1 - s2) abs = omap abs negate = omap negate signum = omap signum fromInteger = konstRLayer . fromInteger instance (KnownNat i, KnownNat o) => Fractional (RLayer i o) where RLayer b1 wI1 wS1 s1 / RLayer b2 wI2 wS2 s2 = RLayer (b1 / b2) (wI1 / wI2) (wS1 / wS2) (s1 / s2) recip (RLayer b wI wS s) = RLayer (recip b) (recip wI) (recip wS) (recip s) fromRational = konstRLayer . fromRational pureNet :: forall i hs o. KnownNet i hs o => (forall j k. (KnownNat j, KnownNat k) => FLayer j k) -> (forall j k. (KnownNat j, KnownNat k) => RLayer j k) -> Network i hs o pureNet lf lr = go natsList where go :: forall j js. KnownNat j => NatList js -> Network j js o go nl = case nl of ØNL -> NetOL lf _ :<# nl' -> lr `NetIL` go nl' konstNet :: KnownNet i hs o => Double -> Network i hs o konstNet x = pureNet (konstFLayer x) (konstRLayer x) zipNet :: forall i hs o. KnownNet i hs o => (forall j k. (KnownNat j, KnownNat k) => FLayer j k -> FLayer j k -> FLayer j k) -> (forall j k. (KnownNat j, KnownNat k) => RLayer j k -> RLayer j k -> RLayer j k) -> Network i hs o -> Network i hs o -> Network i hs o zipNet ff fr = go where go :: forall j js. KnownNet j js o => Network j js o -> Network j js o -> Network j js o go n1 n2 = case n1 of NetOL l1 -> case n2 of NetOL l2 -> NetOL (ff l1 l2) NetIL l1 n1' -> case n2 of NetIL l2 n2' -> NetIL (fr l1 l2) (go n1' n2') instance (KnownNat i, KnownNats hs, KnownNat o) => Num (Network i hs o) where (+) = zipNet (+) (+) (-) = zipNet (-) (-) (*) = zipNet (*) (*) negate = omap negate abs = omap abs signum = omap signum fromInteger = konstNet . fromInteger instance (KnownNat i, KnownNats hs, KnownNat o) => Fractional (Network i hs o) where (/) = zipNet (/) (/) recip = omap recip fromRational = konstNet . fromRational type instance Element (Network i hs o) = Double instance (KnownNat i, KnownNat o) => MonoFunctor (Network i hs o) where omap f = \case NetOL l -> NetOL (omap f l) NetIL l n -> NetIL (omap f l) (omap f n) instance (KnownNat i, KnownNat o) => Random (RLayer i o) where random = runRand $ RLayer <$> randomVec (-1, 1) <*> randomMat (-1, 1) <*> randomMat (-1, 1) <*> randomVec (-1, 1) randomR = error "RLayer i o (randomR): Unimplemented" instance KnownNet i hs o => Random (Network i hs o) where random :: forall g. RandomGen g => g -> (Network i hs o, g) random = runRand $ go natsList where go :: forall j js. KnownNat j => NatList js -> Rand g (Network j js o) go nl = case nl of ØNL -> NetOL <$> getRandom _ :<# nl' -> NetIL <$> getRandom <*> go nl' randomR = error "Network i hs o (randomR): Unimplemented" instance NFData (RLayer i o) instance NFData (Network i hs o) where rnf (NetOL (force -> !_)) = () rnf (NetIL (force -> !_) (force -> !_)) = () instance NFData (NetActs i hs o) where rnf (NetAOL (force -> !_)) = () rnf (NetAIL (force -> !_) (force -> !_)) = () instance (KnownNat i, KnownNat o) => B.Binary (RLayer i o) where instance KnownNet i hs o => B.Binary (Network i hs o) where put (NetOL l) = B.put l put (NetIL l n') = B.put l *> B.put n' get = go natsList where go :: forall j js. KnownNat j => NatList js -> B.Get (Network j js o) go nl = case nl of ØNL -> NetOL <$> B.get _ :<# nl' -> NetIL <$> B.get <*> go nl' instance B.Binary SomeNet where put sn = case sn of SomeNet (n :: Network i hs o) -> do B.put $ natVal (Proxy :: Proxy i) B.put $ natVal (Proxy :: Proxy o) B.put $ OpaqueNet n get = do i <- B.get o <- B.get reifyNat i $ \(Proxy :: Proxy i) -> reifyNat o $ \(Proxy :: Proxy o) -> do oqn <- B.get :: B.Get (OpaqueNet i o) return $ case oqn of OpaqueNet n -> SomeNet n instance (KnownNat i, KnownNat o) => B.Binary (OpaqueNet i o) where put oqn = case oqn of OpaqueNet n -> do case n of NetOL l -> do B.put True B.put l NetIL (l :: RLayer i j) (n' :: Network j js o) -> do B.put False B.put $ natVal (Proxy :: Proxy j) B.put l B.put (OpaqueNet n') get = do isOL <- B.get if isOL then do OpaqueNet . NetOL <$> B.get else do j <- B.get reifyNat j $ \(Proxy :: Proxy j) -> do l <- B.get :: B.Get (RLayer i j) nqo <- B.get :: B.Get (OpaqueNet j o) return $ case nqo of OpaqueNet n -> OpaqueNet $ l `NetIL` n netActsOut :: NetActs i hs o -> R o netActsOut n = case n of NetAIL _ n' -> netActsOut n' NetAOL l -> l runRLayer :: (KnownNat i, KnownNat o) => (Double -> Double) -> RLayer i o -> R i -> (R o, RLayer i o) runRLayer f l@(RLayer b wI wS s) v = (v', l { rLayerState = dvmap f v' }) where v' = b + wI #> v + wS #> s {-# INLINE runRLayer #-} runNetwork :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> Network i hs o -> R i -> (R o, Network i hs o) runNetwork (NA f g) = go where go :: forall i' hs'. KnownNat i' => Network i' hs' o -> R i' -> (R o, Network i' hs' o) go n v = case n of NetOL l -> (dvmap g (runFLayer l v), n) NetIL l nI -> let (v' , l') = runRLayer f l v (v'', nI') = go nI (dvmap f v') in (v'', NetIL l' nI') {-# INLINE runNetwork #-} runNetwork_ :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> Network i hs o -> R i -> R o runNetwork_ na n = fst . runNetwork na n {-# INLINE runNetwork_ #-} runNetworkS :: (KnownNat i, KnownNat o, MonadState (Network i hs o) m) => NeuralActs Double -> R i -> m (R o) runNetworkS na v = state (\n -> runNetwork na n v) {-# INLINE runNetworkS #-} runNetworkActs :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> Network i hs o -> R i -> (NetActs i hs o, Network i hs o) runNetworkActs (NA f g) = go where go :: forall i' hs'. KnownNat i' => Network i' hs' o -> R i' -> (NetActs i' hs' o, Network i' hs' o) go n v = case n of NetOL l -> (NetAOL (dvmap g (runFLayer l v)), n) NetIL l nI -> let (v' , l') = runRLayer f l v vRes = dvmap f v' (nA, nI') = go nI vRes in (NetAIL vRes nA, NetIL l' nI') {-# INLINE runNetworkActs #-} runNetworkActsS :: (KnownNat i, KnownNat o, MonadState (Network i hs o) m) => NeuralActs Double -> R i -> m (NetActs i hs o) runNetworkActsS na v = state (\n -> runNetworkActs na n v) {-# INLINE runNetworkActsS #-} runNetStream :: (KnownNat i, KnownNat o) => NeuralActs Double -> Network i hs o -> [R i] -> ([R o], Network i hs o) runNetStream na n vs = runState (mapM (runNetworkS na) vs) n {-# INLINE runNetStream #-} runNetStream_ :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> Network i hs o -> [R i] -> [R o] runNetStream_ na = go where go :: Network i hs o -> [R i] -> [R o] go n (v:vs) = let (u, n') = runNetwork na n v in u `deepseq` n' `deepseq` u : go n' vs go _ [] = [] {-# INLINE runNetStream_ #-} runNetStreamActs :: (KnownNat i, KnownNat o) => NeuralActs Double -> Network i hs o -> [R i] -> ([NetActs i hs o], Network i hs o) runNetStreamActs na n vs = runState (mapM (runNetworkActsS na) vs) n {-# INLINE runNetStreamActs #-} runNetStreamActs_ :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> Network i hs o -> [R i] -> [NetActs i hs o] runNetStreamActs_ na = go where go :: Network i hs o -> [R i] -> [NetActs i hs o] go n (v:vs) = let (u, n') = runNetworkActs na n v in u `deepseq` n' `deepseq` u : go n' vs go _ [] = [] {-# INLINE runNetStreamActs_ #-} runNetFeedback :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> (R o -> R i) -> Network i hs o -> R i -> [(R o, Network i hs o)] runNetFeedback na nxt = go where go :: Network i hs o -> R i -> [(R o, Network i hs o)] go n v = let res@(v', n') = runNetwork na n v in res : go n' (nxt v') {-# INLINE runNetFeedback #-} runNetFeedback_ :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> (R o -> R i) -> Network i hs o -> R i -> [R o] runNetFeedback_ na nxt = go where go :: Network i hs o -> R i -> [R o] go n v = let (v', n') = runNetwork na n v in v' : go n' (nxt v') {-# INLINE runNetFeedback_ #-} runNetFeedbackM :: forall i hs o m. (KnownNat i, Monad m, KnownNat o) => NeuralActs Double -> (R o -> m (R i)) -> Network i hs o -> Int -> R i -> m [(R o, Network i hs o)] runNetFeedbackM na nxt = go where go :: Network i hs o -> Int -> R i -> m [(R o, Network i hs o)] go n i v | i <= 0 = return [] | otherwise = do let vn'@(v', n') = runNetwork na n v vsns <- go n' (i - 1) =<< nxt v' return $ vn' : vsns runNetFeedbackM_ :: forall i hs o m. (KnownNat i, Monad m, KnownNat o) => NeuralActs Double -> (R o -> m (R i)) -> Network i hs o -> Int -> R i -> m [R o] runNetFeedbackM_ na nxt = go where go :: Network i hs o -> Int -> R i -> m [R o] go n i v | i <= 0 = return [] | otherwise = do let (v', n') = runNetwork na n v vs <- go n' (i - 1) =<< nxt v' return $ v' : vs runNetActsFeedback :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> (R o -> R i) -> Network i hs o -> R i -> [(NetActs i hs o, Network i hs o)] runNetActsFeedback na nxt = go where go :: Network i hs o -> R i -> [(NetActs i hs o, Network i hs o)] go n v = let res@(nacts, n') = runNetworkActs na n v v' = netActsOut nacts in res : go n' (nxt v') runNetActsFeedback_ :: forall i hs o. (KnownNat i, KnownNat o) => NeuralActs Double -> (R o -> R i) -> Network i hs o -> R i -> [NetActs i hs o] runNetActsFeedback_ na nxt = go where go :: Network i hs o -> R i -> [NetActs i hs o] go n v = let (nacts, n') = runNetworkActs na n v v' = netActsOut nacts in nacts : go n' (nxt v') runNetActsFeedbackM :: forall i hs o m. (KnownNat i, Monad m, KnownNat o) => NeuralActs Double -> (R o -> m (R i)) -> Network i hs o -> Int -> R i -> m [(NetActs i hs o, Network i hs o)] runNetActsFeedbackM na nxt = go where go :: Network i hs o -> Int -> R i -> m [(NetActs i hs o, Network i hs o)] go n i v | i <= 0 = return [] | otherwise = do let res@(nacts, n') = runNetworkActs na n v v' = netActsOut nacts vsns <- go n' (i - 1) =<< nxt v' return $ res : vsns runNetActsFeedbackM_ :: forall i hs o m. (KnownNat i, Monad m, KnownNat o) => NeuralActs Double -> (R o -> m (R i)) -> Network i hs o -> Int -> R i -> m [NetActs i hs o] runNetActsFeedbackM_ na nxt = go where go :: Network i hs o -> Int -> R i -> m [NetActs i hs o] go n i v | i <= 0 = return [] | otherwise = do let (nacts, n') = runNetworkActs na n v v' = netActsOut nacts ns <- go n' (i - 1) =<< nxt v' return $ nacts : ns rLayerFromHMat :: (KnownNat i, KnownNat o) => RLayer i o -> N.RLayer i o Double rLayerFromHMat (RLayer b wI wS s) = N.RLayer (L.V . V.fromList $ zipWith3 N.RNode bl wIl wSl) (L.V sv) where bl = H.toList (extract b) sv = VG.convert (extract s) wIl = map (L.V . VG.convert . extract) $ toRows wI wSl = map (L.V . VG.convert . extract) $ toRows wS networkFromHMat :: KnownNet i hs o => Network i hs o -> N.Network i hs o Double networkFromHMat n = case n of NetOL l -> N.NetOL (fLayerFromHMat l) NetIL l n' -> rLayerFromHMat l `N.NetIL` networkFromHMat n' rLayerFromV :: (KnownNat i, KnownNat o) => N.RLayer i o Double -> RLayer i o rLayerFromV (N.RLayer n s0) = RLayer b wI wS s where Just b = create . VG.convert . L.toVector $ N.rNodeBias <$> n Just wI = create . H.fromRows . toList $ VG.convert . L.toVector . N.rNodeIWeights <$> n Just wS = create . H.fromRows . toList $ VG.convert . L.toVector . N.rNodeSWeights <$> n Just s = create . VG.convert . L.toVector $ s0 networkFromV :: KnownNet i hs o => N.Network i hs o Double -> Network i hs o networkFromV n = case n of N.NetOL l -> NetOL (fLayerFromV l) N.NetIL l n' -> rLayerFromV l `NetIL` networkFromV n'
mstksg/neural
src/Data/Neural/HMatrix/Recurrent.hs
mit
18,561
1
20
7,497
7,239
3,662
3,577
457
2
{-# LANGUAGE TupleSections #-} module Turnip.Eval.UtilNumbers (isInt ,toInt ,decimalDigits ,readNumberBase ) where import Data.Char (ord) import Text.Read (readMaybe) import Turnip.Eval.Types (Value(..)) import Text.ParserCombinators.Parsec isInt :: Double -> Bool isInt x = x == (fromIntegral ((floor :: Double -> Int) x)) toInt :: Double -> Maybe Int toInt x = if isInt x then Just . floor $ x else Nothing decimalDigits :: Double -> Maybe Int decimalDigits x = if isInt x then Just 0 else Nothing readNumberBase :: Int -> String -> Value readNumberBase base input = case parse (numberStrBase base) "" input of Left _ -> Nil Right s -> if base == 10 then case readMaybe s of Nothing -> Nil Just n -> Number n else case readBaseMaybe base s of Nothing -> Nil Just n -> Number n numberStrBase :: Int -> Parser String numberStrBase base = do whitespace sign <- choice [ "-" <$ char '-', "" <$ char '+', "" <$ return () ] whitespace digits <- if base == 10 then integralAndFractional <|> justFractional else digitsBase base whitespace eof return (sign ++ digits) where integralAndFractional :: Parser String integralAndFractional = do int <- digitsBase 10 optional $ char '.' frac <- maybe "" ('.':) <$> (optionMaybe $ digitsBase 10) return (int ++ frac) justFractional :: Parser String justFractional = do _ <- char '.' frac <- digitsBase 10 return ('0':'.':frac) whitespace :: Parser () whitespace = const () <$> (many . oneOf $ " \n\t") digitsBase :: Int -> Parser String digitsBase base = many1 $ satisfy (isDigitBase base) isDigitBase :: Int -> Char -> Bool isDigitBase base d = if base <= 10 then (dist d '0') < base else (dist d '0') < 10 || (dist d 'A') < (base - 10) || (dist d 'a') < (base - 10) where dist :: Char -> Char -> Int dist c x = if (ord c - ord x) < 0 then 1000 else (ord c - ord x) readBaseMaybe :: Int -> String -> Maybe Double readBaseMaybe base ('-':digits) = (* (-1.0)) <$> readBaseMaybe base digits readBaseMaybe base digits = fst . foldr accum (Just 0.0 :: Maybe Double, 0 :: Int) $ digits where accum :: Char -> (Maybe Double, Int) -> (Maybe Double, Int) accum d (v, n) = ((+) <$> v <*> (fromIntegral <$> numDigitPos n d), n + 1) numDigitPos :: Int -> Char -> Maybe Int numDigitPos n d = ((base ^ n) *) <$> (numDigit d) numDigit d = digitToIntBase base $ d digitToIntBase :: Int -> Char -> Maybe Int digitToIntBase base c | (fromIntegral dec::Word) <= 9 = Just dec | (fromIntegral alphal::Word) <= nonnumeric = Just $ alphal + 10 | (fromIntegral alphau::Word) <= nonnumeric = Just $ alphau + 10 | otherwise = Nothing where dec = ord c - ord '0' alphal = ord c - ord 'a' alphau = ord c - ord 'A' nonnumeric :: Word nonnumeric = fromIntegral base - 10 - 1
bananu7/Turnip
src/Turnip/Eval/UtilNumbers.hs
mit
3,247
0
13
1,062
1,198
608
590
86
5
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} module Feldspar.OpenCV ( OpenCV (..) , Window , IplImage , importOpenCV , getImageData )where import Feldspar import Feldspar.IO import Language.C.Quote.C type Window = String newtype IplImage = IplImage { unImg :: Object } newtype Point = Point { unPoint :: Object } newtype Color = Color { unColor :: Object } newtype Font = Font { unFont :: Object } newtype Capture = Capture { unCap :: Object } data OpenCV = OpenCV { newImage :: Program IplImage , createImage :: Data IntN -> Data IntN -> Data IntN -> Data IntN -> Program IplImage , loadImage :: FilePath -> IplImage -> Program () , newWindow :: Window -> Program () , imageShow :: Window -> IplImage -> Program () , waitKey :: Int -> Program (Data IntN) , getArr :: IplImage -> Program (Data [Word8]) , setArr :: IplImage -> Data [Word8] -> Data IntN -> Program () , getDim :: IplImage -> Program (Data Index,Data Index) , getChannels :: IplImage -> Program (Data IntN) , getDepth :: IplImage -> Program (Data IntN) , releaseImage:: IplImage -> Program () , captureCam :: Program Capture , queryFrame :: Capture -> Program IplImage } newImage_ :: Program IplImage newImage_ = fmap IplImage $ newObject "IplImage" loadImage_def = [cedecl| void loadImageCV(const char* filename, typename IplImage** image) { *image = cvLoadImage(filename,1); } |] loadImage_ :: String -> IplImage -> Program () loadImage_ f i = callProc "loadImageCV" [ strArg f , addr $ objArg $ unImg i ] imageShow_ :: Window -> IplImage -> Program () imageShow_ w a = callProc "cvShowImage" [ strArg w , objArg $ unImg a ] newWindow_ :: Window -> Program () newWindow_ w = callProc "cvNamedWindow" [ strArg w , valArg (1 :: Data IntN) ] waitKey_ :: Int -> Program (Data IntN) waitKey_ w = callFun "cvWaitKey" [ valArg (value (fromIntegral w) :: Data IntN)] {- releaseImage_ :: IplImage -> Program () releaseImage_ i = callProc "cvReleaseImage" [ objArg (unImg i) ] -} getArr_ :: IplImage -> Program (Data [Word8]) getArr_ i = callFun "getArrData" [ objArg (unImg i) ] getArr_def = [cedecl| typename uchar* getArrData(typename IplImage *image) { typename uchar* data; int step; struct CvSize roi_size; cvGetRawData(image,&data,&step,&roi_size); return data; } |] setArr_ :: IplImage -> Data [Word8] -> Data IntN -> Program () setArr_ i d s = do arr <- unsafeThawArr d callProc "cvSetData" [objArg (unImg i) ,arrArg arr ,valArg s ] createImage_ :: Data IntN -> Data IntN -> Data IntN -> Data IntN -> Program IplImage createImage_ width height depth channels = do size <- initUObject "cvSize" "CvSize" [valArg width, valArg height] fmap IplImage $ initObject "cvCreateImage" "IplImage" [objArg size, valArg depth, valArg channels] captureCam_ :: Program Capture captureCam_ = fmap Capture $ initObject "cvCaptureFromCAM" "CvCapture" [valArg (0 :: Data IntN)] queryFrame_ :: Capture -> Program IplImage queryFrame_ cap = fmap IplImage $ initObject "cvQueryFrame" "IplImage" [objArg (unCap cap)] getDim_ :: IplImage -> Program (Data Index, Data Index) getDim_ i = do dims <- newArr 2 :: Program (Arr Index Index) d <- callFun "cvGetDims" [objArg (unImg i),arrArg dims] :: Program (Data IntN) x <- Feldspar.IO.getArr 1 dims y <- Feldspar.IO.getArr 0 dims return (x,y) {- For this to be useful, we really need dynamic string arguments. putText_ :: IplImage -> String -> Point -> Font -> Color -> Program () putText_ i s p f c = callProc "cvPutText" [ObjArg (unImg i) ,StrArg s ,ObjArg (unPoint p) ,ObjArg f ,ObjArg c ] -} getChannels_def = [cedecl| int getChannels(typename IplImage *image) { return image->nChannels; } |] getChannels_ :: IplImage -> Program (Data IntN) getChannels_ image = callFun "getChannels" [objArg (unImg image)] getDepth_def = [cedecl| int getDepth(typename IplImage *image) { return image->depth; } |] getDepth_ :: IplImage -> Program (Data IntN) getDepth_ image = callFun "getDepth" [objArg (unImg image)] releaseImage_ :: IplImage -> Program () releaseImage_ image = callProc "cvReleaseImage" [addr $ objArg (unImg image)] getImageData :: IplImage -> Program (Data [Word8], Data IntN) getImageData image = do (y,x) <- getDim_ image d <- getDepth_ image arr <- newArr_ step <- newRef :: Program (Ref IntN) callProc "cvGetRawData" [objArg (unImg image) ,addr $ arrArg arr ,refArg step ,valArg (0 :: Data IntN) -- NULL ] farr <- freezeArr arr (x*y*i2n d) s <- getRef step return (farr, s) -- getManifest :: IplImage -> Program (Manifest DIM2 RGB) importOpenCV :: Program OpenCV importOpenCV = do addInclude "<opencv2/core/core_c.h>" addInclude "<opencv2/highgui/highgui_c.h>" addDefinition loadImage_def addDefinition getArr_def addDefinition getChannels_def addDefinition getDepth_def return $ OpenCV newImage_ createImage_ loadImage_ newWindow_ imageShow_ waitKey_ getArr_ setArr_ getDim_ getChannels_ getDepth_ releaseImage_ captureCam_ queryFrame_ opencvLibs = ["opencv_core","opencv_highgui"] opencvIncludes = ["-I/usr/local/include/opencv","-I/usr/local/include/opencv2"] -- Measuring time data Time = Time { time :: forall a . Program a -> Program (a,Data Double) , time_ :: forall a . Program a -> Program (Data Double) } gettime_decl = [cedecl| double feldspar_gettime() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return ts.tv_sec + ts.tv_nsec * 1e-9; } |] time_i :: Program a -> Program (a,Data Double) time_i prog = do d1 <- callFun "feldspar_gettime" [] :: Program (Data Double) a <- prog d2 <- callFun "feldspar_gettime" [] :: Program (Data Double) return (a,Feldspar.max 0 (d1-d1)) time__ :: Program a -> Program (Data Double) time__ prog = do d1 <- callFun "feldspar_gettime" [] :: Program (Data Double) prog d2 <- callFun "feldspar_gettime" [] :: Program (Data Double) return (Feldspar.max 0 (d1-d2)) data Platform = Posix importTime :: Platform -> Program Time importTime Posix = do addInclude "<time.h>" addDefinition gettime_decl return $ Time time_i time__
josefs/feldspar-opencv
Feldspar/OpenCV.hs
mit
6,943
0
13
1,961
1,907
967
940
152
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Feelings.Types where import Data.Aeson import Data.Aeson.Types import Feelings.Batteries -- | A phone number newtype Phone = Phone Text deriving (Show, Eq, FromJSON, ToJSON) -- | v2 lets you SMS data Via = ViaPhone Phone | ViaWeb deriving (Show, Eq, Generic) -- | A record in the database data Feeling = Feeling UTCTime Text Via deriving (Show, Eq) -- ⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜⚜ instance FromJSON Via where instance ToJSON Via where instance FromJSON Feeling where parseJSON (Object o) = Feeling <$> o .: "time" <*> o .: "text" <*> (do via <- o .:? "via" return (fromMaybe ViaWeb via)) parseJSON invalid = typeMismatch "FromJSON Feeling" invalid instance ToJSON Feeling where toJSON (Feeling time text_ via) = object ["time" .= time, "text" .= text_, "via" .= via]
hlian/feelings.blackfriday
src/Feelings/Types.hs
mit
1,133
0
12
270
257
139
118
30
0
module Main where import Prelude import Test.Hspec import IHaskell.Test.Completion (testCompletions) import IHaskell.Test.Parser (testParser) import IHaskell.Test.Eval (testEval) import IHaskell.Test.Hoogle (testHoogle) main :: IO () main = hspec $ do testParser testEval testCompletions testHoogle
gibiansky/IHaskell
src/tests/Hspec.hs
mit
381
0
7
114
87
50
37
14
1
{-# LANGUAGE MultiParamTypeClasses #-} module Functions.Order.Diagrams where import Control.Monad (forM, forM_) import Notes hiding (color, directed, not, (=:)) import Prelude import Relations.Orders.Hasse import Text.Dot import Text.Dot.Class type OrderFunction = [(Text, Text)] type COLOR = Text data OrderFunctionFig = OrderFunctionFig { offHasseDiagrams :: [(Text, HasseDiagram)] , offFunctions :: [(COLOR, OrderFunction)] } data OrderFunctionFigRenderConfig = OrderFunctionFigRenderConfig { offrcNodeConfig :: DotGen () , offrcEdgeConfig :: DotGen () } normalConfig :: OrderFunctionFigRenderConfig normalConfig = OrderFunctionFigRenderConfig (return ()) (return ()) dotsConfig :: OrderFunctionFigRenderConfig dotsConfig = OrderFunctionFigRenderConfig (nodeDec ["shape" =: "point"]) (return ()) instance Graph OrderFunctionFig OrderFunctionFigRenderConfig where defaultGenConfig = normalConfig genGraph c funFig = do offrcNodeConfig c offrcEdgeConfig c graphDec ["nodesep" =: "0.5"] nodeDec ["width" =: "0.05", "height" =: "0.05"] rankdir bottomTop edgeDec [arrowhead =: none] nis <- fmap concat $ forM (offHasseDiagrams funFig) $ \(n, h) -> cluster_ n $ do labelDec n nis <- drawHasseNodes h drawHasseEdges nis h return nis edgeDec [arrowhead =: normal] forM_ (offFunctions funFig) $ \(c, f) -> do edgeDec [color =: c] forM_ f $ drawEdge nis orderFunctionFig :: Double -> OrderFunctionFigRenderConfig -> OrderFunctionFig -> Note orderFunctionFig d c fig = do fp <- dot2tex $ graph_ directed $ genGraph c fig noindent hereFigure $ do packageDep_ "graphicx" includegraphics [KeepAspectRatio True, IGHeight (Cm d), IGWidth (CustomMeasure $ textwidth)] fp
NorfairKing/the-notes
src/Functions/Order/Diagrams.hs
gpl-2.0
1,961
0
15
515
556
287
269
45
1
module Errors where import qualified Data.ByteString.Lazy as BL hiding (pack, unpack) import qualified Data.ByteString.Lazy.Char8 as BL {-- -- Alternative error messages inputError = BL.pack "404 Not Found - Please check input and try again" authenticationError = BL.pack "401 Unauthorized - Authentication Error" urlError = BL.pack "400 Bad Request - Check URL and try again" timeLimitError = BL.pack "401 Unauthorized - Request Limit Reached, please wait and try again" --} -- Errors. inputError :: (BL.ByteString, Int, String) inputError = (BL.pack "Error 8008135", 404, "") authenticationError :: (BL.ByteString, Int, String) authenticationError = (BL.pack "Error 69", 401, "") urlError :: (BL.ByteString, Int, String) urlError = (BL.pack "Error 666", 400, "") timeLimitError :: (BL.ByteString, Int, String) timeLimitError = (BL.pack "Error 420", 401, "") pageDoesNotExistError :: (BL.ByteString, Int, String) pageDoesNotExistError = (BL.pack "Error 13", 404, "") -- This is a full output of an error code, header, and message error405NotAllowed :: BL.ByteString error405NotAllowed = BL.pack $ "HTTP/1.0 405 Method Not Allowed\r\nContent-Type: text/plain; charset=\"Shift_JIS\"\r\nContent-Length: 8\r\n\r\nError 42" error404NotFound :: BL.ByteString error404NotFound = BL.pack $ "HTTP/1.0 404 Not Found\r\nContent-Type: text/plain; charset=\"Shift_JIS\"\r\nContent-Length: 8\r\n\r\nError 13" error400BadRequest :: BL.ByteString error400BadRequest = BL.pack $ "HTTP/1.0 400 Bad Request\r\nContent-Type: text/plain; charset=\"Shift_JIS\"\r\nContent-Length: 8\r\n\r\nError 42" error501NotImplemented :: BL.ByteString error501NotImplemented = BL.pack $ "HTTP/1.0 501 Not Implemented\r\nContent-Type: text/plain; charset=\"Shift_JIS\"\r\nContent-Length: 8\r\n\r\nError 42"
Cipherwraith/Rokka
Errors.hs
gpl-2.0
1,785
0
7
218
282
172
110
21
1
module Posts ( Post, Year, Month, Day, Category, PostType (..), source, title, date, categories, contents, filetype, url, dateString, dayString, postYear, rssDate, postMonth, postDay, postsDir, loadPosts) where import Config import Control.Applicative ((<$>)) import Data.List (sortBy) import Data.Monoid ((<>)) import Data.String.Utils (endswith, startswith) import Data.Time.Calendar (fromGregorian) import Data.Time.Format (formatTime, defaultTimeLocale) import System.Directory (getDirectoryContents) import Text.Parsec import Text.Parsec.Perm import Text.Parsec.String data Post = Post { source :: FilePath, title :: String, date :: (Year, Month, Day), categories :: [Category], contents :: String, filetype :: PostType } deriving Eq type Year = Int type Month = Int type Day = Int type Category = String data PostType = Markdown | Latex | IPythonNotebook | Asciidoc deriving (Show, Eq) -- Metadata present in post file. data PostMeta = PostMeta FilePath String (Year, Month, Day) [Category] url :: Post -> String url post = concat [blogRoot, "/blog/", head $ categories post, "/", source post] dateFmt :: String -> Post -> String dateFmt fmt post = let (year, month, day) = date post postDate = fromGregorian (fromIntegral year) month day in formatTime defaultTimeLocale fmt postDate dateString :: Post -> String dateString = dateFmt "%A, %B %e, %Y" rssDate :: Post -> String rssDate = dateFmt "%a, %e %b %Y 00:00:00" dayString :: Post -> String dayString = dateFmt "%b %e" postYear :: Post -> Year postYear post = yr where (yr, _, _) = date post postMonth :: Post -> Month postMonth post = mn where (_, mn, _) = date post postDay :: Post -> Day postDay post = dy where (_, _, dy) = date post -- | Read and parse the list of posts. -- | Returns a list of sorted posts, recent first. loadPosts :: IO [Post] loadPosts = do parsed <- parseFromFile (many1 postParser) postsFile case parsed of Left err -> error $ show err Right parsedPosts -> let posts = mapM readPost parsedPosts in sortBy compareByDate <$> posts readPost :: PostMeta -> IO Post readPost (PostMeta srcdir postname postdate postcats) = do postfile <- getPostFile $ postsDir ++ srcdir postdata <- readFile $ postsDir ++ srcdir ++ "/" ++ postfile return Post { source = srcdir, title = postname, date = postdate, categories = postcats, contents = postdata, filetype = getPostType postfile } getPostType :: String -> PostType getPostType filename | endswith ".md" filename = Markdown | endswith ".markdown" filename = Markdown | endswith ".tex" filename = Latex | endswith ".ipynb" filename = IPythonNotebook | endswith ".adoc" filename = Asciidoc -- | Compare two posts by their dates. compareByDate :: Post -> Post -> Ordering compareByDate p1 p2 = let (y1, m1, d1) = date p1 (y2, m2, d2) = date p2 in compare y2 y1 <> compare m2 m1 <> compare d2 d1 getPostFile :: FilePath -> IO String getPostFile srcdir = do files <- getDirectoryContents srcdir let potentialPosts = filter (startswith "post.") files case length potentialPosts of 0 -> error $ "Could not find post file in " ++ srcdir 1 -> return $ head potentialPosts _ -> error $ "Too many post files in " ++ srcdir -- | Parse a single post. -- | A post has the format: -- | post { -- | [field value;].. -- | } -- | Fields are currently 'date', 'title', and 'categories'. postParser :: Parser PostMeta postParser = do -- Allow the 'post' and braces tokens to have arbirary whitespace around them. whitespaced $ string "post" whitespaced $ char '{' post <- postData whitespaced $ char '}' return post -- | Parse the actual data fields of a post. -- | These can occur in any order, but must all be present. postData :: Parser PostMeta postData = permute $ PostMeta <$$> directoryParser <||> titleParser <||> dateParser <||> categoryParser -- | Parse a field in the format: -- | title "Text"; -- | Note that quote escaping is not supported. titleParser :: Parser String titleParser = field "title" $ do char '"' manyTill anyChar $ char '"' -- | Parse a date in the form %d-%d-%d (year, month, day). dateParser :: Parser (Year, Month, Day) dateParser = field "date" $ do let int = read <$> many1 digit [year, month, day] <- sepBy int $ char '-' return (year, month, day) -- | Parse a list of categories, separated by commas. categoryParser :: Parser [Category] categoryParser = field "categories" $ sepBy category comma where comma = whitespaced $ char ',' category = many $ letter <|> digit <|> char '-' directoryParser :: Parser FilePath directoryParser = field "source" $ many1 anyChar -- | Parse a generic field in the format 'field: value;' field :: String -> Parser a -> Parser a field name parser = whitespaced $ do -- First, get the string that is the field value string name char ' ' fieldValue <- manyTill anyChar $ char ';' -- Then, parse the actual field value using the field parser loc <- sourceName <$> getPosition case parse parser loc fieldValue of Left err -> error $ show err Right result -> return result -- | Parse anything surrounded by whitespace on both sides. whitespaced :: Parser a -> Parser a whitespaced parser = do whitespace result <- parser whitespace return result -- | Parse whitespace characters. whitespace :: Parser String whitespace = many $ oneOf " \n\t"
gibiansky/blog
Posts.hs
gpl-2.0
5,494
0
14
1,160
1,571
825
746
131
3
-- flatten a list -- sicne haskell lists are homogeneous -- we define a new list type data NestedList a = Elem a | List [NestedList a] p7 :: NestedList a -> [a] p7 (Elem x) = [x] p7 (List xs) = foldr (++) [] $ map p7 xs
yalpul/CENG242
H99/1-10/p7.hs
gpl-3.0
224
0
8
52
89
48
41
4
1
{-| Module : Check Description : Testing Copyright : Erik Edlund License : GPL-3 Maintainer : erik.edlund@32767.se Stability : experimental Portability : POSIX -} module Check where import Test.QuickCheck import Setseer.Glue import Setseer.Color check :: (Testable prop) => prop -> String -> IO () check p name = do putStr $ name ++ ": " quickCheck p main :: IO () main = do check prop_RGB2HSV_HSV2RGB "color:prop_RGB2HSV_HSV2RGB"
edlund/setseer
sources/Check.hs
gpl-3.0
471
0
9
107
97
50
47
15
1
{-# LANGUAGE DeriveDataTypeable #-} module Sound.Tidal.Pattern where import Control.Applicative import Data.Monoid import Data.Fixed import Data.List import Data.Maybe import Data.Ratio import Debug.Trace import Data.Typeable import Data.Function import System.Random.Mersenne.Pure64 import Music.Theory.Bjorklund import Sound.Tidal.Time import Sound.Tidal.Utils -- | The pattern datatype, a function from a time @Arc@ to @Event@ -- values. For discrete patterns, this returns the events which are -- active during that time. For continuous patterns, events with -- values for the midpoint of the given @Arc@ is returned. data Pattern a = Pattern {arc :: Arc -> [Event a]} -- | @show (p :: Pattern)@ returns a text string representing the -- event values active during the first cycle of the given pattern. instance (Show a) => Show (Pattern a) where show p@(Pattern _) = intercalate " " $ map showEvent $ arc p (0, 1) showTime t | denominator t == 1 = show (numerator t) | otherwise = show (numerator t) ++ ('/':show (denominator t)) showArc a = concat[showTime $ fst a, (' ':showTime (snd a))] showEvent (a, b, v) | a == b = concat["(",show v, (' ':showArc a), ")" ] | otherwise = show v instance Functor Pattern where fmap f (Pattern a) = Pattern $ fmap (fmap (mapThd' f)) a -- | @pure a@ returns a pattern with an event with value @a@, which -- has a duration of one cycle, and repeats every cycle. instance Applicative Pattern where pure x = Pattern $ \(s, e) -> map (\t -> ((t%1, (t+1)%1), (t%1, (t+1)%1), x ) ) [floor s .. ((ceiling e) - 1)] (Pattern fs) <*> (Pattern xs) = Pattern $ \a -> concatMap applyX (fs a) where applyX ((s,e), (s', e'), f) = map (\(_, _, x) -> ((s,e), (s', e'), f x)) (filter (\(_, a', _) -> isIn a' s) (xs (s',e')) ) -- | @mempty@ is a synonym for @silence@. -- | @mappend@ is a synonym for @overlay@. instance Monoid (Pattern a) where mempty = silence mappend = overlay instance Monad Pattern where return = pure -- Pattern a -> (a -> Pattern b) -> Pattern b -- Pattern Char -> (Char -> Pattern String) -> Pattern String p >>= f = -- unwrap (f <$> p) Pattern (\a -> concatMap (\((s,e), (s',e'), x) -> map (\ev -> ((s,e), (s',e'), thd' ev)) $ filter (\(a', _, _) -> isIn a' s) (arc (f x) (s,e)) ) (arc p a) ) -- join x = x >>= id -- Take a pattern, and function from elements in the pattern to another pattern, -- and then return that pattern --bind :: Pattern a -> (a -> Pattern b) -> Pattern b --bind p f = -- this is actually join unwrap :: Pattern (Pattern a) -> Pattern a unwrap p = Pattern $ \a -> concatMap ((\p' -> arc p' a) . thd') (arc p a) -- | @atom@ is a synonym for @pure@. atom :: a -> Pattern a atom = pure -- | @silence@ returns a pattern with no events. silence :: Pattern a silence = Pattern $ const [] -- | @withQueryArc f p@ returns a new @Pattern@ with function @f@ -- applied to the @Arc@ values passed to the original @Pattern@ @p@. withQueryArc :: (Arc -> Arc) -> Pattern a -> Pattern a withQueryArc f p = Pattern $ \a -> arc p (f a) -- | @withQueryTime f p@ returns a new @Pattern@ with function @f@ -- applied to the both the start and end @Time@ of the @Arc@ passed to -- @Pattern@ @p@. withQueryTime :: (Time -> Time) -> Pattern a -> Pattern a withQueryTime = withQueryArc . mapArc -- | @withResultArc f p@ returns a new @Pattern@ with function @f@ -- applied to the @Arc@ values in the events returned from the -- original @Pattern@ @p@. withResultArc :: (Arc -> Arc) -> Pattern a -> Pattern a withResultArc f p = Pattern $ \a -> mapArcs f $ arc p a -- | @withResultTime f p@ returns a new @Pattern@ with function @f@ -- applied to the both the start and end @Time@ of the @Arc@ values in -- the events returned from the original @Pattern@ @p@. withResultTime :: (Time -> Time) -> Pattern a -> Pattern a withResultTime = withResultArc . mapArc -- | @overlay@ combines two @Pattern@s into a new pattern, so that -- their events are combined over time. overlay :: Pattern a -> Pattern a -> Pattern a overlay p p' = Pattern $ \a -> (arc p a) ++ (arc p' a) (>+<) = overlay -- | @stack@ combines a list of @Pattern@s into a new pattern, so that -- their events are combined over time. stack :: [Pattern a] -> Pattern a stack ps = foldr overlay silence ps -- | @append@ combines two patterns @Pattern@s into a new pattern, so -- that the events of the second pattern are appended to those of the -- first pattern, within a single cycle append :: Pattern a -> Pattern a -> Pattern a append a b = cat [a,b] -- | @append'@ does the same as @append@, but over two cycles, so that -- the cycles alternate between the two patterns. append' :: Pattern a -> Pattern a -> Pattern a append' a b = slow 2 $ cat [a,b] -- | @cat@ returns a new pattern which interlaces the cycles of the -- given patterns, within a single cycle. It's the equivalent of -- @append@, but with a list of patterns. cat :: [Pattern a] -> Pattern a cat ps = density (fromIntegral $ length ps) $ slowcat ps splitAtSam :: Pattern a -> Pattern a splitAtSam p = splitQueries $ Pattern $ \(s,e) -> mapSnds' (trimArc (sam s)) $ arc p (s,e) where trimArc s' (s,e) = (max (s') s, min (s'+1) e) -- | @slowcat@ does the same as @cat@, but maintaining the duration of -- the original patterns. It is the equivalent of @append'@, but with -- a list of patterns. slowcat :: [Pattern a] -> Pattern a slowcat [] = silence slowcat ps = splitQueries $ Pattern f where ps' = map splitAtSam ps l = length ps' f (s,e) = arc (withResultTime (+offset) p) (s',e') where p = ps' !! n r = (floor s) :: Int n = (r `mod` l) :: Int offset = (fromIntegral $ r - ((r - n) `div` l)) :: Time (s', e') = (s-offset, e-offset) -- | @listToPat@ turns the given list of values to a Pattern, which -- cycles through the list. listToPat :: [a] -> Pattern a listToPat = cat . map atom -- | @maybeListToPat@ is similar to @listToPat@, but allows values to -- be optional using the @Maybe@ type, so that @Nothing@ results in -- gaps in the pattern. maybeListToPat :: [Maybe a] -> Pattern a maybeListToPat = cat . map f where f Nothing = silence f (Just x) = atom x -- | @run@ @n@ returns a pattern representing a cycle of numbers from @0@ to @n-1@. run n = listToPat [0 .. n-1] scan n = cat $ map run [1 .. n] -- | @density@ returns the given pattern with density increased by the -- given @Time@ factor. Therefore @density 2 p@ will return a pattern -- that is twice as fast, and @density (1%3) p@ will return one three -- times as slow. density :: Time -> Pattern a -> Pattern a density 0 p = silence density 1 p = p density r p = withResultTime (/ r) $ withQueryTime (* r) p -- | @densityGap@ is similar to @density@ but maintains its cyclic -- alignment. For example, @densityGap 2 p@ would squash the events in -- pattern @p@ into the first half of each cycle (and the second -- halves would be empty). densityGap :: Time -> Pattern a -> Pattern a densityGap 0 p = silence densityGap r p = splitQueries $ withResultArc (\(s,e) -> (sam s + ((s - sam s)/r), (sam s + ((e - sam s)/r)))) $ Pattern (\a -> arc p $ mapArc (\t -> sam t + (min 1 (r * cyclePos t))) a) -- | @slow@ does the opposite of @density@, i.e. @slow 2 p@ will -- return a pattern that is half the speed. slow :: Time -> Pattern a -> Pattern a slow 0 = id slow t = density (1/t) -- | The @<~@ operator shifts (or rotates) a pattern to the left (or -- counter-clockwise) by the given @Time@ value. For example -- @(1%16) <~ p@ will return a pattern with all the events moved -- one 16th of a cycle to the left. (<~) :: Time -> Pattern a -> Pattern a (<~) t p = withResultTime (subtract t) $ withQueryTime (+ t) p -- | The @~>@ operator does the same as @~>@ but shifts events to the -- right (or clockwise) rather than to the left. (~>) :: Time -> Pattern a -> Pattern a (~>) = (<~) . (0-) brak :: Pattern a -> Pattern a brak = when ((== 1) . (`mod` 2)) (((1%4) ~>) . (\x -> cat [x, silence])) iter :: Int -> Pattern a -> Pattern a iter n p = slowcat $ map (\i -> ((fromIntegral i)%(fromIntegral n)) <~ p) [0 .. n] -- | @rev p@ returns @p@ with the event positions in each cycle -- reversed (or mirrored). rev :: Pattern a -> Pattern a rev p = splitQueries $ Pattern $ \a -> mapArcs mirrorArc (arc p (mirrorArc a)) -- | @palindrome p@ applies @rev@ to @p@ every other cycle, so that -- the pattern alternates between forwards and backwards. palindrome p = append' p (rev p) -- | @when test f p@ applies the function @f@ to @p@, but in a way -- which only affects cycles where the @test@ function applied to the -- cycle number returns @True@. when :: (Int -> Bool) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a when test f p = splitQueries $ Pattern apply where apply a | test (floor $ fst a) = (arc $ f p) a | otherwise = (arc p) a whenT :: (Time -> Bool) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a whenT test f p = splitQueries $ Pattern apply where apply a | test (fst a) = (arc $ f p) a | otherwise = (arc p) a playWhen :: (Time -> Bool) -> Pattern a -> Pattern a playWhen test (Pattern f) = Pattern $ (filter (\e -> test (eventOnset e))) . f playFor :: Time -> Time -> Pattern a -> Pattern a playFor s e = playWhen (\t -> and [t >= s, t < e]) seqP :: [(Time, Time, Pattern a)] -> Pattern a seqP = stack . (map (\(s, e, p) -> playFor s e ((sam s) ~> p))) -- | @every n f p@ applies the function @f@ to @p@, but only affects -- every @n@ cycles. every :: Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a every 0 f p = p every n f p = when ((== 0) . (`mod` n)) f p -- | @foldEvery ns f p@ applies the function @f@ to @p@, and is applied for -- each cycle in @ns@. foldEvery :: [Int] -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a foldEvery ns f p = foldr ($) p (map (\x -> every x f) ns) -- | @sig f@ takes a function from time to values, and turns it into a -- @Pattern@. sig :: (Time -> a) -> Pattern a sig f = Pattern f' where f' (s,e) | s > e = [] | otherwise = [((s,e), (s,e), f s)] -- | @sinewave@ returns a @Pattern@ of continuous @Double@ values following a -- sinewave with frequency of one cycle, and amplitude from -1 to 1. sinewave :: Pattern Double sinewave = sig $ \t -> sin $ pi * 2 * (fromRational t) -- | @sine@ is a synonym for @sinewave. sine = sinewave -- | @sinerat@ is equivalent to @sinewave@ for @Rational@ values, -- suitable for use as @Time@ offsets. sinerat = fmap toRational sine ratsine = sinerat -- | @sinewave1@ is equivalent to @sinewave@, but with amplitude from 0 to 1. sinewave1 :: Pattern Double sinewave1 = fmap ((/ 2) . (+ 1)) sinewave -- | @sine1@ is a synonym for @sinewave1@. sine1 = sinewave1 -- | @sinerat1@ is equivalent to @sinerat@, but with amplitude from 0 to 1. sinerat1 = fmap toRational sine1 -- | @sineAmp1 d@ returns @sinewave1@ with its amplitude offset by @d@. sineAmp1 :: Double -> Pattern Double sineAmp1 offset = (+ offset) <$> sinewave1 -- | @sawwave@ is the equivalent of @sinewave@ for sawtooth waves. sawwave :: Pattern Double sawwave = ((subtract 1) . (* 2)) <$> sawwave1 -- | @saw@ is a synonym for @sawwave@. saw = sawwave -- | @sawrat@ is the same as @sawwave@ but returns @Rational@ values -- suitable for use as @Time@ offsets. sawrat = fmap toRational saw sawwave1 :: Pattern Double sawwave1 = sig $ \t -> mod' (fromRational t) 1 saw1 = sawwave1 sawrat1 = fmap toRational saw1 -- | @triwave@ is the equivalent of @sinewave@ for triangular waves. triwave :: Pattern Double triwave = ((subtract 1) . (* 2)) <$> triwave1 -- | @tri@ is a synonym for @triwave@. tri = triwave -- | @trirat@ is the same as @triwave@ but returns @Rational@ values -- suitable for use as @Time@ offsets. trirat = fmap toRational tri triwave1 :: Pattern Double triwave1 = append sawwave1 (rev sawwave1) tri1 = triwave1 trirat1 = fmap toRational tri1 -- todo - triangular waves again squarewave1 :: Pattern Double squarewave1 = sig $ \t -> fromIntegral $ floor $ (mod' (fromRational t) 1) * 2 square1 = squarewave1 squarewave :: Pattern Double squarewave = ((subtract 1) . (* 2)) <$> squarewave1 square = squarewave -- | @envL@ is a @Pattern@ of continuous @Double@ values, representing -- a linear interpolation between 0 and 1 during the first cycle, then -- staying constant at 1 for all following cycles. Possibly only -- useful if you're using something like the retrig function defined -- in tidal.el. envL :: Pattern Double envL = sig $ \t -> max 0 $ min (fromRational t) 1 -- like envL but reversed. envLR :: Pattern Double envLR = (1-) <$> envL -- 'Equal power' for gain-based transitions envEq :: Pattern Double envEq = sig $ \t -> sin (pi/2 * (max 0 $ min (fromRational (1-t)) 1)) -- Equal power reversed envEqR = sig $ \t -> cos (pi/2 * (max 0 $ min (fromRational (1-t)) 1)) fadeOut :: Time -> Pattern a -> Pattern a fadeOut n = spread' (degradeBy) (slow n $ envL) -- Alternate versions where you can provide the time from which the fade starts fadeOut' :: Time -> Time -> Pattern a -> Pattern a fadeOut' from dur p = spread' (degradeBy) (from ~> slow dur envL) p -- The 1 <~ is so fade ins and outs have different degredations fadeIn' :: Time -> Time -> Pattern a -> Pattern a fadeIn' from dur p = spread' (\n p -> 1 <~ degradeBy n p) (from ~> slow dur ((1-) <$> envL)) p fadeIn :: Time -> Pattern a -> Pattern a fadeIn n = spread' (degradeBy) (slow n $ (1-) <$> envL) spread :: (a -> t -> Pattern b) -> [a] -> t -> Pattern b spread f xs p = cat $ map (\x -> f x p) xs slowspread :: (a -> t -> Pattern b) -> [a] -> t -> Pattern b slowspread f xs p = slowcat $ map (\x -> f x p) xs spread' :: (a -> Pattern b -> Pattern c) -> Pattern a -> Pattern b -> Pattern c spread' f timepat pat = Pattern $ \r -> concatMap (\(_,r', x) -> (arc (f x pat) r')) (rs r) where rs r = arc (filterOnsetsInRange timepat) r filterValues :: (a -> Bool) -> Pattern a -> Pattern a filterValues f (Pattern x) = Pattern $ (filter (f . thd')) . x -- Filter out events that have had their onsets cut off filterOnsets :: Pattern a -> Pattern a filterOnsets (Pattern f) = Pattern $ (filter (\e -> eventOnset e >= eventStart e)) . f -- Filter events which have onsets, which are within the given range filterStartInRange :: Pattern a -> Pattern a filterStartInRange (Pattern f) = Pattern $ \(s,e) -> filter ((>= s) . eventOnset) $ f (s,e) filterOnsetsInRange = filterOnsets . filterStartInRange seqToRelOnsets :: Arc -> Pattern a -> [(Double, a)] seqToRelOnsets (s, e) p = map (\((s', _), _, x) -> (fromRational $ (s'-s) / (e-s), x)) $ arc (filterOnsetsInRange p) (s, e) segment :: Pattern a -> Pattern [a] segment p = Pattern $ \(s,e) -> filter (\(_,(s',e'),_) -> s' < e && e' > s) $ groupByTime (segment' (arc p (s,e))) segment' :: [Event a] -> [Event a] segment' es = foldr split es pts where pts = nub $ points es split :: Time -> [Event a] -> [Event a] split _ [] = [] split t ((ev@(a,(s,e), v)):es) | t > s && t < e = (a,(s,t),v):(a,(t,e),v):(split t es) | otherwise = ev:split t es points :: [Event a] -> [Time] points [] = [] points ((_,(s,e), _):es) = s:e:(points es) groupByTime :: [Event a] -> [Event [a]] groupByTime es = map mrg $ groupBy ((==) `on` snd') $ sortBy (compare `on` snd') es where mrg es@((a, a', _):_) = (a, a', map thd' es) ifp :: (Int -> Bool) -> (Pattern a -> Pattern a) -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a ifp test f1 f2 p = splitQueries $ Pattern apply where apply a | test (floor $ fst a) = (arc $ f1 p) a | otherwise = (arc $ f2 p) a rand :: Pattern Double rand = Pattern $ \a -> [(a, a, timeToRand $ (midPoint a))] timeToRand t = fst $ randomDouble $ pureMT $ floor $ (*1000000) t irand :: Double -> Pattern Int irand i = (floor . (*i)) <$> rand degradeBy :: Double -> Pattern a -> Pattern a degradeBy x p = unMaybe $ (\a f -> toMaybe (f > x) a) <$> p <*> rand where toMaybe False _ = Nothing toMaybe True a = Just a unMaybe = (fromJust <$>) . filterValues isJust unDegradeBy :: Double -> Pattern a -> Pattern a unDegradeBy x p = unMaybe $ (\a f -> toMaybe (f <= x) a) <$> p <*> rand where toMaybe False _ = Nothing toMaybe True a = Just a unMaybe = (fromJust <$>) . filterValues isJust sometimesBy :: Double -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a sometimesBy x f p = overlay (degradeBy x p) (f $ unDegradeBy x p) sometimes = sometimesBy 0.5 often = sometimesBy 0.75 rarely = sometimesBy 0.25 almostNever = sometimesBy 0.1 almostAlways = sometimesBy 0.9 degrade :: Pattern a -> Pattern a degrade = degradeBy 0.5 -- | @wedge t p p'@ combines patterns @p@ and @p'@ by squashing the -- @p@ into the portion of each cycle given by @t@, and @p'@ into the -- remainer of each cycle. wedge :: Time -> Pattern a -> Pattern a -> Pattern a wedge t p p' = overlay (densityGap (1/t) p) (t <~ densityGap (1/(1-t)) p') whenmod :: Int -> Int -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a whenmod a b = Sound.Tidal.Pattern.when ((\t -> (t `mod` a) >= b )) superimpose f p = stack [p, f p] -- | @splitQueries p@ wraps `p` to ensure that it does not get -- queries that span arcs. For example `arc p (0.5, 1.5)` would be -- turned into two queries, `(0.5,1)` and `(1,1.5)`, and the results -- combined. Being able to assume queries don't span cycles often -- makes transformations easier to specify. splitQueries :: Pattern a -> Pattern a splitQueries p = Pattern $ \a -> concatMap (arc p) $ arcCycles a trunc :: Time -> Pattern a -> Pattern a trunc t p = slow t $ splitQueries $ p' where p' = Pattern $ \a -> mapArcs (stretch . trunc') $ arc p (trunc' a) trunc' (s,e) = (min s ((sam s) + t), min e ((sam s) + t)) stretch (s,e) = (sam s + ((s - sam s) / t), sam s + ((e - sam s) / t)) zoom :: Arc -> Pattern a -> Pattern a zoom a@(s,e) p = splitQueries $ withResultArc (mapCycle ((/d) . (subtract s))) $ withQueryArc (mapCycle ((+s) . (*d))) p where d = e-s compress :: Arc -> Pattern a -> Pattern a compress a@(s,e) p | s >= e = silence | otherwise = s ~> densityGap (1/(e-s)) p sliceArc :: Arc -> Pattern a -> Pattern a sliceArc a@(s,e) p | s >= e = silence | otherwise = compress a $ zoom a p -- @within@ uses @compress@ and @zoom to apply @f@ to only part of pattern @p@ -- for example, @within (1%2) (3%4) ((1%8) <~) "bd sn bd cp"@ would shift only -- the second @bd@ within :: Arc -> (Pattern a -> Pattern a) -> Pattern a -> Pattern a within (s,e) f p = stack [sliceArc (0,s) p, compress (s,e) $ f $ zoom (s,e) p, sliceArc (e,1) p ] revArc a = within a rev e :: Int -> Int -> Pattern a -> Pattern a e n k p = (flip const) <$> (filterValues (== True) $ listToPat $ bjorklund (n,k)) <*> p e' :: Int -> Int -> Pattern a -> Pattern a e' n k p = cat $ map (\x -> if x then p else silence) (bjorklund (n,k)) index :: Real b => b -> Pattern b -> Pattern c -> Pattern c index sz indexpat pat = spread' (zoom' $ toRational sz) (toRational . (*(1-sz)) <$> indexpat) pat where zoom' sz start = zoom (start, start+sz) -- | @prr rot (blen, vlen) beatPattern valuePattern@: pattern rotate/replace. prrw :: (a -> b -> c) -> Int -> (Time, Time) -> Pattern a -> Pattern b -> Pattern c prrw f rot (blen, vlen) beatPattern valuePattern = let ecompare (_,e1,_) (_,e2,_) = compare (fst e1) (fst e2) beats = sortBy ecompare $ arc beatPattern (0, blen) values = fmap thd' . sortBy ecompare $ arc valuePattern (0, vlen) cycles = blen * (fromIntegral $ lcm (length beats) (length values) `div` (length beats)) in slow cycles $ stack $ zipWith (\( _, (start, end), v') v -> (start ~>) $ densityGap (1 / (end - start)) $ pure (f v' v)) (sortBy ecompare $ arc (density cycles $ beatPattern) (0, blen)) (drop (rot `mod` length values) $ cycle values) -- | @prr rot (blen, vlen) beatPattern valuePattern@: pattern rotate/replace. prr :: Int -> (Time, Time) -> Pattern a -> Pattern a -> Pattern a prr = prrw $ flip const {-| @preplace (blen, plen) beats values@ combines the timing of @beats@ with the values of @values@. Other ways of saying this are: * sequential convolution * @values@ quantized to @beats@. Examples: @ d1 $ sound $ preplace (1,1) "x [~ x] x x" "bd sn" d1 $ sound $ preplace (1,1) "x(3,8)" "bd sn" d1 $ sound $ "x(3,8)" <~> "bd sn" d1 $ sound "[jvbass jvbass:5]*3" |+| (shape $ "1 1 1 1 1" <~> "0.2 0.9") @ It is assumed the pattern fits into a single cycle. This works well with pattern literals, but not always with patterns defined elsewhere. In those cases use @prr@ and provide desired pattern lengths: @ let p = slow 2 $ "x x x" d1 $ sound $ prr 0 (2,1) p "bd sn" @ -} preplace :: (Time, Time) -> Pattern a -> Pattern a -> Pattern a preplace = preplaceWith $ flip const prep = preplace preplace1 :: Pattern a -> Pattern a -> Pattern a preplace1 = prr 0 (1, 1) preplaceWith :: (a -> b -> c) -> (Time, Time) -> Pattern a -> Pattern b -> Pattern c preplaceWith f (blen, plen) = prrw f 0 (blen, plen) prw = preplaceWith preplaceWith1 :: (a -> b -> c) -> Pattern a -> Pattern b -> Pattern c preplaceWith1 f = prrw f 0 (1, 1) prw1 = preplaceWith1 (<~>) :: Pattern a -> Pattern a -> Pattern a (<~>) = preplace (1, 1) -- | @protate len rot p@ rotates pattern @p@ by @rot@ beats to the left. -- @len@: length of the pattern, in cycles. -- Example: @d1 $ every 4 (protate 2 (-1)) $ slow 2 $ sound "bd hh hh hh"@ protate :: Time -> Int -> Pattern a -> Pattern a protate len rot p = prr rot (len, len) p p prot = protate prot1 = protate 1 {-| The @<<~@ operator rotates a unit pattern to the left, similar to @<~@, but by events rather than linear time. The timing of the pattern remains constant: @ d1 $ (1 <<~) $ sound "bd ~ sn hh" -- will become d1 $ sound "sn ~ hh bd" @ -} (<<~) :: Int -> Pattern a -> Pattern a (<<~) = protate 1 (~>>) :: Int -> Pattern a -> Pattern a (~>>) = (<<~) . (0-) -- | @pequal cycles p1 p2@: quickly test if @p1@ and @p2@ are the same. pequal :: Ord a => Time -> Pattern a -> Pattern a -> Bool pequal cycles p1 p2 = (sort $ arc p1 (0, cycles)) == (sort $ arc p2 (0, cycles)) -- | @discretise n p@: 'samples' the pattern @p@ at a rate of @n@ -- events per cycle. Useful for turning a continuous pattern into a -- discrete one. discretise :: Time -> Pattern a -> Pattern a discretise n p = density n $ (atom (id)) <*> p -- | @randcat ps@: does a @slowcat@ on the list of patterns @ps@ but -- randomises the order in which they are played. randcat :: [Pattern a] -> Pattern a randcat ps = spread' (<~) (discretise 1 $ ((%1) . fromIntegral) <$> irand (fromIntegral $ length ps)) (slowcat ps) toMIDI :: Pattern String -> Pattern Int toMIDI p = fromJust <$> (filterValues (isJust) (noteLookup <$> p)) where noteLookup [] = Nothing noteLookup s | last s `elem` ['0' .. '9'] = elemIndex s names | otherwise = noteLookup (s ++ "5") names = take 128 [(n ++ show o) | o <- octaves, n <- notes ] notes = ["c","cs","d","ds","e","f","fs","g","gs","a","as","b"] octaves = [0 .. 10] fit :: Int -> [a] -> Pattern Int -> Pattern a fit perCycle xs p = (xs !!!) <$> (Pattern $ \a -> map ((\e -> (mapThd' (+ (cyclePos perCycle e)) e))) (arc p a)) where cyclePos perCycle e = perCycle * (floor $ eventStart e)
tpltnt/Tidal
Sound/Tidal/Pattern.hs
gpl-3.0
24,165
0
18
5,903
8,250
4,373
3,877
341
2
{-# LANGUAGE ScopedTypeVariables #-} module Data.HdrHistogram.MutableSpec where import Control.Monad.ST (runST) import Data.HdrHistogram import qualified Data.HdrHistogram.Mutable as MH import qualified Data.Vector as U import Test.Expectations import Test.Hspec import Test.Hspec.QuickCheck (prop) import Test.Utils spec :: Spec spec = describe "Histogram" $ prop "should be close to reference implementation" $ \((ConfigAndVals c vals) :: ConfigAndVals c Int) -> do let v = U.fromList vals median' = median v h :: Histogram c Int Int h = runST $ do h' <- MH.fromConfig c U.forM_ v (MH.record h') MH.unsafeFreeze h' p = percentile h 50 lower p `shouldBeLessThanOrEqual` median' upper p `shouldBeGreaterThanOrEqual` median'
joshbohde/hdr-histogram
test/Data/HdrHistogram/MutableSpec.hs
gpl-3.0
907
0
18
282
231
124
107
25
1
module QFeldspar.Environment.Conversion () where import QFeldspar.MyPrelude import qualified QFeldspar.Environment.Map as EM import qualified QFeldspar.Environment.Plain as EP import qualified QFeldspar.Environment.Typed as ET import qualified QFeldspar.Environment.Scoped as ES import qualified QFeldspar.Type.ADT as TA import qualified QFeldspar.Type.GADT as TG import QFeldspar.Conversion import QFeldspar.Type.Conversion () import QFeldspar.Singleton import qualified QFeldspar.Nat.GADT as NG --------------------------------------------------------------------------------- -- Conversion from EM.Env --------------------------------------------------------------------------------- instance Cnv (a , r) b => Cnv (EM.Env x a , r) (EM.Env x b) where cnv (ee , r) = mapM (\ (x , y) -> do y' <- cnv (y , r) return (x , y')) ee --------------------------------------------------------------------------------- -- Conversion from EP.Env --------------------------------------------------------------------------------- instance Cnv (a , r) b => Cnv (EP.Env a , r) (EP.Env b) where cnv (ee , r) = mapM (cnvWth r) ee instance (n ~ n', a ~ a') => Cnv (EP.Env a , NG.Nat n) (ES.Env n' a') where cnv ([] , NG.Zro) = return ES.Emp cnv (x : xs, NG.Suc n) = do xs' <- cnv (xs , n) return (ES.Ext x xs') cnv _ = fail "Conversion Error!" instance Cnv (a , r) (ExsSin b) => Cnv (EP.Env a , r) (ExsSin (ET.Env b)) where cnv (ee , r) = case ee of [] -> return (ExsSin ET.Emp) t : ts -> do ExsSin t' <- cnvWth r t ExsSin r' <- cnvWth r ts return (ExsSin (ET.Ext t' r')) --------------------------------------------------------------------------------- -- Conversion from ES.Env --------------------------------------------------------------------------------- instance Cnv (ES.Env n t , r ) (EP.Env t) where cnv (ee , r) = case ee of ES.Emp -> pure [] ES.Ext x xs -> (x :) <$> cnvWth r xs instance (Cnv (a , r) b , n ~ n') => Cnv (ES.Env n a , r) (ES.Env n' b) where cnv (ee , r) = mapM (cnvWth r) ee --------------------------------------------------------------------------------- -- Conversion from ES.Env --------------------------------------------------------------------------------- instance n ~ Len r => Cnv (ET.Env TG.Typ r , rr) (ES.Env n TA.Typ) where cnv (ee , r) = case ee of ET.Emp -> pure ES.Emp ET.Ext x xs -> ES.Ext <$> cnvWth r x <*> cnvWth r xs
shayan-najd/QFeldspar
QFeldspar/Environment/Conversion.hs
gpl-3.0
2,585
0
16
576
870
468
402
-1
-1
-- Run tests. ghc --make Test.hs -o test -threaded ; ./test import Test.Reactive
ekmett/reactive
src/Test.hs
agpl-3.0
83
0
4
15
7
4
3
1
0
func :: ()
lspitzner/brittany
data/Test8.hs
agpl-3.0
11
0
5
3
8
4
4
1
0
{-# LANGUAGE PatternSynonyms #-} pattern HeadC x <- x : xs where HeadC x = [x]
lspitzner/brittany
data/Test241.hs
agpl-3.0
81
0
6
18
29
15
14
3
0
module Main where import Awaywox main = awaywoxMain
burnicane/Awaywox
Main.hs
agpl-3.0
53
0
4
9
12
8
4
3
1
module DayOfTheWeekOrd where data DayOfTheWeek = -- disjoint union (sum type) of value symbols -- representing days of the week Mon | Tue | Wed | Thu | Fri | Sat | Sun -- This is looks pretty but is tedious. -- I wonder if there's an easier way? instance Eq DayOfTheWeek where (==) Mon Mon = True (==) Tue Tue = True (==) Wed Wed = True (==) Thu Thu = True (==) Fri Fri = True (==) Sat Sat = True (==) Sun Sun = True (==) _ _ = False data Date = Date DayOfTheWeek Int instance Eq Date where (==) (Date weekday dayOfTheMonth) (Date weekday' dayOfTheMonth') = weekday == weekday' && dayOfTheMonth == dayOfTheMonth'
OCExercise/haskellbook-solutions
chapters/chapter06/scratch/dayoftheweek_ord.hs
bsd-2-clause
728
0
8
233
196
114
82
18
0
{-# LANGUAGE MultiParamTypeClasses #-} module Data.TH.Object ( Object(..) ) where import Data.Map class Object a k v where toObject :: a -> Map k v
fabianbergmark/APIs
src/Data/TH/Object.hs
bsd-2-clause
160
0
8
37
49
28
21
6
0
{-# LANGUAGE OverloadedStrings, CPP, GADTs #-} ----------------------------------------------------------------------------- -- | -- Module : Application.HXournal.ModelAction.File -- Copyright : (c) 2011, 2012 Ian-Woo Kim -- -- License : BSD3 -- Maintainer : Ian-Woo Kim <ianwookim@gmail.com> -- Stability : experimental -- Portability : GHC -- ----------------------------------------------------------------------------- module Application.HXournal.ModelAction.File where import Application.HXournal.Type.XournalState import qualified Text.Xournal.Parse.Enumerator as PE import Data.Maybe import Control.Monad import Control.Category import Data.Label import Prelude hiding ((.),id) import Data.Xournal.Simple import Graphics.Xournal.Render.BBoxMapPDF import Graphics.Xournal.Render.PDFBackground import Graphics.UI.Gtk hiding (get,set) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as C #ifdef POPPLER import qualified Graphics.UI.Gtk.Poppler.Document as Poppler import qualified Graphics.UI.Gtk.Poppler.Page as PopplerPage #endif -- | get file content from xournal file and update xournal state getFileContent :: Maybe FilePath -> HXournalState -> IO HXournalState getFileContent (Just fname) xstate = do -- xojcontent <- P.read_xournal fname PE.parseXojFile fname >>= \x -> case x of Left str -> do putStrLn $ "file reading error : " ++ str return xstate Right xojcontent -> do nxstate <- constructNewHXournalStateFromXournal xojcontent xstate return $ set currFileName (Just fname) nxstate getFileContent Nothing xstate = do newxoj <- mkTXournalBBoxMapPDFBufFromNoBuf <=< mkTXournalBBoxMapPDF $ defaultXournal let newxojstate = ViewAppendState newxoj xstate' = set currFileName Nothing . set xournalstate newxojstate $ xstate return xstate' -- | constructNewHXournalStateFromXournal :: Xournal -> HXournalState -> IO HXournalState constructNewHXournalStateFromXournal xoj' xstate = do xoj <- mkTXournalBBoxMapPDFBufFromNoBuf <=< mkTXournalBBoxMapPDF $ xoj' let startingxojstate = ViewAppendState xoj return $ set xournalstate startingxojstate xstate -- | makeNewXojWithPDF :: FilePath -> IO (Maybe Xournal) makeNewXojWithPDF fp = do #ifdef POPPLER let fname = C.pack fp mdoc <- popplerGetDocFromFile fname case mdoc of Nothing -> do putStrLn $ "no such file " ++ fp return Nothing Just doc -> do n <- Poppler.documentGetNPages doc pg <- Poppler.documentGetPage doc 0 (w,h) <- PopplerPage.pageGetSize pg let dim = Dim w h xoj = set s_title fname . set s_pages (map (createPage dim fname) [1..n]) $ emptyXournal return (Just xoj) #else error "makeNewXojWithPDF should not be used without poppler lib" #endif -- | createPage :: Dimension -> B.ByteString -> Int -> Page createPage dim fn n | n == 1 = let bkg = BackgroundPdf "pdf" (Just "absolute") (Just fn ) n in Page dim bkg [emptyLayer] | otherwise = let bkg = BackgroundPdf "pdf" Nothing Nothing n in Page dim bkg [emptyLayer] -- | toggleSave :: UIManager -> Bool -> IO () toggleSave ui b = do agr <- uiManagerGetActionGroups ui >>= \x -> case x of [] -> error "No action group?" y:_ -> return y Just savea <- actionGroupGetAction agr "SAVEA" actionSetSensitive savea b
wavewave/hxournal
lib/Application/HXournal/ModelAction/File.hs
bsd-2-clause
3,636
0
21
897
835
432
403
56
2
module YesodDsl.Simplify (simplify) where import YesodDsl.AST import Data.Generics import Data.Either import Data.Generics.Uniplate.Data import qualified Data.List as L import Data.Maybe import qualified Data.Map as Map simplify :: Module -> Module simplify m = everywhere ((mkT sHandler) . (mkT sValExpr) . (mkT sBoolExpr) . (mkT sStmt) . (mkT mapEntityRef)) m where sValExpr (SubQueryExpr sq) = SubQueryExpr $ mapSq sq sValExpr x = x sBoolExpr (ExistsExpr sq) = ExistsExpr $ mapSq sq sBoolExpr x = x sStmt (Require sq) = Require $ mapSq sq sStmt (IfFilter (pn,js,be,uf)) = IfFilter (pn, map mapJoin js, be, uf) sStmt (Select sq) = Select $ mapSq sq sStmt x = x mapSq sq = let sq' = sq { sqJoins = map mapJoin $ sqJoins sq } in sq' { sqFields = concatMap (expand sq') $ sqFields sq', sqWhere = everywhere ((mkT sValExpr) . (mkT sBoolExpr)) $ sqWhere sq' } mapJoin j = j { joinEntity = mapEntityRef $ joinEntity j, joinExpr = joinExpr j >>= Just . (everywhere $ (mkT sValExpr) . (mkT sBoolExpr)) } lookupEntity en = L.find ((==en) . entityName) $ modEntities m mapEntityRef l@(Left en) = fromMaybe l $ lookupEntity en >>= Just . Right mapEntityRef x = x expand sq (SelectAllFields (Var vn _ _)) = fromMaybe [] $ do (e,_) <- Map.lookup vn $ sqAliases sq Just $ [ SelectField (Var vn (Left "") False) (fieldName f) Nothing | f <- entityFields e, fieldInternal f == False ] expand _ x = [x] sHandler :: Handler -> Handler sHandler h = everywhere ((mkT mapVarRef) . (mkT mapStmt) . (mkT mapSq)) h where baseAliases = Map.unions [ sqAliases sq | Select sq <- universeBi h ] mapStmt df@(DeleteFrom er vn _) = everywhere (mkT $ mapSqVarRef $ Map.unions [ baseAliases, Map.fromList $ rights [ er >>= \e -> Right (vn, (e, False)) ] ]) df mapStmt i@(IfFilter (_,js,_,_)) = everywhere (mkT $ mapSqVarRef $ Map.unions [ baseAliases, Map.fromList $ rights [ joinEntity j >>= \e -> Right (joinAlias j,(e, isOuterJoin $ joinType j)) | j <- js ] ]) i mapStmt i = i mapSq sq = everywhere (mkT $ mapSqVarRef $ sqAliases sq) sq mapSqVarRef aliases (Var vn (Left "") _) = case Map.lookup vn aliases of Just (e,mf) -> Var vn (Right e) mf _ -> Var vn (lookupEntityRef vn) False mapSqVarRef _ v = v lookupEntityRef vn = case listToMaybe [ er | GetById er _ vn' <- universeBi h, vn' == vn ] of Just er -> er Nothing -> Left "" mapVarRef (Var vn (Left "") _) = Var vn (lookupEntityRef vn) False mapVarRef v = v
codygman/yesod-dsl
YesodDsl/Simplify.hs
bsd-2-clause
2,893
0
21
937
1,164
594
570
52
8
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiWayIf #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE RankNTypes #-} module Highlight.Common.Monad.Input ( FileOrigin(..) , FileReader(..) , getFileOriginFromFileReader , getFilePathFromFileReader , InputData(..) , createInputData , FilenameHandlingFromFiles(..) ) where import Prelude () import Prelude.Compat import Control.Exception (IOException, try) import Control.Monad.IO.Class (MonadIO(liftIO)) import Data.ByteString (ByteString) import Data.List (sort) import Pipes (Pipe, Producer, Producer', Proxy, (>->), await, each, for, next, yield) import Pipes.Prelude (toListM) import qualified Pipes.Prelude as Pipes import System.IO (Handle) import Highlight.Common.Options (InputFilename(unInputFilename), Recursive(Recursive)) import Highlight.Pipes (childOf, fromHandleLines) import Highlight.Util (combineApplicatives, openFilePathForReading) ----------- -- Pipes -- ----------- -- | Place where a file originally came from. data FileOrigin = FileSpecifiedByUser FilePath -- ^ File was specified on the command line by the user. | FileFoundRecursively FilePath -- ^ File was found recursively (not directly specified by the user). | Stdin -- ^ Standard input. It was either specified on the command line as @-@, or -- used as default because the user did not specify any files. deriving (Eq, Read, Show) -- | Get a 'FilePath' from a 'FileOrigin'. -- -- >>> getFilePathFromFileOrigin $ FileSpecifiedByUser "hello.txt" -- Just "hello.txt" -- >>> getFilePathFromFileOrigin $ FileFoundRecursively "bye.txt" -- Just "bye.txt" -- >>> getFilePathFromFileOrigin Stdin -- Nothing getFilePathFromFileOrigin :: FileOrigin -> Maybe FilePath getFilePathFromFileOrigin (FileSpecifiedByUser fp) = Just fp getFilePathFromFileOrigin (FileFoundRecursively fp) = Just fp getFilePathFromFileOrigin Stdin = Nothing -- | This is used in two different places. -- -- One is in 'fileListProducer', where @a@ becomes 'Handle'. This represents a -- single file that has been opened. 'FileReaderSuccess' contains the -- 'FileOrigin' and the 'Handle'. 'FileReaderErr' contains the 'FileOrigin' -- and any errors that occurred when trying to open the 'Handle'. -- -- The other is in 'fileReaderHandleToLine' and 'InputData', where @a@ becomes -- 'ByteString'. This represents a single 'ByteString' line from a file, or an -- error that occurred when trying to read the file. -- -- 'FileReader' is usually wrapped in a 'Producer'. This is a stream of either -- 'Handle's or 'ByteString' lines (with any errors that have occurred). data FileReader a = FileReaderSuccess !FileOrigin !a | FileReaderErr !FileOrigin !IOException !(Maybe IOException) deriving (Eq, Show) -- | Get a 'FileOrigin' from a 'FileReader'. -- -- >>> let fileOrigin1 = FileSpecifiedByUser "hello.txt" -- >>> let fileReader1 = FileReaderSuccess fileOrigin1 "some line" -- >>> getFileOriginFromFileReader fileReader1 -- FileSpecifiedByUser "hello.txt" -- -- >>> let fileOrigin2 = FileFoundRecursively "bye.txt" -- >>> let fileReader2 = FileReaderErr fileOrigin2 (userError "err") Nothing -- >>> getFileOriginFromFileReader fileReader2 -- FileFoundRecursively "bye.txt" getFileOriginFromFileReader :: FileReader a -> FileOrigin getFileOriginFromFileReader (FileReaderSuccess origin _) = origin getFileOriginFromFileReader (FileReaderErr origin _ _) = origin -- | This is just -- @'getFilePathFromFileOrigin' '.' 'getFileOriginFromFileReader'@. -- -- >>> let fileOrigin1 = Stdin -- >>> let fileReader1 = FileReaderSuccess fileOrigin1 "some line" -- >>> getFilePathFromFileReader fileReader1 -- Nothing -- -- >>> let fileOrigin2 = FileFoundRecursively "bye.txt" -- >>> let fileReader2 = FileReaderErr fileOrigin2 (userError "err") Nothing -- >>> getFilePathFromFileReader fileReader2 -- Just "bye.txt" getFilePathFromFileReader :: FileReader a -> Maybe FilePath getFilePathFromFileReader = getFilePathFromFileOrigin . getFileOriginFromFileReader -- | This wraps up two pieces of information. -- -- One is the value of 'FilenameHandlingFromFiles'. This signals as to whether -- or not we need to print the filename when printing each line of output. -- -- This other is a 'Producer' of 'FileReader' 'ByteString's. This is a -- 'Producer' for each line of each input file. -- -- The main job of this module is to define 'createInputData', which produces -- 'InputData'. 'InputData' is what is processed to figure out what to output. data InputData m a = InputData !FilenameHandlingFromFiles !(Producer (FileReader ByteString) m a) -- | Create 'InputData' based 'InputFilename' list. -- -- Setup for examples: -- -- >>> :set -XOverloadedStrings -- >>> import Highlight.Common.Options (InputFilename(InputFilename)) -- >>> import Highlight.Common.Options (Recursive(NotRecursive)) -- -- If the 'InputFilename' list is empty, just create an 'InputData' with -- 'NoFilename' and the standard input 'Producer' passed in. -- -- >>> let stdinProd = yield ("hello" :: ByteString) -- >>> let create = createInputData NotRecursive [] stdinProd -- >>> InputData NoFilename prod <- create -- >>> toListM prod -- [FileReaderSuccess Stdin "hello"] -- -- If the 'InputFilename' list is not empty, create an 'InputData' with lines -- from each file found on the command line. -- -- >>> let inFiles = [InputFilename "test/golden/test-files/file1"] -- >>> let create = createInputData NotRecursive inFiles stdinProd -- >>> InputData NoFilename prod <- create -- >>> Pipes.head prod -- Just (FileReaderSuccess (FileSpecifiedByUser "test/golden/test-files/file1") "The...") createInputData :: forall m. MonadIO m => Recursive -- ^ Whether or not to recursively read in files. -> [InputFilename] -- ^ List of files passed in on the command line. -> Producer ByteString m () -- ^ A producer for standard input -> m (InputData m ()) createInputData recursive inputFilenames stdinProducer = do let fileOrigins = FileSpecifiedByUser . unInputFilename <$> inputFilenames case fileOrigins of [] -> return $ InputData NoFilename (stdinProducerToFileReader stdinProducer) _ -> do let fileListProducers = fmap (fileListProducer recursive) fileOrigins fileProducer = foldl1 combineApplicatives fileListProducers (filenameHandling, newFileProducer) <- computeFilenameHandlingFromFiles fileProducer let fileLineProducer = fileReaderHandleToLine newFileProducer return $ InputData filenameHandling fileLineProducer -- | Change a given 'Producer' into a 'FileReader' 'Producer' with the -- 'FileOrigin' set to 'Stdin'. -- -- You can think of this function as having the following type: -- -- @ -- 'stdinProducerToFileReader' -- :: 'Monad' m -- => 'Producer' a m r -- -> 'Producer' ('FileReader' a) m r -- @ -- -- >>> Pipes.head . stdinProducerToFileReader $ yield "hello" -- Just (FileReaderSuccess Stdin "hello") stdinProducerToFileReader :: forall x' x a m r. Monad m => Proxy x' x () a m r -> Proxy x' x () (FileReader a) m r stdinProducerToFileReader producer = producer >-> Pipes.map go where go :: a -> FileReader a go = FileReaderSuccess Stdin {-# INLINABLE stdinProducerToFileReader #-} -- | Convert a 'Producer' of 'FileReader' 'Handle' into a 'Producer' of -- 'FileReader' 'ByteString', where each line from the 'Handle' is 'yield'ed. -- -- You can think of this function as having the following type: -- -- @ -- 'fileReaderHandleToLine' -- :: 'MonadIO' m -- => 'Producer' ('FileReader' 'Handle') m r -- -> 'Producer' ('FileReader' 'ByteString') m r -- @ -- -- >>> let fileOrigin = FileSpecifiedByUser "test/golden/test-files/file2" -- >>> let producer = fileListProducer Recursive fileOrigin -- >>> Pipes.head $ fileReaderHandleToLine producer -- Just (FileReaderSuccess (FileSpecifiedByUser "test/golden/test-files/file2") "Pr... fileReaderHandleToLine :: forall m x' x r. MonadIO m => Proxy x' x () (FileReader Handle) m r -> Proxy x' x () (FileReader ByteString) m r fileReaderHandleToLine producer = producer >-> pipe where pipe :: Pipe (FileReader Handle) (FileReader ByteString) m r pipe = do fileReaderHandle <- await case fileReaderHandle of FileReaderErr fileOrigin fileErr dirErr -> yield $ FileReaderErr fileOrigin fileErr dirErr FileReaderSuccess fileOrigin handle -> do let linesProducer = fromHandleLines handle linesProducer >-> Pipes.map (FileReaderSuccess fileOrigin) pipe -- | Create a 'Producer' of 'FileReader' 'Handle' for a given 'FileOrigin'. -- -- Setup for examples: -- -- >>> import Highlight.Common.Options (Recursive(NotRecursive, Recursive)) -- -- If 'NoRecursive' is specified, just try to read 'FileOrigin' as a file. -- -- >>> let fileOrigin1 = FileSpecifiedByUser "test/golden/test-files/file2" -- >>> toListM $ fileListProducer NotRecursive fileOrigin1 -- [FileReaderSuccess (FileSpecifiedByUser "test/.../file2") {handle: test/.../file2}] -- -- If the file cannot be read, return an error. -- -- >>> let fileOrigin2 = FileSpecifiedByUser "thisfiledoesnotexist" -- >>> toListM $ fileListProducer NotRecursive fileOrigin2 -- [FileReaderErr (FileSpecifiedByUser "thisfiledoesnotexist") thisfiledoesnotexist: openBinaryFile: does not exist (No such file or directory) Nothing] -- -- If 'Recursive' is specified, then try to read 'FileOrigin' as a directory'. -- -- >>> let fileOrigin3 = FileSpecifiedByUser "test/golden/test-files/dir2" -- >>> toListM $ fileListProducer Recursive fileOrigin3 -- [FileReaderSuccess (FileFoundRecursively "test/.../dir2/file6") {handle: test/.../dir2/file6}] -- -- If the directory cannot be read, return an error. -- -- >>> let fileOrigin4 = FileSpecifiedByUser "thisdirdoesnotexist" -- >>> toListM $ fileListProducer Recursive fileOrigin4 -- [FileReaderErr (FileSpecifiedByUser "thisdirdoesnotexist") thisdirdoesnotexist: openBinaryFile: does not exist (No such file or directory) (Just ...)] fileListProducer :: forall m. MonadIO m => Recursive -> FileOrigin -> Producer' (FileReader Handle) m () fileListProducer recursive = go where go :: FileOrigin -> Producer' (FileReader Handle) m () go fileOrigin = do let maybeFilePath = getFilePathFromFileOrigin fileOrigin case maybeFilePath of -- This is standard input. We don't currently handle this, so just -- return unit. Nothing -> return () -- This is a normal file. Not standard input. Just filePath -> do eitherHandle <- openFilePathForReading filePath case eitherHandle of Right handle -> yield $ FileReaderSuccess fileOrigin handle Left fileIOErr -> if recursive == Recursive then do let fileListM = toListM $ childOf filePath eitherFileList <- liftIO $ try fileListM case eitherFileList of Left dirIOErr -> yield $ FileReaderErr fileOrigin fileIOErr (Just dirIOErr) Right fileList -> do let sortedFileList = sort fileList let fileOrigins = fmap FileFoundRecursively sortedFileList let lalas = fmap (fileListProducer recursive) fileOrigins for (each lalas) id else yield $ FileReaderErr fileOrigin fileIOErr Nothing ----------------------- -- Filename Handling -- ----------------------- -- | This data type specifies how printing filenames will be handled, along -- with the 'computeFilenameHandlingFromFiles' function. data FilenameHandlingFromFiles = NoFilename -- ^ Do not print the filename on stdout. | PrintFilename -- ^ Print the filename on stdout. deriving (Eq, Read, Show) -- | Given a 'Producer' of 'FileReader's, figure out whether or not we should -- print the filename of the file to stdout. -- -- The following examples walk through possible command lines using @highlight@, and the corresponding return values of this function. -- -- @ -- $ highlight expression -- @ -- -- We want to read from stdin. There should be no 'FileReaders' in the -- 'Producer'. Do not print the filename. -- -- >>> let producerStdin = each [] -- >>> (fhStdin, _) <- computeFilenameHandlingFromFiles producerStdin -- >>> fhStdin -- NoFilename -- -- @ -- $ highlight expression file1 -- @ -- -- We want to highlight a single file. There should only be a single -- 'FileReader' in the 'Producer', and it should be 'FileSpecifiedByUser'. Do -- not print the filename. -- -- >>> let fileOriginSingleFile = FileSpecifiedByUser "file1" -- >>> let fileReaderSingleFile = FileReaderSuccess fileOriginSingleFile "hello" -- >>> let producerSingleFile = each [fileReaderSingleFile] -- >>> (fhSingleFile, _) <- computeFilenameHandlingFromFiles producerSingleFile -- >>> fhSingleFile -- NoFilename -- -- @ -- $ highlight expression file1 file2 -- @ -- -- We want to highlight two files. Print the filename. -- -- >>> let fileOriginMulti1 = FileSpecifiedByUser "file1" -- >>> let fileReaderMulti1 = FileReaderSuccess fileOriginMulti1 "hello" -- >>> let fileOriginMulti2 = FileSpecifiedByUser "file2" -- >>> let fileReaderMulti2 = FileReaderSuccess fileOriginMulti2 "bye" -- >>> let producerMultiFile = each [fileReaderMulti1, fileReaderMulti2] -- >>> (fhMultiFile, _) <- computeFilenameHandlingFromFiles producerMultiFile -- >>> fhMultiFile -- PrintFilename -- -- @ -- $ highlight -r expression dir1 -- @ -- -- We want to highlight all files found in @dir1\/@. Print filenames. -- -- >>> let fileOriginRec = FileFoundRecursively "dir1/file1" -- >>> let fileReaderRec = FileReaderSuccess fileOriginRec "cat" -- >>> let producerRec = each [fileReaderRec] -- >>> (fhRec, _) <- computeFilenameHandlingFromFiles producerRec -- >>> fhRec -- PrintFilename computeFilenameHandlingFromFiles :: forall a m r. Monad m => Producer (FileReader a) m r -> m (FilenameHandlingFromFiles, Producer (FileReader a) m r) computeFilenameHandlingFromFiles producer1 = do eitherFileReader1 <- next producer1 case eitherFileReader1 of Left ret -> return (NoFilename, return ret) Right (fileReader1, producer2) -> do let fileOrigin1 = getFileOriginFromFileReader fileReader1 case fileOrigin1 of Stdin -> error "Not currenty handling stdin..." FileSpecifiedByUser _ -> do eitherSecondFile <- next producer2 case eitherSecondFile of Left ret2 -> return (NoFilename, yield fileReader1 *> return ret2) Right (fileReader2, producer3) -> return ( PrintFilename , yield fileReader1 *> yield fileReader2 *> producer3 ) FileFoundRecursively _ -> return (PrintFilename, yield fileReader1 *> producer2)
cdepillabout/highlight
src/Highlight/Common/Monad/Input.hs
bsd-3-clause
15,147
0
30
2,962
1,766
1,007
759
174
5
{-# LANGUAGE OverloadedStrings #-} module Language.Eiffel.PrettyPrint where import Control.Lens hiding (to, lens, from, assign, op) import Data.Hashable import qualified Data.HashMap.Strict as Map import qualified Data.Set as Set import Data.Set (Set) import qualified Data.Text as Text import Data.Text (Text) import Text.PrettyPrint import Language.Eiffel.Syntax import Language.Eiffel.Position ttext = text . Text.unpack defaultIndent = 2 nestDef = nest defaultIndent renderWithTabs = fullRender (mode style) (lineLength style) (ribbonsPerLine style) spacesToTabs "" where spacesToTabs :: TextDetails -> String -> String spacesToTabs (Chr c) s = c:s spacesToTabs (Str s1) s2 = spaceAppend s1 s2 spacesToTabs (PStr s1) s2 = spaceAppend s1 s2 spaceAppend s1 s2 = if s1 == replicate (length s1) ' ' && length s1 > 1 then replicate (length s1 `div` defaultIndent) '\t' ++ s2 else s1 ++ s2 newline = char '\n' emptyLine = text "" ups = Text.toUpper toDoc :: Clas -> Doc toDoc = toDocWith False routineBodyDoc toInterfaceDoc :: ClasInterface -> Doc toInterfaceDoc = toDocWith True interfaceBodyDoc interfaceBodyDoc :: EmptyBody -> Doc interfaceBodyDoc = const (text "do") toDocWith fullAttr bodyDoc c = let defer = if deferredClass c then text "deferred" else empty froz = if frozenClass c then text "frozen" else empty expnd = if expandedClass c then text "expanded" else empty in vsep [ notes (classNote c) $+$ (if null (classNote c) then empty else emptyLine) , defer <+> froz <+> expnd <+> text "class" , nestDef (ttext (ups $ className c)) <+> genericsDoc (generics c) <+> procGenDoc (procGeneric c) , emptyLine , inheritance (inherit c) , vsep (map createClause (creates c)) , convertClause (converts c) , vsep (featureClauses fullAttr bodyDoc (featureMap c)) , invars (invnts c) , text "end" ] inheritance is = vsep (map inheritanceClauses is) inheritanceClauses (Inheritance nonConform cs) = let conformMark | nonConform = text "{NONE}" | otherwise = empty in (text "inherit" <+> conformMark) $+$ nestDef (vsep (map inheritClause cs)) inheritClause (InheritClause cls renames exports undefs redefs selects) = let renameDoc (Rename orig new alias) = ttext orig <+> text "as" <+> ttext new <+> maybe empty (\a -> text "alias" <+> doubleQuotes (ttext a)) alias exportListDoc (ExportFeatureNames l) = vCommaSep (map ttext l) exportListDoc ExportAll = text "all" exportDoc (Export to what) = braces (commaSep (map ttext to)) $+$ nestDef (exportListDoc what) in type' cls $+$ nestDef (vsep [ text "rename" $?$ nestDef (vCommaSep (map renameDoc renames)) , text "export" $?$ nestDef (vsep (map exportDoc exports)) , text "undefine" $?$ nestDef (vCommaSep (map ttext undefs)) , text "redefine" $?$ nestDef (vCommaSep (map ttext redefs)) , text "select" $?$ nestDef (vCommaSep (map ttext selects)) , if null renames && null exports && null undefs && null redefs && null selects then empty else text "end" , emptyLine ]) createClause (CreateClause exports names) = let exps = if null exports then empty else braces (commaSep (map ttext exports)) in (text "create" <+> exps) $+$ nestDef (commaSep (map ttext names)) $+$ emptyLine convertClause [] = empty convertClause convs = let go (ConvertFrom fname ts) = ttext fname <+> parens (braces (commaSep (map type' ts))) go (ConvertTo fname ts) = ttext fname <> colon <+> braces (commaSep (map type' ts)) in text "convert" $+$ nestDef (vCommaSep (map go convs)) $+$ emptyLine featureClauses :: (Ord body) => Bool -> (body -> Doc) -> FeatureMap body Expr -> [Doc] featureClauses fullAttr bodyDoc featMap = concat [ allExports fmRoutines routDoc' , allExports fmAttrs attrDoc' , allExports fmConsts constDoc' ] where insertExport expMap (ExportedFeature exports feat) = Map.insertWith Set.union exports (Set.singleton feat) expMap exportMap lens = Map.foldl' insertExport Map.empty (view lens featMap) exportDoc exports | Set.null exports = empty | otherwise = braces (commaSep (map ttext $ Set.toList exports)) routDoc' r = routineDoc bodyDoc r $+$ emptyLine attrDoc' a = attrDoc fullAttr a $+$ emptyLine constDoc' c = constDoc c $+$ emptyLine printExports featDoc exports someFeats = vsep [ text "feature" <+> exportDoc exports , emptyLine , nestDef $ vsep $ map featDoc $ Set.toList someFeats ] allExports lens featDoc = map (uncurry $ printExports featDoc) $ Map.toList (exportMap lens) vsep = foldr ($+$) empty commaSep = hsep . punctuate comma vCommaSep = vsep . punctuate comma angles d = langle <> d <> rangle langle = char '<' rangle = char '>' squareQuotes t = text "\"[" <> t <> text "]\"" anyStringLiteral s | Text.isPrefixOf "\n" s = squareQuotes $ ttext s | Text.isPrefixOf "\r\n" s = squareQuotes $ ttext s | otherwise = doubleQuotes $ stringLiteral s stringLiteral s = ttext s' where s' = go' s go' = go . Text.uncons go (Just ('\n', cs)) = Text.append "%N" $ go' cs go (Just ('\r', cs)) = Text.append "%R" $ go' cs go (Just ('\t', cs)) = Text.append "%T" $ go' cs go (Just ('"', cs)) = Text.append "%\"" $ go' cs go (Just (c, cs)) = Text.cons c (go' cs) go Nothing = Text.empty procDoc (Proc s) = ttext s procDoc Dot = text "<procdot>" genericsDoc [] = empty genericsDoc gs = brackets (commaSep (map go gs)) where go (Generic name constr createsMb) = ttext name <+> constraints constr <+> maybe empty create createsMb constraints [] = empty constraints [t] = text "->" <+> type' t constraints ts = text "->" <+> braces (commaSep (map type' ts)) create cs = hsep [ text "create" , commaSep (map ttext cs) , text"end" ] notes [] = empty notes ns = vsep [ text "note" , nestDef (vsep $ map note ns) ] note (Note tag content) = ttext tag <> colon <+> commaSep (map (expr' 0) content) invars is = text "invariant" $?$ clausesDoc is procGenDoc [] = empty procGenDoc ps = go ps where go = angles . hsep . punctuate comma . map procDoc decl :: Decl -> Doc decl (Decl label typ) = ttext label <> typeDoc typ typeDoc NoType = empty typeDoc t = text ":" <+> type' t frozen b = if b then text "frozen" else empty require (Contract inh c) = (if inh then text "require else" else text "require") $?$ clausesDoc c ensure (Contract inh c) = (if inh then text "ensure then" else text "ensure") $?$ clausesDoc c constDoc :: Constant Expr -> Doc constDoc (Constant froz d val) = frozen froz <+> decl d <+> text "=" <+> expr val attrDoc :: Bool -> Attribute Expr -> Doc attrDoc fullAttr (Attribute froz d assn ns reqs ens) = frozen froz <+> decl d <+> assignText assn $+$ nestDef (vsep [ notes ns , require reqs , attrKeyword , ensure ens , endKeyword ]) where assignText Nothing = empty assignText (Just a) = text "assign" <+> ttext a hasBody = not (null (contractClauses ens) && null (contractClauses reqs) && null ns) attrKeyword | hasBody || fullAttr = text "attribute" | otherwise = empty endKeyword | hasBody || fullAttr = text "end" | otherwise = empty type' :: Typ -> Doc type' (ClassType str gens) = ttext (ups str) <+> genDoc gens type' VoidType = text "NONE" type' (Like e) = text "like" <+> expr e type' NoType = empty type' (Sep mP ps str) = sepDoc <+> procM mP <+> procs ps <+> ttext str type' (TupleType typeDecls) = let typeArgs = case typeDecls of Left types -> commaSep (map type' types) Right decls -> hcat (punctuate (text ";") (map decl decls)) tupleGen | isEmpty typeArgs = empty | otherwise = text "[" <> typeArgs <> text "]" in text "TUPLE" <+> tupleGen routineDoc :: (body -> Doc) -> AbsRoutine body Expr -> Doc routineDoc bodyDoc f = let header = frozen (routineFroz f) <+> ttext (routineName f) <+> alias <+> formArgs (routineArgs f) <> typeDoc (routineResult f) <+> procs (routineProcs f) alias = case routineAlias f of Nothing -> empty Just name -> text "alias" <+> doubleQuotes (ttext name) assign = case routineAssigner f of Nothing -> empty Just name -> text "assign" <+> ttext name rescue = case routineRescue f of Nothing -> empty Just stmts -> text "rescue" $+$ nestDef (vsep $ map stmt stmts) in header <+> assign $+$ (nestDef $ vsep [ notes (routineNote f) , require (routineReq f) , text "require-order" $?$ nestDef (procExprs f) , text "lock" $?$ nestDef (locks (routineEnsLk f)) , bodyDoc $ routineImpl f , ensure (routineEns f) , rescue , text "end" ] ) routineBodyDoc RoutineDefer = text "deferred" routineBodyDoc (RoutineExternal s aliasMb) = vcat [ text "external" , nestDef (anyStringLiteral s) , text "alias" $?$ maybe empty anyStringLiteral aliasMb ] routineBodyDoc ft = vsep [ locals ft , text "do" , nestDef $ stmt $ routineBody ft ] locals ft = text "local" $?$ nestDef (vsep $ map decl (routineLocal ft)) procExprs = vCommaSep . map procExprD . routineReqLk ($?$) :: Doc -> Doc -> Doc ($?$) l e | isEmpty e = empty | otherwise = l $+$ e (<?>) :: Doc -> Doc -> Doc (<?>) l e | isEmpty e = empty | otherwise = l <?> e clausesDoc :: [Clause Expr] -> Doc clausesDoc cs = nestDef (vsep $ map clause cs) clause :: Clause Expr -> Doc clause (Clause nameMb e) = maybe empty (\n -> ttext n <> colon) nameMb <+> expr e stmt = stmt' . contents stmt' (Assign l e) = expr l <+> text ":=" <+> expr e stmt' (AssignAttempt l e) = expr l <+> text "?=" <+> expr e stmt' (CallStmt e) = expr e stmt' (If cond body elseParts elseMb) = let elsePart = case elseMb of Just elsee -> vsep [text "else", nestDef (stmt elsee)] Nothing -> empty elseifPart (ElseIfPart c s) = vsep [ text "elseif" <+> expr c <+> text "then" , nestDef (stmt s) ] elseifParts es = vsep (map elseifPart es) in vsep [ text "if" <+> expr cond <+> text "then" , nestDef (stmt body) , elseifParts elseParts , elsePart , text "end" ] stmt' (Inspect e whens elseMb) = let elsePart = case elseMb of Nothing -> empty Just s -> text "else" $+$ nestDef (stmt s) whenParts (es', s) = (text "when" <+> commaSep (map expr es') <+> text "then") $+$ nestDef (stmt s) in vsep [ text "inspect" <+> expr e , vsep (map whenParts whens) , elsePart , text "end" ] stmt' (Across e asIdent invs body var) = vcat [ text "across" , nestDef (expr e <+> text "as" <+> ttext asIdent) , text "invariant" $?$ clausesDoc invs , text "loop" , nestDef (stmt body) , text "variant" $?$ maybe empty (nestDef . expr) var , text "end" ] stmt' (BuiltIn) = text "builtin" stmt' (Create t tar n es) = text "create" <+> maybe empty (braces . type') t <+> if n == defaultCreate then expr tar else expr' 0 (QualCall tar n es) stmt' (Block ss) = vsep (map stmt ss) stmt' (Check cs) = if length cs == 1 then text "check" <+> clause (head cs) <+> text "end" else vsep [ text "check" , nestDef (vsep (map clause cs)) , text "end" ] stmt' (CheckBlock cs body) = vsep [ text "check" <+> vsep (map clause cs) <+> text "then" , stmt body , text "end" ] stmt' (Loop from invs cond loop var) = vsep [ text "from" , nestDef (stmt from) , text "invariant" $?$ clausesDoc invs , text "until" , nestDef (expr cond) , text "loop" , nestDef (stmt loop) , text "variant" $?$ maybe empty (nestDef . expr) var , text "end" ] stmt' (Debug str body) = vsep [ text "debug" <+> (if Text.null str then empty else (parens . anyStringLiteral) str) , nestDef (stmt body) , text "end" ] stmt' Retry = text "retry" stmt' s = error ("PrettyPrint.stmt': " ++ show s) expr = exprPrec 0 exprPrec :: Int -> Expr -> Doc exprPrec i = expr' i . contents expr' _ (UnqualCall n es) = ttext n <+> actArgs es expr' _ (QualCall t n es) = target <> ttext n <+> actArgs es where target = case contents t of CurrentVar -> empty _ -> exprPrec 13 t <> char '.' expr' _ (PrecursorCall cname es) = text "Precursor" <+> maybe empty (braces . ttext) cname <+> actArgs es expr' i (AcrossExpr e as q body) = hsep [ text "across" , exprPrec i e , text "as" , ttext as , quant q , expr body , text "end" ] expr' i (UnOpExpr uop e) = condParens (i > 12) $ ttext (unop uop) <+> exprPrec 12 e expr' i (IfThenElse cond t elifs e) = hsep $ [ text "if" , expr cond , text "then" , expr t] ++ concatMap (\(c, elif) -> [text "elseif", expr c, text "then", expr elif]) elifs ++ [ text "else" , expr e , text "end" ] expr' i (Lookup targ args) = case targ of Pos _ (Lookup _ _) -> parens (exprPrec i targ) <+> brackets (commaSep (map expr args)) _ -> exprPrec i targ <+> brackets (commaSep (map expr args)) expr' i (BinOpExpr (SymbolOp op) e1 e2) | op == "[]" = exprPrec i e1 <+> brackets (expr e2) | otherwise = condParens (i > 11) (exprPrec 11 e1 <+> ttext op <+> exprPrec 12 e2) expr' i (BinOpExpr bop e1 e2) = condParens (i > p) (exprPrec lp e1 <+> ttext op <+> exprPrec rp e2) where (op, p) = binop bop lp = p rp = p + 1 expr' _ (Attached t e asVar) = text "attached" <+> maybe empty (braces . type') t <+> expr e <+> maybe empty (\s -> text "as" <+> ttext s) asVar expr' _ (CreateExpr t n es) = text "create" <+> braces (type' t) <> if n == defaultCreate then empty else char '.' <> ttext n <+> actArgs es expr' _ (StaticCall t i args) = braces (type' t) <> char '.' <> ttext i <+> actArgs args expr' _ (LitArray es) = text "<<" <+> commaSep (map expr es) <+> text ">>" expr' _ (ManifestCast t e) = braces (type' t) <+> expr e expr' _ (OnceStr s) = text "once" <+> ttext s expr' _ (Address e) = text "$" <> expr e expr' _ (VarOrCall s) = ttext s expr' _ ResultVar = text "Result" expr' _ CurrentVar = text "Current" expr' _ LitVoid = text "Void" expr' i (LitChar c) = condParens (i >= 13) $ quotes (char c) expr' i (LitString s) = condParens (i >= 13) $ anyStringLiteral s expr' i (LitInt int') = condParens (i >= 13) $ integer int' expr' i (LitBool b) = condParens (i >= 13) $ text (show b) expr' i (LitDouble d) = condParens (i >= 13) $ double d expr' i (LitType t) = condParens (i >= 13) $ braces (type' t) expr' _ (Tuple es) = brackets (hcat $ punctuate comma (map expr es)) expr' _ (Agent e) = text "agent" <+> case contents e of QualCall t n es -> case contents t of VarOrCall _name -> expr e _ -> parens (expr t) <> char '.' <> ttext n <+> actArgs es _ -> expr e expr' _ (InlineAgent ds resMb ss args) = let decls = formArgs ds res = maybe empty (\t -> colon <+> type' t) resMb in vsep [ text "agent" <+> decls <+> res , text "do" , nestDef $ vsep (map stmt ss) , text "end" <+> condParens (not $ null args) (commaSep (map expr args)) ] expr' _ s = error ("expr': " ++ show s) quant All = text "all" quant Some = text "some" condParens True e = parens e condParens False e = e unop Neg = "-" unop Not = "not" unop Old = "old" opList = [ (Pow, ("^", 10)) , (Mul, ("*", 9)) , (Div, ("/", 9)) , (Quot, ("//", 9)) , (Rem, ("\\\\", 9)) , (Add, ("+", 8)) , (Sub, ("-", 8)) , (And, ("and", 5)) , (AndThen, ("and then", 5)) , (Or, ("or", 4)) , (Xor, ("xor", 4)) , (OrElse, ("or else", 4)) , (Implies, ("implies", 3)) ] binop :: BinOp -> (Text, Int) binop (SymbolOp o) = (o, 11) binop (RelOp r _) = (relop r, 6) binop o = case lookup o opList of Just (n,p) -> (n,p) Nothing -> error "binop: could not find operator" relop Lt = "<" relop Lte = "<=" relop Gt = ">" relop Gte = ">=" relop Eq = "=" relop Neq = "/=" relop TildeEq = "~" relop TildeNeq = "/~" actArgs [] = empty actArgs es = parens $ hsep $ punctuate comma (map expr es) formArgs [] = empty formArgs ds = parens $ hsep $ punctuate semi (map decl ds) genDoc :: [Typ] -> Doc genDoc [] = empty genDoc ps = brackets $ hcat $ punctuate comma (map type' ps) procExprD (LessThan a b) = proc a <+> langle <+> proc b locks [] = empty locks ps = hsep $ punctuate comma (map proc ps) procs [] = empty procs ps = angles $ locks ps proc (Proc p) = ttext p proc Dot = text "dot_proc" procM = maybe empty (angles . proc) sepDoc = text "separate" instance Hashable a => Hashable (Set a) where hashWithSalt salt v = hashWithSalt salt (Set.toAscList v)
scottgw/language-eiffel
Language/Eiffel/PrettyPrint.hs
bsd-3-clause
18,245
0
17
5,670
7,233
3,553
3,680
433
6
module JavaScript.AceAjax.Raw.BackgroundTokenizer where import qualified GHCJS.Types as GHCJS import qualified GHCJS.Marshal as GHCJS import qualified Data.Typeable import GHCJS.FFI.TypeScript import GHCJS.DOM.Types (HTMLElement) import JavaScript.AceAjax.Raw.Types foreign import javascript "$1.states" states :: BackgroundTokenizer -> IO (GHCJS.JSArray (GHCJS.JSRef obj0)) foreign import javascript "$1.setTokenizer($2)" setTokenizer :: (BackgroundTokenizer) -> (Tokenizer) -> IO (()) foreign import javascript "$1.setDocument($2)" setDocument :: (BackgroundTokenizer) -> (Document) -> IO (()) foreign import javascript "$1.fireUpdateEvent($2,$3)" fireUpdateEvent :: (BackgroundTokenizer) -> (GHCJS.JSNumber) -> (GHCJS.JSNumber) -> IO (()) foreign import javascript "$1.start($2)" start :: (BackgroundTokenizer) -> (GHCJS.JSNumber) -> IO (()) foreign import javascript "$1.stop()" stop :: (BackgroundTokenizer) -> IO (()) foreign import javascript "$1.getTokens($2)" getTokens :: (BackgroundTokenizer) -> (GHCJS.JSNumber) -> IO (GHCJS.JSArray (TokenInfo)) foreign import javascript "$1.getState($2)" getState :: (BackgroundTokenizer) -> (GHCJS.JSNumber) -> IO (GHCJS.JSString)
fpco/ghcjs-from-typescript
ghcjs-ace/JavaScript/AceAjax/Raw/BackgroundTokenizer.hs
bsd-3-clause
1,180
20
10
121
341
194
147
15
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE DeriveGeneric #-} ------------------------------------------------------------------------------- -- | -- File : minecraftctl.hs -- Copyright : (c) 2016 Michael Carpenter -- License : GPL3 -- Maintainer : Michael Carpenter <oldmanmike.dev@gmail.com> -- Stability : experimental -- Portability : non-portable (requires Tmux) -- ------------------------------------------------------------------------------- import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip import Control.Concurrent import Control.Monad import Data.Aeson import qualified Data.ByteString.Lazy as BL import Data.Functor.Identity import qualified Data.List as List import qualified Data.Map as Map import Data.String import Data.Thyme.LocalTime (getZonedTime) import Data.Thyme.Format (formatTime) import Data.UUID hiding (fromString) import GHC.Generics import Network.HTTP.Conduit import Options.Applicative import System.Directory import System.Exit import System.IO import System.Locale (defaultTimeLocale) import System.Process import Test.QuickCheck testServer :: Server testServer = Server { srvName = "test" , srvPort = 25566 , srvPath = "/srv/test" , srvBackupPath = "/srv/test/backup" , srvLogPath = "/srv/test/logs" , srvWorld = "world" , srvVersion = "16w04a" , srvPlayers = 0 , srvMaxPlayers = 20 , srvMotd = "A Minecraft server" , srvEnabled = True , srvUp = False } ecServer :: Server ecServer = Server { srvName = "ecServer" , srvPort = 25565 , srvPath = "/srv/minecraft" , srvBackupPath = "/home/oldmanmike/backup" , srvLogPath = "/srv/minecraft/logs" , srvWorld = "world" , srvVersion = "1.9" , srvPlayers = 0 , srvMaxPlayers = 20 , srvMotd = "A Minecraft server" , srvEnabled = True , srvUp = False } javaArgs :: [String] javaArgs = [ "-Xmx4G" , "-Xms512M" , "-XX:+UseConcMarkSweepGC" , "-XX:+CMSIncrementalPacing" , "-XX:ParallelGCThreads=4" , "-XX:+AggressiveOpts" ] -- | Takes the absolute path to the server's directory and the server's version -- and constructs the shell command to run in Tmux. minecraftServiceCmd :: FilePath -> String -> String minecraftServiceCmd rootPath v = "cd " ++ rootPath ++"; java -Xmx4G -Xms512M -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalPacing -XX:ParallelGCThreads=4 -XX:+AggressiveOpts -jar minecraft_server." ++ v ++ ".jar nogui" runMinecraftServer :: [String] -> Server -> IO () runMinecraftServer args srv = callCommand ("cd " ++ srvPath srv ++"; java -jar " ++ srvPath srv ++ "/" ++ mcServerJar (srvVersion srv) ++ " nogui") prompt :: String -> Maybe String -> IO String prompt prompt maybeInput = case maybeInput of Just input -> return $ show input Nothing -> do putStr prompt hFlush stdout x <- getLine return x promptInt :: String -> Maybe Int -> IO Int promptInt prompt maybeInput = case maybeInput of Just input -> return input Nothing -> do putStr prompt hFlush stdout x <- getLine return (read x :: Int) setupNewServer :: String -> Maybe Int -> Maybe FilePath -> Maybe String -> Maybe String -> IO () setupNewServer n maybeP maybeR maybeW maybeV = do putStrLn "Welcome to Open Sandbox's Interactive Server Setup!" putStrLn "Please provide the following:" p <- promptInt "Port: " maybeP r <- prompt "Server Path (eg. /srv/minecraft): " maybeR w <- prompt "World Name: " maybeW v <- prompt "Version: " maybeV putStrLn "Setting up new server..." let newServer = Server n (toEnum p) r (r++"/backup") (r++"/logs") w v 0 20 "" False False createDirectoryIfMissing True (srvPath newServer) createDirectoryIfMissing True (srvBackupPath newServer) putStr $ "Downloading minecraft." ++ v ++ ".jar..." hFlush stdout getMCSnapshot (srvPath newServer) (srvVersion newServer) putStrLn "[Done]" writeFile (srvPath newServer ++ "/server.properties") ("server-port="++show p++"\n"++"level-name="++w) runMinecraftServer [] newServer putStrLn "----------------------------------------------------------------" putStrLn "| << Mojang's End User License Agreement >> |" putStrLn "----------------------------------------------------------------" eula <- readFile $ srvPath newServer ++ "/eula.txt" mapM_ putStrLn (lines eula) putStrLn "Do you Agree? (y/n)" c <- getChar when (c == 'y') $ writeFile (srvPath newServer ++ "/eula.txt") (unlines (init (lines eula) ++ ["eula=true"])) newWindow (tmuxID newServer) (srvPath newServer) n sendTmux (tmuxID newServer) (minecraftServiceCmd (srvPath newServer) (srvVersion newServer)) threadDelay 10000000 killWindow $ show p putStrLn "Server Setup Complete!" boot :: IO () boot = tmuxInit shutdown :: IO () shutdown = tmuxClose create :: Servers -> String -> Maybe Int -> Maybe String -> Maybe String -> Maybe String -> IO () create slst n p r w v = case Map.lookup n slst of Just s -> putStrLn "Error: Service already exists!" Nothing -> setupNewServer n p r w v start :: Servers -> String -> IO () start slst n = case Map.lookup n slst of Just s -> mkTmuxWindow s >> launchServerInWindow s Nothing -> putStrLn $ "Error: Cannot find service " ++ n ++ "!" where mkTmuxWindow s = newWindow (tmuxID s) (srvPath s) n launchServerInWindow s = sendTmux (tmuxID s) (minecraftServiceCmd (srvPath s) (srvVersion s)) stop :: Servers -> String -> IO () stop slst n = case Map.lookup n slst of Just s -> sendTmux (tmuxID s) "stop" >> callCommand "sleep 5" >> killWindow (show $ srvPort s) Nothing -> putStrLn $ "Error: Cannot find service " ++ n ++ "!" status :: Servers -> String -> IO () status slst n = putStrLn $ "Getting status of " ++ n ++ "..." enable :: Servers -> String -> IO () enable slst n = putStrLn $ "Disabling " ++ n ++ "..." disable :: Servers -> String -> IO () disable slst n = putStrLn $ "Disabling " ++ n ++ "..." restart :: Servers -> String -> IO () restart slst n = putStrLn $ "Restarting " ++ n ++ "..." reload :: Servers -> String -> IO () reload slst n = putStrLn $ "Reloading " ++ n ++ "..." whoison :: Servers -> String -> IO () whoison slst n = putStrLn $ "The following users are logged into " ++ n ++ "..." -- | Backs up the target Minecraft service. backup :: Servers -> String -> IO () backup slst n = case Map.lookup n slst of Just s -> fullBackup (tmuxID s) (srvPath s) (srvBackupPath s) [srvWorld s, "minecraft_server." ++ srvVersion s ++ ".jar"] Nothing -> putStrLn $ "Error: Cannot find service " ++ n ++ "!" upgrade :: Servers -> String -> String -> String -> IO () upgrade slst n "to" v = putStrLn $ "Upgrading " ++ n ++ "..." upgrade slst n _ v = putStrLn "Error: Invalid command syntax!" downgrade :: Servers -> String -> String -> String -> IO () downgrade slst n "to" v = putStrLn $ "Downgrading " ++ n ++ "..." downgrade slst n _ v = putStrLn "Error: Invalid command syntax!" -- | Executes the 'say' command in the target Minecraft server. -- Must be provided the list of services, the target service, -- and the message to say on the server. say :: Servers -> String -> String -> IO () say slst s m = case Map.lookup s slst of Just s -> sendTmux (tmuxID s) ("say " ++ m) Nothing -> putStrLn "Error: Service cannot be found!" with :: Servers -> String -> String -> IO () with slst s c = putStrLn $ "Running command " ++ c ++ "..." portOption :: Parser (Maybe Int) portOption = optional $ option auto ( long "port" <> short 'p' <> metavar "LABEL" <> help "Assign a service a PORT") rootPathOption :: Parser (Maybe String) rootPathOption = optional $ strOption ( long "rootpath" <> short 'r' <> metavar "ROOTPATH" <> help "Assign a service a root location ROOTPATH") worldOption :: Parser (Maybe String) worldOption = optional $ strOption ( long "world" <> short 'w' <> metavar "WORLD" <> help "Assign a service a WORLD") versionOption :: Parser (Maybe String) versionOption = optional $ strOption ( long "version" <> short 'v' <> metavar "WORLD" <> help "Assign a service a game VERSION") commands :: Servers -> Parser (IO ()) commands slst = subparser ( command "boot" (info (helper <*> pure boot) (fullDesc <> progDesc "Boots the Tmux Server" <> header "boot - starts the Tmux Server")) <> command "shutdown" (info (helper <*> pure shutdown) (fullDesc <> progDesc "Shuts down the Tmux Server" <> header "shutdown - closes the Tmux Server")) <> command "create" (info (helper <*> (create slst <$> argument str idm <*> portOption <*> rootPathOption <*> worldOption <*> versionOption)) (fullDesc <> progDesc "minecraftctl create TARGET" <> header "create - creates a new minecraft server")) <> command "start" (info (helper <*> (start slst <$> argument str idm)) (fullDesc <> progDesc "Starts a TARGET server" <> header "start - starts a server")) <> command "stop" (info (helper <*> (stop slst <$> argument str idm)) (fullDesc <> progDesc "Stops a TARGET server" <> header "stop - stops a server")) <> command "restart" (info (helper <*> (restart slst <$> argument str idm)) (fullDesc <> progDesc "Restarts a TARGET server" <> header "restart - restarts a server")) <> command "status" (info (helper <*> (status slst <$> argument str idm)) (fullDesc <> progDesc "Obtains the status of TARGET service" <> header "status - get the status of the service")) <> command "enable" (info (helper <*> (enable slst <$> argument str idm)) (fullDesc <> progDesc "Enables a TARGET server" <> header "enable - enables a server")) <> command "disable" (info (helper <*> (disable slst <$> argument str idm)) (fullDesc <> progDesc "Disables a TARGET server" <> header "disable - disables a server")) <> command "reload" (info (helper <*> (reload slst <$> argument str idm)) (fullDesc <> progDesc "Reloads a TARGET server" <> header "reload - reload a server")) <> command "whoison" (info (helper <*> (whoison slst <$> argument str idm)) (fullDesc <> progDesc "Lists all users currently logged in on TARGET" <> header "whoison - lists logged in users")) <> command "backup" (info (helper <*> (backup slst <$> argument str idm)) (fullDesc <> progDesc "Backs up a TARGET server" <> header "backup - back ups a server")) <> command "upgrade" (info (helper <*> (upgrade slst <$> argument str idm <*> argument str idm <*> argument str idm)) (fullDesc <> progDesc "Updates a TARGET server" <> header "upgrade - upgrades a server to the given version")) <> command "downgrade" (info (helper <*> (downgrade slst <$> argument str idm <*> argument str idm <*> argument str idm)) (fullDesc <> progDesc "Downgrades a TARGET server" <> header "downgrade - downgrades a server to the given version")) <> command "say" (info (helper <*> (say slst <$> argument str idm <*> argument str idm)) (fullDesc <> progDesc "minecraftctl say TARGET" <> header "say - 'say' something on a server")) <> command "with" (info (helper <*> (with slst <$> argument str idm <*> argument str idm)) (fullDesc <> progDesc "with a TARGET server, run the following COMMAND" <> header "with - Run server commands via a given server"))) opts slst = info (helper <*> commands slst) ( fullDesc <> progDesc "Controls Minecraft Servers" <> header "minecraftctl - [OPTIONS...] {COMMAND} ...") main :: IO () main = do let defaultServices = Map.singleton "ecServer" ecServer join $ execParser (opts defaultServices) backupLabel :: String -> String -> String backupLabel name time = name ++ "-backup-" ++ time ++ ".tar.gz" fullBackup :: TmuxID -> FilePath -> FilePath -> [FilePath] -> IO () fullBackup t rootDir backupDir targets = do sendTmux t "say SERVER BACKUP STARTING. Server going readonly..." localTime <- getZonedTime let label = backupLabel "ecserver3" $ formatTime defaultTimeLocale "%y-%m-%dT%H-%M-%S" localTime sendTmux t "save-off" sendTmux t "save-all" sendTmux t "say Archiving..." tarball <- Tar.pack rootDir targets sendTmux t "save-on" sendTmux t "say Compressing..." BL.writeFile (backupDir ++ "/" ++ label) . GZip.compress . Tar.write $ tarball sendTmux t "say Backup Complete!" type Servers = Map.Map String Server data Server = Server { srvName :: String , srvPort :: Int , srvPath :: FilePath , srvBackupPath :: FilePath , srvLogPath :: FilePath , srvWorld :: String , srvVersion :: String , srvPlayers :: Int , srvMaxPlayers :: Int , srvMotd :: String , srvEnabled :: Bool , srvUp :: Bool } deriving (Show,Eq) newtype TmuxID = TmuxID (TmuxSessionID,TmuxWindowID) deriving (Show,Read,Eq,Ord) instance Arbitrary TmuxID where arbitrary = do let s = arbitrary :: Gen String let w = arbitrary :: Gen String liftM (TmuxID) $ liftM2 (,) s w type TmuxSessionID = String type TmuxWindowID = String tmuxID :: Server -> TmuxID tmuxID s = TmuxID $ ("opensandbox",(show $ srvPort s)) fmtTmuxID :: TmuxID -> String fmtTmuxID (TmuxID (s,w)) = s ++ ":" ++ w -- | Takes a String `"sessionID" ++ ":" ++ "windowID"` and might build a TmuxID out of it. -- -- > parseTmuxID "opensandbox:25565" = Just (TmuxID ("opensandbox","25565")) -- -- It will return `Nothing` if it is given a string that has more or less than 1 ':' present in it. -- -- > parseTmuxID "opensandbox25565" = Nothing -- -- It will also return `Nothing` if either the sessionID or the windowID are an empty string. -- -- > parseTmuxID ":25565" = Nothing -- > parseTmuxID "opensandbox:" = Nothing parseTmuxID :: String -> Maybe TmuxID parseTmuxID x = if cnt ':' x == 1 then if s /= [] && w /= [] then Just (TmuxID (s,w)) else Nothing else Nothing where s = fst $ break (==':') x w = tail . snd $ break (==':') x cnt i lst = length $ filter (==i) lst sendTmux :: TmuxID -> String -> IO () sendTmux t c = callCommand $ "tmux send -t " ++ fmtTmuxID t ++ " " ++ show c ++ " ENTER" detachClient :: TmuxWindowID -> IO () detachClient w = callCommand $ "tmux detach-client -t " ++ w newWindow :: TmuxID -> FilePath -> String -> IO () newWindow t d n = callCommand $ "tmux new-window -t " ++ fmtTmuxID t ++ " -c " ++ d ++ " -n " ++ n killWindow :: TmuxWindowID -> IO () killWindow w = callCommand $ "tmux kill-window -t " ++ w isRunning :: IO Bool isRunning = doesDirectoryExist "/tmp/tmux-1000" tmuxInit :: IO () tmuxInit = do putStr "Starting tmux session: " p <- spawnCommand "tmux new -d -s opensandboxd" code <- waitForProcess p case code of ExitSuccess -> putStrLn "[Success]" ExitFailure i -> putStrLn "[Fail]" tmuxClose :: IO () tmuxClose = do putStr "Closing tmux..." p <- spawnCommand "tmux kill-session -t opensandboxd" code <- waitForProcess p case code of ExitSuccess -> putStrLn "[Success]" ExitFailure i -> putStrLn "[Fail]" type MCVersion = String -- | Grabs the latest Minecraft snapshot from Mojang's servers -- param cacheDir: The path to the cache directory getLatestMCSnapshot :: FilePath -> IO () getLatestMCSnapshot cacheDir = do mcVersion <- findLatestMCSnapshot case mcVersion of Left err -> putStrLn $ "Error: Could not get latest snapshot. " ++ err Right v -> getMCSnapshot cacheDir v -- | Grabs a Minecraft snapshot from Mojang's servers -- param version: The version num of the target snapshot -- param cacheDir: The path to the cache directory -- returns: An IO action that saves the snapshot of said version to the said cache directory getMCSnapshot :: FilePath -> String -> IO () getMCSnapshot dest version = do let url = List.intercalate "/" [mcVersionsURL, version, mcServerJar version] simpleHttp url >>= BL.writeFile (dest ++ "/" ++ mcServerJar version) findLatestMCSnapshot :: IO (Either String MCVersion) findLatestMCSnapshot = do raw <- getMCVersionList case raw of Left err -> return $ Left err Right vList -> return $ Right $ snapshot $ latest vList getMCVersionList :: IO (Either String VersionList) getMCVersionList = eitherDecode <$> simpleHttp mcVersionsListURL mcVersionsURL :: String mcVersionsURL = "https://s3.amazonaws.com/Minecraft.Download/versions" mcVersionsListURL :: String mcVersionsListURL = "https://s3.amazonaws.com/Minecraft.Download/versions/versions.json" mcServerJar :: MCVersion -> String mcServerJar version = "minecraft_server." ++ version ++ ".jar" data VersionList = VersionList { latest :: Latest , versions :: [Version] } deriving (Show,Generic) instance ToJSON VersionList instance FromJSON VersionList data Version = Version { versionID :: String , versionTime :: String , versionReleaseTime :: String , versionType :: String } deriving (Show) instance ToJSON Version where toJSON (Version versionID versionTime versionReleaseTime versionType) = object [ "id" .= versionID , "time" .= versionTime , "releaseTime" .= versionReleaseTime , "type" .= versionType ] instance FromJSON Version where parseJSON (Object v) = Version <$> v .: "id" <*> v .: "time" <*> v .: "releaseTime" <*> v .: "type" parseJSON _ = mzero data Latest = Lastest { snapshot :: String , release :: String } deriving (Show,Generic) instance ToJSON Latest instance FromJSON Latest
oldmanmike/minecraftctl
minecraftctl.hs
bsd-3-clause
18,664
0
32
4,800
4,975
2,494
2,481
418
3
module Text.ICalendar.Component.VEvent ( TimeInterval (..) , Transparency (..) , VEvent (..) , parseVEvent ) where -- haskell platform libraries import Control.Applicative import Data.Time.Clock import Text.Parsec.String -- foreign libraries import Text.Parsec.Permutation -- local libraries import Text.ICalendar.DataType.Duration import Text.ICalendar.DataType.Text import Text.ICalendar.Parser.Validator data TimeInterval = Duration DiffTime | EndDate String deriving (Eq, Show) data Transparency = Transparent | Opaque deriving (Eq, Show) data VEvent = VEvent { startDate :: String , attendees :: [String] , uniqueId :: Maybe String , organizer :: Maybe String , location :: Maybe String , summary :: Maybe String , description :: Maybe String , transparency :: Transparency , timeInterval :: TimeInterval } deriving (Eq, Show) parseVEvent :: Parser VEvent parseVEvent = runPermParser $ VEvent <$> reqProp1 textType "DTSTART" <*> optPropN textType "ATTENDEE" <*> optProp1 textType "UID" <*> optProp1 textType "ORGANIZER" <*> optProp1 textType "LOCATION" <*> optProp1 textType "SUMMARY" <*> optProp1 textType "DESCRIPTION" <*> transp1 textType "TRANSP" <*> reqCoProp1 (tiDurType, "DURATION") (tiDateType, "DTEND") where transp1 par key = toTransp <$> optProp1 par key tiDurType = Duration <$> durationType tiDateType = EndDate <$> textType -- private functions toTransp :: Maybe String -> Transparency toTransp (Just "TRANSPARENT") = Transparent toTransp _ = Opaque
Jonplussed/iCalendar
src/Text/ICalendar/Component/VEvent.hs
bsd-3-clause
2,007
0
14
731
403
228
175
47
1
module Events.ChannelScroll where import Prelude () import Prelude.MH import Brick import qualified Graphics.Vty as Vty import Events.Keybindings import State.ChannelScroll import State.UrlSelect import Types channelScrollKeybindings :: KeyConfig -> [Keybinding] channelScrollKeybindings = mkKeybindings [ mkKb LoadMoreEvent "Load more messages in the current channel" loadMoreMessages , mkKb EnterOpenURLModeEvent "Select and open a URL posted to the current channel" startUrlSelect , mkKb ScrollUpEvent "Scroll up" channelScrollUp , mkKb ScrollDownEvent "Scroll down" channelScrollDown , mkKb PageUpEvent "Scroll up" channelPageUp , mkKb PageDownEvent "Scroll down" channelPageDown , mkKb CancelEvent "Cancel scrolling and return to channel view" $ setMode Main , mkKb ScrollTopEvent "Scroll to top" channelScrollToTop , mkKb ScrollBottomEvent "Scroll to bottom" channelScrollToBottom ] onEventChannelScroll :: Vty.Event -> MH () onEventChannelScroll = handleKeyboardEvent channelScrollKeybindings $ \ e -> case e of (Vty.EvResize _ _) -> do cId <- use csCurrentChannelId mh $ do invalidateCache let vp = ChannelMessages cId vScrollToEnd $ viewportScroll vp _ -> return ()
aisamanra/matterhorn
src/Events/ChannelScroll.hs
bsd-3-clause
1,353
0
18
329
267
137
130
39
2
-- Copyright (c) 1998-1999 Chris Okasaki. -- See COPYRIGHT file for terms and conditions. module LazyPairingHeap ( -- type of pairing heaps Heap, -- instance of Coll/CollX, OrdColl/OrdCollX -- CollX operations empty,single,fromSeq,insert,insertSeq,union,unionSeq,delete,deleteAll, deleteSeq,null,size,member,count, -- Coll operations toSeq, lookup, lookupM, lookupAll, lookupWithDefault, fold, fold1, filter, partition, -- OrdCollX operations deleteMin,deleteMax,unsafeInsertMin,unsafeInsertMax,unsafeFromOrdSeq, unsafeAppend,filterLT,filterLE,filterGT,filterGE,partitionLT_GE, partitionLE_GT,partitionLT_GT, -- OrdColl operations minView,minElem,maxView,maxElem,foldr,foldl,foldr1,foldl1,toOrdSeq, -- other supported operations unsafeMapMonotonic, -- documentation moduleName, -- re-export view type from EdisonPrelude for convenience Maybe2(..) ) where import Prelude hiding (null,foldr,foldl,foldr1,foldl1,lookup,filter) import EdisonPrelude(Maybe2(..)) import qualified Collection as C ( CollX(..), OrdCollX(..), Coll(..), OrdColl(..), toOrdList ) import qualified Sequence as S import CollectionDefaults import List(sort) import Monad import QuickCheck moduleName = "LazyPairingHeap" -- Adapted from -- Chris Okasaki. Purely Functional Data Structures. 1998. -- Section 6.5. data Heap a = E | H1 a (Heap a) | H2 a !(Heap a) (Heap a) -- Invariant: left child of H2 not empty -- second arg is not empty -- not used! link E h = h link (H1 x b) a = H2 x a b link (H2 x a b) a' = H1 x (union (union a a') b) makeH2 x E xs = H1 x xs makeH2 x h xs = H2 x h xs empty :: Heap a empty = E single :: a -> Heap a single x = H1 x E insert :: Ord a => a -> Heap a -> Heap a insert x E = H1 x E insert x h@(H1 y b) | x <= y = H1 x h | otherwise = H2 y (H1 x E) b insert x h@(H2 y a b) | x <= y = H1 x h | otherwise = H1 y (union (insert x a) b) union :: Ord a => Heap a -> Heap a -> Heap a union E h = h union hx@(H1 x xs) E = hx union hx@(H1 x xs) hy@(H1 y ys) | x <= y = H2 x hy xs | otherwise = H2 y hx ys union hx@(H1 x xs) hy@(H2 y a ys) | x <= y = H2 x hy xs | otherwise = H1 y (union (union hx a) ys) union hx@(H2 x a xs) E = hx union hx@(H2 x a xs) hy@(H1 y ys) | x <= y = H1 x (union (union hy a) xs) | otherwise = H2 y hx ys union hx@(H2 x a xs) hy@(H2 y b ys) | x <= y = H1 x (union (union hy a) xs) | otherwise = H1 y (union (union hx b) ys) delete :: Ord a => a -> Heap a -> Heap a delete y h = case del h of Just h' -> h' Nothing -> h where del E = Nothing del (H1 x xs) = case compare x y of LT -> case del xs of Just xs -> Just (H1 x xs) Nothing -> Nothing EQ -> Just xs GT -> Nothing del (H2 x a xs) = case compare x y of LT -> case del a of Just a' -> Just (makeH2 x a' xs) Nothing -> case del xs of Just xs' -> Just (H2 x a xs') Nothing -> Nothing EQ -> Just (union a xs) GT -> Nothing deleteAll :: Ord a => a -> Heap a -> Heap a deleteAll y E = E deleteAll y h@(H1 x xs) = case compare x y of LT -> H1 x (deleteAll y xs) EQ -> deleteAll y xs GT -> h deleteAll y h@(H2 x a xs) = case compare x y of LT -> makeH2 x (deleteAll y a) (deleteAll y xs) EQ -> union (deleteAll y a) (deleteAll y xs) GT -> h deleteSeq :: (Ord a,S.Sequence seq) => seq a -> Heap a -> Heap a deleteSeq = delList . sort . S.toList where delList [] h = h delList (y:ys) h = del y ys h del y ys E = E del y ys h@(H1 x xs) = case compare x y of LT -> H1 x (del y ys xs) EQ -> delList ys xs GT -> delList ys h del y ys h@(H2 x a xs) = case compare x y of LT -> H1 x (del y ys (union a xs)) EQ -> delList ys (union a xs) GT -> delList ys h {- could write the two GT cases as delList (dropWhile (< x) ys) h but this is only a win if we expect many of the ys to be missing from the tree. However, we expect most of the ys to be present. -} null :: Heap a -> Bool null E = True null _ = False size :: Heap a -> Int size E = 0 size (H1 x xs) = 1 + size xs size (H2 x h xs) = 1 + size h + size xs member :: Ord a => Heap a -> a -> Bool member E x = False member (H1 y ys) x = case compare x y of LT -> False EQ -> True GT -> member ys x member (H2 y h ys) x = case compare x y of LT -> False EQ -> True GT -> member h x || member ys x count :: Ord a => Heap a -> a -> Int count E x = 0 count (H1 y ys) x = case compare x y of LT -> 0 EQ -> 1 + count ys x GT -> count ys x count (H2 y h ys) x = case compare x y of LT -> 0 EQ -> 1 + count h x + count ys x GT -> count h x + count ys x deleteMin :: Ord a => Heap a -> Heap a deleteMin E = E deleteMin (H1 x xs) = xs deleteMin (H2 x h xs) = union h xs unsafeInsertMin :: Ord a => a -> Heap a -> Heap a unsafeInsertMin = H1 unsafeInsertMax :: Ord a => Heap a -> a -> Heap a unsafeInsertMax E x = H1 x E unsafeInsertMax (H1 y ys) x = H2 y (H1 x E) ys unsafeInsertMax (H2 y h ys) x = H1 y (union (unsafeInsertMax h x) ys) unsafeAppend :: Ord a => Heap a -> Heap a -> Heap a unsafeAppend h E = h unsafeAppend E h = h unsafeAppend (H1 x xs) h = H2 x h xs unsafeAppend (H2 x a xs) h = H1 x (union (unsafeAppend a h) xs) filterLT :: Ord a => a -> Heap a -> Heap a filterLT y E = E filterLT y (H1 x xs) | x < y = H1 x (filterLT y xs) | otherwise = E filterLT y (H2 x h xs) | x < y = makeH2 x (filterLT y h) (filterLT y xs) | otherwise = E filterLE :: Ord a => a -> Heap a -> Heap a filterLE y E = E filterLE y (H1 x xs) | x <= y = H1 x (filterLE y xs) | otherwise = E filterLE y (H2 x h xs) | x <= y = makeH2 x (filterLE y h) (filterLE y xs) | otherwise = E filterGT :: Ord a => a -> Heap a -> Heap a filterGT y h = fgt h E where fgt E rest = rest fgt h@(H1 x xs) rest | x > y = union h rest | otherwise = fgt xs rest fgt h@(H2 x a xs) rest | x > y = union h rest | otherwise = fgt a (fgt xs rest) filterGE :: Ord a => a -> Heap a -> Heap a filterGE y h = fge h E where fge E rest = rest fge h@(H1 x xs) rest | x >= y = union h rest | otherwise = fge xs rest fge h@(H2 x a xs) rest | x >= y = union h rest | otherwise = fge a (fge xs rest) partitionLT_GE :: Ord a => a -> Heap a -> (Heap a, Heap a) partitionLT_GE y E = (E,E) partitionLT_GE y h@(H1 x xs) | x < y = let (xs',xs'') = partitionLT_GE y xs in (H1 x xs',xs'') | otherwise = (E, h) partitionLT_GE y h@(H2 x a xs) | x < y = let (a',a'') = partitionLT_GE y a (xs',xs'') = partitionLT_GE y xs in (makeH2 x a' xs',union a'' xs'') | otherwise = (E, h) partitionLE_GT :: Ord a => a -> Heap a -> (Heap a, Heap a) partitionLE_GT y E = (E,E) partitionLE_GT y h@(H1 x xs) | x <= y = let (xs',xs'') = partitionLE_GT y xs in (H1 x xs',xs'') | otherwise = (E, h) partitionLE_GT y h@(H2 x a xs) | x <= y = let (a',a'') = partitionLE_GT y a (xs',xs'') = partitionLE_GT y xs in (makeH2 x a' xs',union a'' xs'') | otherwise = (E, h) partitionLT_GT :: Ord a => a -> Heap a -> (Heap a, Heap a) partitionLT_GT y E = (E,E) partitionLT_GT y h@(H1 x xs) = case compare x y of LT -> let (xs',xs'') = partitionLT_GT y xs in (H1 x xs',xs'') EQ -> (E, filterGT y xs) GT -> (E, h) partitionLT_GT y h@(H2 x a xs) = case compare x y of LT -> let (a',a'') = partitionLT_GT y a (xs',xs'') = partitionLT_GT y xs in (makeH2 x a' xs',union a'' xs'') EQ -> (E, union (filterGT y a) (filterGT y xs)) GT -> (E, h) toSeq :: S.Sequence seq => Heap a -> seq a toSeq h = tol h S.empty where tol E rest = rest tol (H1 x xs) rest = S.cons x (tol xs rest) tol (H2 x h xs) rest = S.cons x (tol h (tol xs rest)) fold :: (a -> b -> b) -> b -> Heap a -> b fold f c E = c fold f c (H1 x xs) = f x (fold f c xs) fold f c (H2 x h xs) = f x (fold f (fold f c xs) h) fold1 :: (a -> a -> a) -> Heap a -> a fold1 f E = error "LazyPairingHeap.fold1: empty heap" fold1 f (H1 x xs) = fold f x xs fold1 f (H2 x h xs) = fold f (fold f x xs) h filter :: Ord a => (a -> Bool) -> Heap a -> Heap a filter p E = E filter p (H1 x xs) = if p x then H1 x (filter p xs) else filter p xs filter p (H2 x h xs) = if p x then makeH2 x (filter p h) (filter p xs) else union (filter p h) (filter p xs) partition :: Ord a => (a -> Bool) -> Heap a -> (Heap a, Heap a) partition p E = (E, E) partition p (H1 x xs) = if p x then (H1 x xs',xs'') else (xs',H1 x xs'') where (xs',xs'') = partition p xs partition p (H2 x h xs) = if p x then (makeH2 x h' xs', union h'' xs'') else (union h' xs', makeH2 x h'' xs'') where (h',h'') = partition p h (xs',xs'') = partition p xs lookupAll :: (Ord a,S.Sequence seq) => Heap a -> a -> seq a lookupAll h y = look h S.empty where look E rest = rest look (H1 x xs) rest = case compare x y of LT -> look xs rest EQ -> S.cons x (look xs rest) GT -> rest look (H2 x h xs) rest = case compare x y of LT -> look h (look xs rest) EQ -> S.cons x (look h (look xs rest)) GT -> rest minView :: Ord a => Heap a -> Maybe2 a (Heap a) minView E = Nothing2 minView (H1 x xs) = Just2 x xs minView (H2 x h xs) = Just2 x (union h xs) minElem :: Heap a -> a minElem E = error "LazyPairingHeap.minElem: empty heap" minElem (H1 x xs) = x minElem (H2 x h xs) = x maxView :: Ord a => Heap a -> Maybe2 (Heap a) a maxView E = Nothing2 maxView xs = Just2 xs' y where (xs', y) = maxView' xs -- not exported maxView' (H1 x E) = (E, x) maxView' (H1 x xs) = (H1 x xs', y) where (xs', y) = maxView' xs maxView' (H2 x a E) = (H1 x a', y) where (a', y) = maxView' a maxView' (H2 x a xs) = if y > z then (makeH2 x a' xs, y) else (H2 x a xs', z) where (a', y) = maxView' a (xs', z) = maxView' xs maxElem :: Ord a => Heap a -> a maxElem E = error "LazyPairingHeap.maxElem: empty heap" maxElem (H1 x E) = x maxElem (H1 x xs) = maxElem xs maxElem (H2 x h E) = maxElem h maxElem (H2 x h xs) = max (maxElem h) (maxElem xs) foldr :: Ord a => (a -> b -> b) -> b -> Heap a -> b foldr f c E = c foldr f c (H1 x xs) = f x (foldr f c xs) foldr f c (H2 x h xs) = f x (foldr f c (union h xs)) foldl :: Ord a => (b -> a -> b) -> b -> Heap a -> b foldl f c E = c foldl f c (H1 x xs) = foldl f (f c x) xs foldl f c (H2 x h xs) = foldl f (f c x) (union h xs) foldr1 :: Ord a => (a -> a -> a) -> Heap a -> a foldr1 f E = error "LazyPairingHeap.foldr1: empty heap" foldr1 f (H1 x E) = x foldr1 f (H1 x xs) = f x (foldr1 f xs) foldr1 f (H2 x h xs) = f x (foldr1 f (union h xs)) foldl1 :: Ord a => (a -> a -> a) -> Heap a -> a foldl1 f E = error "LazyPairingHeap.foldl1: empty heap" foldl1 f (H1 x xs) = foldl f x xs foldl1 f (H2 x h xs) = foldl f x (union h xs) unsafeMapMonotonic :: (Ord a,Ord b) => (a -> b) -> Heap a -> Heap b unsafeMapMonotonic = mapm where mapm f E = E mapm f (H1 x xs) = H1 (f x) (mapm f xs) mapm f (H2 x h xs) = H2 (f x) (mapm f h) (mapm f xs) -- the remaining functions all use default definitions fromSeq :: (Ord a,S.Sequence seq) => seq a -> Heap a fromSeq = fromSeqUsingFoldr insertSeq :: (Ord a,S.Sequence seq) => seq a -> Heap a -> Heap a insertSeq = insertSeqUsingFoldr unionSeq :: (Ord a,S.Sequence seq) => seq (Heap a) -> Heap a unionSeq = unionSeqUsingFoldl unsafeFromOrdSeq :: (Ord a,S.Sequence seq) => seq a -> Heap a unsafeFromOrdSeq = unsafeFromOrdSeqUsingUnsafeInsertMin deleteMax :: Ord a => Heap a -> Heap a deleteMax = deleteMaxUsingMaxView lookup :: Ord a => Heap a -> a -> a lookup = lookupUsingLookupAll lookupM :: Ord a => Heap a -> a -> Maybe a lookupM = lookupMUsingLookupAll lookupWithDefault :: Ord a => a -> Heap a -> a -> a lookupWithDefault = lookupWithDefaultUsingLookupAll toOrdSeq :: (Ord a,S.Sequence seq) => Heap a -> seq a toOrdSeq = toOrdSeqUsingFoldr -- instance declarations instance Ord a => C.CollX Heap a where {empty = empty; single = single; fromSeq = fromSeq; insert = insert; insertSeq = insertSeq; union = union; unionSeq = unionSeq; delete = delete; deleteAll = deleteAll; deleteSeq = deleteSeq; null = null; size = size; member = member; count = count; instanceName c = moduleName} instance Ord a => C.OrdCollX Heap a where {deleteMin = deleteMin; deleteMax = deleteMax; unsafeInsertMin = unsafeInsertMin; unsafeInsertMax = unsafeInsertMax; unsafeFromOrdSeq = unsafeFromOrdSeq; unsafeAppend = unsafeAppend; filterLT = filterLT; filterLE = filterLE; filterGT = filterGT; filterGE = filterGE; partitionLT_GE = partitionLT_GE; partitionLE_GT = partitionLE_GT; partitionLT_GT = partitionLT_GT} instance Ord a => C.Coll Heap a where {toSeq = toSeq; lookup = lookup; lookupM = lookupM; lookupAll = lookupAll; lookupWithDefault = lookupWithDefault; fold = fold; fold1 = fold1; filter = filter; partition = partition} instance Ord a => C.OrdColl Heap a where {minView = minView; minElem = minElem; maxView = maxView; maxElem = maxElem; foldr = foldr; foldl = foldl; foldr1 = foldr1; foldl1 = foldl1; toOrdSeq = toOrdSeq} instance Ord a => Eq (Heap a) where xs == ys = C.toOrdList xs == C.toOrdList ys instance (Ord a, Show a) => Show (Heap a) where show xs = show (C.toOrdList xs) instance (Ord a, Arbitrary a) => Arbitrary (Heap a) where arbitrary = sized (\n -> arbTree n) where arbTree 0 = return E arbTree n = frequency [(1, return E), (2, liftM2 sift1 arbitrary (arbTree (n - 1))), (3, liftM3 sift arbitrary (arbTree (n `div` 4)) (arbTree (n `div` 2)))] sift x E a = sift1 x a sift x a E = let H1 x' a' = sift1 x a in H2 x' a' E sift x a b | x <= ma && x <= mb = H2 x a b | ma < x && ma <= mb = H2 ma (siftInto x a) b | otherwise = H2 mb a (siftInto x b) where ma = minElem a mb = minElem b sift1 x E = H1 x E sift1 x a | x <= ma = H1 x a | otherwise = H1 ma (siftInto x a) where ma = minElem a siftInto x (H1 _ a) = sift1 x a siftInto x (H2 _ a b) = sift x a b coarbitrary E = variant 0 coarbitrary (H1 x a) = variant 1 . coarbitrary x . coarbitrary a coarbitrary (H2 x a b) = variant 2 . coarbitrary x . coarbitrary a . coarbitrary b
OS2World/DEV-UTIL-HUGS
oldlib/LazyPairingHeap.hs
bsd-3-clause
15,071
2
18
4,690
7,389
3,719
3,670
-1
-1
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} #ifdef USE_REFLEX_OPTIMIZER {-# OPTIONS_GHC -fplugin=Reflex.Optimizer #-} #endif -- | -- Module: -- Reflex.Adjustable.Class -- Description: -- A class for actions that can be "adjusted" over time based on some 'Event' -- such that, when observed after the firing of any such 'Event', the result -- is as though the action was originally run with the 'Event's value. module Reflex.Adjustable.Class ( -- * The Adjustable typeclass Adjustable(..) , sequenceDMapWithAdjust , sequenceDMapWithAdjustWithMove , mapMapWithAdjustWithMove -- * Deprecated aliases , MonadAdjust ) where import Control.Monad.Identity import Control.Monad.Reader import Data.Dependent.Map (DMap, GCompare (..)) import qualified Data.Dependent.Map as DMap import Data.Functor.Constant import Data.Functor.Misc import Data.IntMap.Strict (IntMap) import qualified Data.IntMap.Strict as IntMap import Data.Map (Map) import Reflex.Class import Reflex.Patch.DMapWithMove -- | A 'Monad' that supports adjustment over time. After an action has been -- run, if the given events fire, it will adjust itself so that its net effect -- is as though it had originally been run with the new value. Note that there -- is some issue here with persistent side-effects: obviously, IO (and some -- other side-effects) cannot be undone, so it is up to the instance implementer -- to determine what the best meaning for this class is in such cases. class (Reflex t, Monad m) => Adjustable t m | m -> t where runWithReplace :: m a -> Event t (m b) -> m (a, Event t b) traverseIntMapWithKeyWithAdjust :: (IntMap.Key -> v -> m v') -> IntMap v -> Event t (PatchIntMap v) -> m (IntMap v', Event t (PatchIntMap v')) traverseDMapWithKeyWithAdjust :: GCompare k => (forall a. k a -> v a -> m (v' a)) -> DMap k v -> Event t (PatchDMap k v) -> m (DMap k v', Event t (PatchDMap k v')) {-# INLINABLE traverseDMapWithKeyWithAdjust #-} traverseDMapWithKeyWithAdjust f dm0 dm' = fmap (fmap (fmap fromPatchWithMove)) $ traverseDMapWithKeyWithAdjustWithMove f dm0 $ fmap toPatchWithMove dm' where toPatchWithMove (PatchDMap m) = PatchDMapWithMove $ DMap.map toNodeInfoWithMove m toNodeInfoWithMove = \case ComposeMaybe (Just v) -> NodeInfo (From_Insert v) $ ComposeMaybe Nothing ComposeMaybe Nothing -> NodeInfo From_Delete $ ComposeMaybe Nothing fromPatchWithMove (PatchDMapWithMove m) = PatchDMap $ DMap.map fromNodeInfoWithMove m fromNodeInfoWithMove (NodeInfo from _) = ComposeMaybe $ case from of From_Insert v -> Just v From_Delete -> Nothing From_Move _ -> error "traverseDMapWithKeyWithAdjust: implementation of traverseDMapWithKeyWithAdjustWithMove inserted spurious move" traverseDMapWithKeyWithAdjustWithMove :: GCompare k => (forall a. k a -> v a -> m (v' a)) -> DMap k v -> Event t (PatchDMapWithMove k v) -> m (DMap k v', Event t (PatchDMapWithMove k v')) instance Adjustable t m => Adjustable t (ReaderT r m) where runWithReplace a0 a' = do r <- ask lift $ runWithReplace (runReaderT a0 r) $ fmap (`runReaderT` r) a' traverseIntMapWithKeyWithAdjust f dm0 dm' = do r <- ask lift $ traverseIntMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm' traverseDMapWithKeyWithAdjust f dm0 dm' = do r <- ask lift $ traverseDMapWithKeyWithAdjust (\k v -> runReaderT (f k v) r) dm0 dm' traverseDMapWithKeyWithAdjustWithMove f dm0 dm' = do r <- ask lift $ traverseDMapWithKeyWithAdjustWithMove (\k v -> runReaderT (f k v) r) dm0 dm' -- | Traverse a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches -- to the 'DMap' can add, remove, or update values. sequenceDMapWithAdjust :: (GCompare k, Adjustable t m) => DMap k m -> Event t (PatchDMap k m) -> m (DMap k Identity, Event t (PatchDMap k Identity)) sequenceDMapWithAdjust = traverseDMapWithKeyWithAdjust $ \_ -> fmap Identity -- | Traverses a 'DMap' of 'Adjustable' actions, running each of them. The provided 'Event' of patches -- to the 'DMap' can add, remove, update, move, or swap values. sequenceDMapWithAdjustWithMove :: (GCompare k, Adjustable t m) => DMap k m -> Event t (PatchDMapWithMove k m) -> m (DMap k Identity, Event t (PatchDMapWithMove k Identity)) sequenceDMapWithAdjustWithMove = traverseDMapWithKeyWithAdjustWithMove $ \_ -> fmap Identity -- | Traverses a 'Map', running the provided 'Adjustable' action. The provided 'Event' of patches to the 'Map' -- can add, remove, update, move, or swap values. mapMapWithAdjustWithMove :: forall t m k v v'. (Adjustable t m, Ord k) => (k -> v -> m v') -> Map k v -> Event t (PatchMapWithMove k v) -> m (Map k v', Event t (PatchMapWithMove k v')) mapMapWithAdjustWithMove f m0 m' = do (out0 :: DMap (Const2 k v) (Constant v'), out') <- traverseDMapWithKeyWithAdjustWithMove (\(Const2 k) (Identity v) -> Constant <$> f k v) (mapToDMap m0) (const2PatchDMapWithMoveWith Identity <$> m') return (dmapToMapWith (\(Constant v') -> v') out0, patchDMapWithMoveToPatchMapWithMoveWith (\(Constant v') -> v') <$> out') -------------------------------------------------------------------------------- -- Deprecated functions -------------------------------------------------------------------------------- {-# DEPRECATED MonadAdjust "Use Adjustable instead" #-} -- | Synonym for 'Adjustable' type MonadAdjust = Adjustable
Saulzar/reflex
src/Reflex/Adjustable/Class.hs
bsd-3-clause
5,730
0
15
1,052
1,401
730
671
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 This module converts Template Haskell syntax into HsSyn -} {-# LANGUAGE ScopedTypeVariables #-} module Convert( convertToHsExpr, convertToPat, convertToHsDecls, convertToHsType, thRdrNameGuesses ) where import HsSyn as Hs import qualified Class import RdrName import qualified Name import Module import RdrHsSyn import qualified OccName import OccName import SrcLoc import Type import qualified Coercion ( Role(..) ) import TysWiredIn import TysPrim (eqPrimTyCon) import BasicTypes as Hs import ForeignCall import Unique import ErrUtils import Bag import Lexeme import Util import FastString import Outputable import MonadUtils ( foldrM ) import qualified Data.ByteString as BS import Control.Monad( unless, liftM, ap ) import Data.Char ( chr ) import Data.Word ( Word8 ) import Data.Maybe( catMaybes, fromMaybe, isNothing ) import Language.Haskell.TH as TH hiding (sigP) import Language.Haskell.TH.Syntax as TH ------------------------------------------------------------------- -- The external interface convertToHsDecls :: SrcSpan -> [TH.Dec] -> Either MsgDoc [LHsDecl RdrName] convertToHsDecls loc ds = initCvt loc (fmap catMaybes (mapM cvt_dec ds)) where cvt_dec d = wrapMsg "declaration" d (cvtDec d) convertToHsExpr :: SrcSpan -> TH.Exp -> Either MsgDoc (LHsExpr RdrName) convertToHsExpr loc e = initCvt loc $ wrapMsg "expression" e $ cvtl e convertToPat :: SrcSpan -> TH.Pat -> Either MsgDoc (LPat RdrName) convertToPat loc p = initCvt loc $ wrapMsg "pattern" p $ cvtPat p convertToHsType :: SrcSpan -> TH.Type -> Either MsgDoc (LHsType RdrName) convertToHsType loc t = initCvt loc $ wrapMsg "type" t $ cvtType t ------------------------------------------------------------------- newtype CvtM a = CvtM { unCvtM :: SrcSpan -> Either MsgDoc (SrcSpan, a) } -- Push down the source location; -- Can fail, with a single error message -- NB: If the conversion succeeds with (Right x), there should -- be no exception values hiding in x -- Reason: so a (head []) in TH code doesn't subsequently -- make GHC crash when it tries to walk the generated tree -- Use the loc everywhere, for lack of anything better -- In particular, we want it on binding locations, so that variables bound in -- the spliced-in declarations get a location that at least relates to the splice point instance Functor CvtM where fmap = liftM instance Applicative CvtM where pure x = CvtM $ \loc -> Right (loc,x) (<*>) = ap instance Monad CvtM where (CvtM m) >>= k = CvtM $ \loc -> case m loc of Left err -> Left err Right (loc',v) -> unCvtM (k v) loc' initCvt :: SrcSpan -> CvtM a -> Either MsgDoc a initCvt loc (CvtM m) = fmap snd (m loc) force :: a -> CvtM () force a = a `seq` return () failWith :: MsgDoc -> CvtM a failWith m = CvtM (\_ -> Left m) getL :: CvtM SrcSpan getL = CvtM (\loc -> Right (loc,loc)) setL :: SrcSpan -> CvtM () setL loc = CvtM (\_ -> Right (loc, ())) returnL :: a -> CvtM (Located a) returnL x = CvtM (\loc -> Right (loc, L loc x)) returnJustL :: a -> CvtM (Maybe (Located a)) returnJustL = fmap Just . returnL wrapParL :: (Located a -> a) -> a -> CvtM a wrapParL add_par x = CvtM (\loc -> Right (loc, add_par (L loc x))) wrapMsg :: (Show a, TH.Ppr a) => String -> a -> CvtM b -> CvtM b -- E.g wrapMsg "declaration" dec thing wrapMsg what item (CvtM m) = CvtM (\loc -> case m loc of Left err -> Left (err $$ getPprStyle msg) Right v -> Right v) where -- Show the item in pretty syntax normally, -- but with all its constructors if you say -dppr-debug msg sty = hang (text "When splicing a TH" <+> text what <> colon) 2 (if debugStyle sty then text (show item) else text (pprint item)) wrapL :: CvtM a -> CvtM (Located a) wrapL (CvtM m) = CvtM (\loc -> case m loc of Left err -> Left err Right (loc',v) -> Right (loc',L loc v)) ------------------------------------------------------------------- cvtDecs :: [TH.Dec] -> CvtM [LHsDecl RdrName] cvtDecs = fmap catMaybes . mapM cvtDec cvtDec :: TH.Dec -> CvtM (Maybe (LHsDecl RdrName)) cvtDec (TH.ValD pat body ds) | TH.VarP s <- pat = do { s' <- vNameL s ; cl' <- cvtClause (Clause [] body ds) ; returnJustL $ Hs.ValD $ mkFunBind s' [cl'] } | otherwise = do { pat' <- cvtPat pat ; body' <- cvtGuard body ; ds' <- cvtLocalDecs (text "a where clause") ds ; returnJustL $ Hs.ValD $ PatBind { pat_lhs = pat', pat_rhs = GRHSs body' (noLoc ds') , pat_rhs_ty = placeHolderType, bind_fvs = placeHolderNames , pat_ticks = ([],[]) } } cvtDec (TH.FunD nm cls) | null cls = failWith (text "Function binding for" <+> quotes (text (TH.pprint nm)) <+> text "has no equations") | otherwise = do { nm' <- vNameL nm ; cls' <- mapM cvtClause cls ; returnJustL $ Hs.ValD $ mkFunBind nm' cls' } cvtDec (TH.SigD nm typ) = do { nm' <- vNameL nm ; ty' <- cvtType typ ; returnJustL $ Hs.SigD (TypeSig [nm'] (mkLHsSigWcType ty')) } cvtDec (TH.InfixD fx nm) -- Fixity signatures are allowed for variables, constructors, and types -- the renamer automatically looks for types during renaming, even when -- the RdrName says it's a variable or a constructor. So, just assume -- it's a variable or constructor and proceed. = do { nm' <- vcNameL nm ; returnJustL (Hs.SigD (FixSig (FixitySig [nm'] (cvtFixity fx)))) } cvtDec (PragmaD prag) = cvtPragmaD prag cvtDec (TySynD tc tvs rhs) = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs ; rhs' <- cvtType rhs ; returnJustL $ TyClD $ SynDecl { tcdLName = tc' , tcdTyVars = tvs', tcdFVs = placeHolderNames , tcdRhs = rhs' } } cvtDec (DataD ctxt tc tvs ksig constrs derivs) = do { let isGadtCon (GadtC _ _ _) = True isGadtCon (RecGadtC _ _ _) = True isGadtCon (ForallC _ _ c) = isGadtCon c isGadtCon _ = False isGadtDecl = all isGadtCon constrs isH98Decl = all (not . isGadtCon) constrs ; unless (isGadtDecl || isH98Decl) (failWith (text "Cannot mix GADT constructors with Haskell 98" <+> text "constructors")) ; unless (isNothing ksig || isGadtDecl) (failWith (text "Kind signatures are only allowed on GADTs")) ; (ctxt', tc', tvs') <- cvt_tycl_hdr ctxt tc tvs ; ksig' <- cvtKind `traverse` ksig ; cons' <- mapM cvtConstr constrs ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = DataType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = ksig' , dd_cons = cons', dd_derivs = derivs' } ; returnJustL $ TyClD (DataDecl { tcdLName = tc', tcdTyVars = tvs' , tcdDataDefn = defn , tcdFVs = placeHolderNames }) } cvtDec (NewtypeD ctxt tc tvs ksig constr derivs) = do { (ctxt', tc', tvs') <- cvt_tycl_hdr ctxt tc tvs ; ksig' <- cvtKind `traverse` ksig ; con' <- cvtConstr constr ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = NewType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = ksig' , dd_cons = [con'] , dd_derivs = derivs' } ; returnJustL $ TyClD (DataDecl { tcdLName = tc', tcdTyVars = tvs' , tcdDataDefn = defn , tcdFVs = placeHolderNames }) } cvtDec (ClassD ctxt cl tvs fds decs) = do { (cxt', tc', tvs') <- cvt_tycl_hdr ctxt cl tvs ; fds' <- mapM cvt_fundep fds ; (binds', sigs', fams', ats', adts') <- cvt_ci_decs (text "a class declaration") decs ; unless (null adts') (failWith $ (text "Default data instance declarations" <+> text "are not allowed:") $$ (Outputable.ppr adts')) ; at_defs <- mapM cvt_at_def ats' ; returnJustL $ TyClD $ ClassDecl { tcdCtxt = cxt', tcdLName = tc', tcdTyVars = tvs' , tcdFDs = fds', tcdSigs = Hs.mkClassOpSigs sigs' , tcdMeths = binds' , tcdATs = fams', tcdATDefs = at_defs, tcdDocs = [] , tcdFVs = placeHolderNames } -- no docs in TH ^^ } where cvt_at_def :: LTyFamInstDecl RdrName -> CvtM (LTyFamDefltEqn RdrName) -- Very similar to what happens in RdrHsSyn.mkClassDecl cvt_at_def decl = case RdrHsSyn.mkATDefault decl of Right def -> return def Left (_, msg) -> failWith msg cvtDec (InstanceD ctxt ty decs) = do { let doc = text "an instance declaration" ; (binds', sigs', fams', ats', adts') <- cvt_ci_decs doc decs ; unless (null fams') (failWith (mkBadDecMsg doc fams')) ; ctxt' <- cvtContext ctxt ; L loc ty' <- cvtType ty ; let inst_ty' = L loc $ HsQualTy { hst_ctxt = ctxt', hst_body = L loc ty' } ; returnJustL $ InstD $ ClsInstD $ ClsInstDecl { cid_poly_ty = mkLHsSigType inst_ty' , cid_binds = binds' , cid_sigs = Hs.mkClassOpSigs sigs' , cid_tyfam_insts = ats', cid_datafam_insts = adts' , cid_overlap_mode = Nothing } } cvtDec (ForeignD ford) = do { ford' <- cvtForD ford ; returnJustL $ ForD ford' } cvtDec (DataFamilyD tc tvs kind) = do { (_, tc', tvs') <- cvt_tycl_hdr [] tc tvs ; result <- cvtMaybeKindToFamilyResultSig kind ; returnJustL $ TyClD $ FamDecl $ FamilyDecl DataFamily tc' tvs' result Nothing } cvtDec (DataInstD ctxt tc tys ksig constrs derivs) = do { (ctxt', tc', typats') <- cvt_tyinst_hdr ctxt tc tys ; ksig' <- cvtKind `traverse` ksig ; cons' <- mapM cvtConstr constrs ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = DataType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = ksig' , dd_cons = cons', dd_derivs = derivs' } ; returnJustL $ InstD $ DataFamInstD { dfid_inst = DataFamInstDecl { dfid_tycon = tc', dfid_pats = typats' , dfid_defn = defn , dfid_fvs = placeHolderNames } }} cvtDec (NewtypeInstD ctxt tc tys ksig constr derivs) = do { (ctxt', tc', typats') <- cvt_tyinst_hdr ctxt tc tys ; ksig' <- cvtKind `traverse` ksig ; con' <- cvtConstr constr ; derivs' <- cvtDerivs derivs ; let defn = HsDataDefn { dd_ND = NewType, dd_cType = Nothing , dd_ctxt = ctxt' , dd_kindSig = ksig' , dd_cons = [con'], dd_derivs = derivs' } ; returnJustL $ InstD $ DataFamInstD { dfid_inst = DataFamInstDecl { dfid_tycon = tc', dfid_pats = typats' , dfid_defn = defn , dfid_fvs = placeHolderNames } }} cvtDec (TySynInstD tc eqn) = do { tc' <- tconNameL tc ; eqn' <- cvtTySynEqn tc' eqn ; returnJustL $ InstD $ TyFamInstD { tfid_inst = TyFamInstDecl { tfid_eqn = eqn' , tfid_fvs = placeHolderNames } } } cvtDec (OpenTypeFamilyD head) = do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head ; returnJustL $ TyClD $ FamDecl $ FamilyDecl OpenTypeFamily tc' tyvars' result' injectivity' } cvtDec (ClosedTypeFamilyD head eqns) = do { (tc', tyvars', result', injectivity') <- cvt_tyfam_head head ; eqns' <- mapM (cvtTySynEqn tc') eqns ; returnJustL $ TyClD $ FamDecl $ FamilyDecl (ClosedTypeFamily (Just eqns')) tc' tyvars' result' injectivity' } cvtDec (TH.RoleAnnotD tc roles) = do { tc' <- tconNameL tc ; let roles' = map (noLoc . cvtRole) roles ; returnJustL $ Hs.RoleAnnotD (RoleAnnotDecl tc' roles') } cvtDec (TH.StandaloneDerivD cxt ty) = do { cxt' <- cvtContext cxt ; L loc ty' <- cvtType ty ; let inst_ty' = L loc $ HsQualTy { hst_ctxt = cxt', hst_body = L loc ty' } ; returnJustL $ DerivD $ DerivDecl { deriv_type = mkLHsSigType inst_ty', deriv_overlap_mode = Nothing } } cvtDec (TH.DefaultSigD nm typ) = do { nm' <- vNameL nm ; ty' <- cvtType typ ; returnJustL $ Hs.SigD $ ClassOpSig True [nm'] (mkLHsSigType ty') } ---------------- cvtTySynEqn :: Located RdrName -> TySynEqn -> CvtM (LTyFamInstEqn RdrName) cvtTySynEqn tc (TySynEqn lhs rhs) = do { lhs' <- mapM cvtType lhs ; rhs' <- cvtType rhs ; returnL $ TyFamEqn { tfe_tycon = tc , tfe_pats = mkHsImplicitBndrs lhs' , tfe_rhs = rhs' } } ---------------- cvt_ci_decs :: MsgDoc -> [TH.Dec] -> CvtM (LHsBinds RdrName, [LSig RdrName], [LFamilyDecl RdrName], [LTyFamInstDecl RdrName], [LDataFamInstDecl RdrName]) -- Convert the declarations inside a class or instance decl -- ie signatures, bindings, and associated types cvt_ci_decs doc decs = do { decs' <- cvtDecs decs ; let (ats', bind_sig_decs') = partitionWith is_tyfam_inst decs' ; let (adts', no_ats') = partitionWith is_datafam_inst bind_sig_decs' ; let (sigs', prob_binds') = partitionWith is_sig no_ats' ; let (binds', prob_fams') = partitionWith is_bind prob_binds' ; let (fams', bads) = partitionWith is_fam_decl prob_fams' ; unless (null bads) (failWith (mkBadDecMsg doc bads)) --We use FromSource as the origin of the bind -- because the TH declaration is user-written ; return (listToBag binds', sigs', fams', ats', adts') } ---------------- cvt_tycl_hdr :: TH.Cxt -> TH.Name -> [TH.TyVarBndr] -> CvtM ( LHsContext RdrName , Located RdrName , LHsQTyVars RdrName) cvt_tycl_hdr cxt tc tvs = do { cxt' <- cvtContext cxt ; tc' <- tconNameL tc ; tvs' <- cvtTvs tvs ; return (cxt', tc', tvs') } cvt_tyinst_hdr :: TH.Cxt -> TH.Name -> [TH.Type] -> CvtM ( LHsContext RdrName , Located RdrName , HsImplicitBndrs RdrName [LHsType RdrName]) cvt_tyinst_hdr cxt tc tys = do { cxt' <- cvtContext cxt ; tc' <- tconNameL tc ; tys' <- mapM cvtType tys ; return (cxt', tc', mkHsImplicitBndrs tys') } ---------------- cvt_tyfam_head :: TypeFamilyHead -> CvtM ( Located RdrName , LHsQTyVars RdrName , Hs.LFamilyResultSig RdrName , Maybe (Hs.LInjectivityAnn RdrName)) cvt_tyfam_head (TypeFamilyHead tc tyvars result injectivity) = do {(_, tc', tyvars') <- cvt_tycl_hdr [] tc tyvars ; result' <- cvtFamilyResultSig result ; injectivity' <- traverse cvtInjectivityAnnotation injectivity ; return (tc', tyvars', result', injectivity') } ------------------------------------------------------------------- -- Partitioning declarations ------------------------------------------------------------------- is_fam_decl :: LHsDecl RdrName -> Either (LFamilyDecl RdrName) (LHsDecl RdrName) is_fam_decl (L loc (TyClD (FamDecl { tcdFam = d }))) = Left (L loc d) is_fam_decl decl = Right decl is_tyfam_inst :: LHsDecl RdrName -> Either (LTyFamInstDecl RdrName) (LHsDecl RdrName) is_tyfam_inst (L loc (Hs.InstD (TyFamInstD { tfid_inst = d }))) = Left (L loc d) is_tyfam_inst decl = Right decl is_datafam_inst :: LHsDecl RdrName -> Either (LDataFamInstDecl RdrName) (LHsDecl RdrName) is_datafam_inst (L loc (Hs.InstD (DataFamInstD { dfid_inst = d }))) = Left (L loc d) is_datafam_inst decl = Right decl is_sig :: LHsDecl RdrName -> Either (LSig RdrName) (LHsDecl RdrName) is_sig (L loc (Hs.SigD sig)) = Left (L loc sig) is_sig decl = Right decl is_bind :: LHsDecl RdrName -> Either (LHsBind RdrName) (LHsDecl RdrName) is_bind (L loc (Hs.ValD bind)) = Left (L loc bind) is_bind decl = Right decl mkBadDecMsg :: Outputable a => MsgDoc -> [a] -> MsgDoc mkBadDecMsg doc bads = sep [ text "Illegal declaration(s) in" <+> doc <> colon , nest 2 (vcat (map Outputable.ppr bads)) ] --------------------------------------------------- -- Data types --------------------------------------------------- cvtConstr :: TH.Con -> CvtM (LConDecl RdrName) cvtConstr (NormalC c strtys) = do { c' <- cNameL c ; cxt' <- returnL [] ; tys' <- mapM cvt_arg strtys ; returnL $ mkConDeclH98 c' Nothing cxt' (PrefixCon tys') } cvtConstr (RecC c varstrtys) = do { c' <- cNameL c ; cxt' <- returnL [] ; args' <- mapM cvt_id_arg varstrtys ; returnL $ mkConDeclH98 c' Nothing cxt' (RecCon (noLoc args')) } cvtConstr (InfixC st1 c st2) = do { c' <- cNameL c ; cxt' <- returnL [] ; st1' <- cvt_arg st1 ; st2' <- cvt_arg st2 ; returnL $ mkConDeclH98 c' Nothing cxt' (InfixCon st1' st2') } cvtConstr (ForallC tvs ctxt con) = do { tvs' <- cvtTvs tvs ; L loc ctxt' <- cvtContext ctxt ; L _ con' <- cvtConstr con ; returnL $ case con' of ConDeclGADT { con_type = conT } -> con' { con_type = HsIB PlaceHolder (noLoc $ HsForAllTy (hsq_explicit tvs') $ (noLoc $ HsQualTy (L loc ctxt') (hsib_body conT))) } ConDeclH98 {} -> let qvars = case (tvs, con_qvars con') of ([], Nothing) -> Nothing (_ , m_qvs ) -> Just $ mkHsQTvs (hsQTvExplicit tvs' ++ maybe [] hsQTvExplicit m_qvs) in con' { con_qvars = qvars , con_cxt = Just $ L loc (ctxt' ++ unLoc (fromMaybe (noLoc []) (con_cxt con'))) } } cvtConstr (GadtC c strtys ty) = do { c' <- mapM cNameL c ; args <- mapM cvt_arg strtys ; L _ ty' <- cvtType ty ; c_ty <- mk_arr_apps args ty' ; returnL $ mkGadtDecl c' (mkLHsSigType c_ty)} cvtConstr (RecGadtC c varstrtys ty) = do { c' <- mapM cNameL c ; ty' <- cvtType ty ; rec_flds <- mapM cvt_id_arg varstrtys ; let rec_ty = noLoc (HsFunTy (noLoc $ HsRecTy rec_flds) ty') ; returnL $ mkGadtDecl c' (mkLHsSigType rec_ty) } cvtSrcUnpackedness :: TH.SourceUnpackedness -> SrcUnpackedness cvtSrcUnpackedness NoSourceUnpackedness = NoSrcUnpack cvtSrcUnpackedness SourceNoUnpack = SrcNoUnpack cvtSrcUnpackedness SourceUnpack = SrcUnpack cvtSrcStrictness :: TH.SourceStrictness -> SrcStrictness cvtSrcStrictness NoSourceStrictness = NoSrcStrict cvtSrcStrictness SourceLazy = SrcLazy cvtSrcStrictness SourceStrict = SrcStrict cvt_arg :: (TH.Bang, TH.Type) -> CvtM (LHsType RdrName) cvt_arg (Bang su ss, ty) = do { ty' <- cvtType ty ; let su' = cvtSrcUnpackedness su ; let ss' = cvtSrcStrictness ss ; returnL $ HsBangTy (HsSrcBang Nothing su' ss') ty' } cvt_id_arg :: (TH.Name, TH.Bang, TH.Type) -> CvtM (LConDeclField RdrName) cvt_id_arg (i, str, ty) = do { L li i' <- vNameL i ; ty' <- cvt_arg (str,ty) ; return $ noLoc (ConDeclField { cd_fld_names = [L li $ FieldOcc (L li i') PlaceHolder] , cd_fld_type = ty' , cd_fld_doc = Nothing}) } cvtDerivs :: TH.Cxt -> CvtM (HsDeriving RdrName) cvtDerivs [] = return Nothing cvtDerivs cs = fmap (Just . mkSigTypes) (cvtContext cs) where mkSigTypes :: Located (HsContext RdrName) -> Located [LHsSigType RdrName] mkSigTypes = fmap (map mkLHsSigType) cvt_fundep :: FunDep -> CvtM (Located (Class.FunDep (Located RdrName))) cvt_fundep (FunDep xs ys) = do { xs' <- mapM tNameL xs ; ys' <- mapM tNameL ys ; returnL (xs', ys') } ------------------------------------------ -- Foreign declarations ------------------------------------------ cvtForD :: Foreign -> CvtM (ForeignDecl RdrName) cvtForD (ImportF callconv safety from nm ty) -- the prim and javascript calling conventions do not support headers -- and are inserted verbatim, analogous to mkImport in RdrHsSyn | callconv == TH.Prim || callconv == TH.JavaScript = mk_imp (CImport (noLoc (cvt_conv callconv)) (noLoc safety') Nothing (CFunction (StaticTarget from (mkFastString from) Nothing True)) (noLoc from)) | Just impspec <- parseCImport (noLoc (cvt_conv callconv)) (noLoc safety') (mkFastString (TH.nameBase nm)) from (noLoc from) = mk_imp impspec | otherwise = failWith $ text (show from) <+> text "is not a valid ccall impent" where mk_imp impspec = do { nm' <- vNameL nm ; ty' <- cvtType ty ; return (ForeignImport { fd_name = nm' , fd_sig_ty = mkLHsSigType ty' , fd_co = noForeignImportCoercionYet , fd_fi = impspec }) } safety' = case safety of Unsafe -> PlayRisky Safe -> PlaySafe Interruptible -> PlayInterruptible cvtForD (ExportF callconv as nm ty) = do { nm' <- vNameL nm ; ty' <- cvtType ty ; let e = CExport (noLoc (CExportStatic as (mkFastString as) (cvt_conv callconv))) (noLoc as) ; return $ ForeignExport { fd_name = nm' , fd_sig_ty = mkLHsSigType ty' , fd_co = noForeignExportCoercionYet , fd_fe = e } } cvt_conv :: TH.Callconv -> CCallConv cvt_conv TH.CCall = CCallConv cvt_conv TH.StdCall = StdCallConv cvt_conv TH.CApi = CApiConv cvt_conv TH.Prim = PrimCallConv cvt_conv TH.JavaScript = JavaScriptCallConv ------------------------------------------ -- Pragmas ------------------------------------------ cvtPragmaD :: Pragma -> CvtM (Maybe (LHsDecl RdrName)) cvtPragmaD (InlineP nm inline rm phases) = do { nm' <- vNameL nm ; let dflt = dfltActivation inline ; let ip = InlinePragma { inl_src = "{-# INLINE" , inl_inline = cvtInline inline , inl_rule = cvtRuleMatch rm , inl_act = cvtPhases phases dflt , inl_sat = Nothing } ; returnJustL $ Hs.SigD $ InlineSig nm' ip } cvtPragmaD (SpecialiseP nm ty inline phases) = do { nm' <- vNameL nm ; ty' <- cvtType ty ; let (inline', dflt) = case inline of Just inline1 -> (cvtInline inline1, dfltActivation inline1) Nothing -> (EmptyInlineSpec, AlwaysActive) ; let ip = InlinePragma { inl_src = "{-# INLINE" , inl_inline = inline' , inl_rule = Hs.FunLike , inl_act = cvtPhases phases dflt , inl_sat = Nothing } ; returnJustL $ Hs.SigD $ SpecSig nm' [mkLHsSigType ty'] ip } cvtPragmaD (SpecialiseInstP ty) = do { ty' <- cvtType ty ; returnJustL $ Hs.SigD $ SpecInstSig "{-# SPECIALISE" (mkLHsSigType ty') } cvtPragmaD (RuleP nm bndrs lhs rhs phases) = do { let nm' = mkFastString nm ; let act = cvtPhases phases AlwaysActive ; bndrs' <- mapM cvtRuleBndr bndrs ; lhs' <- cvtl lhs ; rhs' <- cvtl rhs ; returnJustL $ Hs.RuleD $ HsRules "{-# RULES" [noLoc $ HsRule (noLoc (nm,nm')) act bndrs' lhs' placeHolderNames rhs' placeHolderNames] } cvtPragmaD (AnnP target exp) = do { exp' <- cvtl exp ; target' <- case target of ModuleAnnotation -> return ModuleAnnProvenance TypeAnnotation n -> do n' <- tconName n return (TypeAnnProvenance (noLoc n')) ValueAnnotation n -> do n' <- vcName n return (ValueAnnProvenance (noLoc n')) ; returnJustL $ Hs.AnnD $ HsAnnotation "{-# ANN" target' exp' } cvtPragmaD (LineP line file) = do { setL (srcLocSpan (mkSrcLoc (fsLit file) line 1)) ; return Nothing } dfltActivation :: TH.Inline -> Activation dfltActivation TH.NoInline = NeverActive dfltActivation _ = AlwaysActive cvtInline :: TH.Inline -> Hs.InlineSpec cvtInline TH.NoInline = Hs.NoInline cvtInline TH.Inline = Hs.Inline cvtInline TH.Inlinable = Hs.Inlinable cvtRuleMatch :: TH.RuleMatch -> RuleMatchInfo cvtRuleMatch TH.ConLike = Hs.ConLike cvtRuleMatch TH.FunLike = Hs.FunLike cvtPhases :: TH.Phases -> Activation -> Activation cvtPhases AllPhases dflt = dflt cvtPhases (FromPhase i) _ = ActiveAfter (show i) i cvtPhases (BeforePhase i) _ = ActiveBefore (show i) i cvtRuleBndr :: TH.RuleBndr -> CvtM (Hs.LRuleBndr RdrName) cvtRuleBndr (RuleVar n) = do { n' <- vNameL n ; return $ noLoc $ Hs.RuleBndr n' } cvtRuleBndr (TypedRuleVar n ty) = do { n' <- vNameL n ; ty' <- cvtType ty ; return $ noLoc $ Hs.RuleBndrSig n' $ mkLHsSigWcType ty' } --------------------------------------------------- -- Declarations --------------------------------------------------- cvtLocalDecs :: MsgDoc -> [TH.Dec] -> CvtM (HsLocalBinds RdrName) cvtLocalDecs doc ds | null ds = return EmptyLocalBinds | otherwise = do { ds' <- cvtDecs ds ; let (binds, prob_sigs) = partitionWith is_bind ds' ; let (sigs, bads) = partitionWith is_sig prob_sigs ; unless (null bads) (failWith (mkBadDecMsg doc bads)) ; return (HsValBinds (ValBindsIn (listToBag binds) sigs)) } cvtClause :: TH.Clause -> CvtM (Hs.LMatch RdrName (LHsExpr RdrName)) cvtClause (Clause ps body wheres) = do { ps' <- cvtPats ps ; g' <- cvtGuard body ; ds' <- cvtLocalDecs (text "a where clause") wheres ; returnL $ Hs.Match NonFunBindMatch ps' Nothing (GRHSs g' (noLoc ds')) } ------------------------------------------------------------------- -- Expressions ------------------------------------------------------------------- cvtl :: TH.Exp -> CvtM (LHsExpr RdrName) cvtl e = wrapL (cvt e) where cvt (VarE s) = do { s' <- vName s; return $ HsVar (noLoc s') } cvt (ConE s) = do { s' <- cName s; return $ HsVar (noLoc s') } cvt (LitE l) | overloadedLit l = do { l' <- cvtOverLit l; return $ HsOverLit l' } | otherwise = do { l' <- cvtLit l; return $ HsLit l' } cvt (AppE x@(LamE _ _) y) = do { x' <- cvtl x; y' <- cvtl y ; return $ HsApp (mkLHsPar x') y' } cvt (AppE x y) = do { x' <- cvtl x; y' <- cvtl y ; return $ HsApp x' y' } cvt (LamE ps e) = do { ps' <- cvtPats ps; e' <- cvtl e ; return $ HsLam (mkMatchGroup FromSource [mkSimpleMatch ps' e']) } cvt (LamCaseE ms) = do { ms' <- mapM cvtMatch ms ; return $ HsLamCase placeHolderType (mkMatchGroup FromSource ms') } cvt (TupE [e]) = do { e' <- cvtl e; return $ HsPar e' } -- Note [Dropping constructors] -- Singleton tuples treated like nothing (just parens) cvt (TupE es) = do { es' <- mapM cvtl es ; return $ ExplicitTuple (map (noLoc . Present) es') Boxed } cvt (UnboxedTupE es) = do { es' <- mapM cvtl es ; return $ ExplicitTuple (map (noLoc . Present) es') Unboxed } cvt (CondE x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; ; return $ HsIf (Just noSyntaxExpr) x' y' z' } cvt (MultiIfE alts) | null alts = failWith (text "Multi-way if-expression with no alternatives") | otherwise = do { alts' <- mapM cvtpair alts ; return $ HsMultiIf placeHolderType alts' } cvt (LetE ds e) = do { ds' <- cvtLocalDecs (text "a let expression") ds ; e' <- cvtl e; return $ HsLet (noLoc ds') e' } cvt (CaseE e ms) = do { e' <- cvtl e; ms' <- mapM cvtMatch ms ; return $ HsCase e' (mkMatchGroup FromSource ms') } cvt (DoE ss) = cvtHsDo DoExpr ss cvt (CompE ss) = cvtHsDo ListComp ss cvt (ArithSeqE dd) = do { dd' <- cvtDD dd; return $ ArithSeq noPostTcExpr Nothing dd' } cvt (ListE xs) | Just s <- allCharLs xs = do { l' <- cvtLit (StringL s); return (HsLit l') } -- Note [Converting strings] | otherwise = do { xs' <- mapM cvtl xs ; return $ ExplicitList placeHolderType Nothing xs' } -- Infix expressions cvt (InfixE (Just x) s (Just y)) = do { x' <- cvtl x; s' <- cvtl s; y' <- cvtl y ; wrapParL HsPar $ OpApp (mkLHsPar x') s' undefined (mkLHsPar y') } -- Parenthesise both arguments and result, -- to ensure this operator application does -- does not get re-associated -- See Note [Operator association] cvt (InfixE Nothing s (Just y)) = do { s' <- cvtl s; y' <- cvtl y ; wrapParL HsPar $ SectionR s' y' } -- See Note [Sections in HsSyn] in HsExpr cvt (InfixE (Just x) s Nothing ) = do { x' <- cvtl x; s' <- cvtl s ; wrapParL HsPar $ SectionL x' s' } cvt (InfixE Nothing s Nothing ) = do { s' <- cvtl s; return $ HsPar s' } -- Can I indicate this is an infix thing? -- Note [Dropping constructors] cvt (UInfixE x s y) = do { x' <- cvtl x ; let x'' = case x' of L _ (OpApp {}) -> x' _ -> mkLHsPar x' ; cvtOpApp x'' s y } -- Note [Converting UInfix] cvt (ParensE e) = do { e' <- cvtl e; return $ HsPar e' } cvt (SigE e t) = do { e' <- cvtl e; t' <- cvtType t ; return $ ExprWithTySig e' (mkLHsSigWcType t') } cvt (RecConE c flds) = do { c' <- cNameL c ; flds' <- mapM (cvtFld (mkFieldOcc . noLoc)) flds ; return $ mkRdrRecordCon c' (HsRecFields flds' Nothing) } cvt (RecUpdE e flds) = do { e' <- cvtl e ; flds' <- mapM (cvtFld (mkAmbiguousFieldOcc . noLoc)) flds ; return $ mkRdrRecordUpd e' flds' } cvt (StaticE e) = fmap HsStatic $ cvtl e cvt (UnboundVarE s) = do { s' <- vName s; return $ HsVar (noLoc s') } {- Note [Dropping constructors] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we drop constructors from the input (for instance, when we encounter @TupE [e]@) we must insert parentheses around the argument. Otherwise, @UInfix@ constructors in @e@ could meet @UInfix@ constructors containing the @TupE [e]@. For example: UInfixE x * (TupE [UInfixE y + z]) If we drop the singleton tuple but don't insert parentheses, the @UInfixE@s would meet and the above expression would be reassociated to OpApp (OpApp x * y) + z which we don't want. -} cvtFld :: (RdrName -> t) -> (TH.Name, TH.Exp) -> CvtM (LHsRecField' t (LHsExpr RdrName)) cvtFld f (v,e) = do { v' <- vNameL v; e' <- cvtl e ; return (noLoc $ HsRecField { hsRecFieldLbl = fmap f v' , hsRecFieldArg = e' , hsRecPun = False}) } cvtDD :: Range -> CvtM (ArithSeqInfo RdrName) cvtDD (FromR x) = do { x' <- cvtl x; return $ From x' } cvtDD (FromThenR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromThen x' y' } cvtDD (FromToR x y) = do { x' <- cvtl x; y' <- cvtl y; return $ FromTo x' y' } cvtDD (FromThenToR x y z) = do { x' <- cvtl x; y' <- cvtl y; z' <- cvtl z; return $ FromThenTo x' y' z' } {- Note [Operator assocation] We must be quite careful about adding parens: * Infix (UInfix ...) op arg Needs parens round the first arg * Infix (Infix ...) op arg Needs parens round the first arg * UInfix (UInfix ...) op arg No parens for first arg * UInfix (Infix ...) op arg Needs parens round first arg Note [Converting UInfix] ~~~~~~~~~~~~~~~~~~~~~~~~ When converting @UInfixE@, @UInfixP@, and @UInfixT@ values, we want to readjust the trees to reflect the fixities of the underlying operators: UInfixE x * (UInfixE y + z) ---> (x * y) + z This is done by the renamer (see @mkOppAppRn@, @mkConOppPatRn@, and @mkHsOpTyRn@ in RnTypes), which expects that the input will be completely right-biased for types and left-biased for everything else. So we left-bias the trees of @UInfixP@ and @UInfixE@ and use HsAppsTy for UInfixT. Sample input: UInfixE (UInfixE x op1 y) op2 (UInfixE z op3 w) Sample output: OpApp (OpApp (OpApp x op1 y) op2 z) op3 w The functions @cvtOpApp@, @cvtOpAppP@, and @cvtOpAppT@ are responsible for this biasing. -} {- | @cvtOpApp x op y@ converts @op@ and @y@ and produces the operator application @x `op` y@. The produced tree of infix expressions will be left-biased, provided @x@ is. We can see that @cvtOpApp@ is correct as follows. The inductive hypothesis is that @cvtOpApp x op y@ is left-biased, provided @x@ is. It is clear that this holds for both branches (of @cvtOpApp@), provided we assume it holds for the recursive calls to @cvtOpApp@. When we call @cvtOpApp@ from @cvtl@, the first argument will always be left-biased since we have already run @cvtl@ on it. -} cvtOpApp :: LHsExpr RdrName -> TH.Exp -> TH.Exp -> CvtM (HsExpr RdrName) cvtOpApp x op1 (UInfixE y op2 z) = do { l <- wrapL $ cvtOpApp x op1 y ; cvtOpApp l op2 z } cvtOpApp x op y = do { op' <- cvtl op ; y' <- cvtl y ; return (OpApp x op' undefined y') } ------------------------------------- -- Do notation and statements ------------------------------------- cvtHsDo :: HsStmtContext Name.Name -> [TH.Stmt] -> CvtM (HsExpr RdrName) cvtHsDo do_or_lc stmts | null stmts = failWith (text "Empty stmt list in do-block") | otherwise = do { stmts' <- cvtStmts stmts ; let Just (stmts'', last') = snocView stmts' ; last'' <- case last' of L loc (BodyStmt body _ _ _) -> return (L loc (mkLastStmt body)) _ -> failWith (bad_last last') ; return $ HsDo do_or_lc (noLoc (stmts'' ++ [last''])) placeHolderType } where bad_last stmt = vcat [ text "Illegal last statement of" <+> pprAStmtContext do_or_lc <> colon , nest 2 $ Outputable.ppr stmt , text "(It should be an expression.)" ] cvtStmts :: [TH.Stmt] -> CvtM [Hs.LStmt RdrName (LHsExpr RdrName)] cvtStmts = mapM cvtStmt cvtStmt :: TH.Stmt -> CvtM (Hs.LStmt RdrName (LHsExpr RdrName)) cvtStmt (NoBindS e) = do { e' <- cvtl e; returnL $ mkBodyStmt e' } cvtStmt (TH.BindS p e) = do { p' <- cvtPat p; e' <- cvtl e; returnL $ mkBindStmt p' e' } cvtStmt (TH.LetS ds) = do { ds' <- cvtLocalDecs (text "a let binding") ds ; returnL $ LetStmt (noLoc ds') } cvtStmt (TH.ParS dss) = do { dss' <- mapM cvt_one dss; returnL $ ParStmt dss' noSyntaxExpr noSyntaxExpr } where cvt_one ds = do { ds' <- cvtStmts ds; return (ParStmtBlock ds' undefined noSyntaxExpr) } cvtMatch :: TH.Match -> CvtM (Hs.LMatch RdrName (LHsExpr RdrName)) cvtMatch (TH.Match p body decs) = do { p' <- cvtPat p ; g' <- cvtGuard body ; decs' <- cvtLocalDecs (text "a where clause") decs ; returnL $ Hs.Match NonFunBindMatch [p'] Nothing (GRHSs g' (noLoc decs')) } cvtGuard :: TH.Body -> CvtM [LGRHS RdrName (LHsExpr RdrName)] cvtGuard (GuardedB pairs) = mapM cvtpair pairs cvtGuard (NormalB e) = do { e' <- cvtl e; g' <- returnL $ GRHS [] e'; return [g'] } cvtpair :: (TH.Guard, TH.Exp) -> CvtM (LGRHS RdrName (LHsExpr RdrName)) cvtpair (NormalG ge,rhs) = do { ge' <- cvtl ge; rhs' <- cvtl rhs ; g' <- returnL $ mkBodyStmt ge' ; returnL $ GRHS [g'] rhs' } cvtpair (PatG gs,rhs) = do { gs' <- cvtStmts gs; rhs' <- cvtl rhs ; returnL $ GRHS gs' rhs' } cvtOverLit :: Lit -> CvtM (HsOverLit RdrName) cvtOverLit (IntegerL i) = do { force i; return $ mkHsIntegral (show i) i placeHolderType} cvtOverLit (RationalL r) = do { force r; return $ mkHsFractional (cvtFractionalLit r) placeHolderType} cvtOverLit (StringL s) = do { let { s' = mkFastString s } ; force s' ; return $ mkHsIsString s s' placeHolderType } cvtOverLit _ = panic "Convert.cvtOverLit: Unexpected overloaded literal" -- An Integer is like an (overloaded) '3' in a Haskell source program -- Similarly 3.5 for fractionals {- Note [Converting strings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If we get (ListE [CharL 'x', CharL 'y']) we'd like to convert to a string literal for "xy". Of course, we might hope to get (LitE (StringL "xy")), but not always, and allCharLs fails quickly if it isn't a literal string -} allCharLs :: [TH.Exp] -> Maybe String -- Note [Converting strings] -- NB: only fire up this setup for a non-empty list, else -- there's a danger of returning "" for [] :: [Int]! allCharLs xs = case xs of LitE (CharL c) : ys -> go [c] ys _ -> Nothing where go cs [] = Just (reverse cs) go cs (LitE (CharL c) : ys) = go (c:cs) ys go _ _ = Nothing cvtLit :: Lit -> CvtM HsLit cvtLit (IntPrimL i) = do { force i; return $ HsIntPrim (show i) i } cvtLit (WordPrimL w) = do { force w; return $ HsWordPrim (show w) w } cvtLit (FloatPrimL f) = do { force f; return $ HsFloatPrim (cvtFractionalLit f) } cvtLit (DoublePrimL f) = do { force f; return $ HsDoublePrim (cvtFractionalLit f) } cvtLit (CharL c) = do { force c; return $ HsChar (show c) c } cvtLit (CharPrimL c) = do { force c; return $ HsCharPrim (show c) c } cvtLit (StringL s) = do { let { s' = mkFastString s } ; force s' ; return $ HsString s s' } cvtLit (StringPrimL s) = do { let { s' = BS.pack s } ; force s' ; return $ HsStringPrim (w8ToString s) s' } cvtLit _ = panic "Convert.cvtLit: Unexpected literal" -- cvtLit should not be called on IntegerL, RationalL -- That precondition is established right here in -- Convert.hs, hence panic w8ToString :: [Word8] -> String w8ToString ws = map (\w -> chr (fromIntegral w)) ws cvtPats :: [TH.Pat] -> CvtM [Hs.LPat RdrName] cvtPats pats = mapM cvtPat pats cvtPat :: TH.Pat -> CvtM (Hs.LPat RdrName) cvtPat pat = wrapL (cvtp pat) cvtp :: TH.Pat -> CvtM (Hs.Pat RdrName) cvtp (TH.LitP l) | overloadedLit l = do { l' <- cvtOverLit l ; return (mkNPat (noLoc l') Nothing) } -- Not right for negative patterns; -- need to think about that! | otherwise = do { l' <- cvtLit l; return $ Hs.LitPat l' } cvtp (TH.VarP s) = do { s' <- vName s; return $ Hs.VarPat (noLoc s') } cvtp (TupP [p]) = do { p' <- cvtPat p; return $ ParPat p' } -- Note [Dropping constructors] cvtp (TupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Boxed [] } cvtp (UnboxedTupP ps) = do { ps' <- cvtPats ps; return $ TuplePat ps' Unboxed [] } cvtp (ConP s ps) = do { s' <- cNameL s; ps' <- cvtPats ps ; return $ ConPatIn s' (PrefixCon ps') } cvtp (InfixP p1 s p2) = do { s' <- cNameL s; p1' <- cvtPat p1; p2' <- cvtPat p2 ; wrapParL ParPat $ ConPatIn s' (InfixCon (mkParPat p1') (mkParPat p2')) } -- See Note [Operator association] cvtp (UInfixP p1 s p2) = do { p1' <- cvtPat p1; cvtOpAppP p1' s p2 } -- Note [Converting UInfix] cvtp (ParensP p) = do { p' <- cvtPat p; return $ ParPat p' } cvtp (TildeP p) = do { p' <- cvtPat p; return $ LazyPat p' } cvtp (BangP p) = do { p' <- cvtPat p; return $ BangPat p' } cvtp (TH.AsP s p) = do { s' <- vNameL s; p' <- cvtPat p; return $ AsPat s' p' } cvtp TH.WildP = return $ WildPat placeHolderType cvtp (RecP c fs) = do { c' <- cNameL c; fs' <- mapM cvtPatFld fs ; return $ ConPatIn c' $ Hs.RecCon (HsRecFields fs' Nothing) } cvtp (ListP ps) = do { ps' <- cvtPats ps ; return $ ListPat ps' placeHolderType Nothing } cvtp (SigP p t) = do { p' <- cvtPat p; t' <- cvtType t ; return $ SigPatIn p' (mkLHsSigWcType t') } cvtp (ViewP e p) = do { e' <- cvtl e; p' <- cvtPat p ; return $ ViewPat e' p' placeHolderType } cvtPatFld :: (TH.Name, TH.Pat) -> CvtM (LHsRecField RdrName (LPat RdrName)) cvtPatFld (s,p) = do { L ls s' <- vNameL s; p' <- cvtPat p ; return (noLoc $ HsRecField { hsRecFieldLbl = L ls $ mkFieldOcc (L ls s') , hsRecFieldArg = p' , hsRecPun = False}) } {- | @cvtOpAppP x op y@ converts @op@ and @y@ and produces the operator application @x `op` y@. The produced tree of infix patterns will be left-biased, provided @x@ is. See the @cvtOpApp@ documentation for how this function works. -} cvtOpAppP :: Hs.LPat RdrName -> TH.Name -> TH.Pat -> CvtM (Hs.Pat RdrName) cvtOpAppP x op1 (UInfixP y op2 z) = do { l <- wrapL $ cvtOpAppP x op1 y ; cvtOpAppP l op2 z } cvtOpAppP x op y = do { op' <- cNameL op ; y' <- cvtPat y ; return (ConPatIn op' (InfixCon x y')) } ----------------------------------------------------------- -- Types and type variables cvtTvs :: [TH.TyVarBndr] -> CvtM (LHsQTyVars RdrName) cvtTvs tvs = do { tvs' <- mapM cvt_tv tvs; return (mkHsQTvs tvs') } cvt_tv :: TH.TyVarBndr -> CvtM (LHsTyVarBndr RdrName) cvt_tv (TH.PlainTV nm) = do { nm' <- tNameL nm ; returnL $ UserTyVar nm' } cvt_tv (TH.KindedTV nm ki) = do { nm' <- tNameL nm ; ki' <- cvtKind ki ; returnL $ KindedTyVar nm' ki' } cvtRole :: TH.Role -> Maybe Coercion.Role cvtRole TH.NominalR = Just Coercion.Nominal cvtRole TH.RepresentationalR = Just Coercion.Representational cvtRole TH.PhantomR = Just Coercion.Phantom cvtRole TH.InferR = Nothing cvtContext :: TH.Cxt -> CvtM (LHsContext RdrName) cvtContext tys = do { preds' <- mapM cvtPred tys; returnL preds' } cvtPred :: TH.Pred -> CvtM (LHsType RdrName) cvtPred = cvtType cvtType :: TH.Type -> CvtM (LHsType RdrName) cvtType = cvtTypeKind "type" cvtTypeKind :: String -> TH.Type -> CvtM (LHsType RdrName) cvtTypeKind ty_str ty = do { (head_ty, tys') <- split_ty_app ty ; case head_ty of TupleT n | length tys' == n -- Saturated -> if n==1 then return (head tys') -- Singleton tuples treated -- like nothing (ie just parens) else returnL (HsTupleTy HsBoxedOrConstraintTuple tys') | n == 1 -> failWith (ptext (sLit ("Illegal 1-tuple " ++ ty_str ++ " constructor"))) | otherwise -> mk_apps (HsTyVar (noLoc (getRdrName (tupleTyCon Boxed n)))) tys' UnboxedTupleT n | length tys' == n -- Saturated -> if n==1 then return (head tys') -- Singleton tuples treated -- like nothing (ie just parens) else returnL (HsTupleTy HsUnboxedTuple tys') | otherwise -> mk_apps (HsTyVar (noLoc (getRdrName (tupleTyCon Unboxed n)))) tys' ArrowT | [x',y'] <- tys' -> returnL (HsFunTy x' y') | otherwise -> mk_apps (HsTyVar (noLoc (getRdrName funTyCon))) tys' ListT | [x'] <- tys' -> returnL (HsListTy x') | otherwise -> mk_apps (HsTyVar (noLoc (getRdrName listTyCon))) tys' VarT nm -> do { nm' <- tNameL nm ; mk_apps (HsTyVar nm') tys' } ConT nm -> do { nm' <- tconName nm ; mk_apps (HsTyVar (noLoc nm')) tys' } ForallT tvs cxt ty | null tys' -> do { tvs' <- cvtTvs tvs ; cxt' <- cvtContext cxt ; ty' <- cvtType ty ; loc <- getL ; let hs_ty | null tvs = rho_ty | otherwise = L loc (HsForAllTy { hst_bndrs = hsQTvExplicit tvs' , hst_body = rho_ty }) rho_ty | null cxt = ty' | otherwise = L loc (HsQualTy { hst_ctxt = cxt' , hst_body = ty' }) ; return hs_ty } SigT ty ki -> do { ty' <- cvtType ty ; ki' <- cvtKind ki ; mk_apps (HsKindSig ty' ki') tys' } LitT lit -> returnL (HsTyLit (cvtTyLit lit)) WildCardT -> mk_apps mkAnonWildCardTy tys' InfixT t1 s t2 -> do { s' <- tconName s ; t1' <- cvtType t1 ; t2' <- cvtType t2 ; mk_apps (HsTyVar (noLoc s')) [t1', t2'] } UInfixT t1 s t2 -> do { t1' <- cvtType t1 ; t2' <- cvtType t2 ; s' <- tconName s ; return $ cvtOpAppT t1' s' t2' } -- Note [Converting UInfix] ParensT t -> do { t' <- cvtType t ; returnL $ HsParTy t' } PromotedT nm -> do { nm' <- cName nm ; mk_apps (HsTyVar (noLoc nm')) tys' } -- Promoted data constructor; hence cName PromotedTupleT n | n == 1 -> failWith (ptext (sLit ("Illegal promoted 1-tuple " ++ ty_str))) | m == n -- Saturated -> do { let kis = replicate m placeHolderKind ; returnL (HsExplicitTupleTy kis tys') } where m = length tys' PromotedNilT -> returnL (HsExplicitListTy placeHolderKind []) PromotedConsT -- See Note [Representing concrete syntax in types] -- in Language.Haskell.TH.Syntax | [ty1, L _ (HsExplicitListTy _ tys2)] <- tys' -> returnL (HsExplicitListTy placeHolderKind (ty1:tys2)) | otherwise -> mk_apps (HsTyVar (noLoc (getRdrName consDataCon))) tys' StarT -> returnL (HsTyVar (noLoc (getRdrName liftedTypeKindTyCon))) ConstraintT -> returnL (HsTyVar (noLoc (getRdrName constraintKindTyCon))) EqualityT | [x',y'] <- tys' -> returnL (HsEqTy x' y') | otherwise -> mk_apps (HsTyVar (noLoc (getRdrName eqPrimTyCon))) tys' _ -> failWith (ptext (sLit ("Malformed " ++ ty_str)) <+> text (show ty)) } -- | Constructs an application of a type to arguments passed in a list. mk_apps :: HsType RdrName -> [LHsType RdrName] -> CvtM (LHsType RdrName) mk_apps head_ty [] = returnL head_ty mk_apps head_ty (ty:tys) = do { head_ty' <- returnL head_ty ; mk_apps (HsAppTy head_ty' ty) tys } -- | Constructs an arrow type with a specified return type mk_arr_apps :: [LHsType RdrName] -> HsType RdrName -> CvtM (LHsType RdrName) mk_arr_apps tys return_ty = foldrM go return_ty tys >>= returnL where go :: LHsType RdrName -> HsType RdrName -> CvtM (HsType RdrName) go arg ret_ty = do { ret_ty_l <- returnL ret_ty ; return (HsFunTy arg ret_ty_l) } split_ty_app :: TH.Type -> CvtM (TH.Type, [LHsType RdrName]) split_ty_app ty = go ty [] where go (AppT f a) as' = do { a' <- cvtType a; go f (a':as') } go f as = return (f,as) cvtTyLit :: TH.TyLit -> HsTyLit cvtTyLit (TH.NumTyLit i) = HsNumTy (show i) i cvtTyLit (TH.StrTyLit s) = HsStrTy s (fsLit s) {- | @cvtOpAppT x op y@ takes converted arguments and flattens any HsAppsTy structure in them. -} cvtOpAppT :: LHsType RdrName -> RdrName -> LHsType RdrName -> LHsType RdrName cvtOpAppT t1@(L loc1 _) op t2@(L loc2 _) = L (combineSrcSpans loc1 loc2) $ HsAppsTy (t1' ++ [noLoc $ HsAppInfix (noLoc op)] ++ t2') where t1' | L _ (HsAppsTy t1s) <- t1 = t1s | otherwise = [noLoc $ HsAppPrefix t1] t2' | L _ (HsAppsTy t2s) <- t2 = t2s | otherwise = [noLoc $ HsAppPrefix t2] cvtKind :: TH.Kind -> CvtM (LHsKind RdrName) cvtKind = cvtTypeKind "kind" -- | Convert Maybe Kind to a type family result signature. Used with data -- families where naming of the result is not possible (thus only kind or no -- signature is possible). cvtMaybeKindToFamilyResultSig :: Maybe TH.Kind -> CvtM (LFamilyResultSig RdrName) cvtMaybeKindToFamilyResultSig Nothing = returnL Hs.NoSig cvtMaybeKindToFamilyResultSig (Just ki) = do { ki' <- cvtKind ki ; returnL (Hs.KindSig ki') } -- | Convert type family result signature. Used with both open and closed type -- families. cvtFamilyResultSig :: TH.FamilyResultSig -> CvtM (Hs.LFamilyResultSig RdrName) cvtFamilyResultSig TH.NoSig = returnL Hs.NoSig cvtFamilyResultSig (TH.KindSig ki) = do { ki' <- cvtKind ki ; returnL (Hs.KindSig ki') } cvtFamilyResultSig (TH.TyVarSig bndr) = do { tv <- cvt_tv bndr ; returnL (Hs.TyVarSig tv) } -- | Convert injectivity annotation of a type family. cvtInjectivityAnnotation :: TH.InjectivityAnn -> CvtM (Hs.LInjectivityAnn RdrName) cvtInjectivityAnnotation (TH.InjectivityAnn annLHS annRHS) = do { annLHS' <- tNameL annLHS ; annRHS' <- mapM tNameL annRHS ; returnL (Hs.InjectivityAnn annLHS' annRHS') } ----------------------------------------------------------- cvtFixity :: TH.Fixity -> Hs.Fixity cvtFixity (TH.Fixity prec dir) = Hs.Fixity (show prec) prec (cvt_dir dir) where cvt_dir TH.InfixL = Hs.InfixL cvt_dir TH.InfixR = Hs.InfixR cvt_dir TH.InfixN = Hs.InfixN ----------------------------------------------------------- ----------------------------------------------------------- -- some useful things overloadedLit :: Lit -> Bool -- True for literals that Haskell treats as overloaded overloadedLit (IntegerL _) = True overloadedLit (RationalL _) = True overloadedLit _ = False cvtFractionalLit :: Rational -> FractionalLit cvtFractionalLit r = FL { fl_text = show (fromRational r :: Double), fl_value = r } -------------------------------------------------------------------- -- Turning Name back into RdrName -------------------------------------------------------------------- -- variable names vNameL, cNameL, vcNameL, tNameL, tconNameL :: TH.Name -> CvtM (Located RdrName) vName, cName, vcName, tName, tconName :: TH.Name -> CvtM RdrName -- Variable names vNameL n = wrapL (vName n) vName n = cvtName OccName.varName n -- Constructor function names; this is Haskell source, hence srcDataName cNameL n = wrapL (cName n) cName n = cvtName OccName.dataName n -- Variable *or* constructor names; check by looking at the first char vcNameL n = wrapL (vcName n) vcName n = if isVarName n then vName n else cName n -- Type variable names tNameL n = wrapL (tName n) tName n = cvtName OccName.tvName n -- Type Constructor names tconNameL n = wrapL (tconName n) tconName n = cvtName OccName.tcClsName n cvtName :: OccName.NameSpace -> TH.Name -> CvtM RdrName cvtName ctxt_ns (TH.Name occ flavour) | not (okOcc ctxt_ns occ_str) = failWith (badOcc ctxt_ns occ_str) | otherwise = do { loc <- getL ; let rdr_name = thRdrName loc ctxt_ns occ_str flavour ; force rdr_name ; return rdr_name } where occ_str = TH.occString occ okOcc :: OccName.NameSpace -> String -> Bool okOcc ns str | OccName.isVarNameSpace ns = okVarOcc str | OccName.isDataConNameSpace ns = okConOcc str | otherwise = okTcOcc str -- Determine the name space of a name in a type -- isVarName :: TH.Name -> Bool isVarName (TH.Name occ _) = case TH.occString occ of "" -> False (c:_) -> startsVarId c || startsVarSym c badOcc :: OccName.NameSpace -> String -> SDoc badOcc ctxt_ns occ = text "Illegal" <+> pprNameSpace ctxt_ns <+> text "name:" <+> quotes (text occ) thRdrName :: SrcSpan -> OccName.NameSpace -> String -> TH.NameFlavour -> RdrName -- This turns a TH Name into a RdrName; used for both binders and occurrences -- See Note [Binders in Template Haskell] -- The passed-in name space tells what the context is expecting; -- use it unless the TH name knows what name-space it comes -- from, in which case use the latter -- -- We pass in a SrcSpan (gotten from the monad) because this function -- is used for *binders* and if we make an Exact Name we want it -- to have a binding site inside it. (cf Trac #5434) -- -- ToDo: we may generate silly RdrNames, by passing a name space -- that doesn't match the string, like VarName ":+", -- which will give confusing error messages later -- -- The strict applications ensure that any buried exceptions get forced thRdrName loc ctxt_ns th_occ th_name = case th_name of TH.NameG th_ns pkg mod -> thOrigRdrName th_occ th_ns pkg mod TH.NameQ mod -> (mkRdrQual $! mk_mod mod) $! occ TH.NameL uniq -> nameRdrName $! (((Name.mkInternalName $! mk_uniq uniq) $! occ) loc) TH.NameU uniq -> nameRdrName $! (((Name.mkSystemNameAt $! mk_uniq uniq) $! occ) loc) TH.NameS | Just name <- isBuiltInOcc_maybe occ -> nameRdrName $! name | otherwise -> mkRdrUnqual $! occ -- We check for built-in syntax here, because the TH -- user might have written a (NameS "(,,)"), for example where occ :: OccName.OccName occ = mk_occ ctxt_ns th_occ thOrigRdrName :: String -> TH.NameSpace -> PkgName -> ModName -> RdrName thOrigRdrName occ th_ns pkg mod = (mkOrig $! (mkModule (mk_pkg pkg) (mk_mod mod))) $! (mk_occ (mk_ghc_ns th_ns) occ) thRdrNameGuesses :: TH.Name -> [RdrName] thRdrNameGuesses (TH.Name occ flavour) -- This special case for NameG ensures that we don't generate duplicates in the output list | TH.NameG th_ns pkg mod <- flavour = [ thOrigRdrName occ_str th_ns pkg mod] | otherwise = [ thRdrName noSrcSpan gns occ_str flavour | gns <- guessed_nss] where -- guessed_ns are the name spaces guessed from looking at the TH name guessed_nss | isLexCon (mkFastString occ_str) = [OccName.tcName, OccName.dataName] | otherwise = [OccName.varName, OccName.tvName] occ_str = TH.occString occ -- The packing and unpacking is rather turgid :-( mk_occ :: OccName.NameSpace -> String -> OccName.OccName mk_occ ns occ = OccName.mkOccName ns occ mk_ghc_ns :: TH.NameSpace -> OccName.NameSpace mk_ghc_ns TH.DataName = OccName.dataName mk_ghc_ns TH.TcClsName = OccName.tcClsName mk_ghc_ns TH.VarName = OccName.varName mk_mod :: TH.ModName -> ModuleName mk_mod mod = mkModuleName (TH.modString mod) mk_pkg :: TH.PkgName -> UnitId mk_pkg pkg = stringToUnitId (TH.pkgString pkg) mk_uniq :: Int -> Unique mk_uniq u = mkUniqueGrimily u {- Note [Binders in Template Haskell] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider this TH term construction: do { x1 <- TH.newName "x" -- newName :: String -> Q TH.Name ; x2 <- TH.newName "x" -- Builds a NameU ; x3 <- TH.newName "x" ; let x = mkName "x" -- mkName :: String -> TH.Name -- Builds a NameS ; return (LamE (..pattern [x1,x2]..) $ LamE (VarPat x3) $ ..tuple (x1,x2,x3,x)) } It represents the term \[x1,x2]. \x3. (x1,x2,x3,x) a) We don't want to complain about "x" being bound twice in the pattern [x1,x2] b) We don't want x3 to shadow the x1,x2 c) We *do* want 'x' (dynamically bound with mkName) to bind to the innermost binding of "x", namely x3. d) When pretty printing, we want to print a unique with x1,x2 etc, else they'll all print as "x" which isn't very helpful When we convert all this to HsSyn, the TH.Names are converted with thRdrName. To achieve (b) we want the binders to be Exact RdrNames. Achieving (a) is a bit awkward, because - We must check for duplicate and shadowed names on Names, not RdrNames, *after* renaming. See Note [Collect binders only after renaming] in HsUtils - But to achieve (a) we must distinguish between the Exact RdrNames arising from TH and the Unqual RdrNames that would come from a user writing \[x,x] -> blah So in Convert.thRdrName we translate TH Name RdrName -------------------------------------------------------- NameU (arising from newName) --> Exact (Name{ System }) NameS (arising from mkName) --> Unqual Notice that the NameUs generate *System* Names. Then, when figuring out shadowing and duplicates, we can filter out System Names. This use of System Names fits with other uses of System Names, eg for temporary variables "a". Since there are lots of things called "a" we usually want to print the name with the unique, and that is indeed the way System Names are printed. There's a small complication of course; see Note [Looking up Exact RdrNames] in RnEnv. -}
gridaphobe/ghc
compiler/hsSyn/Convert.hs
bsd-3-clause
60,749
3
24
20,063
17,260
8,695
8,565
981
30
{-# LANGUAGE ScopedTypeVariables, PatternGuards #-} module Cyoa.Parser (parsePages) where import Cyoa.NormalizeXML import Cyoa.PageLang import Control.Monad.Writer import Text.XML.Expat.Tree import Text.XML.Expat.Format import System.Exit import System.IO import Data.List import Data.Maybe import qualified Data.ByteString.Lazy as L import Control.Monad import Data.Char parsePage :: UNode String -> Page parsePage node = Page (getId node) image pageType (map parseItem (filter isElement $ getChildren node)) where pageType | Just "1" <- getAttribute node "death" = DeathPage | Just "1" <- getAttribute node "win" = WinPage | otherwise = NormalPage image = getAttribute node "image" parseItem :: UNode String -> PageItem parseItem (Text t) = TextLit t parseItem node@(Element "p" _ _) = Paragraph (map parseItem $ getChildren node) parseItem node@(Element "goto" [("ref", pageNum)] _) = Goto False (read pageNum) parseItem node@(Element "Goto" [("ref", pageNum)] _) = Goto True (read pageNum) parseItem node@(Element "goto-lucky" [("refYes", yes), ("refNo", no)] _) = GotoLucky (read yes) (read no) -- TODO parseItem node@(Element "if" _ _) = let cond:thn:elss = filter isElement $ getChildren node in If (parseCond cond) (parseBranch thn) $ case elss of [els] -> parseBranch els _ -> [] where parseBranch node@(Element "text" _ _) = map parseItem $ getChildren node parseBranch node = [parseItem node] parseItem node@(Element "inc" [("counter", counter)] _) = Inc counter parseItem node@(Element "dec" [("counter", counter)] _) = Dec counter parseItem node@(Element "clear" [("counter", counter)] _) = Clear counter parseItem node@(Element "take" [("item", item)] _) = Take item parseItem node@(Element "drop" [("item", item)] _) = Drop item parseItem node@(Element "damage" [("stat", stat)] _) = Damage (parseStat stat) (parseExpr expr) where [expr] = filter isElement $ getChildren node parseItem node@(Element "heal" [("stat", stat)] _) = Heal (parseStat stat) (parseExpr expr) where [expr] = filter isElement $ getChildren node parseItem node@(Element "set-flag" [("flag", flag)] _) = Set flag parseItem node@(Element "dice" [("name", name)] _) = DieDef name parseItem node@(Element "fight" _ _) = Fight $ map parseEnemy $ filter isElement $ getChildren node parseEnemy node@(Element "enemy" [("agility", agility), ("health", health)] [(Text name)]) = Enemy name (read agility) (read health) parseStat "health" = Health parseStat "luck" = Luck parseStat "agility" = Agility parseCond :: UNode String -> Cond parseCond node@(Element "or" _ _) = let [left, right] = filter isElement $ getChildren node in parseCond left :||: parseCond right parseCond node@(Element "and" _ _) = let [left, right] = filter isElement $ getChildren node in parseCond left :&&: parseCond right parseCond node@(Element "eq" _ _) = parseBin node (:==:) parseCond node@(Element "le" _ _) = parseBin node (:<=:) parseCond node@(Element "ge" _ _) = parseBin node (:>=:) parseCond node@(Element "lt" _ _) = parseBin node (:<:) parseCond node@(Element "gt" _ _) = parseBin node (:>:) parseCond node@(Element "carry" [("item", item)] _) = Carry item parseCond node@(Element "flag-set" [("flag", flag)] _) = FlagSet flag parseBin node op = let [left, right] = filter isElement $ getChildren node in parseExpr left `op` parseExpr right parseExpr :: UNode String -> Expr parseExpr (Element "intlit" [("value", v)] _) = ELiteral $ read v parseExpr (Element "counter" [("name", counter)] _) = CounterRef counter parseExpr (Element "var" [("ref", name)] _) = DieRef name parseExpr node@(Element "plus" _ _) = parseBin node (:+:) parseExpr node@(Element "minus" _ _) = parseBin node (:-:) parseExpr node@(Element "mul" _ _) = parseBin node (:*:) parseExpr node@(Element "mod" _ _) = parseBin node (:%:) parseExpr (Element "score" [("stat", stat)] _) = StatQuery (parseStat stat) parseExpr node@(Element "cond" _ _) = let [cond, thn, els] = filter isElement $ getChildren node in ECond (parseCond cond) (parseExpr thn) (parseExpr els) getId :: UNode String -> Int getId e@(Element "page" _ _) = case getAttribute e "id" of Just x -> read x parsePages :: FilePath -> IO [Page] parsePages filename = do inputText <- L.readFile filename let (xml, mErr) = parse defaultParseOptions inputText case mErr of Nothing -> do return $ map (parsePage . normalizeXML) (filter isElement $ getChildren xml) Just err -> do hPutStrLn stderr $ "XML parse failed: " ++ show err exitWith $ ExitFailure 2
vikikiss/cyoa
src/Cyoa/Parser.hs
bsd-3-clause
4,692
0
16
897
1,958
1,010
948
91
3
{-# LANGUAGE CPP, MagicHash, UnboxedTuples #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -O -funbox-strict-fields #-} -- We always optimise this, otherwise performance of a non-optimised -- compiler is severely affected -- -- (c) The University of Glasgow 2002-2006 -- -- Binary I/O library, with special tweaks for GHC -- -- Based on the nhc98 Binary library, which is copyright -- (c) Malcolm Wallace and Colin Runciman, University of York, 1998. -- Under the terms of the license for that software, we must tell you -- where you can obtain the original version of the Binary library, namely -- http://www.cs.york.ac.uk/fp/nhc98/ module Binary ( {-type-} Bin, {-class-} Binary(..), {-type-} BinHandle, SymbolTable, Dictionary, openBinMem, -- closeBin, seekBin, seekBy, tellBin, castBin, isEOFBin, withBinBuffer, writeBinMem, readBinMem, putAt, getAt, -- * For writing instances putByte, getByte, -- * Lazy Binary I/O lazyGet, lazyPut, -- * User data UserData(..), getUserData, setUserData, newReadState, newWriteState, putDictionary, getDictionary, putFS, ) where #include "HsVersions.h" -- The *host* architecture version: #include "../includes/MachDeps.h" import {-# SOURCE #-} Name (Name) import FastString import Panic import UniqFM import FastMutInt import Fingerprint import BasicTypes import SrcLoc import Foreign import Data.Array import Data.ByteString (ByteString) import qualified Data.ByteString as BS import qualified Data.ByteString.Unsafe as BS import Data.IORef import Data.Char ( ord, chr ) import Data.Time import Data.Typeable import Control.Monad ( when ) import System.IO as IO import System.IO.Unsafe ( unsafeInterleaveIO ) import System.IO.Error ( mkIOError, eofErrorType ) import GHC.Real ( Ratio(..) ) import GHC.Serialized type BinArray = ForeignPtr Word8 --------------------------------------------------------------- -- BinHandle --------------------------------------------------------------- data BinHandle = BinMem { -- binary data stored in an unboxed array bh_usr :: UserData, -- sigh, need parameterized modules :-) _off_r :: !FastMutInt, -- the current offset _sz_r :: !FastMutInt, -- size of the array (cached) _arr_r :: !(IORef BinArray) -- the array (bounds: (0,size-1)) } -- XXX: should really store a "high water mark" for dumping out -- the binary data to a file. getUserData :: BinHandle -> UserData getUserData bh = bh_usr bh setUserData :: BinHandle -> UserData -> BinHandle setUserData bh us = bh { bh_usr = us } -- | Get access to the underlying buffer. -- -- It is quite important that no references to the 'ByteString' leak out of the -- continuation lest terrible things happen. withBinBuffer :: BinHandle -> (ByteString -> IO a) -> IO a withBinBuffer (BinMem _ ix_r _ arr_r) action = do arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \ptr -> BS.unsafePackCStringLen (castPtr ptr, ix) >>= action --------------------------------------------------------------- -- Bin --------------------------------------------------------------- newtype Bin a = BinPtr Int deriving (Eq, Ord, Show, Bounded) castBin :: Bin a -> Bin b castBin (BinPtr i) = BinPtr i --------------------------------------------------------------- -- class Binary --------------------------------------------------------------- class Binary a where put_ :: BinHandle -> a -> IO () put :: BinHandle -> a -> IO (Bin a) get :: BinHandle -> IO a -- define one of put_, put. Use of put_ is recommended because it -- is more likely that tail-calls can kick in, and we rarely need the -- position return value. put_ bh a = do _ <- put bh a; return () put bh a = do p <- tellBin bh; put_ bh a; return p putAt :: Binary a => BinHandle -> Bin a -> a -> IO () putAt bh p x = do seekBin bh p; put_ bh x; return () getAt :: Binary a => BinHandle -> Bin a -> IO a getAt bh p = do seekBin bh p; get bh openBinMem :: Int -> IO BinHandle openBinMem size | size <= 0 = error "Data.Binary.openBinMem: size must be >= 0" | otherwise = do arr <- mallocForeignPtrBytes size arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r size return (BinMem noUserData ix_r sz_r arr_r) tellBin :: BinHandle -> IO (Bin a) tellBin (BinMem _ r _ _) = do ix <- readFastMutInt r; return (BinPtr ix) seekBin :: BinHandle -> Bin a -> IO () seekBin h@(BinMem _ ix_r sz_r _) (BinPtr p) = do sz <- readFastMutInt sz_r if (p >= sz) then do expandBin h p; writeFastMutInt ix_r p else writeFastMutInt ix_r p seekBy :: BinHandle -> Int -> IO () seekBy h@(BinMem _ ix_r sz_r _) off = do sz <- readFastMutInt sz_r ix <- readFastMutInt ix_r let ix' = ix + off if (ix' >= sz) then do expandBin h ix'; writeFastMutInt ix_r ix' else writeFastMutInt ix_r ix' isEOFBin :: BinHandle -> IO Bool isEOFBin (BinMem _ ix_r sz_r _) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r return (ix >= sz) writeBinMem :: BinHandle -> FilePath -> IO () writeBinMem (BinMem _ ix_r _ arr_r) fn = do h <- openBinaryFile fn WriteMode arr <- readIORef arr_r ix <- readFastMutInt ix_r withForeignPtr arr $ \p -> hPutBuf h p ix hClose h readBinMem :: FilePath -> IO BinHandle -- Return a BinHandle with a totally undefined State readBinMem filename = do h <- openBinaryFile filename ReadMode filesize' <- hFileSize h let filesize = fromIntegral filesize' arr <- mallocForeignPtrBytes (filesize*2) count <- withForeignPtr arr $ \p -> hGetBuf h p filesize when (count /= filesize) $ error ("Binary.readBinMem: only read " ++ show count ++ " bytes") hClose h arr_r <- newIORef arr ix_r <- newFastMutInt writeFastMutInt ix_r 0 sz_r <- newFastMutInt writeFastMutInt sz_r filesize return (BinMem noUserData ix_r sz_r arr_r) -- expand the size of the array to include a specified offset expandBin :: BinHandle -> Int -> IO () expandBin (BinMem _ _ sz_r arr_r) off = do sz <- readFastMutInt sz_r let sz' = head (dropWhile (<= off) (iterate (* 2) sz)) arr <- readIORef arr_r arr' <- mallocForeignPtrBytes sz' withForeignPtr arr $ \old -> withForeignPtr arr' $ \new -> copyBytes new old sz writeFastMutInt sz_r sz' writeIORef arr_r arr' -- ----------------------------------------------------------------------------- -- Low-level reading/writing of bytes putWord8 :: BinHandle -> Word8 -> IO () putWord8 h@(BinMem _ ix_r sz_r arr_r) w = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r -- double the size of the array if it overflows if (ix >= sz) then do expandBin h ix putWord8 h w else do arr <- readIORef arr_r withForeignPtr arr $ \p -> pokeByteOff p ix w writeFastMutInt ix_r (ix+1) return () getWord8 :: BinHandle -> IO Word8 getWord8 (BinMem _ ix_r sz_r arr_r) = do ix <- readFastMutInt ix_r sz <- readFastMutInt sz_r when (ix >= sz) $ ioError (mkIOError eofErrorType "Data.Binary.getWord8" Nothing Nothing) arr <- readIORef arr_r w <- withForeignPtr arr $ \p -> peekByteOff p ix writeFastMutInt ix_r (ix+1) return w putByte :: BinHandle -> Word8 -> IO () putByte bh w = put_ bh w getByte :: BinHandle -> IO Word8 getByte = getWord8 -- ----------------------------------------------------------------------------- -- Primitve Word writes instance Binary Word8 where put_ = putWord8 get = getWord8 instance Binary Word16 where put_ h w = do -- XXX too slow.. inline putWord8? putByte h (fromIntegral (w `shiftR` 8)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 8) .|. fromIntegral w2) instance Binary Word32 where put_ h w = do putByte h (fromIntegral (w `shiftR` 24)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 24) .|. (fromIntegral w2 `shiftL` 16) .|. (fromIntegral w3 `shiftL` 8) .|. (fromIntegral w4)) instance Binary Word64 where put_ h w = do putByte h (fromIntegral (w `shiftR` 56)) putByte h (fromIntegral ((w `shiftR` 48) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 40) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 32) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 24) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 16) .&. 0xff)) putByte h (fromIntegral ((w `shiftR` 8) .&. 0xff)) putByte h (fromIntegral (w .&. 0xff)) get h = do w1 <- getWord8 h w2 <- getWord8 h w3 <- getWord8 h w4 <- getWord8 h w5 <- getWord8 h w6 <- getWord8 h w7 <- getWord8 h w8 <- getWord8 h return $! ((fromIntegral w1 `shiftL` 56) .|. (fromIntegral w2 `shiftL` 48) .|. (fromIntegral w3 `shiftL` 40) .|. (fromIntegral w4 `shiftL` 32) .|. (fromIntegral w5 `shiftL` 24) .|. (fromIntegral w6 `shiftL` 16) .|. (fromIntegral w7 `shiftL` 8) .|. (fromIntegral w8)) -- ----------------------------------------------------------------------------- -- Primitve Int writes instance Binary Int8 where put_ h w = put_ h (fromIntegral w :: Word8) get h = do w <- get h; return $! (fromIntegral (w::Word8)) instance Binary Int16 where put_ h w = put_ h (fromIntegral w :: Word16) get h = do w <- get h; return $! (fromIntegral (w::Word16)) instance Binary Int32 where put_ h w = put_ h (fromIntegral w :: Word32) get h = do w <- get h; return $! (fromIntegral (w::Word32)) instance Binary Int64 where put_ h w = put_ h (fromIntegral w :: Word64) get h = do w <- get h; return $! (fromIntegral (w::Word64)) -- ----------------------------------------------------------------------------- -- Instances for standard types instance Binary () where put_ _ () = return () get _ = return () instance Binary Bool where put_ bh b = putByte bh (fromIntegral (fromEnum b)) get bh = do x <- getWord8 bh; return $! (toEnum (fromIntegral x)) instance Binary Char where put_ bh c = put_ bh (fromIntegral (ord c) :: Word32) get bh = do x <- get bh; return $! (chr (fromIntegral (x :: Word32))) instance Binary Int where put_ bh i = put_ bh (fromIntegral i :: Int64) get bh = do x <- get bh return $! (fromIntegral (x :: Int64)) instance Binary a => Binary [a] where put_ bh l = do let len = length l if (len < 0xff) then putByte bh (fromIntegral len :: Word8) else do putByte bh 0xff; put_ bh (fromIntegral len :: Word32) mapM_ (put_ bh) l get bh = do b <- getByte bh len <- if b == 0xff then get bh else return (fromIntegral b :: Word32) let loop 0 = return [] loop n = do a <- get bh; as <- loop (n-1); return (a:as) loop len instance (Binary a, Binary b) => Binary (a,b) where put_ bh (a,b) = do put_ bh a; put_ bh b get bh = do a <- get bh b <- get bh return (a,b) instance (Binary a, Binary b, Binary c) => Binary (a,b,c) where put_ bh (a,b,c) = do put_ bh a; put_ bh b; put_ bh c get bh = do a <- get bh b <- get bh c <- get bh return (a,b,c) instance (Binary a, Binary b, Binary c, Binary d) => Binary (a,b,c,d) where put_ bh (a,b,c,d) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d get bh = do a <- get bh b <- get bh c <- get bh d <- get bh return (a,b,c,d) instance (Binary a, Binary b, Binary c, Binary d, Binary e) => Binary (a,b,c,d, e) where put_ bh (a,b,c,d, e) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh return (a,b,c,d,e) instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f) => Binary (a,b,c,d, e, f) where put_ bh (a,b,c,d, e, f) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; put_ bh f; get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh f <- get bh return (a,b,c,d,e,f) instance (Binary a, Binary b, Binary c, Binary d, Binary e, Binary f, Binary g) => Binary (a,b,c,d,e,f,g) where put_ bh (a,b,c,d,e,f,g) = do put_ bh a; put_ bh b; put_ bh c; put_ bh d; put_ bh e; put_ bh f; put_ bh g get bh = do a <- get bh b <- get bh c <- get bh d <- get bh e <- get bh f <- get bh g <- get bh return (a,b,c,d,e,f,g) instance Binary a => Binary (Maybe a) where put_ bh Nothing = putByte bh 0 put_ bh (Just a) = do putByte bh 1; put_ bh a get bh = do h <- getWord8 bh case h of 0 -> return Nothing _ -> do x <- get bh; return (Just x) instance (Binary a, Binary b) => Binary (Either a b) where put_ bh (Left a) = do putByte bh 0; put_ bh a put_ bh (Right b) = do putByte bh 1; put_ bh b get bh = do h <- getWord8 bh case h of 0 -> do a <- get bh ; return (Left a) _ -> do b <- get bh ; return (Right b) instance Binary UTCTime where put_ bh u = do put_ bh (utctDay u) put_ bh (utctDayTime u) get bh = do day <- get bh dayTime <- get bh return $ UTCTime { utctDay = day, utctDayTime = dayTime } instance Binary Day where put_ bh d = put_ bh (toModifiedJulianDay d) get bh = do i <- get bh return $ ModifiedJulianDay { toModifiedJulianDay = i } instance Binary DiffTime where put_ bh dt = put_ bh (toRational dt) get bh = do r <- get bh return $ fromRational r --to quote binary-0.3 on this code idea, -- -- TODO This instance is not architecture portable. GMP stores numbers as -- arrays of machine sized words, so the byte format is not portable across -- architectures with different endianess and word size. -- -- This makes it hard (impossible) to make an equivalent instance -- with code that is compilable with non-GHC. Do we need any instance -- Binary Integer, and if so, does it have to be blazing fast? Or can -- we just change this instance to be portable like the rest of the -- instances? (binary package has code to steal for that) -- -- yes, we need Binary Integer and Binary Rational in basicTypes/Literal.hs instance Binary Integer where -- XXX This is hideous put_ bh i = put_ bh (show i) get bh = do str <- get bh case reads str of [(i, "")] -> return i _ -> fail ("Binary Integer: got " ++ show str) {- -- This code is currently commented out. -- See https://ghc.haskell.org/trac/ghc/ticket/3379#comment:10 for -- discussion. put_ bh (S# i#) = do putByte bh 0; put_ bh (I# i#) put_ bh (J# s# a#) = do putByte bh 1 put_ bh (I# s#) let sz# = sizeofByteArray# a# -- in *bytes* put_ bh (I# sz#) -- in *bytes* putByteArray bh a# sz# get bh = do b <- getByte bh case b of 0 -> do (I# i#) <- get bh return (S# i#) _ -> do (I# s#) <- get bh sz <- get bh (BA a#) <- getByteArray bh sz return (J# s# a#) putByteArray :: BinHandle -> ByteArray# -> Int# -> IO () putByteArray bh a s# = loop 0# where loop n# | n# ==# s# = return () | otherwise = do putByte bh (indexByteArray a n#) loop (n# +# 1#) getByteArray :: BinHandle -> Int -> IO ByteArray getByteArray bh (I# sz) = do (MBA arr) <- newByteArray sz let loop n | n ==# sz = return () | otherwise = do w <- getByte bh writeByteArray arr n w loop (n +# 1#) loop 0# freezeByteArray arr -} {- data ByteArray = BA ByteArray# data MBA = MBA (MutableByteArray# RealWorld) newByteArray :: Int# -> IO MBA newByteArray sz = IO $ \s -> case newByteArray# sz s of { (# s, arr #) -> (# s, MBA arr #) } freezeByteArray :: MutableByteArray# RealWorld -> IO ByteArray freezeByteArray arr = IO $ \s -> case unsafeFreezeByteArray# arr s of { (# s, arr #) -> (# s, BA arr #) } writeByteArray :: MutableByteArray# RealWorld -> Int# -> Word8 -> IO () writeByteArray arr i (W8# w) = IO $ \s -> case writeWord8Array# arr i w s of { s -> (# s, () #) } indexByteArray :: ByteArray# -> Int# -> Word8 indexByteArray a# n# = W8# (indexWord8Array# a# n#) -} instance (Binary a) => Binary (Ratio a) where put_ bh (a :% b) = do put_ bh a; put_ bh b get bh = do a <- get bh; b <- get bh; return (a :% b) instance Binary (Bin a) where put_ bh (BinPtr i) = put_ bh (fromIntegral i :: Int32) get bh = do i <- get bh; return (BinPtr (fromIntegral (i :: Int32))) -- ----------------------------------------------------------------------------- -- Instances for Data.Typeable stuff instance Binary TyCon where put_ bh tc = do put_ bh (tyConPackage tc) put_ bh (tyConModule tc) put_ bh (tyConName tc) get bh = do p <- get bh m <- get bh n <- get bh return (mkTyCon3 p m n) instance Binary TypeRep where put_ bh type_rep = do let (ty_con, child_type_reps) = splitTyConApp type_rep put_ bh ty_con put_ bh child_type_reps get bh = do ty_con <- get bh child_type_reps <- get bh return (mkTyConApp ty_con child_type_reps) -- ----------------------------------------------------------------------------- -- Lazy reading/writing lazyPut :: Binary a => BinHandle -> a -> IO () lazyPut bh a = do -- output the obj with a ptr to skip over it: pre_a <- tellBin bh put_ bh pre_a -- save a slot for the ptr put_ bh a -- dump the object q <- tellBin bh -- q = ptr to after object putAt bh pre_a q -- fill in slot before a with ptr to q seekBin bh q -- finally carry on writing at q lazyGet :: Binary a => BinHandle -> IO a lazyGet bh = do p <- get bh -- a BinPtr p_a <- tellBin bh a <- unsafeInterleaveIO $ do -- NB: Use a fresh off_r variable in the child thread, for thread -- safety. off_r <- newFastMutInt getAt bh { _off_r = off_r } p_a seekBin bh p -- skip over the object for now return a -- ----------------------------------------------------------------------------- -- UserData -- ----------------------------------------------------------------------------- -- | Information we keep around during interface file -- serialization/deserialization. Namely we keep the functions for serializing -- and deserializing 'Name's and 'FastString's. We do this because we actually -- use serialization in two distinct settings, -- -- * When serializing interface files themselves -- -- * When computing the fingerprint of an IfaceDecl (which we computing by -- hashing its Binary serialization) -- -- These two settings have different needs while serializing Names: -- -- * Names in interface files are serialized via a symbol table (see Note -- [Symbol table representation of names] in BinIface). -- -- * During fingerprinting a binding Name is serialized as the OccName and a -- non-binding Name is serialized as the fingerprint of the thing they -- represent. See Note [Fingerprinting IfaceDecls] for further discussion. -- data UserData = UserData { -- for *deserialising* only: ud_get_name :: BinHandle -> IO Name, ud_get_fs :: BinHandle -> IO FastString, -- for *serialising* only: ud_put_nonbinding_name :: BinHandle -> Name -> IO (), -- ^ serialize a non-binding 'Name' (e.g. a reference to another -- binding). ud_put_binding_name :: BinHandle -> Name -> IO (), -- ^ serialize a binding 'Name' (e.g. the name of an IfaceDecl) ud_put_fs :: BinHandle -> FastString -> IO () } newReadState :: (BinHandle -> IO Name) -- ^ how to deserialize 'Name's -> (BinHandle -> IO FastString) -> UserData newReadState get_name get_fs = UserData { ud_get_name = get_name, ud_get_fs = get_fs, ud_put_nonbinding_name = undef "put_nonbinding_name", ud_put_binding_name = undef "put_binding_name", ud_put_fs = undef "put_fs" } newWriteState :: (BinHandle -> Name -> IO ()) -- ^ how to serialize non-binding 'Name's -> (BinHandle -> Name -> IO ()) -- ^ how to serialize binding 'Name's -> (BinHandle -> FastString -> IO ()) -> UserData newWriteState put_nonbinding_name put_binding_name put_fs = UserData { ud_get_name = undef "get_name", ud_get_fs = undef "get_fs", ud_put_nonbinding_name = put_nonbinding_name, ud_put_binding_name = put_binding_name, ud_put_fs = put_fs } noUserData :: a noUserData = undef "UserData" undef :: String -> a undef s = panic ("Binary.UserData: no " ++ s) --------------------------------------------------------- -- The Dictionary --------------------------------------------------------- type Dictionary = Array Int FastString -- The dictionary -- Should be 0-indexed putDictionary :: BinHandle -> Int -> UniqFM (Int,FastString) -> IO () putDictionary bh sz dict = do put_ bh sz mapM_ (putFS bh) (elems (array (0,sz-1) (nonDetEltsUFM dict))) -- It's OK to use nonDetEltsUFM here because the elements have indices -- that array uses to create order getDictionary :: BinHandle -> IO Dictionary getDictionary bh = do sz <- get bh elems <- sequence (take sz (repeat (getFS bh))) return (listArray (0,sz-1) elems) --------------------------------------------------------- -- The Symbol Table --------------------------------------------------------- -- On disk, the symbol table is an array of IfExtName, when -- reading it in we turn it into a SymbolTable. type SymbolTable = Array Int Name --------------------------------------------------------- -- Reading and writing FastStrings --------------------------------------------------------- putFS :: BinHandle -> FastString -> IO () putFS bh fs = putBS bh $ fastStringToByteString fs getFS :: BinHandle -> IO FastString getFS bh = do bs <- getBS bh return $! mkFastStringByteString bs putBS :: BinHandle -> ByteString -> IO () putBS bh bs = BS.unsafeUseAsCStringLen bs $ \(ptr, l) -> do put_ bh l let go n | n == l = return () | otherwise = do b <- peekElemOff (castPtr ptr) n putByte bh b go (n+1) go 0 getBS :: BinHandle -> IO ByteString getBS bh = do l <- get bh :: IO Int arr <- readIORef (_arr_r bh) sz <- readFastMutInt (_sz_r bh) off <- readFastMutInt (_off_r bh) when (off + l > sz) $ ioError (mkIOError eofErrorType "Data.Binary.getBS" Nothing Nothing) writeFastMutInt (_off_r bh) (off+l) withForeignPtr arr $ \ptr -> do bs <- BS.unsafePackCStringLen (castPtr $ ptr `plusPtr` off, fromIntegral l) return $! BS.copy bs instance Binary ByteString where put_ bh f = putBS bh f get bh = getBS bh instance Binary FastString where put_ bh f = case getUserData bh of UserData { ud_put_fs = put_fs } -> put_fs bh f get bh = case getUserData bh of UserData { ud_get_fs = get_fs } -> get_fs bh -- Here to avoid loop instance Binary LeftOrRight where put_ bh CLeft = putByte bh 0 put_ bh CRight = putByte bh 1 get bh = do { h <- getByte bh ; case h of 0 -> return CLeft _ -> return CRight } instance Binary Fingerprint where put_ h (Fingerprint w1 w2) = do put_ h w1; put_ h w2 get h = do w1 <- get h; w2 <- get h; return (Fingerprint w1 w2) instance Binary FunctionOrData where put_ bh IsFunction = putByte bh 0 put_ bh IsData = putByte bh 1 get bh = do h <- getByte bh case h of 0 -> return IsFunction 1 -> return IsData _ -> panic "Binary FunctionOrData" instance Binary TupleSort where put_ bh BoxedTuple = putByte bh 0 put_ bh UnboxedTuple = putByte bh 1 put_ bh ConstraintTuple = putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return BoxedTuple 1 -> do return UnboxedTuple _ -> do return ConstraintTuple instance Binary Activation where put_ bh NeverActive = do putByte bh 0 put_ bh AlwaysActive = do putByte bh 1 put_ bh (ActiveBefore src aa) = do putByte bh 2 put_ bh src put_ bh aa put_ bh (ActiveAfter src ab) = do putByte bh 3 put_ bh src put_ bh ab get bh = do h <- getByte bh case h of 0 -> do return NeverActive 1 -> do return AlwaysActive 2 -> do src <- get bh aa <- get bh return (ActiveBefore src aa) _ -> do src <- get bh ab <- get bh return (ActiveAfter src ab) instance Binary InlinePragma where put_ bh (InlinePragma s a b c d) = do put_ bh s put_ bh a put_ bh b put_ bh c put_ bh d get bh = do s <- get bh a <- get bh b <- get bh c <- get bh d <- get bh return (InlinePragma s a b c d) instance Binary RuleMatchInfo where put_ bh FunLike = putByte bh 0 put_ bh ConLike = putByte bh 1 get bh = do h <- getByte bh if h == 1 then return ConLike else return FunLike instance Binary InlineSpec where put_ bh EmptyInlineSpec = putByte bh 0 put_ bh Inline = putByte bh 1 put_ bh Inlinable = putByte bh 2 put_ bh NoInline = putByte bh 3 get bh = do h <- getByte bh case h of 0 -> return EmptyInlineSpec 1 -> return Inline 2 -> return Inlinable _ -> return NoInline instance Binary RecFlag where put_ bh Recursive = do putByte bh 0 put_ bh NonRecursive = do putByte bh 1 get bh = do h <- getByte bh case h of 0 -> do return Recursive _ -> do return NonRecursive instance Binary OverlapMode where put_ bh (NoOverlap s) = putByte bh 0 >> put_ bh s put_ bh (Overlaps s) = putByte bh 1 >> put_ bh s put_ bh (Incoherent s) = putByte bh 2 >> put_ bh s put_ bh (Overlapping s) = putByte bh 3 >> put_ bh s put_ bh (Overlappable s) = putByte bh 4 >> put_ bh s get bh = do h <- getByte bh case h of 0 -> (get bh) >>= \s -> return $ NoOverlap s 1 -> (get bh) >>= \s -> return $ Overlaps s 2 -> (get bh) >>= \s -> return $ Incoherent s 3 -> (get bh) >>= \s -> return $ Overlapping s 4 -> (get bh) >>= \s -> return $ Overlappable s _ -> panic ("get OverlapMode" ++ show h) instance Binary OverlapFlag where put_ bh flag = do put_ bh (overlapMode flag) put_ bh (isSafeOverlap flag) get bh = do h <- get bh b <- get bh return OverlapFlag { overlapMode = h, isSafeOverlap = b } instance Binary FixityDirection where put_ bh InfixL = do putByte bh 0 put_ bh InfixR = do putByte bh 1 put_ bh InfixN = do putByte bh 2 get bh = do h <- getByte bh case h of 0 -> do return InfixL 1 -> do return InfixR _ -> do return InfixN instance Binary Fixity where put_ bh (Fixity src aa ab) = do put_ bh src put_ bh aa put_ bh ab get bh = do src <- get bh aa <- get bh ab <- get bh return (Fixity src aa ab) instance Binary WarningTxt where put_ bh (WarningTxt s w) = do putByte bh 0 put_ bh s put_ bh w put_ bh (DeprecatedTxt s d) = do putByte bh 1 put_ bh s put_ bh d get bh = do h <- getByte bh case h of 0 -> do s <- get bh w <- get bh return (WarningTxt s w) _ -> do s <- get bh d <- get bh return (DeprecatedTxt s d) instance Binary StringLiteral where put_ bh (StringLiteral st fs) = do put_ bh st put_ bh fs get bh = do st <- get bh fs <- get bh return (StringLiteral st fs) instance Binary a => Binary (GenLocated SrcSpan a) where put_ bh (L l x) = do put_ bh l put_ bh x get bh = do l <- get bh x <- get bh return (L l x) instance Binary SrcSpan where put_ bh (RealSrcSpan ss) = do putByte bh 0 put_ bh (srcSpanFile ss) put_ bh (srcSpanStartLine ss) put_ bh (srcSpanStartCol ss) put_ bh (srcSpanEndLine ss) put_ bh (srcSpanEndCol ss) put_ bh (UnhelpfulSpan s) = do putByte bh 1 put_ bh s get bh = do h <- getByte bh case h of 0 -> do f <- get bh sl <- get bh sc <- get bh el <- get bh ec <- get bh return (mkSrcSpan (mkSrcLoc f sl sc) (mkSrcLoc f el ec)) _ -> do s <- get bh return (UnhelpfulSpan s) instance Binary Serialized where put_ bh (Serialized the_type bytes) = do put_ bh the_type put_ bh bytes get bh = do the_type <- get bh bytes <- get bh return (Serialized the_type bytes)
mettekou/ghc
compiler/utils/Binary.hs
bsd-3-clause
31,656
57
19
10,398
9,578
4,663
4,915
675
2
{-| Module : Database.Relational.Add Description : Definition of ADD. Copyright : (c) Alexander Vieth, 2015 Licence : BSD3 Maintainer : aovieth@gmail.com Stability : experimental Portability : non-portable (GHC only) -} {-# LANGUAGE AutoDeriveTypeable #-} module Database.Relational.Add ( ADD(..) ) where data ADD term = ADD term
avieth/Relational
Database/Relational/Add.hs
bsd-3-clause
359
0
6
75
28
19
9
4
0
module Test.Util where import Test.Hspec import Test.Core runUtilTests :: IO () runUtilTests = hspec $ do loadTest loadTest :: Spec loadTest = do describe "load" $ do it "works" $ do testScheme "(load \"lib/util.scm\") (list 1 2 3)" `shouldReturn` [ "#t" , "(1 2 3)" ] pairTest :: Spec pairTest = do describe "cons, car, cdr" $ do it "works" $ do testScheme (concat [ "(cons \"hello, \" \"world!\")" , "(cons 0 ())" , "(cons 1 (cons 10 100))" , "(cons 1 (cons 10 (cons 100 '())))" , "(cons #t (cons \"aa\" (cons 3 '())))" , "(car '(0))" , "(cdr '(0))" , "(car '((1 2 3) (4 5 6)))" , "(cdr '(1 2 3 . 4))" , "(cdr (cons 3 (cons 2 (cons 1 '()))))" ]) `shouldReturn` [ "(\"hello, \" . \"world!\")" , "(0)" , "(1 10 . 100)" , "(1 10 100)" , "(#t \"aa\" 3)" , "0" , "()" , "(1 2 3)" , "(2 3 . 4)" , "(2 1)" ]
amutake/psg-scheme
test/Test/Util.hs
bsd-3-clause
1,260
0
17
621
194
108
86
39
1
{-# LANGUAGE GeneralizedNewtypeDeriving #-} module Hans.Message.Dhcp4Codec where import Control.Applicative import Data.List (find) import qualified Data.Serialize import Data.Serialize.Get import Data.Serialize.Put import Data.Word (Word8, Word16, Word32) import Hans.Address.IP4 (IP4,IP4Mask) import Hans.Address.Mac (Mac) import Hans.Address (Mask(..)) class CodecAtom a where getAtom :: Get a putAtom :: a -> Put atomSize :: a -> Int instance (CodecAtom a, CodecAtom b) => CodecAtom (a,b) where getAtom = (,) <$> getAtom <*> getAtom putAtom (a,b) = putAtom a *> putAtom b atomSize (a,b)= atomSize a + atomSize b instance CodecAtom Word8 where getAtom = getWord8 putAtom n = putWord8 n atomSize _ = 1 instance CodecAtom Word16 where getAtom = getWord16be putAtom n = putWord16be n atomSize _ = 2 instance CodecAtom Word32 where getAtom = getWord32be putAtom n = putWord32be n atomSize _ = 4 instance CodecAtom Bool where getAtom = do b <- getWord8 case b of 0 -> return False 1 -> return True _ -> fail "Expected 0/1 in boolean option" putAtom False = putWord8 0 putAtom True = putWord8 1 atomSize _ = 1 instance CodecAtom IP4 where getAtom = Data.Serialize.get putAtom = Data.Serialize.put atomSize _ = 4 instance CodecAtom IP4Mask where getAtom = withMask <$> getAtom <*> (unmask <$> getAtom) putAtom ip4mask = putAtom addr *> putAtom (SubnetMask mask) where (addr, mask) = getMaskComponents ip4mask atomSize _ = atomSize (undefined :: IP4) + atomSize (undefined :: SubnetMask) instance CodecAtom Mac where getAtom = Data.Serialize.get putAtom = Data.Serialize.put atomSize _ = 6 ----------------------------------------------------------------------- -- Subnet parser/unparser operations ---------------------------------- ----------------------------------------------------------------------- newtype SubnetMask = SubnetMask { unmask :: Int} deriving (Show, Eq) word32ToSubnetMask :: Word32 -> Maybe SubnetMask word32ToSubnetMask mask = SubnetMask <$> find (\ i -> computeMask i == mask) [0..32] subnetMaskToWord32 :: SubnetMask -> Word32 subnetMaskToWord32 (SubnetMask n) = computeMask n computeMask :: Int -> Word32 computeMask n = 0-2^(32-n) instance CodecAtom SubnetMask where getAtom = do x <- getAtom case word32ToSubnetMask x of Just mask -> return mask Nothing -> fail "Invalid subnet mask" putAtom = putAtom . subnetMaskToWord32 atomSize _ = atomSize (undefined :: Word32)
Tener/HaNS
src/Hans/Message/Dhcp4Codec.hs
bsd-3-clause
2,761
0
11
707
778
413
365
70
1
{-# LANGUAGE OverloadedStrings, DeriveGeneric #-} module Kindle where import Config import GHC.Generics import qualified Data.ByteString as B import qualified Data.ByteString.UTF8 as BUTF8 import qualified Network.HTTP.Conduit as HTTP import Network.HTTP.Client.Conduit (defaultManagerSettings) type Username = String type Password = String type Credential = (Username, Password) type Url = String type ApiUrl = String credentials :: SendToReaderConfig -> Credential credentials config = (username config, password config) sendToKindleUrl :: Credential -> ApiUrl sendToKindleUrl (username, password) = "https://sendtoreader.com/api/send/?username=" ++ username ++ "&password=" ++ password ++ "&url=" sendToKindle :: SendToReaderConfig -> Url -> IO() sendToKindle config url = do let post_url = sendToKindleUrl (credentials config) ++ url manager <- HTTP.newManager defaultManagerSettings request <- HTTP.parseRequest post_url HTTP.httpLbs request manager print "Document Sent!"
julienXX/favsToKindle
src/Kindle.hs
bsd-3-clause
1,013
0
13
150
245
137
108
26
1
-- | The type of definitions of key-command mappings to be used for the UI -- and shorthands for specifying command triples in the content files. module Game.LambdaHack.Client.UI.Content.Input ( InputContentRaw(..), InputContent(..), makeData , evalKeyDef , addCmdCategory, replaceDesc, moveItemTriple, repeatTriple, repeatLastTriple , mouseLMB, mouseMMB, mouseMMBMute, mouseRMB , goToCmd, runToAllCmd, autoexploreCmd, autoexplore25Cmd , aimFlingCmd, projectI, projectA, flingTs, applyIK, applyI , grabItems, dropItems, descIs, defaultHeroSelect, macroRun25 , memberCycle, memberCycleLevel #ifdef EXPOSE_INTERNAL -- * Internal operations , replaceCmd, projectICmd, grabCmd, dropCmd #endif ) where import Prelude () import Game.LambdaHack.Core.Prelude import qualified Data.Char as Char import qualified Data.Map.Strict as M import qualified NLP.Miniutter.English as MU import Game.LambdaHack.Client.UI.HumanCmd import qualified Game.LambdaHack.Client.UI.Key as K import Game.LambdaHack.Client.UI.UIOptions import Game.LambdaHack.Common.Misc import Game.LambdaHack.Definition.Defs -- | Key-command mappings to be specified in content and used for the UI. newtype InputContentRaw = InputContentRaw [(K.KM, CmdTriple)] -- | Bindings and other information about human player commands. data InputContent = InputContent { bcmdMap :: M.Map K.KM CmdTriple -- ^ binding of keys to commands , bcmdList :: [(K.KM, CmdTriple)] -- ^ the properly ordered list -- of commands for the help menu , brevMap :: M.Map HumanCmd [K.KM] -- ^ and from commands to their keys } -- | Create binding of keys to movement and other standard commands, -- as well as commands defined in the config file. makeData :: Maybe UIOptions -- ^ UI client options -> InputContentRaw -- ^ default key bindings from the content -> InputContent -- ^ concrete binding makeData muiOptions (InputContentRaw copsClient) = let (uCommands0, uVi0, uLeftHand0) = case muiOptions of Just UIOptions{uCommands, uVi, uLeftHand} -> (uCommands, uVi, uLeftHand) Nothing -> ([], True, True) waitTriple = ([CmdMove], "", Wait) wait10Triple = ([CmdMove], "", Wait10) moveXhairOr n cmd v = ByAimMode $ AimModeCmd { exploration = cmd v , aiming = MoveXhair v n } rawContent = copsClient ++ uCommands0 movementDefinitions = K.moveBinding uVi0 uLeftHand0 (\v -> ([CmdMove], "", moveXhairOr 1 MoveDir v)) (\v -> ([CmdMove], "", moveXhairOr 10 RunDir v)) ++ [ (K.mkKM "KP_Begin", waitTriple) , (K.mkKM "C-KP_Begin", wait10Triple) , (K.mkKM "KP_5", wait10Triple) , (K.mkKM "S-KP_5", wait10Triple) -- rxvt , (K.mkKM "C-KP_5", wait10Triple) ] ++ [(K.mkKM "period", waitTriple) | uVi0] ++ [(K.mkKM "C-period", wait10Triple) | uVi0] ++ [(K.mkKM "s", waitTriple) | uLeftHand0] ++ [(K.mkKM "S", wait10Triple) | uLeftHand0] -- This is the most common case of duplicate keys and it usually -- has an easy solution, so it's tested for first. !_A = flip assert () $ let movementKeys = map fst movementDefinitions filteredNoMovement = filter (\(k, _) -> k `notElem` movementKeys) rawContent in rawContent == filteredNoMovement `blame` "commands overwrite the enabled movement keys (you can disable some in config file and try again)" `swith` rawContent \\ filteredNoMovement bcmdList = rawContent ++ movementDefinitions -- This catches repetitions (usually) not involving movement keys. rejectRepetitions _ t1 (_, "", _) = t1 rejectRepetitions _ (_, "", _) t2 = t2 rejectRepetitions k t1 t2 = error $ "duplicate key among command definitions (you can instead disable some movement key sets in config file and overwrite the freed keys)" `showFailure` (k, t1, t2) in InputContent { bcmdMap = M.fromListWithKey rejectRepetitions bcmdList , bcmdList , brevMap = M.fromListWith (flip (++)) $ concat [ [(cmd, [k])] | (k, (cats, _desc, cmd)) <- bcmdList , not (null cats) && CmdDebug `notElem` cats ] } evalKeyDef :: (String, CmdTriple) -> (K.KM, CmdTriple) evalKeyDef (t, triple@(cats, _, _)) = let km = if CmdInternal `elem` cats then K.KM K.NoModifier $ K.Unknown t else K.mkKM t in (km, triple) addCmdCategory :: CmdCategory -> CmdTriple -> CmdTriple addCmdCategory cat (cats, desc, cmd) = (cat : cats, desc, cmd) replaceDesc :: Text -> CmdTriple -> CmdTriple replaceDesc desc (cats, _, cmd) = (cats, desc, cmd) replaceCmd :: HumanCmd -> CmdTriple -> CmdTriple replaceCmd cmd (cats, desc, _) = (cats, desc, cmd) moveItemTriple :: [CStore] -> CStore -> MU.Part -> Bool -> CmdTriple moveItemTriple stores1 store2 object auto = let verb = MU.Text $ verbCStore store2 desc = makePhrase [verb, object] in ([CmdItemMenu, CmdItem], desc, MoveItem stores1 store2 Nothing auto) repeatTriple :: Int -> [CmdCategory] -> CmdTriple repeatTriple n cats = ( cats , if n == 1 then "voice recorded macro again" else "voice recorded macro" <+> tshow n <+> "times" , Repeat n ) repeatLastTriple :: Int -> [CmdCategory] -> CmdTriple repeatLastTriple n cats = ( cats , if n == 1 then "voice last action again" else "voice last action" <+> tshow n <+> "times in a row" , RepeatLast n ) -- @AimFloor@ is not there, but @AimEnemy@ and @AimItem@ almost make up for it. mouseLMB :: HumanCmd -> Text -> CmdTriple mouseLMB goToOrRunTo desc = ([CmdMouse], desc, ByAimMode aimMode) where aimMode = AimModeCmd { exploration = ByArea $ common ++ -- exploration mode [ (CaMapLeader, grabCmd) , (CaMapParty, PickLeaderWithPointer) , (CaMap, goToOrRunTo) , (CaArenaName, Dashboard) , (CaPercentSeen, autoexploreCmd) ] , aiming = ByArea $ common ++ -- aiming mode [ (CaMap, aimFlingCmd) , (CaArenaName, Accept) , (CaPercentSeen, XhairStair True) ] } common = [ (CaMessage, AllHistory) , (CaLevelNumber, AimAscend 1) , (CaXhairDesc, AimEnemy) -- inits aiming and then cycles enemies , (CaSelected, PickLeaderWithPointer) -- , (CaCalmGauge, Macro ["KP_Begin", "C-v"]) , (CaCalmValue, Yell) , (CaHPGauge, Macro ["KP_Begin", "C-v"]) , (CaHPValue, Wait) , (CaLeaderDesc, projectICmd flingTs) ] mouseMMB :: CmdTriple mouseMMB = ( [CmdMouse] , "snap crosshair to floor under pointer/cycle detail level" , XhairPointerFloor ) mouseMMBMute :: CmdTriple mouseMMBMute = ([CmdMouse], "", XhairPointerMute) mouseRMB :: CmdTriple mouseRMB = ( [CmdMouse] , "start aiming at enemy under pointer/cycle detail level" , ByAimMode aimMode ) where aimMode = AimModeCmd { exploration = ByArea $ common ++ [ (CaMapLeader, dropCmd) , (CaMapParty, SelectWithPointer) , (CaMap, AimPointerEnemy) , (CaArenaName, ExecuteIfClear MainMenuAutoOff) , (CaPercentSeen, autoexplore25Cmd) ] , aiming = ByArea $ common ++ [ (CaMap, XhairPointerEnemy) -- hack; same effect, but matches LMB , (CaArenaName, Cancel) , (CaPercentSeen, XhairStair False) ] } common = [ (CaMessage, Hint) , (CaLevelNumber, AimAscend (-1)) , (CaXhairDesc, AimItem) , (CaSelected, SelectWithPointer) -- , (CaCalmGauge, Macro ["C-KP_Begin", "A-v"]) , (CaCalmValue, Yell) , (CaHPGauge, Macro ["C-KP_Begin", "A-v"]) , (CaHPValue, Wait10) , (CaLeaderDesc, ComposeUnlessError ClearTargetIfItemClear ItemClear) ] -- This is duplicated wrt content, instead of included via @semicolon@, -- because the C- commands are less likely to be modified by the player -- and so more dependable than @semicolon@, @colon@, etc. goToCmd :: HumanCmd goToCmd = Macro ["A-MiddleButtonRelease", "C-semicolon", "C-quotedbl", "C-v"] -- This is duplicated wrt content, instead of included via @colon@, -- because the C- commands are less likely to be modified by the player -- and so more dependable than @semicolon@, @colon@, etc. runToAllCmd :: HumanCmd runToAllCmd = Macro ["A-MiddleButtonRelease", "C-colon", "C-quotedbl", "C-v"] autoexploreCmd :: HumanCmd autoexploreCmd = Macro ["C-?", "C-quotedbl", "C-v"] autoexplore25Cmd :: HumanCmd autoexplore25Cmd = Macro ["'", "C-?", "C-quotedbl", "'", "C-V"] aimFlingCmd :: HumanCmd aimFlingCmd = ComposeIfLocal AimPointerEnemy (projectICmd flingTs) projectICmd :: [TriggerItem] -> HumanCmd projectICmd ts = ComposeUnlessError (ChooseItemProject ts) Project projectI :: [TriggerItem] -> CmdTriple projectI ts = ([CmdItem], descIs ts, projectICmd ts) projectA :: [TriggerItem] -> CmdTriple projectA ts = let fling = Compose2ndLocal Project ItemClear flingICmd = ComposeUnlessError (ChooseItemProject ts) fling in replaceCmd (ByAimMode AimModeCmd { exploration = AimTgt , aiming = flingICmd }) (projectI ts) -- | flingTs - list containing one flingable projectile -- >>> flingTs -- [TriggerItem {tiverb = Text "fling", tiobject = Text "in-range projectile", tisymbols = ""}] -- -- I question the value of that test. But would Bob Martin like it -- on the grounds it's like double-bookkeeping? flingTs :: [TriggerItem] flingTs = [TriggerItem { tiverb = "fling" , tiobject = "in-range projectile" , tisymbols = [] }] applyIK :: [TriggerItem] -> CmdTriple applyIK ts = ([CmdItem], descIs ts, ComposeUnlessError (ChooseItemApply ts) Apply) applyI :: [TriggerItem] -> CmdTriple applyI ts = let apply = Compose2ndLocal Apply ItemClear in ([CmdItem], descIs ts, ComposeUnlessError (ChooseItemApply ts) apply) grabCmd :: HumanCmd grabCmd = MoveItem [CGround] CStash (Just "grab") True -- @CStash@ is the implicit default; refined in HandleHumanGlobalM grabItems :: Text -> CmdTriple grabItems t = ([CmdItemMenu, CmdItem], t, grabCmd) dropCmd :: HumanCmd dropCmd = MoveItem [CStash, CEqp] CGround Nothing False dropItems :: Text -> CmdTriple dropItems t = ([CmdItemMenu, CmdItem], t, dropCmd) descIs :: [TriggerItem] -> Text descIs [] = "trigger an item" descIs (t : _) = makePhrase [tiverb t, tiobject t] defaultHeroSelect :: Int -> (String, CmdTriple) defaultHeroSelect k = ([Char.intToDigit k], ([CmdMeta], "", PickLeader k)) macroRun25 :: [String] macroRun25 = ["C-comma", "C-v"] memberCycle :: Direction -> [CmdCategory] -> CmdTriple memberCycle d cats = ( cats , "cycle" <+> (if d == Backward then "backwards" else "") <+> "among all party members" , PointmanCycle d ) memberCycleLevel :: Direction -> [CmdCategory] -> CmdTriple memberCycleLevel d cats = ( cats , "cycle" <+> (if d == Backward then "backwards" else "") <+> " among party members on the level" , PointmanCycleLevel d )
LambdaHack/LambdaHack
engine-src/Game/LambdaHack/Client/UI/Content/Input.hs
bsd-3-clause
11,266
0
18
2,694
2,762
1,624
1,138
-1
-1