code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TemplateHaskell #-} module Keenser.Middleware ( middleware , record , retry , runMiddleware ) where import Data.Aeson import Keenser.Types import Keenser.Import import Keenser.Middleware.Retry import Keenser.Middleware.Stats middleware :: Monad m => Middleware m -> Configurator m middleware m = modify $ \c -> c { kMiddleware = m : kMiddleware c } runMiddleware :: Monad m => [Middleware m] -> Manager -> Worker m Value -> Object -> Queue -> m () -> m () runMiddleware (t:ts) m w j q start = t m w j q $ runMiddleware ts m w j q start runMiddleware _ _ _ _ _ start = start
jamesdabbs/keenser
src/Keenser/Middleware.hs
bsd-3-clause
693
0
13
181
229
120
109
21
1
module Main where import EFA.Signal.Base import EFA.Signal.Data import EFA.Signal.Vector -- The following arithmetic should be implemented for InTerm. -- Example terms... data SimpleTerm = Const Int | Add SimpleTerm SimpleTerm | Mult SimpleTerm SimpleTerm deriving (Show) one :: SimpleTerm one = Const 1 two :: SimpleTerm two = Const 2 three :: SimpleTerm three = Const 3 four :: SimpleTerm four = Const 4 u :: List SimpleTerm u = dfromList [one, two] v :: List SimpleTerm v = dfromList [two, three] s :: DVal SimpleTerm s = Data (D0 four) main :: IO () main = do print (dzipWith Add u v) print (dzipWith Mult u v) print (dzipWith Add s u)
energyflowanalysis/efa-2.1
attic/demo/symbolicArith/Main.hs
bsd-3-clause
692
0
9
165
235
126
109
26
1
module Main where import Test.HUnit import Codes.Hamming main :: IO Counts main = runTestTT tests tests :: Test tests = TestList [ TestLabel "decode $ encode msg = msg" encodeDecode ] encodeDecode :: Test encodeDecode = TestCase $ (snd . decode hc $ encode hc msg) @?= msg hc :: HammingCode hc = hamming 11 msg :: [Int] msg = [0,1,1,0,1,1,1,0,0,1,0]
nitroFamily/hamming
test/Test.hs
bsd-3-clause
371
0
10
82
147
84
63
15
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE LambdaCase #-} module Device where import Hans import System.Environment (getArgs) import Data.ByteString.Char8 hiding (putStrLn) import Data.Maybe (listToMaybe) getDevice :: NetworkStack -> IO Device getDevice ns = listToMaybe <$> getArgs >>= \case Nothing -> error "Please enter tap device name (example: ./hello-halvm-tap tap0)" Just deviceName -> addDevice ns (pack deviceName) defaultDeviceConfig
dmjio/Hello-HaLVM
linux-src/Device.hs
bsd-3-clause
462
0
11
68
102
56
46
12
2
module Bead.Persistence.SQL.Notification where import Control.Applicative ((<$>)) import Database.Persist.Sql import Data.Maybe (listToMaybe) import qualified Bead.Domain.Entities as Domain (Username) import qualified Bead.Domain.Relationships as Domain import qualified Bead.Domain.Entity.Notification as Domain import Bead.Persistence.SQL.Class import Bead.Persistence.SQL.Entities import Bead.Persistence.SQL.User (usernames) attachNotificationToUser :: Domain.Username -> Domain.NotificationKey -> Persist () attachNotificationToUser username nk = withUser username (persistError "attachNotificationToUser" $ "User is not found:" ++ show username) $ \user -> void $ insertUnique (UserNotification (entityKey user) (fromDomainKey nk)) notificationsOfUser :: Domain.Username -> Persist [Domain.NotificationKey] notificationsOfUser username = withUser username (return []) $ \user -> map (toDomainKey . userNotificationNotification . entityVal) <$> selectList [UserNotificationUser ==. (entityKey user)] [] saveCommentNotification :: Domain.CommentKey -> Domain.Notification -> Persist Domain.NotificationKey saveCommentNotification ck n = do key <- insert (fromDomainValue n) insertUnique (CommentNotification (fromDomainKey ck) key) return (toDomainKey key) saveFeedbackNotification :: Domain.FeedbackKey -> Domain.Notification -> Persist Domain.NotificationKey saveFeedbackNotification fk n = do key <- insert (fromDomainValue n) insertUnique (FeedbackNotification (fromDomainKey fk) key) return (toDomainKey key) saveSystemNotification :: Domain.Notification -> Persist Domain.NotificationKey saveSystemNotification n = do key <- insert (fromDomainValue n) return (toDomainKey key) loadNotification :: Domain.NotificationKey -> Persist Domain.Notification loadNotification nk = do mNot <- get (fromDomainKey nk) return $! maybe (persistError "loadNotification" $ "Notification is not found: " ++ show nk) toDomainValue mNot commentOfNotification :: Domain.NotificationKey -> Persist (Maybe Domain.CommentKey) commentOfNotification nk = do keys <- map (toDomainKey . commentNotificationComment . entityVal) <$> selectList [CommentNotificationNotification ==. (fromDomainKey nk)] [] return $! listToMaybe keys feedbackOfNotification :: Domain.NotificationKey -> Persist (Maybe Domain.FeedbackKey) feedbackOfNotification nk = do keys <- map (toDomainKey . feedbackNotificationFeedback . entityVal) <$> selectList [FeedbackNotificationNotification ==. (fromDomainKey nk)] [] return $! listToMaybe keys usersOfNotification :: Domain.NotificationKey -> Persist [Domain.Username] usersOfNotification nk = do userIds <- map (userNotificationUser . entityVal) <$> selectList [UserNotificationNotification ==. (fromDomainKey nk)] [] usernames userIds
pgj/bead
src/Bead/Persistence/SQL/Notification.hs
bsd-3-clause
2,862
0
13
400
799
404
395
55
1
-- |various utility functions module Angel.Util ( sleepSecs , waitForWake , expandPath , split , strip , nnull ) where import Control.Concurrent.STM (atomically , retry , TVar , readTVar , writeTVar) import Control.Concurrent (threadDelay) import Data.Char (isSpace) import Data.Maybe (catMaybes) import System.Posix.User (getEffectiveUserName, UserEntry(homeDirectory), getUserEntryForName) -- |sleep for `s` seconds in an thread sleepSecs :: Int -> IO () sleepSecs s = threadDelay $ s * 1000000 -- |wait for the STM TVar to be non-nothing waitForWake :: TVar (Maybe Int) -> IO () waitForWake wakeSig = atomically $ do state <- readTVar wakeSig case state of Just _ -> writeTVar wakeSig Nothing Nothing -> retry expandPath :: FilePath -> IO FilePath expandPath ('~':rest) = do home <- getHome =<< getUser return $ home ++ relativePath where (userName, relativePath) = span (/= '/') rest getUser = if null userName then getEffectiveUserName else return userName getHome user = homeDirectory `fmap` getUserEntryForName user expandPath path = return path nnull :: [a] -> Bool nnull = not . null split :: Eq a => a -> [a] -> [[a]] split a = catMaybes . foldr go [] where go x acc = case (x == a, acc) of (True, xs) -> Nothing:xs (False, []) -> [Just [x]] (False, Nothing:rest) -> Just [x]:Nothing:rest (False, Just xs:rest) -> Just (x:xs):rest strip :: String -> String strip = reverse . dropWhile isSpace . reverse . dropWhile isSpace
zalora/Angel
src/Angel/Util.hs
bsd-3-clause
1,904
0
13
702
553
298
255
45
4
-------------------------------------------------------------------------------- -- 2016.09.08 -- | -- Module : Language.Hakaru.CodeGen.Pretty -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : zsulliva@indiana.edu -- Stability : experimental -- Portability : GHC-only -- -- A pretty printer for the CodeGen AST -- -------------------------------------------------------------------------------- module Language.Hakaru.CodeGen.Pretty ( pretty , prettyPrint , Pretty ) where import Text.PrettyPrint import Language.Hakaru.CodeGen.AST prettyPrint :: Pretty a => a -> String prettyPrint = render . pretty class Pretty a where pretty :: a -> Doc prettyPrec :: Int -> a -> Doc pretty = prettyPrec 0 prettyPrec _ = pretty mpretty :: Pretty a => Maybe a -> Doc mpretty Nothing = empty mpretty (Just x) = pretty x mPrettyPrec :: Pretty a => Int -> Maybe a -> Doc mPrettyPrec _ Nothing = empty mPrettyPrec p (Just x) = prettyPrec p x -- will compare two precs and put parens if the prec is lower parensPrec :: Int -> Int -> Doc -> Doc parensPrec x y = if x <= y then parens else id emptyText = text "" instance Pretty a => Pretty (Maybe a) where pretty Nothing = empty pretty (Just x) = pretty x -------------------------------------------------------------------------------- -- Top Level -- -------------------------------------------------------------------------------- instance Pretty Ident where pretty (Ident i) = text i instance Pretty CAST where pretty (CAST extdecls) = vcat . fmap pretty $ extdecls instance Pretty CExtDecl where pretty (CDeclExt d) = emptyText $+$ pretty d <> semi pretty (CFunDefExt f) = emptyText $+$ pretty f pretty (CCommentExt s) = text "/*" <+> text s <+> text "*/" pretty (CPPExt p) = pretty p instance Pretty CFunDef where pretty (CFunDef dspecs dr ds s) = ((hsep . fmap pretty $ dspecs) <+> pretty dr <> (parens . hsep . punctuate comma . fmap pretty $ ds)) $+$ (pretty s) -------------------------------------------------------------------------------- -- Preprocessor -- -------------------------------------------------------------------------------- instance Pretty Preprocessor where pretty (PPDefine n x) = hsep . fmap text $ ["#define",n,x] pretty (PPInclude s) = text "#include" <+> text "<" <> text s <> text ">" pretty (PPUndef s) = text "#undef" <+> text s pretty (PPIf s) = text "#if" <+> text s pretty (PPIfDef s) = text "#ifdef" <+> text s pretty (PPIfNDef s) = text "#ifndef" <+> text s pretty (PPElse s) = text "#else" <+> text s pretty (PPElif s) = text "#elif" <+> text s pretty (PPEndif s) = text "#endif" <+> text s pretty (PPError s) = text "#error" <+> text s pretty (PPPragma ts) = space $$ text "#pragma" <+> (hsep . fmap text $ ts) -------------------------------------------------------------------------------- -- CDeclarations -- -------------------------------------------------------------------------------- instance Pretty CDecl where pretty (CDecl ds ps) = hsep [ hsep . fmap pretty $ ds , hsep . punctuate comma . fmap declarators $ ps] where declarators (dr, Nothing) = pretty dr declarators (dr, Just ilist) = pretty dr <+> text "=" <+> pretty ilist instance Pretty CDeclr where pretty (CDeclr mp dd) = mpretty mp <+> (pretty $ dd) instance Pretty CPtrDeclr where pretty (CPtrDeclr ts) = text "*" <+> (hsep . fmap pretty $ ts) instance Pretty CDirectDeclr where pretty (CDDeclrIdent i) = pretty i pretty (CDDeclrArr dd e) = pretty dd <+> (brackets . pretty $ e) pretty (CDDeclrFun dd ts) = pretty dd <> (parens . hsep . punctuate comma . fmap (hsep . fmap pretty) $ ts) pretty (CDDeclrRec declr) = parens . pretty $ declr instance Pretty CDeclSpec where pretty (CStorageSpec ss) = pretty ss pretty (CTypeSpec ts) = pretty ts pretty (CTypeQual tq) = pretty tq pretty (CFunSpec _ ) = text "inline" -- inline is the only CFunSpec instance Pretty CStorageSpec where pretty CTypeDef = text "typedef" pretty CExtern = text "extern" pretty CStatic = text "static" pretty CAuto = text "auto" pretty CRegister = text "register" instance Pretty CTypeQual where pretty CConstQual = text "const" pretty CVolatQual = text "volatile" instance Pretty CTypeSpec where pretty CVoid = text "void" pretty CChar = text "char" pretty CShort = text "short" pretty CInt = text "int" pretty CLong = text "long" pretty CFloat = text "float" pretty CDouble = text "double" pretty CSigned = text "signed" pretty CUnsigned = text "unsigned" pretty (CSUType cs) = pretty cs pretty (CTypeDefType sid) = pretty sid pretty (CEnumType _) = error "TODO: Pretty EnumType" instance Pretty CTypeName where pretty (CTypeName tspecs pb) = let ss = sep . fmap pretty $ tspecs in if pb then ss <+> text "*" else ss instance Pretty CSUSpec where pretty (CSUSpec tag mi []) = pretty tag <+> mpretty mi pretty (CSUSpec tag mi ds) = (pretty tag <+> pretty mi) $+$ ( lbrace $+$ (nest 2 . sep . fmap (\d -> pretty d <> semi) $ ds) $+$ rbrace ) instance Pretty CSUTag where pretty CStructTag = text "struct" pretty CUnionTag = text "union" instance Pretty CEnum where pretty (CEnum _ _) = error "TODO: Pretty Enum" instance Pretty CInit where pretty (CInitExpr _) = error "TODO: Pretty Init" pretty (CInitList _) = error "TODO: Pretty Init list" instance Pretty CPartDesig where pretty (CArrDesig _) = error "TODO: Pretty Arr Desig" pretty (CMemberDesig _) = error "TODO: Pretty Memdesig" -------------------------------------------------------------------------------- -- CStatements -- -------------------------------------------------------------------------------- instance Pretty CStat where pretty (CLabel lId s) = pretty lId <> colon $$ nest 2 (pretty s) pretty (CGoto lId) = text "goto" <+> pretty lId <> semi pretty (CSwitch e s) = text "switch" <+> pretty e <+> (parens . pretty $ s ) pretty (CCase e s) = text "case" <+> pretty e <> colon $$ nest 2 (pretty s) pretty (CDefault s) = text "default" <> colon $$ nest 2 (pretty s) pretty (CExpr me) = mpretty me <> semi pretty (CCompound bs) = lbrace $+$ (nest 2 . vcat . fmap pretty $ bs) $+$ rbrace pretty (CIf ce thns (Just elss)) = text "if" <+> (parens . prettyPrec (-5) $ ce) $+$ (pretty thns) $+$ text "else" $+$ (pretty elss) pretty (CIf ce thns Nothing) = text "if" <+> (parens . prettyPrec (-5) $ ce) $+$ (pretty thns) pretty (CWhile ce s b) = if b then text "do" $+$ pretty s $+$ (text "while" <+> (parens $ pretty ce) <> semi) else (text "while" <+> (parens $ pretty ce)) $+$ (pretty s) pretty (CFor me mce mie s) = text "for" <+> (parens . hsep . punctuate semi . fmap (mPrettyPrec 10) $ [me,mce,mie]) $$ (pretty s) pretty CCont = text "continue" <> semi pretty CBreak = text "break" <> semi pretty (CReturn me) = text "return" <+> mpretty me <> semi pretty (CComment s) = text "/*" <+> text s <+> text "*/" pretty (CPPStat p) = pretty p instance Pretty CCompoundBlockItem where pretty (CBlockStat s) = pretty s pretty (CBlockDecl d) = pretty d <> semi -------------------------------------------------------------------------------- -- CExpressions -- -------------------------------------------------------------------------------- instance Pretty CExpr where prettyPrec _ (CComma es) = hsep . punctuate comma . fmap pretty $ es prettyPrec _ (CAssign op le re) = pretty le <+> pretty op <+> pretty re prettyPrec _ (CCond ce thn els) = pretty ce <+> text "?" <+> pretty thn <+> colon <+> pretty els prettyPrec p (CBinary op e1 e2) = parensPrec p 0 . hsep $ [pretty e1, pretty op, pretty e2] prettyPrec p (CCast d e) = parensPrec p (2) $ parens (pretty d) <> pretty e prettyPrec p (CUnary op e) = if elem op [CPostIncOp,CPostDecOp] then parensPrec p (-1) $ prettyPrec (-1) e <> pretty op else parens $ pretty op <> prettyPrec (-1) e prettyPrec _ (CSizeOfExpr e) = text "sizeof" <> (parens . pretty $ e) prettyPrec _ (CSizeOfType d) = text "sizeof" <> (parens . pretty $ d) prettyPrec _ (CIndex arrId ie) = pretty arrId <> (brackets . pretty $ ie) prettyPrec _ (CCall fune es) = pretty fune <> (parens . hcat . punctuate comma . fmap pretty $ es) prettyPrec _ (CMember ve memId isPtr) = let op = text $ if isPtr then "." else "->" in pretty ve <> op <> pretty memId prettyPrec _ (CVar varId) = pretty varId prettyPrec _ (CConstant c) = pretty c prettyPrec _ (CCompoundLit d ini) = parens (pretty d) <> pretty ini instance Pretty CAssignOp where pretty CAssignOp = text "=" pretty CMulAssOp = text "*=" pretty CDivAssOp = text "/=" pretty CRmdAssOp = text "%=" pretty CAddAssOp = text "+=" pretty CSubAssOp = text "-=" pretty CShlAssOp = text "<<=" pretty CShrAssOp = text ">>=" pretty CAndAssOp = text "&=" pretty CXorAssOp = text "^=" pretty COrAssOp = text "|=" instance Pretty CBinaryOp where pretty CMulOp = text "*" pretty CDivOp = text "/" pretty CRmdOp = text "%" pretty CAddOp = text "+" pretty CSubOp = text "-" pretty CShlOp = text "<<" pretty CShrOp = text ">>" pretty CLeOp = text "<" pretty CGrOp = text ">" pretty CLeqOp = text "<=" pretty CGeqOp = text ">=" pretty CEqOp = text "==" pretty CNeqOp = text "!=" pretty CAndOp = text "&" pretty CXorOp = text "^" pretty COrOp = text "|" pretty CLndOp = text "&&" pretty CLorOp = text "||" instance Pretty CUnaryOp where pretty CPreIncOp = text "++" pretty CPreDecOp = text "--" pretty CPostIncOp = text "++" pretty CPostDecOp = text "--" pretty CAdrOp = text "&" pretty CIndOp = text "*" pretty CPlusOp = text "+" pretty CMinOp = text "-" pretty CCompOp = text "~" pretty CNegOp = text "!" instance Pretty CConst where pretty (CIntConst i) = text . show $ i pretty (CCharConst c) = text . show $ c pretty (CFloatConst f) = float f pretty (CStringConst s) = text . show $ s
zachsully/hakaru
haskell/Language/Hakaru/CodeGen/Pretty.hs
bsd-3-clause
10,553
0
17
2,600
3,726
1,809
1,917
223
2
{- (c) Galois, 2006 (c) University of Glasgow, 2007 -} {-# LANGUAGE CPP, NondecreasingIndentation, RecordWildCards #-} module Coverage (addTicksToBinds, hpcInitCode) where #ifdef GHCI import qualified GHCi import GHCi.RemoteTypes import Data.Array import ByteCodeTypes import GHC.Stack.CCS import Foreign.C import qualified Data.ByteString as B #endif import Type import HsSyn import Module import Outputable import DynFlags import Control.Monad import SrcLoc import ErrUtils import NameSet hiding (FreeVars) import Name import Bag import CostCentre import CoreSyn import Id import VarSet import Data.List import FastString import HscTypes import TyCon import UniqSupply import BasicTypes import MonadUtils import Maybes import CLabel import Util import Data.Time import System.Directory import Trace.Hpc.Mix import Trace.Hpc.Util import Data.Map (Map) import qualified Data.Map as Map {- ************************************************************************ * * * The main function: addTicksToBinds * * ************************************************************************ -} addTicksToBinds :: HscEnv -> Module -> ModLocation -- ... off the current module -> NameSet -- Exported Ids. When we call addTicksToBinds, -- isExportedId doesn't work yet (the desugarer -- hasn't set it), so we have to work from this set. -> [TyCon] -- Type constructor in this module -> LHsBinds Id -> IO (LHsBinds Id, HpcInfo, Maybe ModBreaks) addTicksToBinds hsc_env mod mod_loc exports tyCons binds | let dflags = hsc_dflags hsc_env passes = coveragePasses dflags, not (null passes), Just orig_file <- ml_hs_file mod_loc = do if "boot" `isSuffixOf` orig_file then return (binds, emptyHpcInfo False, Nothing) else do us <- mkSplitUniqSupply 'C' -- for cost centres let orig_file2 = guessSourceFile binds orig_file tickPass tickish (binds,st) = let env = TTE { fileName = mkFastString orig_file2 , declPath = [] , tte_dflags = dflags , exports = exports , inlines = emptyVarSet , inScope = emptyVarSet , blackList = Map.fromList [ (getSrcSpan (tyConName tyCon),()) | tyCon <- tyCons ] , density = mkDensity tickish dflags , this_mod = mod , tickishType = tickish } (binds',_,st') = unTM (addTickLHsBinds binds) env st in (binds', st') initState = TT { tickBoxCount = 0 , mixEntries = [] , uniqSupply = us } (binds1,st) = foldr tickPass (binds, initState) passes let tickCount = tickBoxCount st entries = reverse $ mixEntries st hashNo <- writeMixEntries dflags mod tickCount entries orig_file2 modBreaks <- mkModBreaks hsc_env mod tickCount entries when (dopt Opt_D_dump_ticked dflags) $ log_action dflags dflags SevDump noSrcSpan defaultDumpStyle (pprLHsBinds binds1) return (binds1, HpcInfo tickCount hashNo, Just modBreaks) | otherwise = return (binds, emptyHpcInfo False, Nothing) guessSourceFile :: LHsBinds Id -> FilePath -> FilePath guessSourceFile binds orig_file = -- Try look for a file generated from a .hsc file to a -- .hs file, by peeking ahead. let top_pos = catMaybes $ foldrBag (\ (L pos _) rest -> srcSpanFileName_maybe pos : rest) [] binds in case top_pos of (file_name:_) | ".hsc" `isSuffixOf` unpackFS file_name -> unpackFS file_name _ -> orig_file mkModBreaks :: HscEnv -> Module -> Int -> [MixEntry_] -> IO ModBreaks #ifndef GHCI mkModBreaks _hsc_env _mod _count _entries = return emptyModBreaks #else mkModBreaks hsc_env mod count entries | HscInterpreted <- hscTarget (hsc_dflags hsc_env) = do breakArray <- GHCi.newBreakArray hsc_env (length entries) ccs <- mkCCSArray hsc_env mod count entries let locsTicks = listArray (0,count-1) [ span | (span,_,_,_) <- entries ] varsTicks = listArray (0,count-1) [ vars | (_,_,vars,_) <- entries ] declsTicks = listArray (0,count-1) [ decls | (_,decls,_,_) <- entries ] return emptyModBreaks { modBreaks_flags = breakArray , modBreaks_locs = locsTicks , modBreaks_vars = varsTicks , modBreaks_decls = declsTicks , modBreaks_ccs = ccs } | otherwise = return emptyModBreaks mkCCSArray :: HscEnv -> Module -> Int -> [MixEntry_] -> IO (Array BreakIndex (RemotePtr GHC.Stack.CCS.CostCentre)) mkCCSArray hsc_env modul count entries = do if interpreterProfiled (hsc_dflags hsc_env) then do let module_bs = fastStringToByteString (moduleNameFS (moduleName modul)) c_module <- GHCi.mallocData hsc_env (module_bs `B.snoc` 0) -- NB. null-terminate the string costcentres <- mapM (mkCostCentre hsc_env (castRemotePtr c_module)) entries return (listArray (0,count-1) costcentres) else do return (listArray (0,-1) []) where mkCostCentre :: HscEnv -> RemotePtr CChar -> MixEntry_ -> IO (RemotePtr GHC.Stack.CCS.CostCentre) mkCostCentre hsc_env@HscEnv{..} c_module (srcspan, decl_path, _, _) = do let name = concat (intersperse "." decl_path) src = showSDoc hsc_dflags (ppr srcspan) GHCi.mkCostCentre hsc_env c_module name src #endif writeMixEntries :: DynFlags -> Module -> Int -> [MixEntry_] -> FilePath -> IO Int writeMixEntries dflags mod count entries filename | not (gopt Opt_Hpc dflags) = return 0 | otherwise = do let hpc_dir = hpcDir dflags mod_name = moduleNameString (moduleName mod) hpc_mod_dir | moduleUnitId mod == mainUnitId = hpc_dir | otherwise = hpc_dir ++ "/" ++ unitIdString (moduleUnitId mod) tabStop = 8 -- <tab> counts as a normal char in GHC's -- location ranges. createDirectoryIfMissing True hpc_mod_dir modTime <- getModificationUTCTime filename let entries' = [ (hpcPos, box) | (span,_,_,box) <- entries, hpcPos <- [mkHpcPos span] ] when (length entries' /= count) $ do panic "the number of .mix entries are inconsistent" let hashNo = mixHash filename modTime tabStop entries' mixCreate hpc_mod_dir mod_name $ Mix filename modTime (toHash hashNo) tabStop entries' return hashNo -- ----------------------------------------------------------------------------- -- TickDensity: where to insert ticks data TickDensity = TickForCoverage -- for Hpc | TickForBreakPoints -- for GHCi | TickAllFunctions -- for -prof-auto-all | TickTopFunctions -- for -prof-auto-top | TickExportedFunctions -- for -prof-auto-exported | TickCallSites -- for stack tracing deriving Eq mkDensity :: TickishType -> DynFlags -> TickDensity mkDensity tickish dflags = case tickish of HpcTicks -> TickForCoverage SourceNotes -> TickForCoverage Breakpoints -> TickForBreakPoints ProfNotes -> case profAuto dflags of ProfAutoAll -> TickAllFunctions ProfAutoTop -> TickTopFunctions ProfAutoExports -> TickExportedFunctions ProfAutoCalls -> TickCallSites _other -> panic "mkDensity" -- | Decide whether to add a tick to a binding or not. shouldTickBind :: TickDensity -> Bool -- top level? -> Bool -- exported? -> Bool -- simple pat bind? -> Bool -- INLINE pragma? -> Bool shouldTickBind density top_lev exported _simple_pat inline = case density of TickForBreakPoints -> False -- we never add breakpoints to simple pattern bindings -- (there's always a tick on the rhs anyway). TickAllFunctions -> not inline TickTopFunctions -> top_lev && not inline TickExportedFunctions -> exported && not inline TickForCoverage -> True TickCallSites -> False shouldTickPatBind :: TickDensity -> Bool -> Bool shouldTickPatBind density top_lev = case density of TickForBreakPoints -> False TickAllFunctions -> True TickTopFunctions -> top_lev TickExportedFunctions -> False TickForCoverage -> False TickCallSites -> False -- ----------------------------------------------------------------------------- -- Adding ticks to bindings addTickLHsBinds :: LHsBinds Id -> TM (LHsBinds Id) addTickLHsBinds = mapBagM addTickLHsBind addTickLHsBind :: LHsBind Id -> TM (LHsBind Id) addTickLHsBind (L pos bind@(AbsBinds { abs_binds = binds, abs_exports = abs_exports })) = do withEnv add_exports $ do withEnv add_inlines $ do binds' <- addTickLHsBinds binds return $ L pos $ bind { abs_binds = binds' } where -- in AbsBinds, the Id on each binding is not the actual top-level -- Id that we are defining, they are related by the abs_exports -- field of AbsBinds. So if we're doing TickExportedFunctions we need -- to add the local Ids to the set of exported Names so that we know to -- tick the right bindings. add_exports env = env{ exports = exports env `extendNameSetList` [ idName mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , idName pid `elemNameSet` (exports env) ] } add_inlines env = env{ inlines = inlines env `extendVarSetList` [ mid | ABE{ abe_poly = pid, abe_mono = mid } <- abs_exports , isAnyInlinePragma (idInlinePragma pid) ] } addTickLHsBind (L pos bind@(AbsBindsSig { abs_sig_bind = val_bind , abs_sig_export = poly_id })) | L _ FunBind { fun_id = L _ mono_id } <- val_bind = do withEnv (add_export mono_id) $ do withEnv (add_inlines mono_id) $ do val_bind' <- addTickLHsBind val_bind return $ L pos $ bind { abs_sig_bind = val_bind' } | otherwise = pprPanic "addTickLHsBind" (ppr bind) where -- see AbsBinds comments add_export mono_id env | idName poly_id `elemNameSet` exports env = env { exports = exports env `extendNameSet` idName mono_id } | otherwise = env add_inlines mono_id env | isAnyInlinePragma (idInlinePragma poly_id) = env { inlines = inlines env `extendVarSet` mono_id } | otherwise = env addTickLHsBind (L pos (funBind@(FunBind { fun_id = (L _ id) }))) = do let name = getOccString id decl_path <- getPathEntry density <- getDensity inline_ids <- liftM inlines getEnv let inline = isAnyInlinePragma (idInlinePragma id) || id `elemVarSet` inline_ids -- See Note [inline sccs] tickish <- tickishType `liftM` getEnv if inline && tickish == ProfNotes then return (L pos funBind) else do (fvs, mg@(MG { mg_alts = matches' })) <- getFreeVars $ addPathEntry name $ addTickMatchGroup False (fun_matches funBind) blackListed <- isBlackListed pos exported_names <- liftM exports getEnv -- We don't want to generate code for blacklisted positions -- We don't want redundant ticks on simple pattern bindings -- We don't want to tick non-exported bindings in TickExportedFunctions let simple = isSimplePatBind funBind toplev = null decl_path exported = idName id `elemNameSet` exported_names tick <- if not blackListed && shouldTickBind density toplev exported simple inline then bindTick density name pos fvs else return Nothing let mbCons = maybe Prelude.id (:) return $ L pos $ funBind { fun_matches = mg { mg_alts = matches' } , fun_tick = tick `mbCons` fun_tick funBind } where -- a binding is a simple pattern binding if it is a funbind with -- zero patterns isSimplePatBind :: HsBind a -> Bool isSimplePatBind funBind = matchGroupArity (fun_matches funBind) == 0 -- TODO: Revisit this addTickLHsBind (L pos (pat@(PatBind { pat_lhs = lhs, pat_rhs = rhs }))) = do let name = "(...)" (fvs, rhs') <- getFreeVars $ addPathEntry name $ addTickGRHSs False False rhs let pat' = pat { pat_rhs = rhs'} -- Should create ticks here? density <- getDensity decl_path <- getPathEntry let top_lev = null decl_path if not (shouldTickPatBind density top_lev) then return (L pos pat') else do -- Allocate the ticks rhs_tick <- bindTick density name pos fvs let patvars = map getOccString (collectPatBinders lhs) patvar_ticks <- mapM (\v -> bindTick density v pos fvs) patvars -- Add to pattern let mbCons = maybe id (:) rhs_ticks = rhs_tick `mbCons` fst (pat_ticks pat') patvar_tickss = zipWith mbCons patvar_ticks (snd (pat_ticks pat') ++ repeat []) return $ L pos $ pat' { pat_ticks = (rhs_ticks, patvar_tickss) } -- Only internal stuff, not from source, uses VarBind, so we ignore it. addTickLHsBind var_bind@(L _ (VarBind {})) = return var_bind addTickLHsBind patsyn_bind@(L _ (PatSynBind {})) = return patsyn_bind bindTick :: TickDensity -> String -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) bindTick density name pos fvs = do decl_path <- getPathEntry let toplev = null decl_path count_entries = toplev || density == TickAllFunctions top_only = density /= TickAllFunctions box_label = if toplev then TopLevelBox [name] else LocalBox (decl_path ++ [name]) -- allocATickBox box_label count_entries top_only pos fvs -- Note [inline sccs] -- -- It should be reasonable to add ticks to INLINE functions; however -- currently this tickles a bug later on because the SCCfinal pass -- does not look inside unfoldings to find CostCentres. It would be -- difficult to fix that, because SCCfinal currently works on STG and -- not Core (and since it also generates CostCentres for CAFs, -- changing this would be difficult too). -- -- Another reason not to add ticks to INLINE functions is that this -- sometimes handy for avoiding adding a tick to a particular function -- (see #6131) -- -- So for now we do not add any ticks to INLINE functions at all. -- ----------------------------------------------------------------------------- -- Decorate an LHsExpr with ticks -- selectively add ticks to interesting expressions addTickLHsExpr :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExpr e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | isGoodBreakExpr e0 -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- Add a tick to an expression which is the RHS of an equation or a binding. -- We always consider these to be breakpoints, unless the expression is a 'let' -- (because the body will definitely have a tick somewhere). ToDo: perhaps -- we should treat 'case' and 'if' the same way? addTickLHsExprRHS :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprRHS e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it TickForCoverage -> tick_it TickCallSites | isCallSite e0 -> tick_it _other -> dont_tick_it where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- The inner expression of an evaluation context: -- let binds in [], ( [] ) -- we never tick these if we're doing HPC, but otherwise -- we treat it like an ordinary expression. addTickLHsExprEvalInner :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprEvalInner e = do d <- getDensity case d of TickForCoverage -> addTickLHsExprNever e _otherwise -> addTickLHsExpr e -- | A let body is treated differently from addTickLHsExprEvalInner -- above with TickForBreakPoints, because for breakpoints we always -- want to tick the body, even if it is not a redex. See test -- break012. This gives the user the opportunity to inspect the -- values of the let-bound variables. addTickLHsExprLetBody :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprLetBody e@(L pos e0) = do d <- getDensity case d of TickForBreakPoints | HsLet{} <- e0 -> dont_tick_it | otherwise -> tick_it _other -> addTickLHsExprEvalInner e where tick_it = allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 dont_tick_it = addTickLHsExprNever e -- version of addTick that does not actually add a tick, -- because the scope of this tick is completely subsumed by -- another. addTickLHsExprNever :: LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprNever (L pos e0) = do e1 <- addTickHsExpr e0 return $ L pos e1 -- general heuristic: expressions which do not denote values are good -- break points isGoodBreakExpr :: HsExpr Id -> Bool isGoodBreakExpr (HsApp {}) = True isGoodBreakExpr (OpApp {}) = True isGoodBreakExpr _other = False isCallSite :: HsExpr Id -> Bool isCallSite HsApp{} = True isCallSite OpApp{} = True isCallSite _ = False addTickLHsExprOptAlt :: Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickLHsExprOptAlt oneOfMany (L pos e0) = ifDensity TickForCoverage (allocTickBox (ExpBox oneOfMany) False False pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) addBinTickLHsExpr :: (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addBinTickLHsExpr boxLabel (L pos e0) = ifDensity TickForCoverage (allocBinTickBox boxLabel pos $ addTickHsExpr e0) (addTickLHsExpr (L pos e0)) -- ----------------------------------------------------------------------------- -- Decoarate an HsExpr with ticks addTickHsExpr :: HsExpr Id -> TM (HsExpr Id) addTickHsExpr e@(HsVar (L _ id)) = do freeVar id; return e addTickHsExpr (HsUnboundVar {}) = panic "addTickHsExpr.HsUnboundVar" addTickHsExpr e@(HsIPVar _) = return e addTickHsExpr e@(HsOverLit _) = return e addTickHsExpr e@(HsOverLabel _) = return e addTickHsExpr e@(HsLit _) = return e addTickHsExpr (HsLam matchgroup) = liftM HsLam (addTickMatchGroup True matchgroup) addTickHsExpr (HsLamCase ty mgs) = liftM (HsLamCase ty) (addTickMatchGroup True mgs) addTickHsExpr (HsApp e1 e2) = liftM2 HsApp (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (OpApp e1 e2 fix e3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsExprNever e2) (return fix) (addTickLHsExpr e3) addTickHsExpr (NegApp e neg) = liftM2 NegApp (addTickLHsExpr e) (addTickSyntaxExpr hpcSrcSpan neg) addTickHsExpr (HsPar e) = liftM HsPar (addTickLHsExprEvalInner e) addTickHsExpr (SectionL e1 e2) = liftM2 SectionL (addTickLHsExpr e1) (addTickLHsExprNever e2) addTickHsExpr (SectionR e1 e2) = liftM2 SectionR (addTickLHsExprNever e1) (addTickLHsExpr e2) addTickHsExpr (ExplicitTuple es boxity) = liftM2 ExplicitTuple (mapM addTickTupArg es) (return boxity) addTickHsExpr (HsCase e mgs) = liftM2 HsCase (addTickLHsExpr e) -- not an EvalInner; e might not necessarily -- be evaluated. (addTickMatchGroup False mgs) addTickHsExpr (HsIf cnd e1 e2 e3) = liftM3 (HsIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsExprOptAlt True e2) (addTickLHsExprOptAlt True e3) addTickHsExpr (HsMultiIf ty alts) = do { let isOneOfMany = case alts of [_] -> False; _ -> True ; alts' <- mapM (liftL $ addTickGRHS isOneOfMany False) alts ; return $ HsMultiIf ty alts' } addTickHsExpr (HsLet (L l binds) e) = bindLocals (collectLocalBinders binds) $ liftM2 (HsLet . L l) (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsExprLetBody e) addTickHsExpr (HsDo cxt (L l stmts) srcloc) = do { (stmts', _) <- addTickLStmts' forQual stmts (return ()) ; return (HsDo cxt (L l stmts') srcloc) } where forQual = case cxt of ListComp -> Just $ BinBox QualBinBox _ -> Nothing addTickHsExpr (ExplicitList ty wit es) = liftM3 ExplicitList (return ty) (addTickWit wit) (mapM (addTickLHsExpr) es) where addTickWit Nothing = return Nothing addTickWit (Just fln) = do fln' <- addTickHsExpr fln return (Just fln') addTickHsExpr (ExplicitPArr ty es) = liftM2 ExplicitPArr (return ty) (mapM (addTickLHsExpr) es) addTickHsExpr (HsStatic e) = HsStatic <$> addTickLHsExpr e addTickHsExpr expr@(RecordCon { rcon_flds = rec_binds }) = do { rec_binds' <- addTickHsRecordBinds rec_binds ; return (expr { rcon_flds = rec_binds' }) } addTickHsExpr expr@(RecordUpd { rupd_expr = e, rupd_flds = flds }) = do { e' <- addTickLHsExpr e ; flds' <- mapM addTickHsRecField flds ; return (expr { rupd_expr = e', rupd_flds = flds' }) } addTickHsExpr (ExprWithTySig e ty) = liftM2 ExprWithTySig (addTickLHsExprNever e) -- No need to tick the inner expression -- for expressions with signatures (return ty) addTickHsExpr (ArithSeq ty wit arith_seq) = liftM3 ArithSeq (return ty) (addTickWit wit) (addTickArithSeqInfo arith_seq) where addTickWit Nothing = return Nothing addTickWit (Just fl) = do fl' <- addTickHsExpr fl return (Just fl') -- We might encounter existing ticks (multiple Coverage passes) addTickHsExpr (HsTick t e) = liftM (HsTick t) (addTickLHsExprNever e) addTickHsExpr (HsBinTick t0 t1 e) = liftM (HsBinTick t0 t1) (addTickLHsExprNever e) addTickHsExpr (HsTickPragma _ _ _ (L pos e0)) = do e2 <- allocTickBox (ExpBox False) False False pos $ addTickHsExpr e0 return $ unLoc e2 addTickHsExpr (PArrSeq ty arith_seq) = liftM2 PArrSeq (return ty) (addTickArithSeqInfo arith_seq) addTickHsExpr (HsSCC src nm e) = liftM3 HsSCC (return src) (return nm) (addTickLHsExpr e) addTickHsExpr (HsCoreAnn src nm e) = liftM3 HsCoreAnn (return src) (return nm) (addTickLHsExpr e) addTickHsExpr e@(HsBracket {}) = return e addTickHsExpr e@(HsTcBracketOut {}) = return e addTickHsExpr e@(HsRnBracketOut {}) = return e addTickHsExpr e@(HsSpliceE {}) = return e addTickHsExpr (HsProc pat cmdtop) = liftM2 HsProc (addTickLPat pat) (liftL (addTickHsCmdTop) cmdtop) addTickHsExpr (HsWrap w e) = liftM2 HsWrap (return w) (addTickHsExpr e) -- Explicitly no tick on inside addTickHsExpr (ExprWithTySigOut e ty) = liftM2 ExprWithTySigOut (addTickLHsExprNever e) -- No need to tick the inner expression (return ty) -- for expressions with signatures addTickHsExpr e@(HsTypeOut _) = return e -- Others should never happen in expression content. addTickHsExpr e = pprPanic "addTickHsExpr" (ppr e) addTickTupArg :: LHsTupArg Id -> TM (LHsTupArg Id) addTickTupArg (L l (Present e)) = do { e' <- addTickLHsExpr e ; return (L l (Present e')) } addTickTupArg (L l (Missing ty)) = return (L l (Missing ty)) addTickMatchGroup :: Bool{-is lambda-} -> MatchGroup Id (LHsExpr Id) -> TM (MatchGroup Id (LHsExpr Id)) addTickMatchGroup is_lam mg@(MG { mg_alts = L l matches }) = do let isOneOfMany = matchesOneOfMany matches matches' <- mapM (liftL (addTickMatch isOneOfMany is_lam)) matches return $ mg { mg_alts = L l matches' } addTickMatch :: Bool -> Bool -> Match Id (LHsExpr Id) -> TM (Match Id (LHsExpr Id)) addTickMatch isOneOfMany isLambda (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickGRHSs isOneOfMany isLambda gRHSs return $ Match mf pats opSig gRHSs' addTickGRHSs :: Bool -> Bool -> GRHSs Id (LHsExpr Id) -> TM (GRHSs Id (LHsExpr Id)) addTickGRHSs isOneOfMany isLambda (GRHSs guarded (L l local_binds)) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL (addTickGRHS isOneOfMany isLambda)) guarded return $ GRHSs guarded' (L l local_binds') where binders = collectLocalBinders local_binds addTickGRHS :: Bool -> Bool -> GRHS Id (LHsExpr Id) -> TM (GRHS Id (LHsExpr Id)) addTickGRHS isOneOfMany isLambda (GRHS stmts expr) = do (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickGRHSBody isOneOfMany isLambda expr) return $ GRHS stmts' expr' addTickGRHSBody :: Bool -> Bool -> LHsExpr Id -> TM (LHsExpr Id) addTickGRHSBody isOneOfMany isLambda expr@(L pos e0) = do d <- getDensity case d of TickForCoverage -> addTickLHsExprOptAlt isOneOfMany expr TickAllFunctions | isLambda -> addPathEntry "\\" $ allocTickBox (ExpBox False) True{-count-} False{-not top-} pos $ addTickHsExpr e0 _otherwise -> addTickLHsExprRHS expr addTickLStmts :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM [ExprLStmt Id] addTickLStmts isGuard stmts = do (stmts, _) <- addTickLStmts' isGuard stmts (return ()) return stmts addTickLStmts' :: (Maybe (Bool -> BoxLabel)) -> [ExprLStmt Id] -> TM a -> TM ([ExprLStmt Id], a) addTickLStmts' isGuard lstmts res = bindLocals (collectLStmtsBinders lstmts) $ do { lstmts' <- mapM (liftL (addTickStmt isGuard)) lstmts ; a <- res ; return (lstmts', a) } addTickStmt :: (Maybe (Bool -> BoxLabel)) -> Stmt Id (LHsExpr Id) -> TM (Stmt Id (LHsExpr Id)) addTickStmt _isGuard (LastStmt e noret ret) = do liftM3 LastStmt (addTickLHsExpr e) (pure noret) (addTickSyntaxExpr hpcSrcSpan ret) addTickStmt _isGuard (BindStmt pat e bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsExprRHS e) (addTickSyntaxExpr hpcSrcSpan bind) (addTickSyntaxExpr hpcSrcSpan fail) addTickStmt isGuard (BodyStmt e bind' guard' ty) = do liftM4 BodyStmt (addTick isGuard e) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickStmt _isGuard (LetStmt (L l binds)) = do liftM (LetStmt . L l) (addTickHsLocalBinds binds) addTickStmt isGuard (ParStmt pairs mzipExpr bindExpr) = do liftM3 ParStmt (mapM (addTickStmtAndBinders isGuard) pairs) (addTickSyntaxExpr hpcSrcSpan mzipExpr) (addTickSyntaxExpr hpcSrcSpan bindExpr) addTickStmt isGuard (ApplicativeStmt args mb_join body_ty) = do args' <- mapM (addTickApplicativeArg isGuard) args return (ApplicativeStmt args' mb_join body_ty) addTickStmt isGuard stmt@(TransStmt { trS_stmts = stmts , trS_by = by, trS_using = using , trS_ret = returnExpr, trS_bind = bindExpr , trS_fmap = liftMExpr }) = do t_s <- addTickLStmts isGuard stmts t_y <- fmapMaybeM addTickLHsExprRHS by t_u <- addTickLHsExprRHS using t_f <- addTickSyntaxExpr hpcSrcSpan returnExpr t_b <- addTickSyntaxExpr hpcSrcSpan bindExpr t_m <- addTickSyntaxExpr hpcSrcSpan liftMExpr return $ stmt { trS_stmts = t_s, trS_by = t_y, trS_using = t_u , trS_ret = t_f, trS_bind = t_b, trS_fmap = t_m } addTickStmt isGuard stmt@(RecStmt {}) = do { stmts' <- addTickLStmts isGuard (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTick :: Maybe (Bool -> BoxLabel) -> LHsExpr Id -> TM (LHsExpr Id) addTick isGuard e | Just fn <- isGuard = addBinTickLHsExpr fn e | otherwise = addTickLHsExprRHS e addTickApplicativeArg :: Maybe (Bool -> BoxLabel) -> (SyntaxExpr Id, ApplicativeArg Id Id) -> TM (SyntaxExpr Id, ApplicativeArg Id Id) addTickApplicativeArg isGuard (op, arg) = liftM2 (,) (addTickSyntaxExpr hpcSrcSpan op) (addTickArg arg) where addTickArg (ApplicativeArgOne pat expr) = ApplicativeArgOne <$> addTickLPat pat <*> addTickLHsExpr expr addTickArg (ApplicativeArgMany stmts ret pat) = ApplicativeArgMany <$> addTickLStmts isGuard stmts <*> addTickSyntaxExpr hpcSrcSpan ret <*> addTickLPat pat addTickStmtAndBinders :: Maybe (Bool -> BoxLabel) -> ParStmtBlock Id Id -> TM (ParStmtBlock Id Id) addTickStmtAndBinders isGuard (ParStmtBlock stmts ids returnExpr) = liftM3 ParStmtBlock (addTickLStmts isGuard stmts) (return ids) (addTickSyntaxExpr hpcSrcSpan returnExpr) addTickHsLocalBinds :: HsLocalBinds Id -> TM (HsLocalBinds Id) addTickHsLocalBinds (HsValBinds binds) = liftM HsValBinds (addTickHsValBinds binds) addTickHsLocalBinds (HsIPBinds binds) = liftM HsIPBinds (addTickHsIPBinds binds) addTickHsLocalBinds (EmptyLocalBinds) = return EmptyLocalBinds addTickHsValBinds :: HsValBindsLR Id a -> TM (HsValBindsLR Id b) addTickHsValBinds (ValBindsOut binds sigs) = liftM2 ValBindsOut (mapM (\ (rec,binds') -> liftM2 (,) (return rec) (addTickLHsBinds binds')) binds) (return sigs) addTickHsValBinds _ = panic "addTickHsValBinds" addTickHsIPBinds :: HsIPBinds Id -> TM (HsIPBinds Id) addTickHsIPBinds (IPBinds ipbinds dictbinds) = liftM2 IPBinds (mapM (liftL (addTickIPBind)) ipbinds) (return dictbinds) addTickIPBind :: IPBind Id -> TM (IPBind Id) addTickIPBind (IPBind nm e) = liftM2 IPBind (return nm) (addTickLHsExpr e) -- There is no location here, so we might need to use a context location?? addTickSyntaxExpr :: SrcSpan -> SyntaxExpr Id -> TM (SyntaxExpr Id) addTickSyntaxExpr pos x = do L _ x' <- addTickLHsExpr (L pos x) return $ x' -- we do not walk into patterns. addTickLPat :: LPat Id -> TM (LPat Id) addTickLPat pat = return pat addTickHsCmdTop :: HsCmdTop Id -> TM (HsCmdTop Id) addTickHsCmdTop (HsCmdTop cmd tys ty syntaxtable) = liftM4 HsCmdTop (addTickLHsCmd cmd) (return tys) (return ty) (return syntaxtable) addTickLHsCmd :: LHsCmd Id -> TM (LHsCmd Id) addTickLHsCmd (L pos c0) = do c1 <- addTickHsCmd c0 return $ L pos c1 addTickHsCmd :: HsCmd Id -> TM (HsCmd Id) addTickHsCmd (HsCmdLam matchgroup) = liftM HsCmdLam (addTickCmdMatchGroup matchgroup) addTickHsCmd (HsCmdApp c e) = liftM2 HsCmdApp (addTickLHsCmd c) (addTickLHsExpr e) {- addTickHsCmd (OpApp e1 c2 fix c3) = liftM4 OpApp (addTickLHsExpr e1) (addTickLHsCmd c2) (return fix) (addTickLHsCmd c3) -} addTickHsCmd (HsCmdPar e) = liftM HsCmdPar (addTickLHsCmd e) addTickHsCmd (HsCmdCase e mgs) = liftM2 HsCmdCase (addTickLHsExpr e) (addTickCmdMatchGroup mgs) addTickHsCmd (HsCmdIf cnd e1 c2 c3) = liftM3 (HsCmdIf cnd) (addBinTickLHsExpr (BinBox CondBinBox) e1) (addTickLHsCmd c2) (addTickLHsCmd c3) addTickHsCmd (HsCmdLet (L l binds) c) = bindLocals (collectLocalBinders binds) $ liftM2 (HsCmdLet . L l) (addTickHsLocalBinds binds) -- to think about: !patterns. (addTickLHsCmd c) addTickHsCmd (HsCmdDo (L l stmts) srcloc) = do { (stmts', _) <- addTickLCmdStmts' stmts (return ()) ; return (HsCmdDo (L l stmts') srcloc) } addTickHsCmd (HsCmdArrApp e1 e2 ty1 arr_ty lr) = liftM5 HsCmdArrApp (addTickLHsExpr e1) (addTickLHsExpr e2) (return ty1) (return arr_ty) (return lr) addTickHsCmd (HsCmdArrForm e fix cmdtop) = liftM3 HsCmdArrForm (addTickLHsExpr e) (return fix) (mapM (liftL (addTickHsCmdTop)) cmdtop) addTickHsCmd (HsCmdWrap w cmd) = liftM2 HsCmdWrap (return w) (addTickHsCmd cmd) -- Others should never happen in a command context. --addTickHsCmd e = pprPanic "addTickHsCmd" (ppr e) addTickCmdMatchGroup :: MatchGroup Id (LHsCmd Id) -> TM (MatchGroup Id (LHsCmd Id)) addTickCmdMatchGroup mg@(MG { mg_alts = L l matches }) = do matches' <- mapM (liftL addTickCmdMatch) matches return $ mg { mg_alts = L l matches' } addTickCmdMatch :: Match Id (LHsCmd Id) -> TM (Match Id (LHsCmd Id)) addTickCmdMatch (Match mf pats opSig gRHSs) = bindLocals (collectPatsBinders pats) $ do gRHSs' <- addTickCmdGRHSs gRHSs return $ Match mf pats opSig gRHSs' addTickCmdGRHSs :: GRHSs Id (LHsCmd Id) -> TM (GRHSs Id (LHsCmd Id)) addTickCmdGRHSs (GRHSs guarded (L l local_binds)) = do bindLocals binders $ do local_binds' <- addTickHsLocalBinds local_binds guarded' <- mapM (liftL addTickCmdGRHS) guarded return $ GRHSs guarded' (L l local_binds') where binders = collectLocalBinders local_binds addTickCmdGRHS :: GRHS Id (LHsCmd Id) -> TM (GRHS Id (LHsCmd Id)) -- The *guards* are *not* Cmds, although the body is -- C.f. addTickGRHS for the BinBox stuff addTickCmdGRHS (GRHS stmts cmd) = do { (stmts',expr') <- addTickLStmts' (Just $ BinBox $ GuardBinBox) stmts (addTickLHsCmd cmd) ; return $ GRHS stmts' expr' } addTickLCmdStmts :: [LStmt Id (LHsCmd Id)] -> TM [LStmt Id (LHsCmd Id)] addTickLCmdStmts stmts = do (stmts, _) <- addTickLCmdStmts' stmts (return ()) return stmts addTickLCmdStmts' :: [LStmt Id (LHsCmd Id)] -> TM a -> TM ([LStmt Id (LHsCmd Id)], a) addTickLCmdStmts' lstmts res = bindLocals binders $ do lstmts' <- mapM (liftL addTickCmdStmt) lstmts a <- res return (lstmts', a) where binders = collectLStmtsBinders lstmts addTickCmdStmt :: Stmt Id (LHsCmd Id) -> TM (Stmt Id (LHsCmd Id)) addTickCmdStmt (BindStmt pat c bind fail) = do liftM4 BindStmt (addTickLPat pat) (addTickLHsCmd c) (return bind) (return fail) addTickCmdStmt (LastStmt c noret ret) = do liftM3 LastStmt (addTickLHsCmd c) (pure noret) (addTickSyntaxExpr hpcSrcSpan ret) addTickCmdStmt (BodyStmt c bind' guard' ty) = do liftM4 BodyStmt (addTickLHsCmd c) (addTickSyntaxExpr hpcSrcSpan bind') (addTickSyntaxExpr hpcSrcSpan guard') (return ty) addTickCmdStmt (LetStmt (L l binds)) = do liftM (LetStmt . L l) (addTickHsLocalBinds binds) addTickCmdStmt stmt@(RecStmt {}) = do { stmts' <- addTickLCmdStmts (recS_stmts stmt) ; ret' <- addTickSyntaxExpr hpcSrcSpan (recS_ret_fn stmt) ; mfix' <- addTickSyntaxExpr hpcSrcSpan (recS_mfix_fn stmt) ; bind' <- addTickSyntaxExpr hpcSrcSpan (recS_bind_fn stmt) ; return (stmt { recS_stmts = stmts', recS_ret_fn = ret' , recS_mfix_fn = mfix', recS_bind_fn = bind' }) } addTickCmdStmt ApplicativeStmt{} = panic "ToDo: addTickCmdStmt ApplicativeLastStmt" -- Others should never happen in a command context. addTickCmdStmt stmt = pprPanic "addTickHsCmd" (ppr stmt) addTickHsRecordBinds :: HsRecordBinds Id -> TM (HsRecordBinds Id) addTickHsRecordBinds (HsRecFields fields dd) = do { fields' <- mapM addTickHsRecField fields ; return (HsRecFields fields' dd) } addTickHsRecField :: LHsRecField' id (LHsExpr Id) -> TM (LHsRecField' id (LHsExpr Id)) addTickHsRecField (L l (HsRecField id expr pun)) = do { expr' <- addTickLHsExpr expr ; return (L l (HsRecField id expr' pun)) } addTickArithSeqInfo :: ArithSeqInfo Id -> TM (ArithSeqInfo Id) addTickArithSeqInfo (From e1) = liftM From (addTickLHsExpr e1) addTickArithSeqInfo (FromThen e1 e2) = liftM2 FromThen (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromTo e1 e2) = liftM2 FromTo (addTickLHsExpr e1) (addTickLHsExpr e2) addTickArithSeqInfo (FromThenTo e1 e2 e3) = liftM3 FromThenTo (addTickLHsExpr e1) (addTickLHsExpr e2) (addTickLHsExpr e3) liftL :: (Monad m) => (a -> m a) -> Located a -> m (Located a) liftL f (L loc a) = do a' <- f a return $ L loc a' data TickTransState = TT { tickBoxCount:: Int , mixEntries :: [MixEntry_] , uniqSupply :: UniqSupply } data TickTransEnv = TTE { fileName :: FastString , density :: TickDensity , tte_dflags :: DynFlags , exports :: NameSet , inlines :: VarSet , declPath :: [String] , inScope :: VarSet , blackList :: Map SrcSpan () , this_mod :: Module , tickishType :: TickishType } -- deriving Show data TickishType = ProfNotes | HpcTicks | Breakpoints | SourceNotes deriving (Eq) coveragePasses :: DynFlags -> [TickishType] coveragePasses dflags = ifa (hscTarget dflags == HscInterpreted) Breakpoints $ ifa (gopt Opt_Hpc dflags) HpcTicks $ ifa (gopt Opt_SccProfilingOn dflags && profAuto dflags /= NoProfAuto) ProfNotes $ ifa (debugLevel dflags > 0) SourceNotes [] where ifa f x xs | f = x:xs | otherwise = xs -- | Tickishs that only make sense when their source code location -- refers to the current file. This might not always be true due to -- LINE pragmas in the code - which would confuse at least HPC. tickSameFileOnly :: TickishType -> Bool tickSameFileOnly HpcTicks = True tickSameFileOnly _other = False type FreeVars = OccEnv Id noFVs :: FreeVars noFVs = emptyOccEnv -- Note [freevars] -- For breakpoints we want to collect the free variables of an -- expression for pinning on the HsTick. We don't want to collect -- *all* free variables though: in particular there's no point pinning -- on free variables that are will otherwise be in scope at the GHCi -- prompt, which means all top-level bindings. Unfortunately detecting -- top-level bindings isn't easy (collectHsBindsBinders on the top-level -- bindings doesn't do it), so we keep track of a set of "in-scope" -- variables in addition to the free variables, and the former is used -- to filter additions to the latter. This gives us complete control -- over what free variables we track. data TM a = TM { unTM :: TickTransEnv -> TickTransState -> (a,FreeVars,TickTransState) } -- a combination of a state monad (TickTransState) and a writer -- monad (FreeVars). instance Functor TM where fmap = liftM instance Applicative TM where pure a = TM $ \ _env st -> (a,noFVs,st) (<*>) = ap instance Monad TM where (TM m) >>= k = TM $ \ env st -> case m env st of (r1,fv1,st1) -> case unTM (k r1) env st1 of (r2,fv2,st2) -> (r2, fv1 `plusOccEnv` fv2, st2) instance HasDynFlags TM where getDynFlags = TM $ \ env st -> (tte_dflags env, noFVs, st) instance MonadUnique TM where getUniqueSupplyM = TM $ \_ st -> (uniqSupply st, noFVs, st) getUniqueM = TM $ \_ st -> let (u, us') = takeUniqFromSupply (uniqSupply st) in (u, noFVs, st { uniqSupply = us' }) getState :: TM TickTransState getState = TM $ \ _ st -> (st, noFVs, st) setState :: (TickTransState -> TickTransState) -> TM () setState f = TM $ \ _ st -> ((), noFVs, f st) getEnv :: TM TickTransEnv getEnv = TM $ \ env st -> (env, noFVs, st) withEnv :: (TickTransEnv -> TickTransEnv) -> TM a -> TM a withEnv f (TM m) = TM $ \ env st -> case m (f env) st of (a, fvs, st') -> (a, fvs, st') getDensity :: TM TickDensity getDensity = TM $ \env st -> (density env, noFVs, st) ifDensity :: TickDensity -> TM a -> TM a -> TM a ifDensity d th el = do d0 <- getDensity; if d == d0 then th else el getFreeVars :: TM a -> TM (FreeVars, a) getFreeVars (TM m) = TM $ \ env st -> case m env st of (a, fv, st') -> ((fv,a), fv, st') freeVar :: Id -> TM () freeVar id = TM $ \ env st -> if id `elemVarSet` inScope env then ((), unitOccEnv (nameOccName (idName id)) id, st) else ((), noFVs, st) addPathEntry :: String -> TM a -> TM a addPathEntry nm = withEnv (\ env -> env { declPath = declPath env ++ [nm] }) getPathEntry :: TM [String] getPathEntry = declPath `liftM` getEnv getFileName :: TM FastString getFileName = fileName `liftM` getEnv isGoodSrcSpan' :: SrcSpan -> Bool isGoodSrcSpan' pos@(RealSrcSpan _) = srcSpanStart pos /= srcSpanEnd pos isGoodSrcSpan' (UnhelpfulSpan _) = False isGoodTickSrcSpan :: SrcSpan -> TM Bool isGoodTickSrcSpan pos = do file_name <- getFileName tickish <- tickishType `liftM` getEnv let need_same_file = tickSameFileOnly tickish same_file = Just file_name == srcSpanFileName_maybe pos return (isGoodSrcSpan' pos && (not need_same_file || same_file)) ifGoodTickSrcSpan :: SrcSpan -> TM a -> TM a -> TM a ifGoodTickSrcSpan pos then_code else_code = do good <- isGoodTickSrcSpan pos if good then then_code else else_code bindLocals :: [Id] -> TM a -> TM a bindLocals new_ids (TM m) = TM $ \ env st -> case m env{ inScope = inScope env `extendVarSetList` new_ids } st of (r, fv, st') -> (r, fv `delListFromOccEnv` occs, st') where occs = [ nameOccName (idName id) | id <- new_ids ] isBlackListed :: SrcSpan -> TM Bool isBlackListed pos = TM $ \ env st -> case Map.lookup pos (blackList env) of Nothing -> (False,noFVs,st) Just () -> (True,noFVs,st) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocTickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocTickBox boxLabel countEntries topOnly pos m = ifGoodTickSrcSpan pos (do (fvs, e) <- getFreeVars m env <- getEnv tickish <- mkTickish boxLabel countEntries topOnly pos fvs (declPath env) return (L pos (HsTick tickish (L pos e))) ) (do e <- m return (L pos e) ) -- the tick application inherits the source position of its -- expression argument to support nested box allocations allocATickBox :: BoxLabel -> Bool -> Bool -> SrcSpan -> FreeVars -> TM (Maybe (Tickish Id)) allocATickBox boxLabel countEntries topOnly pos fvs = ifGoodTickSrcSpan pos (do let mydecl_path = case boxLabel of TopLevelBox x -> x LocalBox xs -> xs _ -> panic "allocATickBox" tickish <- mkTickish boxLabel countEntries topOnly pos fvs mydecl_path return (Just tickish) ) (return Nothing) mkTickish :: BoxLabel -> Bool -> Bool -> SrcSpan -> OccEnv Id -> [String] -> TM (Tickish Id) mkTickish boxLabel countEntries topOnly pos fvs decl_path = do let ids = filter (not . isUnLiftedType . idType) $ occEnvElts fvs -- unlifted types cause two problems here: -- * we can't bind them at the GHCi prompt -- (bindLocalsAtBreakpoint already fliters them out), -- * the simplifier might try to substitute a literal for -- the Id, and we can't handle that. me = (pos, decl_path, map (nameOccName.idName) ids, boxLabel) cc_name | topOnly = head decl_path | otherwise = concat (intersperse "." decl_path) dflags <- getDynFlags env <- getEnv case tickishType env of HpcTicks -> do c <- liftM tickBoxCount getState setState $ \st -> st { tickBoxCount = c + 1 , mixEntries = me : mixEntries st } return $ HpcTick (this_mod env) c ProfNotes -> do ccUnique <- getUniqueM let cc = mkUserCC (mkFastString cc_name) (this_mod env) pos ccUnique count = countEntries && gopt Opt_ProfCountEntries dflags return $ ProfNote cc count True{-scopes-} Breakpoints -> do c <- liftM tickBoxCount getState setState $ \st -> st { tickBoxCount = c + 1 , mixEntries = me:mixEntries st } return $ Breakpoint c ids SourceNotes | RealSrcSpan pos' <- pos -> return $ SourceNote pos' cc_name _otherwise -> panic "mkTickish: bad source span!" allocBinTickBox :: (Bool -> BoxLabel) -> SrcSpan -> TM (HsExpr Id) -> TM (LHsExpr Id) allocBinTickBox boxLabel pos m = do env <- getEnv case tickishType env of HpcTicks -> do e <- liftM (L pos) m ifGoodTickSrcSpan pos (mkBinTickBoxHpc boxLabel pos e) (return e) _other -> allocTickBox (ExpBox False) False False pos m mkBinTickBoxHpc :: (Bool -> BoxLabel) -> SrcSpan -> LHsExpr Id -> TM (LHsExpr Id) mkBinTickBoxHpc boxLabel pos e = TM $ \ env st -> let meT = (pos,declPath env, [],boxLabel True) meF = (pos,declPath env, [],boxLabel False) meE = (pos,declPath env, [],ExpBox False) c = tickBoxCount st mes = mixEntries st in ( L pos $ HsTick (HpcTick (this_mod env) c) $ L pos $ HsBinTick (c+1) (c+2) e -- notice that F and T are reversed, -- because we are building the list in -- reverse... , noFVs , st {tickBoxCount=c+3 , mixEntries=meF:meT:meE:mes} ) mkHpcPos :: SrcSpan -> HpcPos mkHpcPos pos@(RealSrcSpan s) | isGoodSrcSpan' pos = toHpcPos (srcSpanStartLine s, srcSpanStartCol s, srcSpanEndLine s, srcSpanEndCol s - 1) -- the end column of a SrcSpan is one -- greater than the last column of the -- span (see SrcLoc), whereas HPC -- expects to the column range to be -- inclusive, hence we subtract one above. mkHpcPos _ = panic "bad source span; expected such spans to be filtered out" hpcSrcSpan :: SrcSpan hpcSrcSpan = mkGeneralSrcSpan (fsLit "Haskell Program Coverage internals") matchesOneOfMany :: [LMatch Id body] -> Bool matchesOneOfMany lmatches = sum (map matchCount lmatches) > 1 where matchCount (L _ (Match _ _pats _ty (GRHSs grhss _binds))) = length grhss type MixEntry_ = (SrcSpan, [String], [OccName], BoxLabel) -- For the hash value, we hash everything: the file name, -- the timestamp of the original source file, the tab stop, -- and the mix entries. We cheat, and hash the show'd string. -- This hash only has to be hashed at Mix creation time, -- and is for sanity checking only. mixHash :: FilePath -> UTCTime -> Int -> [MixEntry] -> Int mixHash file tm tabstop entries = fromIntegral $ hashString (show $ Mix file tm 0 tabstop entries) {- ************************************************************************ * * * initialisation * * ************************************************************************ Each module compiled with -fhpc declares an initialisation function of the form `hpc_init_<module>()`, which is emitted into the _stub.c file and annotated with __attribute__((constructor)) so that it gets executed at startup time. The function's purpose is to call hs_hpc_module to register this module with the RTS, and it looks something like this: static void hpc_init_Main(void) __attribute__((constructor)); static void hpc_init_Main(void) {extern StgWord64 _hpc_tickboxes_Main_hpc[]; hs_hpc_module("Main",8,1150288664,_hpc_tickboxes_Main_hpc);} -} hpcInitCode :: Module -> HpcInfo -> SDoc hpcInitCode _ (NoHpcInfo {}) = Outputable.empty hpcInitCode this_mod (HpcInfo tickCount hashNo) = vcat [ text "static void hpc_init_" <> ppr this_mod <> text "(void) __attribute__((constructor));" , text "static void hpc_init_" <> ppr this_mod <> text "(void)" , braces (vcat [ text "extern StgWord64 " <> tickboxes <> text "[]" <> semi, text "hs_hpc_module" <> parens (hcat (punctuate comma [ doubleQuotes full_name_str, int tickCount, -- really StgWord32 int hashNo, -- really StgWord32 tickboxes ])) <> semi ]) ] where tickboxes = ppr (mkHpcTicksLabel $ this_mod) module_name = hcat (map (text.charToC) $ bytesFS (moduleNameFS (Module.moduleName this_mod))) package_name = hcat (map (text.charToC) $ bytesFS (unitIdFS (moduleUnitId this_mod))) full_name_str | moduleUnitId this_mod == mainUnitId = module_name | otherwise = package_name <> char '/' <> module_name
gridaphobe/ghc
compiler/deSugar/Coverage.hs
bsd-3-clause
51,692
0
25
15,319
13,459
6,805
6,654
946
8
module CalculatorKata.Day6Spec (spec) where import Test.Hspec import CalculatorKata.Day6 (calculate) spec :: Spec spec = do it "calculates one digit" (calculate "5" == 5.0) it "calculates many digits" (calculate "5467" == 5467.0) it "calculates addition" (calculate "54+26" == 54.0+26.0) it "calculates subtraction" (calculate "76-23" == 76.0-23.0) it "calculates multiplication" (calculate "45*23" == 45.0*23.0) it "calculates division" (calculate "567/34" == 567.0/34.0)
Alex-Diez/haskell-tdd-kata
old-katas/test/CalculatorKata/Day6Spec.hs
bsd-3-clause
616
0
11
202
160
78
82
17
1
module Tests.Development.Cake.Options where import Development.Cake.Options import Development.Cake.Core.Types import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit tests = [ testGroup "parseOptions" $ [ testCase "noflags" $ let (opts', [], []) = parseOptions [] defaultOptions in opts' @?= defaultOptions , testCase "-v" $ let (opts', [], []) = parseOptions ["-v"] defaultOptions in optionVerbosity opts' @?= verbose , testCase "-v0" $ let (opts', [], []) = parseOptions ["-v0"] defaultOptions in optionVerbosity opts' @?= silent , testCase "-v42" $ let (opts', [], []) = parseOptions ["-v42"] defaultOptions in optionVerbosity opts' @?= chatty , testCase "-j" $ let (opts', [], [_warn]) = parseOptions ["-j"] defaultOptions in optionThreads opts' @?= optionThreads defaultOptions , testCase "-j0" $ let (opts', [], [_warn]) = parseOptions ["-j0"] defaultOptions in optionThreads opts' @?= 1 , testCase "-j5" $ let (opts', [], []) = parseOptions ["-j5"] defaultOptions in optionThreads opts' @?= 5 , testCase "unknownFlags" $ do let (opts', rest, warns) = parseOptions ["-j5", "-v", "-xy", "--blah"] defaultOptions optionThreads opts' @?= 5 optionVerbosity opts' @?= verbose rest @?= ["-xy", "--blah"] warns @?= [] ] ]
nominolo/cake
unittests/Tests/Development/Cake/Options.hs
bsd-3-clause
1,483
0
15
410
492
254
238
36
1
{-# LANGUAGE BangPatterns, CPP, ForeignFunctionInterface, MagicHash, ScopedTypeVariables, UnliftedFFITypes #-} #ifdef GENERICS {-# LANGUAGE DefaultSignatures, FlexibleContexts #-} #endif ------------------------------------------------------------------------ -- | -- Module : Data.Hashable.Class -- Copyright : (c) Milan Straka 2010 -- (c) Johan Tibell 2011 -- (c) Bryan O'Sullivan 2011, 2012 -- License : BSD-style -- Maintainer : johan.tibell@gmail.com -- Stability : provisional -- Portability : portable -- -- This module defines a class, 'Hashable', for types that can be -- converted to a hash value. This class exists for the benefit of -- hashing-based data structures. The module provides instances for -- most standard types. module Data.Hashable.Class ( -- * Computing hash values Hashable(..) #ifdef GENERICS -- ** Support for generics , GHashable(..) #endif -- * Creating new instances , hashUsing , hashPtr , hashPtrWithSalt , hashByteArray , hashByteArrayWithSalt ) where import Control.Exception (assert) import Data.Bits (shiftL, shiftR, xor) import qualified Data.ByteString as B import qualified Data.ByteString.Internal as B import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Unsafe as B import Data.Int (Int8, Int16, Int32, Int64) import Data.List (foldl') import Data.Ratio (Ratio, denominator, numerator) import qualified Data.Text as T import qualified Data.Text.Array as TA import qualified Data.Text.Internal as T import qualified Data.Text.Lazy as TL import Data.Typeable import Data.Version (Version(..)) import Data.Word (Word8, Word16, Word32, Word64) import Foreign.C (CString) import Foreign.Marshal.Utils (with) import Foreign.Ptr (Ptr, castPtr) import Foreign.Storable (alignment, peek, sizeOf) import GHC.Base (ByteArray#) import GHC.Conc (ThreadId(..)) import GHC.Prim (ThreadId#) import System.IO.Unsafe (unsafePerformIO) import System.Mem.StableName #if MIN_VERSION_base(4,8,0) import Data.Unique (Unique, hashUnique) #endif #if MIN_VERSION_base(4,7,0) import Data.Fixed (Fixed(..)) #endif #ifdef GENERICS import GHC.Generics #endif #if __GLASGOW_HASKELL__ >= 710 import GHC.Fingerprint.Type(Fingerprint(..)) #elif __GLASGOW_HASKELL__ >= 702 import Data.Typeable.Internal(TypeRep(..)) import GHC.Fingerprint.Type(Fingerprint(..)) #endif #if __GLASGOW_HASKELL__ >= 703 import Foreign.C (CLong(..)) import Foreign.C.Types (CInt(..)) #else import Foreign.C (CLong) import Foreign.C.Types (CInt) #endif #if !(MIN_VERSION_base(4,8,0)) import Data.Word (Word) #endif #if MIN_VERSION_base(4,7,0) import Data.Bits (finiteBitSize) #else import Data.Bits (bitSize) #endif #if !(MIN_VERSION_bytestring(0,10,0)) import qualified Data.ByteString.Lazy.Internal as BL -- foldlChunks #endif #if MIN_VERSION_bytestring(0,10,4) import qualified Data.ByteString.Short.Internal as BSI #endif #ifdef VERSION_integer_gmp # if MIN_VERSION_integer_gmp(1,0,0) # define MIN_VERSION_integer_gmp_1_0_0 # endif import GHC.Exts (Int(..)) import GHC.Integer.GMP.Internals (Integer(..)) # if defined(MIN_VERSION_integer_gmp_1_0_0) import GHC.Exts (sizeofByteArray#) import GHC.Integer.GMP.Internals (BigNat(BN#)) # endif #endif #if MIN_VERSION_base(4,8,0) import Data.Void (Void, absurd) import GHC.Natural (Natural(..)) import GHC.Exts (Word(..)) #endif #include "MachDeps.h" infixl 0 `hashWithSalt` ------------------------------------------------------------------------ -- * Computing hash values -- | A default salt used in the implementation of 'hash'. defaultSalt :: Int #if WORD_SIZE_IN_BITS == 64 defaultSalt = -2578643520546668380 -- 0xdc36d1615b7400a4 #else defaultSalt = 0x087fc72c #endif {-# INLINE defaultSalt #-} -- | The class of types that can be converted to a hash value. -- -- Minimal implementation: 'hashWithSalt'. class Hashable a where -- | Return a hash value for the argument, using the given salt. -- -- The general contract of 'hashWithSalt' is: -- -- * If two values are equal according to the '==' method, then -- applying the 'hashWithSalt' method on each of the two values -- /must/ produce the same integer result if the same salt is -- used in each case. -- -- * It is /not/ required that if two values are unequal -- according to the '==' method, then applying the -- 'hashWithSalt' method on each of the two values must produce -- distinct integer results. However, the programmer should be -- aware that producing distinct integer results for unequal -- values may improve the performance of hashing-based data -- structures. -- -- * This method can be used to compute different hash values for -- the same input by providing a different salt in each -- application of the method. This implies that any instance -- that defines 'hashWithSalt' /must/ make use of the salt in -- its implementation. hashWithSalt :: Int -> a -> Int -- | Like 'hashWithSalt', but no salt is used. The default -- implementation uses 'hashWithSalt' with some default salt. -- Instances might want to implement this method to provide a more -- efficient implementation than the default implementation. hash :: a -> Int hash = hashWithSalt defaultSalt #ifdef GENERICS default hashWithSalt :: (Generic a, GHashable (Rep a)) => Int -> a -> Int hashWithSalt salt = ghashWithSalt salt . from -- | The class of types that can be generically hashed. class GHashable f where ghashWithSalt :: Int -> f a -> Int #endif -- Since we support a generic implementation of 'hashWithSalt' we -- cannot also provide a default implementation for that method for -- the non-generic instance use case. Instead we provide -- 'defaultHashWith'. defaultHashWithSalt :: Hashable a => Int -> a -> Int defaultHashWithSalt salt x = salt `combine` hash x -- | Transform a value into a 'Hashable' value, then hash the -- transformed value using the given salt. -- -- This is a useful shorthand in cases where a type can easily be -- mapped to another type that is already an instance of 'Hashable'. -- Example: -- -- > data Foo = Foo | Bar -- > deriving (Enum) -- > -- > instance Hashable Foo where -- > hashWithSalt = hashUsing fromEnum hashUsing :: (Hashable b) => (a -> b) -- ^ Transformation function. -> Int -- ^ Salt. -> a -- ^ Value to transform. -> Int hashUsing f salt x = hashWithSalt salt (f x) {-# INLINE hashUsing #-} instance Hashable Int where hash = id hashWithSalt = defaultHashWithSalt instance Hashable Int8 where hash = fromIntegral hashWithSalt = defaultHashWithSalt instance Hashable Int16 where hash = fromIntegral hashWithSalt = defaultHashWithSalt instance Hashable Int32 where hash = fromIntegral hashWithSalt = defaultHashWithSalt instance Hashable Int64 where hash n #if MIN_VERSION_base(4,7,0) | finiteBitSize (undefined :: Int) == 64 = fromIntegral n #else | bitSize (undefined :: Int) == 64 = fromIntegral n #endif | otherwise = fromIntegral (fromIntegral n `xor` (fromIntegral n `shiftR` 32 :: Word64)) hashWithSalt = defaultHashWithSalt instance Hashable Word where hash = fromIntegral hashWithSalt = defaultHashWithSalt instance Hashable Word8 where hash = fromIntegral hashWithSalt = defaultHashWithSalt instance Hashable Word16 where hash = fromIntegral hashWithSalt = defaultHashWithSalt instance Hashable Word32 where hash = fromIntegral hashWithSalt = defaultHashWithSalt instance Hashable Word64 where hash n #if MIN_VERSION_base(4,7,0) | finiteBitSize (undefined :: Int) == 64 = fromIntegral n #else | bitSize (undefined :: Int) == 64 = fromIntegral n #endif | otherwise = fromIntegral (n `xor` (n `shiftR` 32)) hashWithSalt = defaultHashWithSalt instance Hashable () where hash = fromEnum hashWithSalt = defaultHashWithSalt instance Hashable Bool where hash = fromEnum hashWithSalt = defaultHashWithSalt instance Hashable Ordering where hash = fromEnum hashWithSalt = defaultHashWithSalt instance Hashable Char where hash = fromEnum hashWithSalt = defaultHashWithSalt #if defined(MIN_VERSION_integer_gmp_1_0_0) instance Hashable BigNat where hashWithSalt salt (BN# ba) = hashByteArrayWithSalt ba 0 numBytes salt `hashWithSalt` size where size = numBytes `quot` SIZEOF_HSWORD numBytes = I# (sizeofByteArray# ba) #endif #if MIN_VERSION_base(4,8,0) instance Hashable Natural where # if defined(MIN_VERSION_integer_gmp_1_0_0) hash (NatS# n) = hash (W# n) hash (NatJ# bn) = hash bn hashWithSalt salt (NatS# n) = hashWithSalt salt (W# n) hashWithSalt salt (NatJ# bn) = hashWithSalt salt bn # else hash (Natural n) = hash n hashWithSalt salt (Natural n) = hashWithSalt salt n # endif #endif instance Hashable Integer where #if defined(VERSION_integer_gmp) # if defined(MIN_VERSION_integer_gmp_1_0_0) hash (S# n) = (I# n) hash (Jp# bn) = hash bn hash (Jn# bn) = negate (hash bn) hashWithSalt salt (S# n) = hashWithSalt salt (I# n) hashWithSalt salt (Jp# bn) = hashWithSalt salt bn hashWithSalt salt (Jn# bn) = negate (hashWithSalt salt bn) # else hash (S# int) = I# int hash n@(J# size# byteArray) | n >= minInt && n <= maxInt = fromInteger n :: Int | otherwise = let size = I# size# numBytes = SIZEOF_HSWORD * abs size in hashByteArrayWithSalt byteArray 0 numBytes defaultSalt `hashWithSalt` size where minInt = fromIntegral (minBound :: Int) maxInt = fromIntegral (maxBound :: Int) hashWithSalt salt (S# n) = hashWithSalt salt (I# n) hashWithSalt salt n@(J# size# byteArray) | n >= minInt && n <= maxInt = hashWithSalt salt (fromInteger n :: Int) | otherwise = let size = I# size# numBytes = SIZEOF_HSWORD * abs size in hashByteArrayWithSalt byteArray 0 numBytes salt `hashWithSalt` size where minInt = fromIntegral (minBound :: Int) maxInt = fromIntegral (maxBound :: Int) # endif #else hashWithSalt salt = foldl' hashWithSalt salt . go where go n | inBounds n = [fromIntegral n :: Int] | otherwise = fromIntegral n : go (n `shiftR` WORD_SIZE_IN_BITS) maxInt = fromIntegral (maxBound :: Int) inBounds x = x >= fromIntegral (minBound :: Int) && x <= maxInt #endif instance (Integral a, Hashable a) => Hashable (Ratio a) where {-# SPECIALIZE instance Hashable (Ratio Integer) #-} hash a = hash (numerator a) `hashWithSalt` denominator a hashWithSalt s a = s `hashWithSalt` numerator a `hashWithSalt` denominator a instance Hashable Float where hash x | isIEEE x = assert (sizeOf x >= sizeOf (0::Word32) && alignment x >= alignment (0::Word32)) $ hash ((unsafePerformIO $ with x $ peek . castPtr) :: Word32) | otherwise = hash (show x) hashWithSalt = defaultHashWithSalt instance Hashable Double where hash x | isIEEE x = assert (sizeOf x >= sizeOf (0::Word64) && alignment x >= alignment (0::Word64)) $ hash ((unsafePerformIO $ with x $ peek . castPtr) :: Word64) | otherwise = hash (show x) hashWithSalt = defaultHashWithSalt -- | A value with bit pattern (01)* (or 5* in hexa), for any size of Int. -- It is used as data constructor distinguisher. GHC computes its value during -- compilation. distinguisher :: Int distinguisher = fromIntegral $ (maxBound :: Word) `quot` 3 {-# INLINE distinguisher #-} instance Hashable a => Hashable (Maybe a) where hash Nothing = 0 hash (Just a) = distinguisher `hashWithSalt` a hashWithSalt s Nothing = s `combine` 0 hashWithSalt s (Just a) = s `combine` distinguisher `hashWithSalt` a instance (Hashable a, Hashable b) => Hashable (Either a b) where hash (Left a) = 0 `hashWithSalt` a hash (Right b) = distinguisher `hashWithSalt` b hashWithSalt s (Left a) = s `combine` 0 `hashWithSalt` a hashWithSalt s (Right b) = s `combine` distinguisher `hashWithSalt` b instance (Hashable a1, Hashable a2) => Hashable (a1, a2) where hash (a1, a2) = hash a1 `hashWithSalt` a2 hashWithSalt s (a1, a2) = s `hashWithSalt` a1 `hashWithSalt` a2 instance (Hashable a1, Hashable a2, Hashable a3) => Hashable (a1, a2, a3) where hash (a1, a2, a3) = hash a1 `hashWithSalt` a2 `hashWithSalt` a3 hashWithSalt s (a1, a2, a3) = s `hashWithSalt` a1 `hashWithSalt` a2 `hashWithSalt` a3 instance (Hashable a1, Hashable a2, Hashable a3, Hashable a4) => Hashable (a1, a2, a3, a4) where hash (a1, a2, a3, a4) = hash a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 hashWithSalt s (a1, a2, a3, a4) = s `hashWithSalt` a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 instance (Hashable a1, Hashable a2, Hashable a3, Hashable a4, Hashable a5) => Hashable (a1, a2, a3, a4, a5) where hash (a1, a2, a3, a4, a5) = hash a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 `hashWithSalt` a5 hashWithSalt s (a1, a2, a3, a4, a5) = s `hashWithSalt` a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 `hashWithSalt` a5 instance (Hashable a1, Hashable a2, Hashable a3, Hashable a4, Hashable a5, Hashable a6) => Hashable (a1, a2, a3, a4, a5, a6) where hash (a1, a2, a3, a4, a5, a6) = hash a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 `hashWithSalt` a5 `hashWithSalt` a6 hashWithSalt s (a1, a2, a3, a4, a5, a6) = s `hashWithSalt` a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 `hashWithSalt` a5 `hashWithSalt` a6 instance (Hashable a1, Hashable a2, Hashable a3, Hashable a4, Hashable a5, Hashable a6, Hashable a7) => Hashable (a1, a2, a3, a4, a5, a6, a7) where hash (a1, a2, a3, a4, a5, a6, a7) = hash a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 `hashWithSalt` a5 `hashWithSalt` a6 `hashWithSalt` a7 hashWithSalt s (a1, a2, a3, a4, a5, a6, a7) = s `hashWithSalt` a1 `hashWithSalt` a2 `hashWithSalt` a3 `hashWithSalt` a4 `hashWithSalt` a5 `hashWithSalt` a6 `hashWithSalt` a7 instance Hashable (StableName a) where hash = hashStableName hashWithSalt = defaultHashWithSalt -- Auxillary type for Hashable [a] definition data SPInt = SP !Int !Int instance Hashable a => Hashable [a] where {-# SPECIALIZE instance Hashable [Char] #-} hashWithSalt salt arr = finalise (foldl' step (SP salt 0) arr) where finalise (SP s l) = hashWithSalt s l step (SP s l) x = SP (hashWithSalt s x) (l + 1) instance Hashable B.ByteString where hashWithSalt salt bs = B.inlinePerformIO $ B.unsafeUseAsCStringLen bs $ \(p, len) -> hashPtrWithSalt p (fromIntegral len) salt instance Hashable BL.ByteString where hashWithSalt = BL.foldlChunks hashWithSalt #if MIN_VERSION_bytestring(0,10,4) instance Hashable BSI.ShortByteString where #if MIN_VERSION_base(4,3,0) hashWithSalt salt sbs@(BSI.SBS ba) = #else hashWithSalt salt sbs@(BSI.SBS ba _) = #endif hashByteArrayWithSalt ba 0 (BSI.length sbs) salt #endif instance Hashable T.Text where hashWithSalt salt (T.Text arr off len) = hashByteArrayWithSalt (TA.aBA arr) (off `shiftL` 1) (len `shiftL` 1) salt instance Hashable TL.Text where hashWithSalt = TL.foldlChunks hashWithSalt -- | Compute the hash of a ThreadId. hashThreadId :: ThreadId -> Int hashThreadId (ThreadId t) = hash (fromIntegral (getThreadId t) :: Int) foreign import ccall unsafe "rts_getThreadId" getThreadId :: ThreadId# -> CInt instance Hashable ThreadId where hash = hashThreadId hashWithSalt = defaultHashWithSalt -- | Compute the hash of a TypeRep, in various GHC versions we can do this quickly. hashTypeRep :: TypeRep -> Int {-# INLINE hashTypeRep #-} #if __GLASGOW_HASKELL__ >= 710 -- Fingerprint is just the MD5, so taking any Int from it is fine hashTypeRep tr = let Fingerprint x _ = typeRepFingerprint tr in fromIntegral x #elif __GLASGOW_HASKELL__ >= 702 -- Fingerprint is just the MD5, so taking any Int from it is fine hashTypeRep (TypeRep (Fingerprint x _) _ _) = fromIntegral x #elif __GLASGOW_HASKELL__ >= 606 hashTypeRep = B.inlinePerformIO . typeRepKey #else hashTypeRep = hash . show #endif instance Hashable TypeRep where hash = hashTypeRep hashWithSalt = defaultHashWithSalt {-# INLINE hash #-} #if MIN_VERSION_base(4,8,0) instance Hashable Void where hashWithSalt _ = absurd #endif -- | Compute a hash value for the content of this pointer. hashPtr :: Ptr a -- ^ pointer to the data to hash -> Int -- ^ length, in bytes -> IO Int -- ^ hash value hashPtr p len = hashPtrWithSalt p len defaultSalt -- | Compute a hash value for the content of this pointer, using an -- initial salt. -- -- This function can for example be used to hash non-contiguous -- segments of memory as if they were one contiguous segment, by using -- the output of one hash as the salt for the next. hashPtrWithSalt :: Ptr a -- ^ pointer to the data to hash -> Int -- ^ length, in bytes -> Int -- ^ salt -> IO Int -- ^ hash value hashPtrWithSalt p len salt = fromIntegral `fmap` c_hashCString (castPtr p) (fromIntegral len) (fromIntegral salt) foreign import ccall unsafe "hashable_fnv_hash" c_hashCString :: CString -> CLong -> CLong -> IO CLong -- | Compute a hash value for the content of this 'ByteArray#', -- beginning at the specified offset, using specified number of bytes. hashByteArray :: ByteArray# -- ^ data to hash -> Int -- ^ offset, in bytes -> Int -- ^ length, in bytes -> Int -- ^ hash value hashByteArray ba0 off len = hashByteArrayWithSalt ba0 off len defaultSalt {-# INLINE hashByteArray #-} -- | Compute a hash value for the content of this 'ByteArray#', using -- an initial salt. -- -- This function can for example be used to hash non-contiguous -- segments of memory as if they were one contiguous segment, by using -- the output of one hash as the salt for the next. hashByteArrayWithSalt :: ByteArray# -- ^ data to hash -> Int -- ^ offset, in bytes -> Int -- ^ length, in bytes -> Int -- ^ salt -> Int -- ^ hash value hashByteArrayWithSalt ba !off !len !h = fromIntegral $ c_hashByteArray ba (fromIntegral off) (fromIntegral len) (fromIntegral h) foreign import ccall unsafe "hashable_fnv_hash_offset" c_hashByteArray :: ByteArray# -> CLong -> CLong -> CLong -> CLong -- | Combine two given hash values. 'combine' has zero as a left -- identity. combine :: Int -> Int -> Int combine h1 h2 = (h1 * 16777619) `xor` h2 #if MIN_VERSION_base(4,8,0) instance Hashable Unique where hash = hashUnique hashWithSalt = defaultHashWithSalt #endif instance Hashable Version where hashWithSalt salt (Version branch tags) = salt `hashWithSalt` branch `hashWithSalt` tags #if MIN_VERSION_base(4,7,0) instance Hashable (Fixed a) where hashWithSalt salt (MkFixed i) = hashWithSalt salt i #endif
ekmett/hashable
Data/Hashable/Class.hs
bsd-3-clause
19,845
0
14
4,643
4,334
2,473
1,861
255
1
----------------------------------------------------------- -- | -- Module : Database.HaskellDB.HDBC -- Copyright : HWT Group 2003, -- Bjorn Bringert 2005-2006 -- License : BSD-style -- -- Maintainer : haskelldb-users@lists.sourceforge.net -- Stability : experimental -- Portability : portable -- -- HDBC interface for HaskellDB -- ----------------------------------------------------------- module Database.HaskellDB.HDBC (hdbcConnect) where import Database.HaskellDB import Database.HaskellDB.Database import Database.HaskellDB.Sql.Generate (SqlGenerator(..)) import Database.HaskellDB.Sql.Print import Database.HaskellDB.PrimQuery import Database.HaskellDB.Query import Database.HaskellDB.FieldType import Database.HDBC as HDBC hiding (toSql) import Control.Monad.Trans (MonadIO, liftIO) import Data.Char (toLower) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (fromMaybe) -- | Run an action on a HDBC IConnection and close the connection. hdbcConnect :: (MonadIO m, IConnection conn) => SqlGenerator -> IO conn -- ^ connection function -> (Database -> m a) -> m a hdbcConnect gen connect action = do conn <- liftIO $ handleSqlError connect x <- action (mkDatabase gen conn) -- FIXME: should we really commit here? liftIO $ HDBC.commit conn liftIO $ handleSqlError (HDBC.disconnect conn) return x mkDatabase :: (IConnection conn) => SqlGenerator -> conn -> Database mkDatabase gen connection = Database { dbQuery = hdbcQuery gen connection, dbInsert = hdbcInsert gen connection, dbInsertQuery = hdbcInsertQuery gen connection, dbDelete = hdbcDelete gen connection, dbUpdate = hdbcUpdate gen connection, dbTables = hdbcTables connection, dbDescribe = hdbcDescribe connection, dbTransaction = hdbcTransaction connection, dbCreateDB = hdbcCreateDB gen connection, dbCreateTable = hdbcCreateTable gen connection, dbDropDB = hdbcDropDB gen connection, dbDropTable = hdbcDropTable gen connection } hdbcQuery :: (GetRec er vr, IConnection conn) => SqlGenerator -> conn -> PrimQuery -> Rel er -> IO [Record vr] hdbcQuery gen connection q rel = hdbcPrimQuery connection sql scheme rel where sql = show $ ppSql $ sqlQuery gen q scheme = attributes q hdbcInsert :: (IConnection conn) => SqlGenerator -> conn -> TableName -> Assoc -> IO () hdbcInsert gen conn table assoc = hdbcPrimExecute conn $ show $ ppInsert $ sqlInsert gen table assoc hdbcInsertQuery :: (IConnection conn) => SqlGenerator -> conn -> TableName -> PrimQuery -> IO () hdbcInsertQuery gen conn table assoc = hdbcPrimExecute conn $ show $ ppInsert $ sqlInsertQuery gen table assoc hdbcDelete :: (IConnection conn) => SqlGenerator -> conn -> TableName -> [PrimExpr] -> IO () hdbcDelete gen conn table exprs = hdbcPrimExecute conn $ show $ ppDelete $ sqlDelete gen table exprs hdbcUpdate :: (IConnection conn) => SqlGenerator -> conn -> TableName -> [PrimExpr] -> Assoc -> IO () hdbcUpdate gen conn table criteria assigns = hdbcPrimExecute conn $ show $ ppUpdate $ sqlUpdate gen table criteria assigns hdbcTables :: (IConnection conn) => conn -> IO [TableName] hdbcTables conn = handleSqlError $ HDBC.getTables conn hdbcDescribe :: (IConnection conn) => conn -> TableName -> IO [(Attribute,FieldDesc)] hdbcDescribe conn table = handleSqlError $ do cs <- HDBC.describeTable conn table return [(n,colDescToFieldDesc c) | (n,c) <- cs] colDescToFieldDesc :: SqlColDesc -> FieldDesc colDescToFieldDesc c = (t, nullable) where nullable = fromMaybe True (colNullable c) string = maybe StringT BStrT (colSize c) t = case colType c of SqlCharT -> string SqlVarCharT -> string SqlLongVarCharT -> string SqlWCharT -> string SqlWVarCharT -> string SqlWLongVarCharT -> string SqlDecimalT -> IntegerT SqlNumericT -> IntegerT SqlSmallIntT -> IntT SqlIntegerT -> IntT SqlRealT -> DoubleT SqlFloatT -> DoubleT SqlDoubleT -> DoubleT SqlBitT -> BoolT SqlTinyIntT -> IntT SqlBigIntT -> IntT SqlBinaryT -> string SqlVarBinaryT -> string SqlLongVarBinaryT -> string SqlDateT -> CalendarTimeT SqlTimeT -> CalendarTimeT SqlTimestampT -> CalendarTimeT SqlUTCDateTimeT -> CalendarTimeT SqlUTCTimeT -> CalendarTimeT SqlTimeWithZoneT -> CalendarTimeT SqlTimestampWithZoneT -> CalendarTimeT SqlIntervalT _ -> string SqlGUIDT -> string SqlUnknownT _ -> string hdbcCreateDB :: (IConnection conn) => SqlGenerator -> conn -> String -> IO () hdbcCreateDB gen conn name = hdbcPrimExecute conn $ show $ ppCreate $ sqlCreateDB gen name hdbcCreateTable :: (IConnection conn) => SqlGenerator -> conn -> TableName -> [(Attribute,FieldDesc)] -> IO () hdbcCreateTable gen conn name attrs = hdbcPrimExecute conn $ show $ ppCreate $ sqlCreateTable gen name attrs hdbcDropDB :: (IConnection conn) => SqlGenerator -> conn -> String -> IO () hdbcDropDB gen conn name = hdbcPrimExecute conn $ show $ ppDrop $ sqlDropDB gen name hdbcDropTable :: (IConnection conn) => SqlGenerator -> conn -> TableName -> IO () hdbcDropTable gen conn name = hdbcPrimExecute conn $ show $ ppDrop $ sqlDropTable gen name -- | HDBC implementation of 'Database.dbTransaction'. hdbcTransaction :: (IConnection conn) => conn -> IO a -> IO a hdbcTransaction conn action = handleSqlError $ HDBC.withTransaction conn (\_ -> action) ----------------------------------------------------------- -- Primitive operations ----------------------------------------------------------- type HDBCRow = Map String HDBC.SqlValue -- | Primitive query hdbcPrimQuery :: (GetRec er vr, IConnection conn) => conn -- ^ Database connection. -> String -- ^ SQL query -> Scheme -- ^ List of field names to retrieve -> Rel er -- ^ Phantom argument to get the return type right. -> IO [Record vr] -- ^ Query results hdbcPrimQuery conn sql scheme rel = do stmt <- handleSqlError $ HDBC.prepare conn sql handleSqlError $ HDBC.execute stmt [] rows <- HDBC.fetchAllRowsMap stmt mapM (getRec (hdbcGetInstances sql) rel scheme) rows -- | Primitive execute hdbcPrimExecute :: (IConnection conn) => conn -- ^ Database connection. -> String -- ^ SQL query. -> IO () hdbcPrimExecute conn sql = do handleSqlError $ HDBC.run conn sql [] return () ----------------------------------------------------------- -- Getting data from a statement ----------------------------------------------------------- hdbcGetInstances :: String -> GetInstances HDBCRow hdbcGetInstances s = GetInstances { getString = hdbcGetValue s , getInt = hdbcGetValue s , getInteger = hdbcGetValue s , getDouble = hdbcGetValue s , getBool = hdbcGetValue s , getCalendarTime = hdbcGetValue s } -- hdbcGetValue :: Data.Convertible.Base.Convertible SqlValue a -- => HDBCRow -> String -> IO (Maybe a) hdbcGetValue s m f = case Map.lookup (map toLower f) m of Nothing -> fail $ "No such field " ++ f ++ " from query " ++ show s Just x -> return $ HDBC.fromSql x
chrisdone/haskelldb-demo
lib/haskelldb/driver-hdbc/Database/HaskellDB/HDBC.hs
bsd-3-clause
7,772
88
14
2,022
1,983
1,036
947
149
29
----------------------------------------------------------------------------- -- | -- Module : Examples.Arrays.Memory -- Copyright : (c) Levent Erkok -- License : BSD3 -- Maintainer : erkokl@gmail.com -- Stability : experimental -- -- Simple memory abstraction and properties ----------------------------------------------------------------------------- module Examples.Arrays.Memory where import Data.SBV type Address = SWord32 type Value = SWord64 type Memory = SArray Word32 Word64 -- | read-after-write: If you write a value and read it back, you'll get it raw :: Address -> Value -> Memory -> SBool raw a v m = readArray (writeArray m a v) a .== v -- | write-after-write: If you write to the same location twice, then the first one is ignored waw :: Address -> Value -> Value -> Memory -> SBool waw a v1 v2 m0 = m2 .== m3 where m1 = writeArray m0 a v1 m2 = writeArray m1 a v2 m3 = writeArray m0 a v2 -- | Two writes to different locations commute, i.e., can be done in any order wcommutesGood :: (Address, Value) -> (Address, Value) -> Memory -> SBool wcommutesGood (a, x) (b, y) m = a ./= b ==> wcommutesBad (a, x) (b, y) m -- | Two writes do not commute if they can be done to the same location wcommutesBad :: (Address, Value) -> (Address, Value) -> Memory -> SBool wcommutesBad (a, x) (b, y) m = writeArray (writeArray m a x) b y .== writeArray (writeArray m b y) a x tests :: IO () tests = do print =<< prove raw print =<< prove waw print =<< prove wcommutesBad print =<< prove wcommutesGood
Copilot-Language/sbv-for-copilot
SBVUnitTest/Examples/Arrays/Memory.hs
bsd-3-clause
1,583
0
8
341
400
218
182
21
1
{-# LANGUAGE ScopedTypeVariables #-} module ReadWriteTest where import Init import PersistentTestModels specsWith :: forall m. Runner SqlBackend m => RunDb SqlBackend m -> Spec specsWith originalRunDb = describe "ReadWriteTest" $ do let personFilters = [] :: [Filter Person] describe "SqlReadBackend" $ do let runDb :: RunDb SqlReadBackend m runDb = changeBackend SqlReadBackend originalRunDb it "type checks on all PersistStoreRead functions" $ do runDb $ do _ <- get (PersonKey 3) _ <- getMany [PersonKey 1, PersonKey 2] pure () it "type checks on all PersistQueryRead functions" $ do runDb $ do _ <- selectList personFilters [] _ <- count personFilters pure () it "type checks on PersistUniqueRead functions" $ do runDb $ do _ <- getBy (PersonNameKey "Matt") pure () describe "SqlWriteBackend" $ do let runDb :: RunDb SqlWriteBackend m runDb = changeBackend SqlWriteBackend originalRunDb it "type checks on PersistStoreWrite and Read functions" $ do runDb $ do let person = Person "Matt Parsons" 30 Nothing k <- insert person mperson <- get k Just person @== mperson it "type checks on PersistQueryWrite and Read functions" $ do runDb $ do _ <- selectList personFilters [] updateWhere personFilters [] it "type checks on PersistUniqueWrite/Read functions" $ do runDb $ do let name_ = "Matt Parsons New" person = Person name_ 30 Nothing _mkey0 <- insertUnique person mkey1 <- insertUnique person mkey1 @== Nothing mperson <- selectFirst [PersonName ==. name_] [] fmap entityVal mperson @== Just person
yesodweb/persistent
persistent-test/src/ReadWriteTest.hs
mit
2,025
0
20
757
500
220
280
-1
-1
import Drawing import Exercises import Geometry main = drawPicture myPicture myPicture points = red ( drawPointsLabels [a,b,c,d] ["A","B","C","D"] & drawSegment (a,b) & drawSegment (b,c) & drawSegment (c,d) ) & faint ( drawCircle (b,a) & drawCircle (c,d) ) & draw (map (\x -> drawSegment (b,x) & drawSegment (c,x)) inter) & drawPointsLabels inter ["X","Y"] & message $ "Construct triangle with lengths" ++ ": AB=" ++ shownum (dist a b) ++ ", BC=" ++ shownum (dist b c) ++ ", CD=" ++ shownum (dist c d) where [a,b,c',d'] = take 4 points Just c = find_beyond (a,b) $ line_circle (a,b) (b,c') d = transport_beyond (c',d') (a,c) inter = circle_circle (b,a) (c,d)
alphalambda/hsmath
src/Learn/Geometry/ex10euclid1_22.hs
gpl-2.0
832
0
22
281
365
197
168
21
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.SQS.SetQueueAttributes -- 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) -- -- Sets the value of one or more queue attributes. When you change a -- queue\'s attributes, the change can take up to 60 seconds for most of -- the attributes to propagate throughout the SQS system. Changes made to -- the 'MessageRetentionPeriod' attribute can take up to 15 minutes. -- -- Going forward, new attributes might be added. If you are writing code -- that calls this action, we recommend that you structure your code so -- that it can handle new attributes gracefully. -- -- /See:/ <http://docs.aws.amazon.com/AWSSimpleQueueService/latest/APIReference/API_SetQueueAttributes.html AWS API Reference> for SetQueueAttributes. module Network.AWS.SQS.SetQueueAttributes ( -- * Creating a Request setQueueAttributes , SetQueueAttributes -- * Request Lenses , sqaQueueURL , sqaAttributes -- * Destructuring the Response , setQueueAttributesResponse , SetQueueAttributesResponse ) where import Network.AWS.Prelude import Network.AWS.Request import Network.AWS.Response import Network.AWS.SQS.Types import Network.AWS.SQS.Types.Product -- | /See:/ 'setQueueAttributes' smart constructor. data SetQueueAttributes = SetQueueAttributes' { _sqaQueueURL :: !Text , _sqaAttributes :: !(Map QueueAttributeName Text) } deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SetQueueAttributes' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'sqaQueueURL' -- -- * 'sqaAttributes' setQueueAttributes :: Text -- ^ 'sqaQueueURL' -> SetQueueAttributes setQueueAttributes pQueueURL_ = SetQueueAttributes' { _sqaQueueURL = pQueueURL_ , _sqaAttributes = mempty } -- | The URL of the Amazon SQS queue to take action on. sqaQueueURL :: Lens' SetQueueAttributes Text sqaQueueURL = lens _sqaQueueURL (\ s a -> s{_sqaQueueURL = a}); -- | A map of attributes to set. -- -- The following lists the names, descriptions, and values of the special -- request parameters the 'SetQueueAttributes' action uses: -- -- - 'DelaySeconds' - The time in seconds that the delivery of all -- messages in the queue will be delayed. An integer from 0 to 900 (15 -- minutes). The default for this attribute is 0 (zero). -- - 'MaximumMessageSize' - The limit of how many bytes a message can -- contain before Amazon SQS rejects it. An integer from 1024 bytes (1 -- KiB) up to 262144 bytes (256 KiB). The default for this attribute is -- 262144 (256 KiB). -- - 'MessageRetentionPeriod' - The number of seconds Amazon SQS retains -- a message. Integer representing seconds, from 60 (1 minute) to -- 1209600 (14 days). The default for this attribute is 345600 (4 -- days). -- - 'Policy' - The queue\'s policy. A valid AWS policy. For more -- information about policy structure, see -- <http://docs.aws.amazon.com/IAM/latest/UserGuide/PoliciesOverview.html Overview of AWS IAM Policies> -- in the /Amazon IAM User Guide/. -- - 'ReceiveMessageWaitTimeSeconds' - The time for which a -- ReceiveMessage call will wait for a message to arrive. An integer -- from 0 to 20 (seconds). The default for this attribute is 0. -- - 'VisibilityTimeout' - The visibility timeout for the queue. An -- integer from 0 to 43200 (12 hours). The default for this attribute -- is 30. For more information about visibility timeout, see Visibility -- Timeout in the /Amazon SQS Developer Guide/. -- - 'RedrivePolicy' - The parameters for dead letter queue functionality -- of the source queue. For more information about RedrivePolicy and -- dead letter queues, see Using Amazon SQS Dead Letter Queues in the -- /Amazon SQS Developer Guide/. sqaAttributes :: Lens' SetQueueAttributes (HashMap QueueAttributeName Text) sqaAttributes = lens _sqaAttributes (\ s a -> s{_sqaAttributes = a}) . _Map; instance AWSRequest SetQueueAttributes where type Rs SetQueueAttributes = SetQueueAttributesResponse request = postQuery sQS response = receiveNull SetQueueAttributesResponse' instance ToHeaders SetQueueAttributes where toHeaders = const mempty instance ToPath SetQueueAttributes where toPath = const "/" instance ToQuery SetQueueAttributes where toQuery SetQueueAttributes'{..} = mconcat ["Action" =: ("SetQueueAttributes" :: ByteString), "Version" =: ("2012-11-05" :: ByteString), "QueueUrl" =: _sqaQueueURL, toQueryMap "Attribute" "Name" "Value" _sqaAttributes] -- | /See:/ 'setQueueAttributesResponse' smart constructor. data SetQueueAttributesResponse = SetQueueAttributesResponse' deriving (Eq,Read,Show,Data,Typeable,Generic) -- | Creates a value of 'SetQueueAttributesResponse' with the minimum fields required to make a request. -- setQueueAttributesResponse :: SetQueueAttributesResponse setQueueAttributesResponse = SetQueueAttributesResponse'
fmapfmapfmap/amazonka
amazonka-sqs/gen/Network/AWS/SQS/SetQueueAttributes.hs
mpl-2.0
5,739
0
11
1,148
493
310
183
62
1
{-# LANGUAGE NamedFieldPuns #-} {- | Module : Neovim.Debug Description : Utilities to debug Neovim and nvim-hs functionality Copyright : (c) Sebastian Witte License : Apache-2.0 Maintainer : woozletoff@gmail.com Stability : experimental Portability : GHC -} module Neovim.Debug ( debug, debug', NvimHSDebugInstance(..), develMain, quitDevelMain, restartDevelMain, printGlobalFunctionMap, runNeovim, runNeovim', module Neovim, ) where import Neovim import Neovim.Classes import Neovim.Context (runNeovim) import qualified Neovim.Context.Internal as Internal import Neovim.Log (disableLogger) import Neovim.Main (CommandLineOptions (..), runPluginProvider) import Neovim.RPC.Common (RPCConfig) import Control.Monad import qualified Data.Map as Map import Foreign.Store import UnliftIO.Async (Async, async, cancel) import UnliftIO.Concurrent (putMVar, takeMVar) import UnliftIO.STM import Data.Text.Prettyprint.Doc (nest, softline, vcat, vsep) import Prelude -- | Run a 'Neovim' function. -- -- This function connects to the socket pointed to by the environment variable -- @$NVIM_LISTEN_ADDRESS@ and executes the command. It does not register itself -- as a real plugin provider, you can simply call neovim-functions from the -- module "Neovim.API.String" this way. -- -- Tip: If you run a terminal inside a neovim instance, then this variable is -- automatically set. debug :: env -> Internal.Neovim env a -> IO (Either (Doc AnsiStyle) a) debug env a = disableLogger $ do runPluginProvider def { envVar = True } Nothing transitionHandler where transitionHandler tids cfg = takeMVar (Internal.transitionTo cfg) >>= \case Internal.Failure e -> return $ Left e Internal.InitSuccess -> do res <- Internal.runNeovimInternal return (cfg { Internal.customConfig = env, Internal.pluginSettings = Nothing }) a mapM_ cancel tids return res _ -> return . Left $ "Unexpected transition state." -- | Run a 'Neovim'' function. -- -- @ -- debug' = debug () -- @ -- -- See documentation for 'debug'. debug' :: Internal.Neovim () a -> IO (Either (Doc AnsiStyle) a) debug' = debug () -- | Simple datatype storing neccessary information to start, stop and reload a -- set of plugins. This is passed to most of the functions in this module for -- storing state even when the ghci-session has been reloaded. data NvimHSDebugInstance = NvimHSDebugInstance { threads :: [Async ()] , neovimConfig :: NeovimConfig , internalConfig :: Internal.Config RPCConfig } -- | This function is intended to be run _once_ in a ghci session that to -- give a REPL based workflow when developing a plugin. -- -- Note that the dyre-based reload mechanisms, i.e. the -- "Neovim.Plugin.ConfigHelper" plugin, is not started this way. -- -- To use this in ghci, you simply bind the results to some variables. After -- each reload of ghci, you have to rebind those variables. -- -- Example: -- -- @ -- λ di <- 'develMain' 'Nothing' -- -- λ 'runNeovim'' di \$ vim_call_function \"getqflist\" [] -- 'Right' ('Right' ('ObjectArray' [])) -- -- λ :r -- -- λ di <- 'develMain' 'Nothing' -- @ -- -- You can also create a GHCI alias to get rid of most the busy-work: -- @ -- :def! x \\_ -> return \":reload\\nJust di <- develMain 'defaultConfig'{ 'plugins' = [ myDebugPlugin ] }\" -- @ -- develMain :: NeovimConfig -> IO (Maybe NvimHSDebugInstance) develMain neovimConfig = lookupStore 0 >>= \case Nothing -> do x <- disableLogger $ runPluginProvider def{ envVar = True } (Just neovimConfig) transitionHandler void $ newStore x return x Just x -> readStore x where transitionHandler tids cfg = takeMVar (Internal.transitionTo cfg) >>= \case Internal.Failure e -> do putDoc e return Nothing Internal.InitSuccess -> do transitionHandlerThread <- async $ do void $ transitionHandler (tids) cfg return . Just $ NvimHSDebugInstance { threads = (transitionHandlerThread:tids) , neovimConfig = neovimConfig , internalConfig = cfg } Internal.Quit -> do lookupStore 0 >>= \case Nothing -> return () Just x -> deleteStore x mapM_ cancel tids putStrLn "Quit develMain" return Nothing _ -> do putStrLn $ "Unexpected transition state for develMain." return Nothing -- | Quit a previously started plugin provider. quitDevelMain :: NvimHSDebugInstance -> IO () quitDevelMain NvimHSDebugInstance{internalConfig} = putMVar (Internal.transitionTo internalConfig) Internal.Quit -- | Restart the development plugin provider. restartDevelMain :: NvimHSDebugInstance -> IO (Maybe NvimHSDebugInstance) restartDevelMain di = do quitDevelMain di develMain (neovimConfig di) -- | Convenience function to run a stateless 'Neovim' function. runNeovim' :: NFData a => NvimHSDebugInstance -> Neovim () a -> IO (Either (Doc AnsiStyle) a) runNeovim' NvimHSDebugInstance{internalConfig} = runNeovim (Internal.retypeConfig () (internalConfig)) -- | Print the global function map to the console. printGlobalFunctionMap :: NvimHSDebugInstance -> IO () printGlobalFunctionMap NvimHSDebugInstance{internalConfig} = do es <- fmap Map.toList . atomically $ readTMVar (Internal.globalFunctionMap internalConfig) let header = "Printing global function map:" funs = map (\(fname, (d, f)) -> nest 3 (pretty fname <> softline <> "->" <> softline <> pretty d <+> ":" <+> pretty f)) es putDoc $ nest 2 $ vsep [header, vcat funs, mempty]
saep/nvim-hs
library/Neovim/Debug.hs
apache-2.0
6,587
0
21
2,114
1,149
613
536
-1
-1
{-# Language FlexibleInstances #-} module Network.IPTables.IsabelleToString where import qualified Network.IPTables.Generated as Isabelle type Word32 = Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 Isabelle.Num1)))) type Word128 = Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 (Isabelle.Bit0 Isabelle.Num1)))))) instance Show a => Show (Isabelle.Negation_type a) where show (Isabelle.Pos x) = "Pos " ++ show x show (Isabelle.Neg x) = "Neg " ++ show x instance Show Isabelle.Nat where show n = "Nat " ++ show (Isabelle.integer_of_nat n) instance Show (Isabelle.Common_primitive Word32) where show = Isabelle.common_primitive_ipv4_toString instance Show (Isabelle.Common_primitive Word128) where show = Isabelle.common_primitive_ipv6_toString instance Show Isabelle.Action where show = Isabelle.action_toString instance Show (Isabelle.Simple_rule Word32) where show = Isabelle.simple_rule_ipv4_toString instance Show (Isabelle.Simple_rule Word128) where show = Isabelle.simple_rule_ipv6_toString instance Show Isabelle.Iface where show (Isabelle.Iface i) = i instance Show (Isabelle.Ipt_iprange Word32) where show = Isabelle.ipt_ipv4range_toString instance Show (Isabelle.Ipt_iprange Word128) where show = Isabelle.ipt_ipv6range_toString instance Show (Isabelle.Match_expr (Isabelle.Common_primitive Word32)) where show = Isabelle.common_primitive_match_expr_ipv4_toString instance Show (Isabelle.Match_expr (Isabelle.Common_primitive Word128)) where show = Isabelle.common_primitive_match_expr_ipv6_toString instance Show (Isabelle.Rule (Isabelle.Common_primitive Word32)) where --TODO: unify with Isabelle.common_primitive_rule_toString show (Isabelle.Rule m a) = "(" ++ show m ++ ", " ++ show a ++ ")" instance Show (Isabelle.Rule (Isabelle.Common_primitive Word128)) where --TODO: unify with Isabelle.common_primitive_rule_toString show (Isabelle.Rule m a) = "(" ++ show m ++ ", " ++ show a ++ ")" {- I'm hesitant to make an instance (Show (Isabelle.Word Word32)), there may be other things than IP addresses -} instance Show (Isabelle.Prefix_match Word32) where show = Isabelle.prefix_match_32_toString instance Show (Isabelle.Prefix_match Word128) where show = Isabelle.prefix_match_128_toString instance Show (Isabelle.Routing_rule_ext Word32 ()) where show = Isabelle.routing_rule_32_toString instance Show (Isabelle.Routing_rule_ext Word128 ()) where show = Isabelle.routing_rule_128_toString
diekmann/Iptables_Semantics
haskell_tool/lib/Network/IPTables/IsabelleToString.hs
bsd-2-clause
2,671
0
18
460
699
359
340
45
0
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} module Distribution.Types.ExeDependency ( ExeDependency(..) , qualifiedExeName ) where import Prelude () import Distribution.Compat.Prelude import Distribution.Types.ComponentName import Distribution.Types.UnqualComponentName import Distribution.Types.PackageName import Distribution.Version ( VersionRange, anyVersion ) import qualified Distribution.Compat.ReadP as Parse import Distribution.Compat.ReadP import Distribution.Text import Text.PrettyPrint ((<+>), text) -- | Describes a dependency on an executable from a package -- data ExeDependency = ExeDependency PackageName UnqualComponentName -- name of executable component of package VersionRange deriving (Generic, Read, Show, Eq, Typeable, Data) instance Binary ExeDependency instance NFData ExeDependency where rnf = genericRnf instance Text ExeDependency where disp (ExeDependency name exe ver) = (disp name <<>> text ":" <<>> disp exe) <+> disp ver parse = do name <- parse _ <- Parse.char ':' exe <- parse Parse.skipSpaces ver <- parse <++ return anyVersion Parse.skipSpaces return (ExeDependency name exe ver) qualifiedExeName :: ExeDependency -> ComponentName qualifiedExeName (ExeDependency _ ucn _) = CExeName ucn
themoritz/cabal
Cabal/Distribution/Types/ExeDependency.hs
bsd-3-clause
1,434
0
10
334
316
172
144
34
1
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Test.Framework (defaultMain, testGroup) import Test.Framework.Providers.HUnit import Test.Framework.Providers.QuickCheck2 (testProperty) import Test.QuickCheck import Test.HUnit import qualified Data.Set as S import Data.List import Control.Monad (liftM) main = defaultMain tests tests = [] -- testGroup "SemiRing Props" [ -- testProperty "semiProb bool" prop_boolRing, --instance Arbitrary Prob where -- arbitrary = Prob `liftM` choose (0.0, 1.0)
srush/ProbDist
tests/Tests.hs
bsd-3-clause
555
0
5
104
89
58
31
12
1
module Dump(trace, traceM) where import GHC.IO trace :: String -> a -> a trace msg x = unsafePerformIO $ do putStrLn msg return(x) traceM :: Monad m => String -> m() traceM msg = trace msg $ return()
ml9951/ghc
libraries/pastm/examples/damp-comparing-linked-lists/Dump.hs
bsd-3-clause
254
0
9
92
100
50
50
9
1
-- Time-stamp: <2010-05-13 23:35:27 cklin> module Types where import Control.Monad (guard) import Data.List ((\\), intercalate, nub) import qualified Data.Map as Map import Common --------- Program abstract syntax tree types type Ident = String type Branch = (Pat, Term) data Term = Var Ident | Con String | Int Integer | App Term Term | Lam Ident Term | Let [(Ident, Term)] Term | Case Term [Branch] deriving (Eq, Show) data Pat = PatCon String [Ident] | PatInt Integer deriving Eq data Type = TyVar Ident | TyCon String [Type] | TyMeta Int | TySkol Int deriving Eq data Data = Data String [Ident] deriving (Eq, Show) data Cons = Cons String Type deriving (Eq, Show) data Program = Value Ident Term | Decl Data [Cons] | Info [String] deriving (Eq, Show) --------- Lexical analyzer token types data Terminal = LexOp -- + | LexDef -- = | LexArr -- -> | LexLam -- \ | LexSemi -- ; | LexComa -- , | LexType -- :: | LexParL -- ( | LexParR -- ) | LexBraL -- { | LexBraR -- } | LexVar Ident -- identifier | LexCon String -- Constructor | LexInt Integer -- 42 | LexData -- data (keyword) | LexWhere -- where (keyword) | LexCase -- case (keyword) | LexOf -- of (keyword) | LexLet -- let (keyword) | LexIn -- in (keyword) | LexNext | LexDoc String | LexError deriving (Eq, Show) --------- Type inference engine data structures type Subst = Map.Map Int Type type Rename = Map.Map Int Int type Type2 = (Type, Type) -- The (polymorphic) variable types and the (polymorphic) data -- constructor types no longer contain a list of their free type -- variables because the list is easily reconstructed with freeType. data VarTy = VarTy Type data ConsTy = ConsTy Type type VarE = Map.Map Ident VarTy type ConsE = Map.Map String ConsTy mapVarE :: Endo Type -> Endo VarE mapVarE = Map.map . mapVarTy mapVarTy :: Endo Type -> Endo VarTy mapVarTy f (VarTy t) = VarTy (f t) --------- Frequently used types botType = TyVar "a" intType = TyCon "Int" [] arrType t1 t2 = TyCon "->" [t1, t2] plusType = arrType intType (arrType intType intType) tupleType = arrType varx (arrType vary tuple) where tuple = TyCon "," [varx, vary] varx = TyVar "x" vary = TyVar "y" --------- General type utility functions metaP :: Type -> Bool metaP (TyMeta _) = True metaP _ = False consP :: Type -> Bool consP (TyCon _ _) = True consP _ = False deCons :: [Type] -> Maybe (String, [[Type]]) deCons tx = let consTc (TyCon tc _) = tc consAx (TyCon _ ax) = ax in do guard (tx /= []) guard (all consP tx) guard (same (map consTc tx)) return (consTc (head tx), map consAx tx) -- Collect free or meta type variables in either a type or a type -- environment. collectType :: Eq a => Endo (Type -> [a]) collectType f = walk where walk (TyCon _ tas) = unions (map walk tas) walk t = f t freeType :: Type -> [Ident] freeType = collectType free where free (TyVar tv) = [tv] free _ = [] skolType :: Type -> [Int] skolType = collectType skol where skol (TySkol idx) = [idx] skol _ = [] skolTypes :: [Type] -> [Int] skolTypes = unionMap skolType metaType :: Type -> [Int] metaType = collectType meta where meta (TyMeta idx) = [idx] meta _ = [] metaTypes :: [Type] -> [Int] metaTypes = unionMap metaType metaVarE :: VarE -> [Int] metaVarE = unionMap (metaType . unwrap) . Map.elems where unwrap (VarTy t) = t -- Separate the type of a user-defined data constructor into a list of -- argument types and the range type. Used in pattern matching. spine :: Type -> ([Type], Type) spine = walk [] where walk ax (TyCon "->" [t1, t2]) = walk (t1:ax) t2 walk ax t = if consP t then (reverse ax, t) else bug "Malformed data constructor type" -- Check if a meta type variable appears in multiple elements of the -- list of types. Multiple occurrences in one element does not count. multiP :: [Type] -> Int -> Bool multiP tx = flip elem multi where skol = concat (map skolType tx) meta = concat (map metaType tx) tvs = meta ++ skol multi = nub (tvs \\ nub tvs) --------- Pretty-printing types and constraints instance Show Pat where show (PatCon "," ax) = paren (intercalate ", " ax) show (PatCon tc ax) = unwords (tc:ax) show (PatInt i) = show i instance Show Type where show = showType showType (TyVar tv) = tv showType (TyMeta idx) = '?' : show idx showType (TySkol idx) = '!' : show idx showType (TyCon "->" [t1, t2]) = unwords [showType1 t1, "->", showType t2] showType (TyCon "," [t1, t2]) = paren (concat [showType1 t1, ", ", showType t2]) showType (TyCon tc ax) = unwords (tc : map showType2 ax) paren :: String -> String paren str = concat ["(", str, ")"] showType1 t@(TyCon "->" _) = paren (showType t) showType1 t = showType t showType2 t@(TyCon "," _) = showType t showType2 t@(TyCon _ (_:_)) = paren (showType t) showType2 t = showType1 t showLocal :: (Ident, VarTy) -> String showLocal (x, vt) = unwords [x, "::", show vt] instance Show VarTy where show (VarTy t) = showPolyType t instance Show ConsTy where show (ConsTy t) = showPolyType t showPolyType t = quant ++ show t where btvx = freeType t only ax s = if null ax then "" else s quant = only btvx (unwords ("forall" : btvx) ++ ". ")
minad/omega
vendor/algorithm-p/Types.hs
bsd-3-clause
5,767
0
13
1,677
1,942
1,049
893
162
3
{-# Language TemplateHaskell #-} {-# OPTIONS_GHC -Wall #-} module Main (main) where import Distribution.Package (PackageName(..), PackageIdentifier(..), PackageInstalled) import Distribution.PackageDescription ( PackageDescription() ) import Distribution.InstalledPackageInfo (InstalledPackageInfo, libraryDirs, hsLibraries, extraLibraries, sourcePackageId, license, copyright, author) import Distribution.Simple ( defaultMainWithHooks, UserHooks(..), simpleUserHooks ) import Distribution.Simple.Utils ( rewriteFile, createDirectoryIfMissingVerbose ) import Distribution.Simple.BuildPaths ( autogenModulesDir ) import Distribution.Simple.Setup ( ConfigFlags(configVerbosity,configProfLib), fromFlag, fromFlagOrDefault) import Distribution.Simple.LocalBuildInfo import Distribution.Simple.PackageIndex import Distribution.Verbosity ( Verbosity ) import Distribution.License (License(..)) import Data.Char (isAscii) import Data.Graph (topSort) import Data.Version (showVersion) import System.FilePath import Distribution.Package import Language.Haskell.TH main :: IO () main = defaultMainWithHooks simpleUserHooks { postConf = \args flags pkg lbi -> do generateBuildModule (fromFlag (configVerbosity flags)) pkg lbi postConf simpleUserHooks args flags pkg lbi } -- | Generate a part of a Makefile which contains all libraries and -- include locations used by the Cabal library. generateBuildModule :: Verbosity -> PackageDescription -> LocalBuildInfo -> IO () generateBuildModule verbosity pkgDesc lbi = do let autodir = autogenModulesDir lbi createDirectoryIfMissingVerbose verbosity True autodir let installDirs = absoluteInstallDirs pkgDesc lbi NoCopyDest withLibLBI pkgDesc lbi $ \_ libLBI -> do let thisLib = libPackageKey libLBI let pkgs = orderedPackagesList (installedPkgs lbi) libdirs = libdir installDirs : concatMap libraryDirs pkgs libNames = thisLib : map threadedVersion (concatMap hsLibraries pkgs) mkLibName x | fromFlagOrDefault False (configProfLib (configFlags lbi)) = x ++ "_p" | otherwise = x case filter (not . goodLicense . license) pkgs of [] -> return () bad -> print bad >> fail "BAD LICENSE" -- rewriteFile tries to decode the file to check for changes but only -- supports ASCII rewriteFile (autodir </> "HS_COPYRIGHTS") $ filter isAscii $ unlines $ map licenseInfoString pkgs rewriteFile (autodir </> "HS_LIBRARIES_LIST") $ unlines $ map mkLibName libNames rewriteFile (autodir </> "HS_LIBRARY_PATHS_LIST") $ unlines libdirs rewriteFile (autodir </> "EXTRA_LIBRARIES_LIST") $ unlines $ extraLibraries =<< pkgs orderedPackagesList :: PackageInstalled a => PackageIndex a -> [a] orderedPackagesList pkgs = lookupVertex <$> topSort g where (g, lookupVertex, _findVertex) = dependencyGraph pkgs goodLicense :: License -> Bool goodLicense BSD2 = True goodLicense BSD3 = True goodLicense MIT = True goodLicense ISC = True goodLicense _ = False licenseInfoString :: InstalledPackageInfo -> String licenseInfoString pkg = unwords [ unPackageName (pkgName (sourcePackageId pkg)) ++ "-" ++ showVersion (pkgVersion (sourcePackageId pkg)) , "-" , show (license pkg) , "-" , copyright pkg , "-" , author pkg ] -- We needed the threaded run-time so that SIGINT can be handled -- cleanly when C code has called into Haskell threadedVersion :: String -> String threadedVersion lib = case lib of "Cffi" -> "Cffi_thr" "HSrts" -> "HSrts_thr" _ -> lib libPackageKey :: ComponentLocalBuildInfo -> String libPackageKey x = $( do mbSUI <- lookupValueName "SimpleUnitId" mbCI <- lookupValueName "ComponentId" mbCUI <- lookupValueName "componentUnitId" mbLN <- lookupValueName "LibraryName" mbCL <- lookupValueName "componentLibraries" y <- newName "y" case (mbSUI, mbCI, mbCUI, mbLN, mbCL) of -- Cabal-1.24 (Just sui, Just ci, Just cui, _, _) -> [| case $(varE cui) x of $(conP sui [conP ci [varP y]]) -> "HS" ++ $(varE y) |] -- Cabal-1.22 (_,_,_,Just ln, Just cl) -> [| case $(varE cl) x of [$(conP ln [varP y])] -> $(varE y) _ -> error "libPackageKey: bad componentLibraries" |] _ -> fail "Setup.hs, libPackageKey: Unsupported Cabal version" ) -- where -- SimpleUnitId (ComponentId y) = componentUnitId x -- [LibraryName y] = componentLibraries x
GaloisInc/galua
galua/Setup.hs
mit
4,692
0
21
1,082
1,087
572
515
105
4
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module TrieMap( -- * Maps over 'Maybe' values MaybeMap, -- * Maps over 'List' values ListMap, -- * Maps over 'Literal's LiteralMap, -- * 'TrieMap' class TrieMap(..), insertTM, deleteTM, -- * Things helpful for adding additional Instances. (>.>), (|>), (|>>), XT, foldMaybe, -- * Map for leaf compression GenMap, lkG, xtG, mapG, fdG, xtList, lkList ) where import GhcPrelude import Literal import UniqDFM import Unique( Unique ) import qualified Data.Map as Map import qualified Data.IntMap as IntMap import Outputable import Control.Monad( (>=>) ) {- This module implements TrieMaps, which are finite mappings whose key is a structured value like a CoreExpr or Type. This file implements tries over general data structures. Implementation for tries over Core Expressions/Types are available in coreSyn/TrieMap. The regular pattern for handling TrieMaps on data structures was first described (to my knowledge) in Connelly and Morris's 1995 paper "A generalization of the Trie Data Structure"; there is also an accessible description of the idea in Okasaki's book "Purely Functional Data Structures", Section 10.3.2 ************************************************************************ * * The TrieMap class * * ************************************************************************ -} type XT a = Maybe a -> Maybe a -- How to alter a non-existent elt (Nothing) -- or an existing elt (Just) class TrieMap m where type Key m :: * emptyTM :: m a lookupTM :: forall b. Key m -> m b -> Maybe b alterTM :: forall b. Key m -> XT b -> m b -> m b mapTM :: (a->b) -> m a -> m b foldTM :: (a -> b -> b) -> m a -> b -> b -- The unusual argument order here makes -- it easy to compose calls to foldTM; -- see for example fdE below insertTM :: TrieMap m => Key m -> a -> m a -> m a insertTM k v m = alterTM k (\_ -> Just v) m deleteTM :: TrieMap m => Key m -> m a -> m a deleteTM k m = alterTM k (\_ -> Nothing) m ---------------------- -- Recall that -- Control.Monad.(>=>) :: (a -> Maybe b) -> (b -> Maybe c) -> a -> Maybe c (>.>) :: (a -> b) -> (b -> c) -> a -> c -- Reverse function composition (do f first, then g) infixr 1 >.> (f >.> g) x = g (f x) infixr 1 |>, |>> (|>) :: a -> (a->b) -> b -- Reverse application x |> f = f x ---------------------- (|>>) :: TrieMap m2 => (XT (m2 a) -> m1 (m2 a) -> m1 (m2 a)) -> (m2 a -> m2 a) -> m1 (m2 a) -> m1 (m2 a) (|>>) f g = f (Just . g . deMaybe) deMaybe :: TrieMap m => Maybe (m a) -> m a deMaybe Nothing = emptyTM deMaybe (Just m) = m {- ************************************************************************ * * IntMaps * * ************************************************************************ -} instance TrieMap IntMap.IntMap where type Key IntMap.IntMap = Int emptyTM = IntMap.empty lookupTM k m = IntMap.lookup k m alterTM = xtInt foldTM k m z = IntMap.foldr k z m mapTM f m = IntMap.map f m xtInt :: Int -> XT a -> IntMap.IntMap a -> IntMap.IntMap a xtInt k f m = IntMap.alter f k m instance Ord k => TrieMap (Map.Map k) where type Key (Map.Map k) = k emptyTM = Map.empty lookupTM = Map.lookup alterTM k f m = Map.alter f k m foldTM k m z = Map.foldr k z m mapTM f m = Map.map f m {- Note [foldTM determinism] ~~~~~~~~~~~~~~~~~~~~~~~~~ We want foldTM to be deterministic, which is why we have an instance of TrieMap for UniqDFM, but not for UniqFM. Here's an example of some things that go wrong if foldTM is nondeterministic. Consider: f a b = return (a <> b) Depending on the order that the typechecker generates constraints you get either: f :: (Monad m, Monoid a) => a -> a -> m a or: f :: (Monoid a, Monad m) => a -> a -> m a The generated code will be different after desugaring as the dictionaries will be bound in different orders, leading to potential ABI incompatibility. One way to solve this would be to notice that the typeclasses could be sorted alphabetically. Unfortunately that doesn't quite work with this example: f a b = let x = a <> a; y = b <> b in x where you infer: f :: (Monoid m, Monoid m1) => m1 -> m -> m1 or: f :: (Monoid m1, Monoid m) => m1 -> m -> m1 Here you could decide to take the order of the type variables in the type according to depth first traversal and use it to order the constraints. The real trouble starts when the user enables incoherent instances and the compiler has to make an arbitrary choice. Consider: class T a b where go :: a -> b -> String instance (Show b) => T Int b where go a b = show a ++ show b instance (Show a) => T a Bool where go a b = show a ++ show b f = go 10 True GHC is free to choose either dictionary to implement f, but for the sake of determinism we'd like it to be consistent when compiling the same sources with the same flags. inert_dicts :: DictMap is implemented with a TrieMap. In getUnsolvedInerts it gets converted to a bag of (Wanted) Cts using a fold. Then in solve_simple_wanteds it's merged with other WantedConstraints. We want the conversion to a bag to be deterministic. For that purpose we use UniqDFM instead of UniqFM to implement the TrieMap. See Note [Deterministic UniqFM] in UniqDFM for more details on how it's made deterministic. -} instance TrieMap UniqDFM where type Key UniqDFM = Unique emptyTM = emptyUDFM lookupTM k m = lookupUDFM m k alterTM k f m = alterUDFM f m k foldTM k m z = foldUDFM k z m mapTM f m = mapUDFM f m {- ************************************************************************ * * Maybes * * ************************************************************************ If m is a map from k -> val then (MaybeMap m) is a map from (Maybe k) -> val -} data MaybeMap m a = MM { mm_nothing :: Maybe a, mm_just :: m a } instance TrieMap m => TrieMap (MaybeMap m) where type Key (MaybeMap m) = Maybe (Key m) emptyTM = MM { mm_nothing = Nothing, mm_just = emptyTM } lookupTM = lkMaybe lookupTM alterTM = xtMaybe alterTM foldTM = fdMaybe mapTM = mapMb mapMb :: TrieMap m => (a->b) -> MaybeMap m a -> MaybeMap m b mapMb f (MM { mm_nothing = mn, mm_just = mj }) = MM { mm_nothing = fmap f mn, mm_just = mapTM f mj } lkMaybe :: (forall b. k -> m b -> Maybe b) -> Maybe k -> MaybeMap m a -> Maybe a lkMaybe _ Nothing = mm_nothing lkMaybe lk (Just x) = mm_just >.> lk x xtMaybe :: (forall b. k -> XT b -> m b -> m b) -> Maybe k -> XT a -> MaybeMap m a -> MaybeMap m a xtMaybe _ Nothing f m = m { mm_nothing = f (mm_nothing m) } xtMaybe tr (Just x) f m = m { mm_just = mm_just m |> tr x f } fdMaybe :: TrieMap m => (a -> b -> b) -> MaybeMap m a -> b -> b fdMaybe k m = foldMaybe k (mm_nothing m) . foldTM k (mm_just m) {- ************************************************************************ * * Lists * * ************************************************************************ -} data ListMap m a = LM { lm_nil :: Maybe a , lm_cons :: m (ListMap m a) } instance TrieMap m => TrieMap (ListMap m) where type Key (ListMap m) = [Key m] emptyTM = LM { lm_nil = Nothing, lm_cons = emptyTM } lookupTM = lkList lookupTM alterTM = xtList alterTM foldTM = fdList mapTM = mapList instance (TrieMap m, Outputable a) => Outputable (ListMap m a) where ppr m = text "List elts" <+> ppr (foldTM (:) m []) mapList :: TrieMap m => (a->b) -> ListMap m a -> ListMap m b mapList f (LM { lm_nil = mnil, lm_cons = mcons }) = LM { lm_nil = fmap f mnil, lm_cons = mapTM (mapTM f) mcons } lkList :: TrieMap m => (forall b. k -> m b -> Maybe b) -> [k] -> ListMap m a -> Maybe a lkList _ [] = lm_nil lkList lk (x:xs) = lm_cons >.> lk x >=> lkList lk xs xtList :: TrieMap m => (forall b. k -> XT b -> m b -> m b) -> [k] -> XT a -> ListMap m a -> ListMap m a xtList _ [] f m = m { lm_nil = f (lm_nil m) } xtList tr (x:xs) f m = m { lm_cons = lm_cons m |> tr x |>> xtList tr xs f } fdList :: forall m a b. TrieMap m => (a -> b -> b) -> ListMap m a -> b -> b fdList k m = foldMaybe k (lm_nil m) . foldTM (fdList k) (lm_cons m) foldMaybe :: (a -> b -> b) -> Maybe a -> b -> b foldMaybe _ Nothing b = b foldMaybe k (Just a) b = k a b {- ************************************************************************ * * Basic maps * * ************************************************************************ -} type LiteralMap a = Map.Map Literal a {- ************************************************************************ * * GenMap * * ************************************************************************ Note [Compressed TrieMap] ~~~~~~~~~~~~~~~~~~~~~~~~~ The GenMap constructor augments TrieMaps with leaf compression. This helps solve the performance problem detailed in #9960: suppose we have a handful H of entries in a TrieMap, each with a very large key, size K. If you fold over such a TrieMap you'd expect time O(H). That would certainly be true of an association list! But with TrieMap we actually have to navigate down a long singleton structure to get to the elements, so it takes time O(K*H). This can really hurt on many type-level computation benchmarks: see for example T9872d. The point of a TrieMap is that you need to navigate to the point where only one key remains, and then things should be fast. So the point of a SingletonMap is that, once we are down to a single (key,value) pair, we stop and just use SingletonMap. 'EmptyMap' provides an even more basic (but essential) optimization: if there is nothing in the map, don't bother building out the (possibly infinite) recursive TrieMap structure! Compressed triemaps are heavily used by CoreMap. So we have to mark some things as INLINEABLE to permit specialization. -} data GenMap m a = EmptyMap | SingletonMap (Key m) a | MultiMap (m a) instance (Outputable a, Outputable (m a)) => Outputable (GenMap m a) where ppr EmptyMap = text "Empty map" ppr (SingletonMap _ v) = text "Singleton map" <+> ppr v ppr (MultiMap m) = ppr m -- TODO undecidable instance instance (Eq (Key m), TrieMap m) => TrieMap (GenMap m) where type Key (GenMap m) = Key m emptyTM = EmptyMap lookupTM = lkG alterTM = xtG foldTM = fdG mapTM = mapG --We want to be able to specialize these functions when defining eg --tries over (GenMap CoreExpr) which requires INLINEABLE {-# INLINEABLE lkG #-} lkG :: (Eq (Key m), TrieMap m) => Key m -> GenMap m a -> Maybe a lkG _ EmptyMap = Nothing lkG k (SingletonMap k' v') | k == k' = Just v' | otherwise = Nothing lkG k (MultiMap m) = lookupTM k m {-# INLINEABLE xtG #-} xtG :: (Eq (Key m), TrieMap m) => Key m -> XT a -> GenMap m a -> GenMap m a xtG k f EmptyMap = case f Nothing of Just v -> SingletonMap k v Nothing -> EmptyMap xtG k f m@(SingletonMap k' v') | k' == k -- The new key matches the (single) key already in the tree. Hence, -- apply @f@ to @Just v'@ and build a singleton or empty map depending -- on the 'Just'/'Nothing' response respectively. = case f (Just v') of Just v'' -> SingletonMap k' v'' Nothing -> EmptyMap | otherwise -- We've hit a singleton tree for a different key than the one we are -- searching for. Hence apply @f@ to @Nothing@. If result is @Nothing@ then -- we can just return the old map. If not, we need a map with *two* -- entries. The easiest way to do that is to insert two items into an empty -- map of type @m a@. = case f Nothing of Nothing -> m Just v -> emptyTM |> alterTM k' (const (Just v')) >.> alterTM k (const (Just v)) >.> MultiMap xtG k f (MultiMap m) = MultiMap (alterTM k f m) {-# INLINEABLE mapG #-} mapG :: TrieMap m => (a -> b) -> GenMap m a -> GenMap m b mapG _ EmptyMap = EmptyMap mapG f (SingletonMap k v) = SingletonMap k (f v) mapG f (MultiMap m) = MultiMap (mapTM f m) {-# INLINEABLE fdG #-} fdG :: TrieMap m => (a -> b -> b) -> GenMap m a -> b -> b fdG _ EmptyMap = \z -> z fdG k (SingletonMap _ v) = \z -> k v z fdG k (MultiMap m) = foldTM k m
sdiehl/ghc
compiler/utils/TrieMap.hs
bsd-3-clause
13,536
0
16
3,966
3,068
1,581
1,487
171
4
{-# OPTIONS_GHC -fplugin Simple.SourcePlugin #-} module A where
sdiehl/ghc
testsuite/tests/plugins/plugins11.hs
bsd-3-clause
64
0
2
8
5
4
1
2
0
#!/usr/bin/env runghc {-# LANGUAGE StandaloneDeriving #-} import MessageHandling import Text.Printf import Text.ParserCombinators.Parsec import System.Process import Data.Functor import Data.Maybe import Data.List import Control.Monad.Trans.Either import Control.Monad.Trans.Maybe import Control.Monad.Trans import Control.Monad import System.Exit import Test.QuickCheck import Test.QuickCheck.Gen import Test.QuickCheck.Monadic (assert, monadicIO, run) type IP = String type CIDR = String type ASN = Int --deriving instance Show PolicyResult deriving instance Show BGPPathAttributes deriving instance Show TraceError deriving instance Show Event deriving instance Show Setup deriving instance Show Match deriving instance Show Modify deriving instance Show Action -- deriving instance Show Rule ignore :: Parser b -> a -> Parser a ignore p a = p >> return a eol :: Parser () eol = (string "\n" <|> string "\r\n") >> return () decimal :: Parser Int decimal = read <$> many1 digit ip :: Int -> Int -> Int -> Int -> IP ip a b c d = printf "%d.%d.%d.%d" a b c d parseIP :: Parser IP parseIP = do a <- decimal char '.' b <- decimal char '.' c <- decimal char '.' d <- decimal return $ ip a b c d cidr :: IP -> Int -> CIDR cidr ip mask = printf "%s/%d" ip mask parseCIDR :: Parser CIDR parseCIDR = do ip <- parseIP char '/' mask <- decimal return $ cidr ip mask parsePath :: Parser [ASN] parsePath = (string "null" >> return []) <|> decimal `sepBy1` char ' ' -- described here: -- http://c-bgp.sourceforge.net/doc/html/nodes/bgp_router_show_rib.html parseAnnouncement :: Parser (Maybe (CIDR, BGPPathAttributes)) parseAnnouncement = parseNA <|> parseA where parseNA :: Parser (Maybe (CIDR, BGPPathAttributes)) parseNA = do string "(null)" return Nothing parseA :: Parser (Maybe (CIDR, BGPPathAttributes)) parseA = do char '*' <|> char 'i' char '>' <|> char ' ' char ' ' nlri <- parseCIDR char '\t' parseIP char '\t' pref <- decimal char '\t' decimal char '\t' path <- parsePath char '\t' char 'i' -- CBGP's trace doesn't contain the communities return . Just $ (nlri, Build_BGPPathAttributes pref [] path) parseASN :: Parser ASN parseASN = decimal parseRouter :: Parser (ASN, IP) parseRouter = do string "AS" as <- parseASN char ':' r <- parseIP return (as, r) parseMode :: Parser Mode parseMode = do m <- string "INT" <|> string "EXT" string " --> " m' <- string "INT" <|> string "EXT" return $ if m == "INT" && m' == "INT" then Ibgp else Ebgp -- policyResultParser :: Parser PolicyResult -- policyResultParser = try iBGPFilter <|> try ssldFilter <|> try srcFilter <|> fwdFilter -- where -- iBGPFilter = string "out-filtered(iBGP-peer --> iBGP-peer)" >> eol >> -- string "\tfiltered" >> eol >> return Filtered -- ssldFilter = string "out-filtered(ssld)" >> eol >> -- string "\tfiltered" >> eol >> return Filtered -- srcFilter = string "out-filtered(next-hop-peer)" >> eol >> -- string "\tfiltered" >> eol >> return Filtered -- fwdFilter = string "announce_route to " >> parseRouter >> eol >> -- string "\treplaced" >> eol >> return Replaced -- That up there? It's a smart parser. Instead, let's use a dumb parser. policyResultParser :: Parser PolicyResult policyResultParser = try filtered <|> replaced where filtered = manyTill anyChar eol >> string "\tfiltered" >> eol >> optional (string "\texplicit-withdraw" >> eol) >> return Filtered replaced = manyTill anyChar eol >> string "\treplaced" >> eol >> return Replaced parseDisseminate :: Parser ((ASN, IP), PolicyResult) parseDisseminate = do string "DISSEMINATE (" >> parseCIDR >> string ") from " >> parseRouter >> string " to " (as, r) <- parseRouter eol string "advertise_to_peer (" >> parseCIDR >> string ") from " >> parseRouter string " to " >> parseRouter >> string " (" >> parseMode >> char ')' >> eol res <- policyResultParser return ((as, r), res) parseRule :: Parser String parseRule = try (string "Lowest ORIGIN") <|> try (string "Lowest MED") <|> string "Lowest ROUTER-ID" <|> string "Highest LOCAL-PREF" <|> string "Shortest AS-PATH" <|> string "eBGP over iBGP" <|> string "Nearest NEXT-HOP" parseMessage :: Parser (Maybe (CIDR, BGPPathAttributes)) parseMessage = try parseUpdate <|> parseWithdraw where parseUpdate = do string "BGP_MSG_RCVD: UPDATE" >> eol string "BGP_FSM_STATE: ESTABLISHED" >> eol string "\tupdate: " parseAnnouncement parseWithdraw = do string "BGP_MSG_RCVD: WITHDRAW" >> eol string "BGP_FSM_STATE: ESTABLISHED" return Nothing parseDecisionProcess :: Parser (Maybe CIDR) parseDecisionProcess = do string "-------------------------------------------------------------------------------" >> eol string "DECISION PROCESS for " nlri <- parseCIDR string " in " >> parseRouter >> eol string "\told-best: " oldal <- parseAnnouncement eol ins <- many . try $ string "\teligible: " >> parseAnnouncement >>= ignore eol many $ string "rule: [ " >> parseRule >>= ignore (string " ]") >>= ignore eol string "\tnew-best: " al <- parseAnnouncement eol -- optional explanation optional ((try (string "different NEXT-HOP") <|> try (string "different LOCAL-PREFs") <|> try (string "different COMMUNITIES") <|> string "different AS-PATHs" ) >>= ignore eol) string "\t*** " string "NEW BEST ROUTE" <|> string "BEST ROUTE UNCHANGED" <|> string "UPDATED BEST ROUTE" <|> string "NO BEST ROUTE" string " ***" >> eol dissems <- many $ parseDisseminate string "-------------------------------------------------------------------------------" >> eol many $ string "\tremove: " >> parseAnnouncement >> eol return $ Just nlri parseDecision :: Parser (Maybe CIDR) parseDecision = do try parseDecisionProcess <|> return Nothing parseEvent :: Parser Event parseEvent = do string "=====<<< EVENT " e <- decimal char '.' >> decimal >> string " >>>=====" >> eol string "HANDLE_MESSAGE from " r' <- parseRouter string " in " r <- parseRouter eol ai <- parseMessage eol nlri <- parseDecision case (nlri, ai) of (Just p, Just (_, a)) -> eol >> (return $ Build_Event e r' r (Just p) (Just a)) (_, Just (p, a)) -> (string "in-filtered(filter)" >> eol >> eol >> (return $ Build_Event e r' r (Just p) (Just a))) (Just p, _) -> eol >> (return $ Build_Event e r' r (Just p) Nothing) _ -> eol >> (return $ Build_Event e r' r Nothing Nothing) parseCBGPTrace :: String -> Either ParseError [Event] parseCBGPTrace s = parse (many parseEvent >>= ignore eof) "" s cbgpConfig :: Setup -> String cbgpConfig setup = unlines $ createASes ++ createExternalLinks ++ [ printf "sim run" ] ++ createInjections ++ [ printf "sim options log-level everything", printf "sim run"] where createASes :: [String] createASes = do (as, rs) <- ases setup id [ printf "net add domain %d igp" as ] ++ createRouters as rs ++ createInternalLinks rs ++ [ printf "net domain %d compute" as, printf "bgp domain %d full-mesh" as] createRouters :: ASN -> [IP] -> [String] createRouters as rs = do r <- rs [ printf "net add node %s" r, printf "net node %s domain %d" r as, printf "bgp add router %d %s" as r] createInternalLinks :: [IP] -> [String] createInternalLinks rs = do r <- rs r' <- rs if r >= r' then [] else [ printf "net add link %s %s" r r', printf "net link %s %s igp-weight --bidir 1" r r'] createExternalLinks :: [String] createExternalLinks = do (pref, ((((as, r), i1), e1), (((as', r'), i2), e2))) <- zip [0,2..] $ links setup [ printf "net add link %s %s" r r' ] ++ createExternalBGPConfig pref r r' i1 e1 as' ++ createExternalBGPConfig (pref + 1) r' r i2 e2 as createExternalBGPConfig :: Int -> IP -> IP -> [Rule] -> [Rule] -> ASN -> [String] createExternalBGPConfig pref r r' i e as' = [ printf "net node %s route add --oif=%s %s/32 1" r r' r', printf "bgp router %s" r, printf " add peer %d %s" as' r', printf " peer %s next-hop-self" r', printf " peer %s filter in add-rule action \"local-pref %d\"" r' (pref + 100)] ++ map (\ s -> printf " peer %s filter in %s" r' s) (cbgpRules i) ++ map (\ s -> printf " peer %s filter out %s" r' s) (cbgpRules e) ++ [printf " peer %s up" r', printf " exit" ] createInjections :: [String] createInjections = do ((_,r),p) <- injections setup [ printf "bgp router %s add network %s" r p ] cbgpMatch :: Match -> String cbgpMatch RAny = "any" cbgpMatch (RNot m) = printf "! (%s)" (cbgpMatch m) cbgpMatch (RAnd m1 m2) = printf "(%s & %s)" (cbgpMatch m1) (cbgpMatch m2) cbgpMatch (ROr m1 m2) = printf "(%s | %s)" (cbgpMatch m1) (cbgpMatch m2) cbgpMatch (RCommunityIs c) = printf "community is %d" c cbgpAction :: Action -> String cbgpAction AAccept = "accept" cbgpAction AReject = "deny" cbgpAction (AModify (MAddCommunity c)) = printf "community add %d" c cbgpAction (AModify MStripCommunities) = "community strip" cbgpRules :: [Rule] -> [String] cbgpRules = map (\ (m, a) -> printf "add-rule\n match \"%s\"\n action \"%s\"\n exit" (cbgpMatch m) (cbgpAction a)) -- based on http://c-bgp.sourceforge.net/tutorial.php -- testSetup :: Setup -- testSetup = Build_Setup -- [(1, ["1.0.0.1", "1.0.0.2", "1.0.0.3"]), -- (2, ["2.0.0.1", "2.0.0.2", "2.0.0.3"]), -- (3, ["3.0.0.1"])] -- [((1, "1.0.0.1"), (2, "2.0.0.1")), ((1, "1.0.0.2"), (2, "2.0.0.2")), -- ((2, "2.0.0.3"), (3, "3.0.0.1"))] -- [((1, "1.0.0.1"), "11.0.0.0/24")] genASIP :: Int -> Gen String genASIP as = do x1 <- choose (0, 255) x2 <- choose (0, 255) x3 <- choose (0, 255) return $ ip as x1 x2 x3 genCommunity :: Gen Int genCommunity = do Positive c <- arbitrary return c genAS :: Int -> Gen (Int, [String]) genAS as = do x <- listOf1 (genASIP as) return $ (as, nub x) genASes :: Gen [(Int, [String])] genASes = do Positive numASes <- (arbitrary :: Gen (Positive Int)) `suchThat` (\ x -> (getPositive x) <= 255) sequence $ map genAS [1 .. numASes + 1] genRouter :: [(Int, [String])] -> Int -> Gen (Int, String) genRouter ases as = do ip <- elements $ snd $ ases !! (as - 1) return $ (as, ip) genLink' :: [(Int, [String])] -> Int -> Int -> Gen ((Int, String), (Int, String)) genLink' ases as1 as2 = do r1 <- genRouter ases as1 r2 <- genRouter ases as2 return $ (r1, r2) genLink :: [(Int, [String])] -> Gen ((Int, String), (Int, String)) genLink ases = do as1 <- choose (1, length ases - 1) as2 <- choose (as1 + 1, length ases) genLink' ases as1 as2 type LinkWithRules = ((((Int, String), [Rule]), [Rule]), (((Int, String), [Rule]), [Rule])) genMatch :: Int -> Gen Match genMatch 0 = oneof [liftM RCommunityIs genCommunity, return RAny] genMatch n | n>0 = oneof [liftM RCommunityIs genCommunity, return RAny, -- liftM RNot sub, liftM2 RAnd sub sub, liftM2 ROr sub sub] where sub = genMatch (n `div` 2) instance Arbitrary Match where arbitrary = sized genMatch instance Arbitrary Action where arbitrary = oneof [return AAccept, return AReject, return (AModify MStripCommunities), liftM (AModify . MAddCommunity) genCommunity] genRule :: Gen Rule genRule = do m <- arbitrary ac <- arbitrary return (m, ac) genRules :: Gen [Rule] genRules = listOf1 genRule genLinkWithRules :: [(Int, [String])] -> Gen LinkWithRules genLinkWithRules ases = do (l1, l2) <- genLink ases i1 <- genRules e1 <- genRules i2 <- genRules e2 <- genRules return $ (((l1, i1), e1), ((l2, i2), e2)) nubByKey :: Eq b => (a -> b) -> [a] -> [a] nubByKey f l = nubBy (\ x y -> f x == f y) l genLinks :: [(Int, [String])] -> Gen [LinkWithRules] genLinks ases = do links <- listOf1 $ genLinkWithRules ases return $ nubByKey linkWithoutRules links genIP :: Gen String genIP = do as <- choose (0, 255) genASIP as genSubnet :: Gen String genSubnet = do ip <- genIP sub <- (choose (1, 32) :: Gen Int) return $ ip ++ "/" ++ (show sub) genAnnouncement :: [(Int, [String])] -> Gen ((Int, String), String) genAnnouncement ases = do as <- choose (1, length ases - 1) router <- genRouter ases as subnet <- genSubnet return $ (router, subnet) genAnnouncements ases = do anns <- listOf1 $ genAnnouncement ases return $ nub anns smallerSubSequences :: Eq a => [a] => [[a]] smallerSubSequences l = filter (\x -> x /= l) (subsequences l) instance Arbitrary Setup where arbitrary = do ases <- genASes links <- genLinks ases announcements <- genAnnouncements ases return $ Build_Setup ases links announcements --shrink (Build_Setup ases links announcements) = --map (\links' -> Build_Setup ases links' announcements) (smallerSubSequences links) -- configs third :: (a,b,c) -> c third (_,_,c) = c applyInjections :: Setup -> [((ASN, IP), CIDR)] -> TraceExists -> EitherT TraceError IO TraceExists applyInjections _ [] ns = return ns applyInjections setup (i:is) ns = do -- liftIO . putStrLn . unlines $ show <$> debugTraceExists setup ns -- liftIO $ printf "injecting: %s\n" (show i) ns' <- hoistEither $ applyInjection setup i ns applyInjections setup is ns' applyEvents :: Setup -> [Event] -> TraceExists -> EitherT TraceError IO TraceExists applyEvents _ [] ns = return ns applyEvents setup (e:es) ns = do --liftIO . putStrLn . unlines $ show <$> debugTraceExists setup ns --liftIO $ printf "event: %s\n" (show e) ns' <- hoistEither $ applyEvent setup e ns applyEvents setup es ns' checkEvents :: Setup -> [Event] -> EitherT TraceError IO TraceExists checkEvents setup es = return (emptyNetwork setup) >>= applyInjections setup (injections setup) >>= applyEvents setup es -- assert that the network is now empty checkSetup :: Setup -> IO (Maybe TraceError) checkSetup setup = do config <- return $ cbgpConfig setup (_, _, trace) <- readProcessWithExitCode "cbgp" [] config e <- return $ parseCBGPTrace trace case e of Left err -> error $ printf "parse error on config %s" (show setup) Right events -> do result <- runEitherT $ checkEvents setup events return $ either Just (Prelude.const Nothing) result empty :: Maybe a -> Bool empty Nothing = True empty (Just _) = False verifyReturnsNothing :: Setup -> Property verifyReturnsNothing setup = monadicIO $ do run $ putStrLn $ show setup error <- run $ checkSetup setup assert $ empty error verify :: Setup -> IO () verify setup = do config <- return $ cbgpConfig setup (_, _, trace) <- readProcessWithExitCode "cbgp" [] config printf trace e <- return $ parseCBGPTrace trace case e of Left err -> error $ printf "parse error on config %s\n\n\n%s" (show setup) (show err) Right events -> do result <- runEitherT $ checkEvents setup events printf "error: %s\n" $ show $ either Just (Prelude.const Nothing) result test :: Setup -> IO Bool test setup = do result <- checkSetup setup --now <- getCurrentTime case result of Nothing -> putStrLn $ printf "SUCCESS" Just e -> putStrLn $ printf "FAILURE on config %s" $ show setup return $ empty result main :: IO () main = do setup <- generate (resize 8 arbitrary) result <- test setup if result then exitSuccess else exitFailure
konne88/bagpipe
src/bagpipe/coq/Test/TestCBGP.hs
mit
15,779
3
16
3,703
5,198
2,596
2,602
-1
-1
-- Get the mean of an array -- http://www.codewars.com/kata/563e320cee5dddcf77000158 module Codewars.AverageCalculator where getAverage :: [Int] -> Int getAverage marks = sum marks `div` length marks
gafiatulin/codewars
src/8 kyu/AverageCalculator.hs
mit
203
0
6
28
40
23
17
3
1
-- Author: Jayden Navarro -- Date: 1-15-2016 -- Class: CMPS 112 import Encode import Decode main = do putStrLn "Huffman Codes in Haskell" putChar '\n' encodeOutput putChar '\n' decodeOutput encodeOutput = do putStrLn "-- ENCODE EXAMPLE --" putStrLn "-> Inputs" putStrLn $ "String to encode: " ++ rawInput putStrLn "-> Outputs" putStrLn $ "Map: " ++ show charMap putStrLn $ "Bitstring: " ++ bitString putStrLn "-> Reversing operation..." putStrLn $ "Decoded string: " ++ decodedString where -- raw data rawInput = "Hello World!" -- constructed data (encoding) encodeObj = encode rawInput charMap = snd encodeObj bitString = fst encodeObj -- reversing the operation...(decoding) decodedString = decode bitString charMap decodeOutput = do putStrLn "-- DECODE EXAMPLE --" putStrLn "-> Inputs" putStrLn $ "Initial Map: " ++ show rawCharMap putStrLn $ "Bitstring to decode: " ++ rawBitString putStrLn "-> Outputs" putStrLn $ "Decoded string: " ++ decodedString putStrLn "-> Reversing operation..." putStrLn $ "Map: " ++ show charMap putStrLn $ "Bitstring: " ++ bitString where -- raw data rawBitString = "01001" rawCharMap = [('H',"01"),('i',"00"),('!',"1")] -- constructed data (decoding) decodedString = decode rawBitString rawCharMap -- reversing the operation...(encoding) encodeObj = encode decodedString charMap = snd encodeObj bitString = fst encodeObj
JDNdeveloper/Huffman-Codes
src/Haskell/main.hs
mit
1,477
0
8
320
325
157
168
38
1
module Data.NearestNeighbors ( NN(..) , LinearNN , mkLinearNN , KdTree , mkKdTreeNN ) where -- import Data.List (sortBy, foldl') import Data.List hiding (insert) import Data.Function (on) import Data.MotionPlanningProblem import qualified Data.KdMap.Static as KD class NN n where insert :: n k d -> k -> d -> n k d nearest :: n k d -> k -> (k,d) nearestK :: (Eq k) => n k d -> Int -> k -> [(k,d)] -- nearestR :: n k d -> Double -> k -> [(k,d)] size :: n k d -> Int toList :: n k d -> [(k,d)] -------------------------------------------------------------------------------- -- Linear nearest neighbors -------------------------------------------------------------------------------- data LinearNN k d = LinearNN (DistFn k) [(k,d)] instance NN LinearNN where insert (LinearNN dist elems) k d = LinearNN dist $ (k,d) : elems -- TODO why is this nice way just so much slower? :( -- nearest (LinearNN dist elems) k = minimumBy near elems -- where near = compare `on` (dist k . fst) nearest (LinearNN dist (e : es)) k = fst $ foldl' f (e, dist k $ fst e) es where {-# INLINE f #-} f b@(_, dBest) x | d < dBest = (x, d) | otherwise = b where d = dist k $ fst x nearest (LinearNN _ []) _ = error "LinearNN.nearest was called on an empty structure!" nearestK (LinearNN dist elems) k q = take k $ sortBy near elems where near = compare `on` (dist q . fst) -- nearestR (LinearNN dist elems) r q = filter withinRadius elems -- where withinRadius (e,_) = dist q e <= r*r size (LinearNN _ elems) = length elems toList (LinearNN _ elems) = elems mkLinearNN :: StateSpace s -> LinearNN s d mkLinearNN ss = LinearNN (_stateDistanceSqrd ss) [] -------------------------------------------------------------------------------- -- KdTree nearest neighbors -------------------------------------------------------------------------------- newtype KdTree p d = KdTree (KD.KdMap Double p d) instance NN KdTree where insert (KdTree t) k d = KdTree $ KD.insertUnbalanced t k d nearest (KdTree t) k = KD.nearest t k nearestK (KdTree t) k q = KD.kNearest t k q size (KdTree t) = KD.size t toList (KdTree t) = KD.assocs t mkKdTreeNN :: StateSpace p -> (p -> [Double]) -> KdTree p d mkKdTreeNN ss stateAsList = KdTree $ KD.emptyWithDist stateAsList (_stateDistanceSqrd ss)
giogadi/hs-motion-planning
lib-src/Data/NearestNeighbors.hs
mit
2,417
0
12
554
759
402
357
42
1
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.HTMLOutputElement (js_checkValidity, checkValidity, js_setCustomValidity, setCustomValidity, js_getHtmlFor, getHtmlFor, js_getForm, getForm, js_setName, setName, js_getName, getName, js_getType, getType, js_setDefaultValue, setDefaultValue, js_getDefaultValue, getDefaultValue, js_setValue, setValue, js_getValue, getValue, js_getWillValidate, getWillValidate, js_getValidity, getValidity, js_getValidationMessage, getValidationMessage, js_getLabels, getLabels, HTMLOutputElement, castToHTMLOutputElement, gTypeHTMLOutputElement) 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 (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) 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.Enums foreign import javascript unsafe "($1[\"checkValidity\"]() ? 1 : 0)" js_checkValidity :: JSRef HTMLOutputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.checkValidity Mozilla HTMLOutputElement.checkValidity documentation> checkValidity :: (MonadIO m) => HTMLOutputElement -> m Bool checkValidity self = liftIO (js_checkValidity (unHTMLOutputElement self)) foreign import javascript unsafe "$1[\"setCustomValidity\"]($2)" js_setCustomValidity :: JSRef HTMLOutputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.setCustomValidity Mozilla HTMLOutputElement.setCustomValidity documentation> setCustomValidity :: (MonadIO m, ToJSString error) => HTMLOutputElement -> Maybe error -> m () setCustomValidity self error = liftIO (js_setCustomValidity (unHTMLOutputElement self) (toMaybeJSString error)) foreign import javascript unsafe "$1[\"htmlFor\"]" js_getHtmlFor :: JSRef HTMLOutputElement -> IO (JSRef DOMSettableTokenList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.htmlFor Mozilla HTMLOutputElement.htmlFor documentation> getHtmlFor :: (MonadIO m) => HTMLOutputElement -> m (Maybe DOMSettableTokenList) getHtmlFor self = liftIO ((js_getHtmlFor (unHTMLOutputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"form\"]" js_getForm :: JSRef HTMLOutputElement -> IO (JSRef HTMLFormElement) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.form Mozilla HTMLOutputElement.form documentation> getForm :: (MonadIO m) => HTMLOutputElement -> m (Maybe HTMLFormElement) getForm self = liftIO ((js_getForm (unHTMLOutputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"name\"] = $2;" js_setName :: JSRef HTMLOutputElement -> JSString -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.name Mozilla HTMLOutputElement.name documentation> setName :: (MonadIO m, ToJSString val) => HTMLOutputElement -> val -> m () setName self val = liftIO (js_setName (unHTMLOutputElement self) (toJSString val)) foreign import javascript unsafe "$1[\"name\"]" js_getName :: JSRef HTMLOutputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.name Mozilla HTMLOutputElement.name documentation> getName :: (MonadIO m, FromJSString result) => HTMLOutputElement -> m result getName self = liftIO (fromJSString <$> (js_getName (unHTMLOutputElement self))) foreign import javascript unsafe "$1[\"type\"]" js_getType :: JSRef HTMLOutputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.type Mozilla HTMLOutputElement.type documentation> getType :: (MonadIO m, FromJSString result) => HTMLOutputElement -> m result getType self = liftIO (fromJSString <$> (js_getType (unHTMLOutputElement self))) foreign import javascript unsafe "$1[\"defaultValue\"] = $2;" js_setDefaultValue :: JSRef HTMLOutputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.defaultValue Mozilla HTMLOutputElement.defaultValue documentation> setDefaultValue :: (MonadIO m, ToJSString val) => HTMLOutputElement -> Maybe val -> m () setDefaultValue self val = liftIO (js_setDefaultValue (unHTMLOutputElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"defaultValue\"]" js_getDefaultValue :: JSRef HTMLOutputElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.defaultValue Mozilla HTMLOutputElement.defaultValue documentation> getDefaultValue :: (MonadIO m, FromJSString result) => HTMLOutputElement -> m (Maybe result) getDefaultValue self = liftIO (fromMaybeJSString <$> (js_getDefaultValue (unHTMLOutputElement self))) foreign import javascript unsafe "$1[\"value\"] = $2;" js_setValue :: JSRef HTMLOutputElement -> JSRef (Maybe JSString) -> IO () -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.value Mozilla HTMLOutputElement.value documentation> setValue :: (MonadIO m, ToJSString val) => HTMLOutputElement -> Maybe val -> m () setValue self val = liftIO (js_setValue (unHTMLOutputElement self) (toMaybeJSString val)) foreign import javascript unsafe "$1[\"value\"]" js_getValue :: JSRef HTMLOutputElement -> IO (JSRef (Maybe JSString)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.value Mozilla HTMLOutputElement.value documentation> getValue :: (MonadIO m, FromJSString result) => HTMLOutputElement -> m (Maybe result) getValue self = liftIO (fromMaybeJSString <$> (js_getValue (unHTMLOutputElement self))) foreign import javascript unsafe "($1[\"willValidate\"] ? 1 : 0)" js_getWillValidate :: JSRef HTMLOutputElement -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.willValidate Mozilla HTMLOutputElement.willValidate documentation> getWillValidate :: (MonadIO m) => HTMLOutputElement -> m Bool getWillValidate self = liftIO (js_getWillValidate (unHTMLOutputElement self)) foreign import javascript unsafe "$1[\"validity\"]" js_getValidity :: JSRef HTMLOutputElement -> IO (JSRef ValidityState) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.validity Mozilla HTMLOutputElement.validity documentation> getValidity :: (MonadIO m) => HTMLOutputElement -> m (Maybe ValidityState) getValidity self = liftIO ((js_getValidity (unHTMLOutputElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"validationMessage\"]" js_getValidationMessage :: JSRef HTMLOutputElement -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.validationMessage Mozilla HTMLOutputElement.validationMessage documentation> getValidationMessage :: (MonadIO m, FromJSString result) => HTMLOutputElement -> m result getValidationMessage self = liftIO (fromJSString <$> (js_getValidationMessage (unHTMLOutputElement self))) foreign import javascript unsafe "$1[\"labels\"]" js_getLabels :: JSRef HTMLOutputElement -> IO (JSRef NodeList) -- | <https://developer.mozilla.org/en-US/docs/Web/API/HTMLOutputElement.labels Mozilla HTMLOutputElement.labels documentation> getLabels :: (MonadIO m) => HTMLOutputElement -> m (Maybe NodeList) getLabels self = liftIO ((js_getLabels (unHTMLOutputElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/HTMLOutputElement.hs
mit
8,355
98
11
1,341
1,727
938
789
132
1
{-# LANGUAGE FlexibleInstances #-} module Data.UTC.Format.Rfc3339 ( -- * Parsing Rfc3339Parser(..) -- * Rendering , Rfc3339Renderer(..) -- * Low-Level , rfc3339Parser, rfc3339Builder ) where import Control.Monad.Catch import qualified Data.Attoparsec.ByteString as Atto import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as BSL import qualified Data.ByteString.Builder as B import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TL import Data.UTC.Class.Epoch import Data.UTC.Class.IsDate import Data.UTC.Class.IsTime import Data.UTC.Type.Local import Data.UTC.Type.Exception import Data.UTC.Format.Rfc3339.Parser import Data.UTC.Format.Rfc3339.Builder class Rfc3339Parser a where parseRfc3339 :: (MonadThrow m, IsDate t, IsTime t, Epoch t) => a -> m (Local t) instance Rfc3339Parser BS.ByteString where parseRfc3339 s = case Atto.parseOnly rfc3339Parser s of Right t -> t Left _ -> throwM $ UtcException $ "Rfc3339Parser: parseRfc3339 " ++ show s instance Rfc3339Parser BSL.ByteString where parseRfc3339 s = parseRfc3339 (BSL.toStrict s) instance Rfc3339Parser T.Text where parseRfc3339 s = parseRfc3339 (T.encodeUtf8 s) instance Rfc3339Parser TL.Text where parseRfc3339 s = parseRfc3339 (TL.encodeUtf8 s) instance Rfc3339Parser [Char] where parseRfc3339 s = parseRfc3339 (T.pack s) -- | > setYear 1987 (epoch :: DateTime) -- > >>= setMonth 7 -- > >>= setDay 10 -- > >>= setHour 12 -- > >>= setMinute 4 -- > >>= return . (flip Local) (Just 0) -- > >>= renderRfc3339 :: Maybe String -- > > Just "1987-07-10T12:04:00Z" class Rfc3339Renderer string where renderRfc3339 :: (MonadThrow m, IsDate t, IsTime t, Epoch t) => Local t -> m string instance Rfc3339Renderer BS.ByteString where renderRfc3339 t = renderRfc3339 t >>= return . BSL.toStrict instance Rfc3339Renderer BSL.ByteString where renderRfc3339 t = rfc3339Builder t >>= return . B.toLazyByteString instance Rfc3339Renderer T.Text where renderRfc3339 t = renderRfc3339 t >>= return . T.decodeUtf8 instance Rfc3339Renderer TL.Text where renderRfc3339 t = renderRfc3339 t >>= return . TL.decodeUtf8 instance Rfc3339Renderer [Char] where renderRfc3339 t = renderRfc3339 t >>= return . T.unpack
lpeterse/haskell-utc
Data/UTC/Format/Rfc3339.hs
mit
2,501
0
11
531
610
343
267
58
0
module Constellation.Api.System (resource) where import Constellation.Api.System.Internal
ClassyCoding/constellation-server
src/Constellation/Api/System.hs
mit
101
0
4
17
19
13
6
2
0
{-# OPTIONS_GHC -fno-warn-type-defaults #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE PatternGuards #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE Arrows #-} module Yage.Rendering.Pipeline.Deferred ( module Pass , module Yage.Viewport , module RenderSystem , yDeferredLighting ) where import Yage.Prelude hiding ((</>), cons) import Yage.Lens hiding (cons) import Yage.Math import Yage.HDR import Yage.Rendering.GL import Yage.Rendering.RenderSystem as RenderSystem import Yage.Rendering.RenderTarget import Yage.Rendering.Resources.GL import Yage.Scene import Yage.Viewport import Yage.Material hiding (over) import Yage.Rendering.Pipeline.Deferred.BaseGPass as Pass import Yage.Rendering.Pipeline.Deferred.Common as Pass import Yage.Rendering.Pipeline.Deferred.Types as Pass import Yage.Rendering.Pipeline.Deferred.Downsampling as Pass -- import Yage.Rendering.Pipeline.Deferred.GuiPass as Pass -- import Yage.Rendering.Pipeline.Deferred.HDR as Pass import Yage.Rendering.Pipeline.Deferred.PostAmbientPass as Pass import Yage.Rendering.Pipeline.Deferred.Bloom as Pass import Yage.Rendering.Pipeline.Deferred.Tonemap as Pass import Yage.Rendering.Pipeline.Deferred.LightPass as Pass import Yage.Rendering.Pipeline.Deferred.ScreenPass as Pass import Yage.Rendering.Pipeline.Deferred.SkyPass as Pass import Yage.Rendering.Pipeline.Voxel.Base import Control.Arrow import Quine.GL.Shader import Data.Maybe (fromJust) yDeferredLighting :: (HasScene a DeferredEntity DeferredEnvironment, HasHDRCamera a, HasDeferredSettings a, DeferredMonad m env) => YageResource (RenderSystem m a (Texture2D PixelRGB8)) yDeferredLighting = do throwWithStack $ glEnable GL_FRAMEBUFFER_SRGB throwWithStack $ buildNamedStrings embeddedShaders ((++) "/res/glsl/") -- throwWithStack $ setupDefaultTexture drawGBuffer <- gPass skyPass <- drawSky defaultRadiance <- textureRes (pure (defaultMaterialSRGB^.materialTexture) :: Cubemap (Image PixelRGB8)) voxelize <- voxelizePass 256 256 256 visVoxel <- visualizeVoxelPass drawLights <- lightPass postAmbient <- postAmbientPass renderBloom <- addBloom tonemapPass <- toneMapper debugOverlay <- toneMapper return $ proc input -> do mainViewport <- sysEnv viewport -< () -- render surface attributes for lighting out gbufferTarget <- autoResized mkGbufferTarget -< mainViewport^.rectangle gBuffer <- processPassWithGlobalEnv drawGBuffer -< ( gbufferTarget , input^.scene , input^.hdrCamera.camera ) -- voxelize for ambient occlusion mVoxelOcclusion <- if input^.deferredSettings.activeVoxelAmbientOcclusion then fmap Just voxelize -< input else pure Nothing -< () voxelSceneTarget <- autoResized mkVisVoxelTarget -< mainViewport^.rectangle -- lighting lBufferTarget <- autoResized mkLightBuffer -< mainViewport^.rectangle _lBuffer <- processPassWithGlobalEnv drawLights -< ( lBufferTarget , input^.scene.environment.lights , input^.hdrCamera.camera , gBuffer ) -- ambient let radiance = maybe defaultRadiance (view $ materials.radianceMap.materialTexture) (input^.scene.environment.sky) post <- processPassWithGlobalEnv postAmbient -< ( lBufferTarget , radiance , mVoxelOcclusion , input^.hdrCamera.camera , gBuffer ) -- sky pass skyTarget <- onChange -< (post, gBuffer^.depthChannel) sceneTex <- if isJust $ input^.scene.environment.sky then skyPass -< ( fromJust $ input^.scene.environment.sky , input^.hdrCamera.camera , skyTarget ) else returnA -< post -- bloom pass bloomed <- renderBloom -< (input^.hdrCamera.bloomSettings, sceneTex) -- tone map from hdr (floating) to discrete Word8 finalScene <- tonemapPass -< (input^.hdrCamera.hdrSensor, sceneTex, Just bloomed) if input^.deferredSettings.showDebugOverlay && isJust mVoxelOcclusion then do visVoxTex <- processPassWithGlobalEnv visVoxel -< ( voxelSceneTarget , fromJust mVoxelOcclusion , input^.hdrCamera.camera , [VisualizeSceneVoxel] -- [VisualizePageMask] -- [VisualizeSceneVoxel] ) debugOverlay -< (input^.hdrCamera.hdrSensor, finalScene, Just visVoxTex) else returnA -< finalScene where mkGbufferTarget :: Rectangle Int -> YageResource GBuffer mkGbufferTarget rect | V2 w h <- rect^.extend = GBuffer <$> createTexture2D GL_TEXTURE_2D (Tex2D w h) 1 -- a channel <*> createTexture2D GL_TEXTURE_2D (Tex2D w h) 1 -- b channel <*> createTexture2D GL_TEXTURE_2D (Tex2D w h) 1 -- c channel <*> createTexture2D GL_TEXTURE_2D (Tex2D w h) 1 -- d channel <*> createTexture2D GL_TEXTURE_2D (Tex2D w h) 1 -- depth channel mkLightBuffer :: Rectangle Int -> YageResource LightBuffer mkLightBuffer rect = let V2 w h = rect^.extend in createTexture2D GL_TEXTURE_2D (Tex2D w h) 1 -- setupDefaultTexture :: MonadIO m => m () -- setupDefaultTexture = do -- throwWithStack $ bindTextures GL_TEXTURE_2D [(0, Just def :: Maybe (Texture PixelRGBA8))] -- -- throwWithStack $ store black GL_TEXTURE_2D -- -- throwWithStack $ upload black GL_TEXTURE_2D 0 -- glTexParameteri GL_TEXTURE_2D GL_TEXTURE_BASE_LEVEL 0 -- glTexParameteri GL_TEXTURE_2D GL_TEXTURE_MAX_LEVEL 0 -- glTexImage2D GL_TEXTURE_2D 0 GL_RGBA8 1 1 0 GL_RGBA GL_UNSIGNED_BYTE nullPtr
MaxDaten/yage
src/Yage/Rendering/Pipeline/Deferred.hs
mit
6,615
1
18
2,042
1,164
642
522
-1
-1
-- A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, -- -- a^2 + b^2 = c^2 -- -- For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. -- -- There exists exactly one Pythagorean triplet for which a + b + c = 1000. -- Find the product abc. -- Given the constraints: -- -- a^2 + b^2 = c^2 -- a + b + c = 1000 -- -- it follows that -- -- a /= b (because they have to be natural numbers) -- -- and -- -- a < 1000 -- b < 1000 -- -- and, by substituting [c = 1000 - (a + b)] in [a^2 + b^2 = c^2], -- -- 1000(a + b) = 500000 + ab pairs :: [Int] -> [(Int, Int)] pairs (x:[y]) = [(x, x), (x, y), (y, y)] pairs (x:xs) = (x, x) : (zip [x, x ..] xs) ++ pairs xs pairs _ = error "pairs: Invalid input" validPair :: (Int, Int) -> Bool validPair (a, b) = 1000 * (a + b) == 500000 + a * b result = (a, b, c, abc) where (a, b) = head $ dropWhile (not . validPair) (pairs [1 .. 1000]) c = truncate $ sqrt (a' ** 2 + b' ** 2) abc = a * b * c a' = fromIntegral a::Double b' = fromIntegral b::Double main = do putStrLn (show result)
carletes/project-euler
problem-9.hs
mit
1,109
0
12
325
340
201
139
14
1
{-# LANGUAGE PackageImports #-} module Elm.Marshall.Internal.Type where import "ghcjs-base" GHCJS.Types ( JSVal, IsJSVal ) -- | Represents a value that can pass through an Elm port. It is parameterised -- by its corresponding Haskell type to prevent different Elm values from -- being mixed. newtype ElmValue a = ElmValue { unElmValue :: JSVal } instance IsJSVal (ElmValue a) where
FPtje/elm-marshall
src/Elm/Marshall/Internal/Type.hs
mit
392
0
7
69
54
36
18
5
0
{-| Module : HsToCoq.Coq.Gallina.Rewrite Description : Rewrite rule enginge for the Gallina AST Copyright : Copyright © 2018 Joachim Breitner License : MIT Maintainer : antal.b.sz@gmail.com Stability : experimental This module implements rewrite rules. So far, this is straight forward and not very efficiently. Efficiency of finding a rewrite rule (candidate) could be greatly improved by * sorting the rewrite rules into a map, based on the outermost functions. * implementing an actual trie This can be relevant when the numer of rewrite rules increases. Another improvemet would be to detect bad patterns (non-linear ones, unsupported AST nodes) and report such errors upon parsing. -} {-# LANGUAGE OverloadedLists #-} module HsToCoq.Coq.Gallina.Rewrite (Rewrite(..), Rewrites, rewrite) where import qualified Data.Map as M import qualified Data.Set as S import Control.Applicative import Control.Monad import Control.Monad.Trans.Writer.Strict import Data.Foldable import HsToCoq.Coq.Subst import HsToCoq.Coq.Gallina import HsToCoq.Coq.Gallina.Util data Rewrite = Rewrite { patternVars :: [Ident] , lhs :: Term , rhs :: Term } deriving (Eq, Ord, Show) -- | This could be replaced by something more efficient, if needed. -- See comments in HsToCoq.Coq.Gallina.Rewrite. type Rewrites = [Rewrite] -- | Applies all rewrite rules that match at the root of the given term. rewrite :: Rewrites -> Term -> Term rewrite rws t = foldl' (flip rewrite1) t rws rewrite1 :: Rewrite -> Term -> Term rewrite1 (Rewrite patVars lhs rhs) term | Just s <- match patVars lhs term = subst s rhs | otherwise = term -- | Normalizes the outermost constructor -- (Maybe we should drop InFix completely) norm :: Term -> Term norm (HsString s) = String s norm t | Right (f, args) <- collectArgs t = appList (Qualid f) (map PosArg args) norm t = t match :: [Ident] -> Term -> Term -> Maybe (M.Map Qualid Term) match patVars lhs term = execWriterT (go lhs term) where isPatVar = (`S.member` S.fromList patVars) go :: Term -> Term -> WriterT (M.Map Qualid Term) Maybe () go lhs term = go' (norm lhs) (norm term) go' :: Term -> Term -> WriterT (M.Map Qualid Term) Maybe () go' (String s1) (String s2) = guard (s1 == s2) go' (Num n1) (Num n2) = guard (n1 == n2) go' (Qualid qid@(Bare v)) t | isPatVar v = do tell (M.singleton qid t) return () go' (Qualid pqid) (Qualid qid) = guard (pqid == qid) go' (App pf pa) (App f a) = do go pf f zipWithSameLengthM_ goA (toList pa) (toList a) -- Simple matching of simple `match`es only – no dependent match clauses, no -- return types, no reordering match clauses. We are VERY DUMB ABOUT BINDING. go' (Match scruts1 Nothing eqs1) (Match scruts2 Nothing eqs2) = do zipWithSameLengthM_ goMI scruts1 scruts2 zipWithSameLengthM_ goE eqs1 eqs2 go' _lhs _term = mzero goA :: Arg -> Arg -> WriterT (M.Map Qualid Term) Maybe () goA (PosArg pt) (PosArg p) = go pt p goA (NamedArg pi pt) (NamedArg i p) = do guard (pi == i) go pt p goA _lhs _term = mzero -- Handle simple `MatchItem`s only – terms without `as` or `in` clauses goMI (MatchItem tm1 Nothing Nothing) (MatchItem tm2 Nothing Nothing) = go tm1 tm2 goMI _ _ = mzero goE (Equation mps1 tm1) (Equation mps2 tm2) = do zipWithSameLengthM_ goMP mps1 mps2 go tm1 tm2 goMP (MultPattern mps1) (MultPattern mps2) = zipWithSameLengthM_ goP mps1 mps2 -- We are VERY DUMB ABOUT BINDING. goP UnderscorePat UnderscorePat = pure () goP (NumPat num1) (NumPat num2) = guard $ num1 == num2 goP (StringPat str1) (StringPat str2) = guard $ str1 == str2 goP (InScopePat pat1 scope1) (InScopePat pat2 scope2) = do guard $ scope1 == scope2 goP pat1 pat2 goP (ArgsPat con1 args1) (ArgsPat con2 args2) = do goPQid con1 con2 zipWithSameLengthM_ goP args1 args2 goP (ExplicitArgsPat con1 args1) (ExplicitArgsPat con2 args2) = do goPQid con1 con2 zipWithSameLengthM_ goP args1 args2 goP (InfixPat lhs1 op1 rhs1) (InfixPat lhs2 op2 rhs2) = do goPQid (Bare op1) (Bare op2) goP lhs1 lhs2 goP rhs1 rhs2 goP (AsPat pat1 var1) (AsPat pat2 var2) = do goPQid var1 var2 goP pat1 pat2 goP (QualidPat qid1@(Bare v)) p | isPatVar v, Just t <- patToTerm p = tell $ M.singleton qid1 t goP (QualidPat qid1) (QualidPat qid2) = guard $ qid1 == qid2 goP (OrPats pats1) (OrPats pats2) = zipWithSameLengthM_ goOP pats1 pats2 goP _ _ = mzero patToTerm (ArgsPat con args) = appList (Qualid con) <$> traverse (fmap PosArg . patToTerm) args patToTerm (ExplicitArgsPat con args) = ExplicitApp con . toList <$> traverse patToTerm args patToTerm (InfixPat lhs op rhs) = App2 (Qualid $ Bare op) <$> patToTerm lhs <*> patToTerm rhs patToTerm (InScopePat p scope) = InScope <$> patToTerm p <*> pure scope patToTerm (QualidPat qid) = Just $ Qualid qid patToTerm (NumPat n) = Just $ Num n patToTerm (StringPat s) = Just $ String s patToTerm (AsPat _ _) = Nothing patToTerm UnderscorePat = Nothing patToTerm (OrPats _) = Nothing goPQid lhs@(Bare v) rhs | isPatVar v = tell $ M.singleton lhs (Qualid rhs) goPQid lhs rhs = guard $ lhs == rhs goOP (OrPattern pats1) (OrPattern pats2) = zipWithSameLengthM_ goP pats1 pats2 zipWithSameLengthM_ :: (Alternative f, Foldable g, Foldable h) => (a -> b -> f c) -> g a -> h b -> f () zipWithSameLengthM_ f as0 bs0 = let zipGo (a:as) (b:bs) = f a b *> zipGo as bs zipGo [] [] = pure () zipGo _ _ = empty in zipGo (toList as0) (toList bs0)
antalsz/hs-to-coq
src/lib/HsToCoq/Coq/Gallina/Rewrite.hs
mit
5,948
0
13
1,576
1,956
966
990
108
33
module Cards (cards) where import Control.Monad import qualified Cards.BNG as BNG import qualified Cards.M11 as M11 import qualified Cards.M14 as M14 import qualified Cards.NinthEdition as NinthEdition import qualified Cards.RTR as RTR import qualified Cards.SOI as SOI import qualified Cards.Theros as Theros cards = join [ BNG.cards , M11.cards , M14.cards , NinthEdition.cards , RTR.cards , SOI.cards , Theros.cards ]
mplamann/magic-spieler
src/Cards.hs
mit
535
0
7
173
113
76
37
16
1
nwd3 :: Integer -> Integer -> Integer nwd3 0 y = abs y nwd3 x 0 = abs x nwd3 x y = maximum $ filter (\xx -> x `mod` xx == 0) . filter (\yy -> y `mod` yy == 0) $ if x > y then [1..abs y] else [1..abs x]
RAFIRAF/HASKELL
nwd3.hs
mit
201
0
12
52
132
69
63
4
2
-- greatest product of 13 adjacent digits in a large number main = print getProblem8Value getProblem8Value :: Integer getProblem8Value = getLargestProductOf13Digits largeNum getLargestProductOf13Digits :: [Integer] -> Integer getLargestProductOf13Digits list@(a:b:c:d:e:f:g:h:i:j:k:l:m:rest) = max (a*b*c*d*e*f*g*h*i*j*k*l*m) (getLargestProductOf13Digits next) where (_:next) = list getLargestProductOf13Digits _ = 0 largeNum :: [Integer] largeNum = map (read . (\x -> [x])) (concat [ "73167176531330624919225119674426574742355349194934", "96983520312774506326239578318016984801869478851843", "85861560789112949495459501737958331952853208805511", "12540698747158523863050715693290963295227443043557", "66896648950445244523161731856403098711121722383113", "62229893423380308135336276614282806444486645238749", "30358907296290491560440772390713810515859307960866", "70172427121883998797908792274921901699720888093776", "65727333001053367881220235421809751254540594752243", "52584907711670556013604839586446706324415722155397", "53697817977846174064955149290862569321978468622482", "83972241375657056057490261407972968652414535100474", "82166370484403199890008895243450658541227588666881", "16427171479924442928230863465674813919123162824586", "17866458359124566529476545682848912883142607690042", "24219022671055626321111109370544217506941658960408", "07198403850962455444362981230987879927244284909188", "84580156166097919133875499200524063689912560717606", "05886116467109405077541002256983155200055935729725", "71636269561882670428252483600823257530420752963450" ])
jchitel/ProjectEuler.hs
Problems/Problem0008.hs
mit
1,654
0
20
163
288
160
128
29
1
{-# LANGUAGE CPP #-} -- | Internal utilities and types for BPOR. module Test.DejaFu.SCT.Internal where import Control.DeepSeq (NFData(..)) import Data.IntMap.Strict (IntMap) import Data.List (foldl', partition, maximumBy) import Data.Maybe (mapMaybe, fromJust) import Data.Ord (comparing) import Data.Sequence (Seq, ViewL(..)) import Data.Set (Set) import Test.DejaFu.Deterministic import qualified Data.IntMap.Strict as I import qualified Data.Sequence as Sq import qualified Data.Set as S #if __GLASGOW_HASKELL__ < 710 import Control.Applicative ((<$>), (<*>)) #endif -- * BPOR state -- | One step of the execution, including information for backtracking -- purposes. This backtracking information is used to generate new -- schedules. data BacktrackStep = BacktrackStep { _threadid :: ThreadId -- ^ The thread running at this step , _decision :: (Decision, ThreadAction) -- ^ What happened at this step. , _runnable :: Set ThreadId -- ^ The threads runnable at this step , _backtrack :: IntMap Bool -- ^ The list of alternative threads to run, and whether those -- alternatives were added conservatively due to the bound. } deriving (Eq, Show) instance NFData BacktrackStep where rnf b = rnf (_threadid b, _decision b, _runnable b, _backtrack b) -- | BPOR execution is represented as a tree of states, characterised -- by the decisions that lead to that state. data BPOR = BPOR { _brunnable :: Set ThreadId -- ^ What threads are runnable at this step. , _btodo :: IntMap Bool -- ^ Follow-on decisions still to make, and whether that decision -- was added conservatively due to the bound. , _bignore :: Set ThreadId -- ^ Follow-on decisions never to make, because they will result in -- the chosen thread immediately blocking without achieving -- anything, which can't have any effect on the result of the -- program. , _bdone :: IntMap BPOR -- ^ Follow-on decisions that have been made. , _bsleep :: IntMap ThreadAction -- ^ Transitions to ignore (in this node and children) until a -- dependent transition happens. , _btaken :: IntMap ThreadAction -- ^ Transitions which have been taken, excluding -- conservatively-added ones, in the (reverse) order that they were -- taken, as the 'Map' doesn't preserve insertion order. This is -- used in implementing sleep sets. } -- | Initial BPOR state. initialState :: BPOR initialState = BPOR { _brunnable = S.singleton 0 , _btodo = I.singleton 0 False , _bignore = S.empty , _bdone = I.empty , _bsleep = I.empty , _btaken = I.empty } -- | Produce a new schedule from a BPOR tree. If there are no new -- schedules remaining, return 'Nothing'. Also returns whether the -- decision made was added conservatively. -- -- This returns the longest prefix, on the assumption that this will -- lead to lots of backtracking points being identified before -- higher-up decisions are reconsidered, so enlarging the sleep sets. next :: BPOR -> Maybe ([ThreadId], Bool, BPOR) next = go 0 where go tid bpor = -- All the possible prefix traces from this point, with -- updated BPOR subtrees if taken from the done list. let prefixes = mapMaybe go' (I.toList $ _bdone bpor) ++ [Left t | t <- I.toList $ _btodo bpor] -- Sort by number of preemptions, in descending order. cmp = comparing $ preEmps tid bpor . either (\(a,_) -> [a]) (\(a,_,_) -> a) in if null prefixes then Nothing else case maximumBy cmp prefixes of -- If the prefix with the most preemptions is from the done list, update that. Right (ts@(t:_), c, b) -> Just (ts, c, bpor { _bdone = I.insert t b $ _bdone bpor }) Right ([], _, _) -> error "Invariant failure in 'next': empty done prefix!" -- If from the todo list, remove it. Left (t,c) -> Just ([t], c, bpor { _btodo = I.delete t $ _btodo bpor }) go' (tid, bpor) = (\(ts,c,b) -> Right (tid:ts, c, b)) <$> go tid bpor preEmps tid bpor (t:ts) = let rest = preEmps t (fromJust . I.lookup t $ _bdone bpor) ts in if tid /= t && tid `S.member` _brunnable bpor then 1 + rest else rest preEmps _ _ [] = 0::Int -- | Produce a list of new backtracking points from an execution -- trace. findBacktrack :: ([BacktrackStep] -> Int -> ThreadId -> [BacktrackStep]) -> Seq (NonEmpty (ThreadId, Lookahead), [ThreadId]) -> Trace' -> [BacktrackStep] findBacktrack backtrack = go S.empty 0 [] . Sq.viewl where go allThreads tid bs ((e,i):<is) ((d,_,a):ts) = let tid' = tidOf tid d this = BacktrackStep { _threadid = tid' , _decision = (d, a) , _runnable = S.fromList . map fst . toList $ e , _backtrack = I.fromList $ map (\i' -> (i', False)) i } bs' = doBacktrack allThreads (toList e) bs allThreads' = allThreads `S.union` _runnable this in go allThreads' tid' (bs' ++ [this]) (Sq.viewl is) ts go _ _ bs _ _ = bs doBacktrack allThreads enabledThreads bs = let tagged = reverse $ zip [0..] bs idxs = [ (head is, u) | (u, n) <- enabledThreads , v <- S.toList allThreads , u /= v , let is = [ i | (i, b) <- tagged , _threadid b == v , dependent' (snd $ _decision b) (u, n) ] , not $ null is] :: [(Int, ThreadId)] in foldl' (\b (i, u) -> backtrack b i u) bs idxs -- | Add a new trace to the tree, creating a new subtree. grow :: Bool -> Trace' -> BPOR -> BPOR grow conservative = grow' initialCVState 0 where grow' cvstate tid trc@((d, _, a):rest) bpor = let tid' = tidOf tid d cvstate' = updateCVState cvstate a in case I.lookup tid' $ _bdone bpor of Just bpor' -> bpor { _bdone = I.insert tid' (grow' cvstate' tid' rest bpor') $ _bdone bpor } Nothing -> bpor { _btaken = if conservative then _btaken bpor else I.insert tid' a $ _btaken bpor , _bdone = I.insert tid' (subtree cvstate' tid' (_bsleep bpor `I.union` _btaken bpor) trc) $ _bdone bpor } grow' _ _ [] bpor = bpor subtree cvstate tid sleep ((d, ts, a):rest) = let cvstate' = updateCVState cvstate a sleep' = I.filterWithKey (\t a' -> not $ dependent a (t,a')) sleep in BPOR { _brunnable = S.fromList $ tids tid d a ts , _btodo = I.empty , _bignore = S.fromList [tidOf tid d' | (d',as) <- ts, willBlockSafely cvstate' $ toList as] , _bdone = I.fromList $ case rest of ((d', _, _):_) -> let tid' = tidOf tid d' in [(tid', subtree cvstate' tid' sleep' rest)] [] -> [] , _bsleep = sleep' , _btaken = case rest of ((d', _, a'):_) -> I.singleton (tidOf tid d') a' [] -> I.empty } subtree _ _ _ [] = error "Invariant failure in 'subtree': suffix empty!" tids tid d (Fork t) ts = tidOf tid d : t : map (tidOf tid . fst) ts tids tid _ (BlockedPut _) ts = map (tidOf tid . fst) ts tids tid _ (BlockedRead _) ts = map (tidOf tid . fst) ts tids tid _ (BlockedTake _) ts = map (tidOf tid . fst) ts tids tid _ BlockedSTM ts = map (tidOf tid . fst) ts tids tid _ (BlockedThrowTo _) ts = map (tidOf tid . fst) ts tids tid _ Stop ts = map (tidOf tid . fst) ts tids tid d _ ts = tidOf tid d : map (tidOf tid . fst) ts -- | Add new backtracking points, if they have not already been -- visited, fit into the bound, and aren't in the sleep set. todo :: ([Decision] -> Bool) -> [BacktrackStep] -> BPOR -> BPOR todo bv = step where step bs bpor = let (bpor', bs') = go 0 [] Nothing bs bpor in if all (I.null . _backtrack) bs' then bpor' else step bs' bpor' go tid pref lastb (b:bs) bpor = let (bpor', blocked) = backtrack pref b bpor tid' = tidOf tid . fst $ _decision b (child, blocked') = go tid' (pref++[fst $ _decision b]) (Just b) bs . fromJust $ I.lookup tid' (_bdone bpor) bpor'' = bpor' { _bdone = I.insert tid' child $ _bdone bpor' } in case lastb of Just b' -> (bpor'', b' { _backtrack = blocked } : blocked') Nothing -> (bpor'', blocked') go _ _ (Just b') _ bpor = (bpor, [b' { _backtrack = I.empty }]) go _ _ Nothing _ bpor = (bpor, []) backtrack pref b bpor = let todo' = [ x | x@(t,c) <- I.toList $ _backtrack b , bv $ pref ++ [decisionOf (Just $ activeTid pref) (_brunnable bpor) t] , t `notElem` I.keys (_bdone bpor) , c || I.notMember t (_bsleep bpor) ] (blocked, nxt) = partition (\(t,_) -> t `S.member` _bignore bpor) todo' in (bpor { _btodo = _btodo bpor `I.union` I.fromList nxt }, I.fromList blocked) -- * Utilities -- | Get the resultant 'ThreadId' of a 'Decision', with a default case -- for 'Continue'. tidOf :: ThreadId -> Decision -> ThreadId tidOf _ (Start t) = t tidOf _ (SwitchTo t) = t tidOf tid Continue = tid -- | Get the 'Decision' that would have resulted in this 'ThreadId', -- given a prior 'ThreadId' (if any) and list of runnable threads. decisionOf :: Maybe ThreadId -> Set ThreadId -> ThreadId -> Decision decisionOf prior runnable chosen | prior == Just chosen = Continue | prior `S.member` S.map Just runnable = SwitchTo chosen | otherwise = Start chosen -- | Get the tid of the currently active thread after executing a -- series of decisions. The list MUST begin with a 'Start'. activeTid :: [Decision] -> ThreadId activeTid = foldl' go 0 where go _ (Start t) = t go _ (SwitchTo t) = t go t Continue = t -- | Count the number of pre-emptions in a schedule preEmpCount :: [Decision] -> Int preEmpCount (SwitchTo _:ds) = 1 + preEmpCount ds preEmpCount (_:ds) = preEmpCount ds preEmpCount [] = 0 -- | Check if an action is dependent on another, assumes the actions -- are from different threads (two actions in the same thread are -- always dependent). dependent :: ThreadAction -> (ThreadId, ThreadAction) -> Bool dependent Lift (_, Lift) = True dependent (ThrowTo t) (t2, _) = t == t2 dependent d1 (_, d2) = cref || cvar || ctvar where cref = Just True == ((\(r1, w1) (r2, w2) -> r1 == r2 && (w1 || w2)) <$> cref' d1 <*> cref' d2) cref' (ReadRef r) = Just (r, False) cref' (ModRef r) = Just (r, True) cref' _ = Nothing cvar = Just True == ((==) <$> cvar' d1 <*> cvar' d2) cvar' (TryPut c _ _) = Just c cvar' (TryTake c _ _) = Just c cvar' (Put c _) = Just c cvar' (Read c) = Just c cvar' (Take c _) = Just c cvar' _ = Nothing ctvar = ctvar' d1 && ctvar' d2 ctvar' (STM _) = True ctvar' _ = False -- | Variant of 'dependent' to handle 'ThreadAction''s dependent' :: ThreadAction -> (ThreadId, Lookahead) -> Bool dependent' Lift (_, WillLift) = True dependent' (ThrowTo t) (t2, _) = t == t2 dependent' d1 (_, d2) = cref || cvar || ctvar where cref = Just True == ((\(r1, w1) (r2, w2) -> r1 == r2 && (w1 || w2)) <$> cref' d1 <*> cref'' d2) cref' (ReadRef r) = Just (r, False) cref' (ModRef r) = Just (r, True) cref' _ = Nothing cref'' (WillReadRef r) = Just (r, False) cref'' (WillModRef r) = Just (r, True) cref'' _ = Nothing cvar = Just True == ((==) <$> cvar' d1 <*> cvar'' d2) cvar' (TryPut c _ _) = Just c cvar' (TryTake c _ _) = Just c cvar' (Put c _) = Just c cvar' (Read c) = Just c cvar' (Take c _) = Just c cvar' _ = Nothing cvar'' (WillTryPut c) = Just c cvar'' (WillTryTake c) = Just c cvar'' (WillPut c) = Just c cvar'' (WillRead c) = Just c cvar'' (WillTake c) = Just c cvar'' _ = Nothing ctvar = ctvar' d1 && ctvar'' d2 ctvar' (STM _) = True ctvar' _ = False ctvar'' WillSTM = True ctvar'' _ = False -- * Keeping track of 'CVar' full/empty states -- | Initial global 'CVar' state initialCVState :: IntMap Bool initialCVState = I.empty -- | Update the 'CVar' state with the action that has just happened. updateCVState :: IntMap Bool -> ThreadAction -> IntMap Bool updateCVState cvstate (Put c _) = I.insert c True cvstate updateCVState cvstate (Take c _) = I.insert c False cvstate updateCVState cvstate (TryPut c True _) = I.insert c True cvstate updateCVState cvstate (TryTake c True _) = I.insert c False cvstate updateCVState cvstate _ = cvstate -- | Check if an action will block. willBlock :: IntMap Bool -> Lookahead -> Bool willBlock cvstate (WillPut c) = I.lookup c cvstate == Just True willBlock cvstate (WillTake c) = I.lookup c cvstate == Just False willBlock _ _ = False -- | Check if a list of actions will block safely (without modifying -- any global state). This allows further lookahead at, say, the -- 'spawn' of a thread (which always starts with 'KnowsAbout'). willBlockSafely :: IntMap Bool -> [Lookahead] -> Bool willBlockSafely cvstate (WillKnowsAbout:as) = willBlockSafely cvstate as willBlockSafely cvstate (WillForgets:as) = willBlockSafely cvstate as willBlockSafely cvstate (WillAllKnown:as) = willBlockSafely cvstate as willBlockSafely cvstate (WillPut c:_) = willBlock cvstate (WillPut c) willBlockSafely cvstate (WillTake c:_) = willBlock cvstate (WillTake c) willBlockSafely _ _ = False
bitemyapp/dejafu
Test/DejaFu/SCT/Internal.hs
mit
13,519
0
21
3,627
4,467
2,365
2,102
224
17
module Y2017.M01.D17.Solution where import Control.Arrow ((***)) import Data.Traversable {-- Following up from yesterday's exercise on our Data.Traversable-exploration via @yoeight's blog post at the URL: http://www.corecursion.net/post/2017-01-12-Why_Traversable_is_the_real_deal Today we will be implementing minAF and maxAF over Traversable types. --} -- Well, following the theme of the blogpost: newtype Min a = Min { mini :: a } instance (Bounded a, Ord a) => Monoid (Min a) where mempty = Min maxBound mappend (Min a) (Min b) = Min (min a b) newtype Max a = Max { maxi :: a } instance (Bounded a, Ord a) => Monoid (Max a) where mempty = Max minBound mappend (Max a) (Max b) = Max (max a b) minAF, maxAF :: (Traversable t, Ord a, Bounded a) => t a -> a minAF = mini . foldMap Min maxAF = maxi . foldMap Max -- Question: are minAF and maxAF partial functions? -- what are minAF and maxAF for: nada, uno, rnds :: [Int] nada = [] uno = [1] rnds = [95902198162138,136017932361032,5827212341670,92864718312210, 78260380050431,62591985123053,46614386344434,156252552367524, 38573429178097,9798683366671] -- rnds combputed via: *Data.Random> rndSeed >>= evalStateT (gimme 10) {-- *Y2017.M01.D17.Solution> [minAF] <*> [nada, uno, rnds] [9223372036854775807,1,5827212341670] *Y2017.M01.D17.Solution> [maxAF] <*> [nada, uno, rnds] [-9223372036854775808,1,156252552367524] --} {-- BONUS ----------------------------------------------------------------- Fun fact: there's a trick question on google interviews that asks: what is an efficient algorithm for finding the min and the max values in a large list, where "large" means billions or trillions of elements. Answer: O(1), they are lookups. Somebody had to construct those lists, either you, in which case you retain those min and max values as you construct them, knowing that question is asked frequently, or if somebody else constructs them, require those meta-data in the delivery, as you are the customer and therefore get to set the requirements. So, given Traversable t, construct MetaTrav t such that: --} data MetaTrav t a = MT { minT, maxT :: a, struct :: t a } deriving Show -- So now we can construct a MetaTrav from any Traversable type. How? toMT :: (Traversable t, Bounded a, Ord a) => t a -> MetaTrav t a toMT = uncurry MT . foldr (\e -> min e *** max e) (maxBound, minBound) <*> id {-- *Y2017.M01.D17.Solution> mapM_ (print . toMT) [nada, uno, rnds] MT {minT = 9223372036854775807, maxT = -9223372036854775808, struct = []}, MT {minT = 1, maxT = 1, struct = [1]}, MT {minT = 5827212341670, maxT = 156252552367524, struct = [95902198162138,136017932361032,5827212341670,92864718312210, 78260380050431,62591985123053,46614386344434,156252552367524, 38573429178097,9798683366671]} so your maxT and minT functions are now O(1) for MetaTrav values. lolneat. --}
geophf/1HaskellADay
exercises/HAD/Y2017/M01/D17/Solution.hs
mit
2,916
0
11
514
437
250
187
24
1
module Y2017.M10.D30.Solution where {-- Hello! Welcome back! Happy Monday! Of course, when you're working in a start-up, the days can run together in a blur, I've found. So, we've been working with the NYT archive for more than a month now. Did you notice anything about the data? I have: --} import Control.Arrow ((&&&)) import Control.Monad import Data.Char (ord) import Data.Function (on) import Data.List (groupBy, sortOn) import Data.Map (Map) import qualified Data.Map as Map -- below imports available via 1HaskellADay git repository import Control.DList import Y2017.M10.D23.Solution -- for Article structure import Y2017.M10.D24.Solution (articlesFromFile) sampleText :: String sampleText = "GALVESTON, Tex. \226\128\148 Adolfo Guerra, a landscaper" -- The thing is, if you look at this in a text editor (worth its salt) you see: -- GALVESTON, Tex. — Adolfo Guerra, a landscaper {-- So, we need: 1. to identify the documents that have special characters 2. the context of where these special characters occur 3. once marked, replace the special characters with a simple ASCII equivalent Let's do it. --} data Context = Ctx { ctxid :: Integer, spcCharCtx :: SpecialCharacterContext } deriving (Eq, Show) type SpecialCharacterContext = Map SpecialChars [Line] type SpecialChars = String type Line = String identify :: MonadPlus m => Article -> m Context identify art = case extractSpecialChars (words $ fullText art) of [] -> mzero yup@(_:_) -> return (Ctx (artIdx art) (enmapify yup)) enmapify :: [(SpecialChars, Line)] -> SpecialCharacterContext enmapify = Map.fromList . map (fst . head &&& map snd) . groupBy ((==) `on` fst) . sortOn fst -- identifies the places in the text where there are special characters and -- shows these characters in context ... now, since the full text is one -- continuous line, getting a line is rather fun, isn't it? How would you -- form the words around the special characters? Also, how do you extract -- the special characters from the full text body? {-- >>> (identify (head hurr)) :: Maybe Context Just (Ctx {ctxid = 321, spcCharCtx = fromList [("\226\128\148",["Rights movement \226\128\148 but it", "your skin \226\128\148 those images", "GALVESTON, Tex. \226\128\148 Adolfo Guerra,"]), ("\226\128\152",["to myself, \226\128\152Maybe this is"]),...]}) --} type BodyContext = [String] extractSpecialChars :: BodyContext -> [(SpecialChars, Line)] extractSpecialChars [] = [] extractSpecialChars (w:ords) = esc [] w ords [] -- sees if we're at a set of special characters then accumulates a context -- around those characters. N.b.: special characters can occur as their own -- word, or in a word at the beginning, or within, or at the end of a word, -- e.g. ("Don't..." he said) if the quotes and apostrophe and ellipse are -- special characters then you have an example of special characters all around -- the word 'don't' including the (') within the word. {-- >>> extractSpecialChars (words sampleText) [("\226\128\148","GALVESTON, Tex. \226\128\148 Adolfo Guerra,")] --} esc :: [String] -> String -> [String] -> [(SpecialChars, Line)] -> [(SpecialChars, Line)] esc ctx lastword [] ans = case specialChars lastword [] of [] -> ans spc@(_:_) -> zip spc (repeat (unwords . reverse $ take 5 ctx)) ++ ans esc ctx wrd (h:t) acc = esc (wrd:ctx) h t ((case specialChars wrd [] of [] -> [] spc@(_:_) -> zip spc (repeat (unwords (reverse (take 2 ctx) ++ (wrd:h:take 1 t))))) ++ acc) -- seeks to special character set -- (n.b.: we must account for multiple special characters in one word.) specialChars :: String -> [String] -> [String] specialChars [] ans = ans specialChars (c:hars) acc | ord c > 127 = let (spec,rest) = charing hars (dl' c) in specialChars rest (spec:acc) | otherwise = specialChars hars acc -- now that we're in special character territory, accums them until done charing :: String -> DList Char -> (String, String) charing [] acc = (dlToList acc, []) charing (c:hars) acc | ord c > 127 = charing hars (acc <| c) | otherwise = (dlToList acc, c:hars) -- intentionally dropped c: we know it's not a special character, so drop it. -- With the set of articles from Y2017/M10/D24/hurricanes.json.gz -- What are the special characters, in which articles, and in what contexts? {-- >>> hurr <- articlesFromFile "Y2017/M10/D24/hurricanes.json.gz" >>> ans = hurr >>= identify >>> length ans 169 >>> take 5 (map ctxid ans) [321,655,1211,2184,3171] >>> Map.keys . spcCharCtx $ head ans ["\226\128\148","\226\128\152","\226\128\153","\226\128\153\226\128\157", "\226\128\156","\226\128\157"] --} -- Tomorrow we'll look at building a replacement dictionary
geophf/1HaskellADay
exercises/HAD/Y2017/M10/D30/Solution.hs
mit
4,876
0
21
991
911
503
408
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE StrictData #-} {-# LANGUAGE TupleSections #-} -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-loadbalancersconfig.html module Stratosphere.ResourceProperties.EC2SpotFleetLoadBalancersConfig where import Stratosphere.ResourceImports import Stratosphere.ResourceProperties.EC2SpotFleetClassicLoadBalancersConfig import Stratosphere.ResourceProperties.EC2SpotFleetTargetGroupsConfig -- | Full data type definition for EC2SpotFleetLoadBalancersConfig. See -- 'ec2SpotFleetLoadBalancersConfig' for a more convenient constructor. data EC2SpotFleetLoadBalancersConfig = EC2SpotFleetLoadBalancersConfig { _eC2SpotFleetLoadBalancersConfigClassicLoadBalancersConfig :: Maybe EC2SpotFleetClassicLoadBalancersConfig , _eC2SpotFleetLoadBalancersConfigTargetGroupsConfig :: Maybe EC2SpotFleetTargetGroupsConfig } deriving (Show, Eq) instance ToJSON EC2SpotFleetLoadBalancersConfig where toJSON EC2SpotFleetLoadBalancersConfig{..} = object $ catMaybes [ fmap (("ClassicLoadBalancersConfig",) . toJSON) _eC2SpotFleetLoadBalancersConfigClassicLoadBalancersConfig , fmap (("TargetGroupsConfig",) . toJSON) _eC2SpotFleetLoadBalancersConfigTargetGroupsConfig ] -- | Constructor for 'EC2SpotFleetLoadBalancersConfig' containing required -- fields as arguments. ec2SpotFleetLoadBalancersConfig :: EC2SpotFleetLoadBalancersConfig ec2SpotFleetLoadBalancersConfig = EC2SpotFleetLoadBalancersConfig { _eC2SpotFleetLoadBalancersConfigClassicLoadBalancersConfig = Nothing , _eC2SpotFleetLoadBalancersConfigTargetGroupsConfig = Nothing } -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-loadbalancersconfig.html#cfn-ec2-spotfleet-loadbalancersconfig-classicloadbalancersconfig ecsflbcClassicLoadBalancersConfig :: Lens' EC2SpotFleetLoadBalancersConfig (Maybe EC2SpotFleetClassicLoadBalancersConfig) ecsflbcClassicLoadBalancersConfig = lens _eC2SpotFleetLoadBalancersConfigClassicLoadBalancersConfig (\s a -> s { _eC2SpotFleetLoadBalancersConfigClassicLoadBalancersConfig = a }) -- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-loadbalancersconfig.html#cfn-ec2-spotfleet-loadbalancersconfig-targetgroupsconfig ecsflbcTargetGroupsConfig :: Lens' EC2SpotFleetLoadBalancersConfig (Maybe EC2SpotFleetTargetGroupsConfig) ecsflbcTargetGroupsConfig = lens _eC2SpotFleetLoadBalancersConfigTargetGroupsConfig (\s a -> s { _eC2SpotFleetLoadBalancersConfigTargetGroupsConfig = a })
frontrowed/stratosphere
library-gen/Stratosphere/ResourceProperties/EC2SpotFleetLoadBalancersConfig.hs
mit
2,613
0
12
204
252
147
105
29
1
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ImpredicativeTypes #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DefaultSignatures #-} {- | The central concept is that of a 'Pipe', which has a typed input and a typed output. Pipes pass input and output to one another via typed 'Event' objects, and each pipe runs its own event 'Processor' in a separate lightweight thread created with 'forkIO'. The mechanics of how pipes pass events to each other (or, more precisely, how processors pass events to one another) is hidden in the concept of an 'Emitter': a function whose sole job is to accept an 'Event' and dispatch it, typically to the next 'Processor' in the chain. Writers of new types of 'Processor' should take care that their implementation *always* terminates by emitting 'EOS' as the last event before exiting its processing loop. The 'EOS' event signals to downstream 'Pipe' instances that processing should cease, and any event processing loops can exit. Failing to emit an 'EOS' but still exiting an event processing loop can cause downstream processors to deadlock, as they continue to wait on an 'EOS' (or other 'Event') that will never come. The default implementation of an event loop in 'processEvents' attempts to be safe by wrapping the event loop in an exception handler that simply emits an 'EOS' to close the stream. One easy way to avoid these types of deadlock issues may be to use the 'process' construction function as often as posible, as it will produce a pipe that automatically emits an 'EOS' downstream when an 'EOS' is received as input Event. The function supplied to 'process' will only be called when the input 'Event' contains a value. -} module Data.Pipes.Core ( -- * Basic functional types Emitter, Processor, Transmitter, -- * Pipes and pipe construction Pipe, transmit, pipe, statefulPipe, process, -- * Building more complex pipes (=&=), (>>>), connect, pass, processEvents, -- * Running pipes runPipe, -- * Events Event(..), ) where -- Local imports -- External imports import Control.Category import Control.Concurrent ( forkIO ) import Control.Concurrent.STM ( TChan, atomically, newTChan, readTChan, writeTChan, newEmptyTMVar, putTMVar, takeTMVar ) import Control.Exception ( catch, SomeException ) import Data.Serialize ( Serialize ) import GHC.Generics (Generic) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- | An event is a typed container of data passed from one 'Pipe' to another data Event e = Event e | EOS deriving (Show,Generic) instance (Serialize e) => Serialize (Event e) -- | An emitter takes an 'Event' as input and passes it downstream type Emitter o = Event o -> IO () {- | A processor accepts an 'Event' and an 'Emitter', and may (or may not) invoke the emitter 1 or more times for the input event. A processor in stream processing terms is analogous to function subroutine in imperative programming models: while one invokes return in @return@ in imperative program languages to supply a value back to the caller, in stream processing one can use an 'Emitter' to pass a value to the next processor in the chain. -} type Processor i o = Event i -> Emitter o -> IO () {- | A transmitter produces a new 'Emitter', given a target output 'Emitter', and is the type for the basic mechanism of connecting pipes together. -} type Transmitter i o = Emitter o -> IO (Emitter i) {- | The central data type for processing events. -} data Pipe i o = Pipe { transmitEvents :: Transmitter i o } instance Category Pipe where id = pass (.) = (flip connect) {- | Read each 'Event' from the specified channel and allow the provided 'Processor' to handle it with the provided 'Emitter' for any output. -} processEvents :: TChan (Event i) -> Processor i o -> Emitter o -> IO () processEvents c p emo = do evt <- atomically $ readTChan c p evt emo case evt of EOS -> do return () _ -> do processEvents c p emo {- | Construct a 'Pipe' with a given 'Transmitter'. -} transmit :: Transmitter i o -> Pipe i o transmit tm = Pipe {transmitEvents = tm} {- | Construct a pipe that runs the given processor in its own thread. -} pipe :: Processor i o -> Pipe i o pipe pio = transmit (\emo -> do ci <- atomically $ newTChan _ <- forkIO $ catch (processEvents ci pio emo) (handle emo) return (\evi -> do atomically $ writeTChan ci $! evi)) where handle :: Emitter o -> SomeException -> IO () handle emo e = do emo EOS putStrLn $ "Encountered error: " ++ (show e) {- | Construct a pipe that starts with an initial state, and which passes that state to a function which returns the processor to use for the pipe. Useful for stateful pipes that require some context preserved across events. -} statefulPipe :: IO s -> (s -> Processor i o) -> Pipe i o statefulPipe initialState p = transmit (\emi -> do ci <- atomically newTChan state <- initialState _ <- forkIO $ processEvents ci (p state) emi return (\evi -> do atomically $ writeTChan ci $! evi)) {- | A simplified constructor for pipes that takes a function that does not use typed 'Event' objects in its input or output definitions. This may be useful in many cases, as the returned 'Pipe' will automatically handle 'EOS', leaving the supplied function with the task of simply performing whatever calculation on the input data that is appropriate to produce output (if any). -} process :: (i -> (o -> IO () ) -> IO () ) -> Pipe i o process fn = pipe (\evi emo -> case evi of EOS -> emo EOS Event i -> fn i (\o -> emo $ Event o) ) {- | The identity or 'id' 'Pipe' that simply emits as output any value given to it as input. -} pass :: Pipe i i pass = pipe (\evi emi -> emi evi) {- | Joins two pipes together to form a longer chain by connecting the transmitters for each pipe to one another. This is also the basis for implementing '>>>' in the 'Pipe' 'Category' instance -} connect :: Pipe i o -> Pipe o p -> Pipe i p connect pio pop = Pipe { transmitEvents = (\emp -> do emo <- (transmitEvents pop) emp emi <- (transmitEvents pio) emo return emi) } {- | At once a synonym for 'connect' and '>>>', this may be most useful for connecting pipes together into longer chains in a visual style that may be less distracting than using 'connect'. -} (=&=) :: Pipe i o -> Pipe o p -> Pipe i p (=&=) = connect {- | Given an input value and a 'Pipe', run the pipe to completion. Note that this function does not itself produce any output values, regardless of the value of the @o@ parameter to the supplied 'Pipe' type. -} runPipe :: i -> Pipe i o -> IO () runPipe i p = do done <- atomically $ newEmptyTMVar let eo ev = do case ev of Event _ -> return () EOS -> atomically $ putTMVar done () ei <- (transmitEvents p) eo ei $ Event i ei EOS _ <- atomically $ takeTMVar done return ()
hargettp/copper
src/Data/Pipes/Core.hs
mit
7,489
0
17
1,878
1,182
613
569
104
2
module Fresh.Module where import Fresh.Types (Id, Class, ClassId, Instance) import Fresh.Expr (EVarName) import Data.Map ( Map ) import Data.Monoid ((<>)) data Module t e = Module { moduleTypes :: Map Id t , moduleExprs :: Map EVarName (e) , moduleClasses :: Map ClassId (Class t e) , moduleInstances :: [ Instance t e ] } instance Monoid (Module t e) where mempty = Module { moduleTypes = mempty , moduleExprs = mempty , moduleClasses = mempty , moduleInstances = mempty } mappend x y = Module { moduleTypes = moduleTypes x <> moduleTypes y , moduleExprs = moduleExprs x <> moduleExprs y , moduleClasses = moduleClasses x <> moduleClasses y , moduleInstances = moduleInstances x <> moduleInstances y }
sinelaw/fresh
src/Fresh/Module.hs
gpl-2.0
848
0
11
264
249
141
108
24
0
-- Take the number 192 and multiply it by each of 1, 2, and 3: -- -- 192 × 1 = 192 -- 192 × 2 = 384 -- 192 × 3 = 576 -- -- By concatenating each product we get the 1 to 9 pandigital, 192384576. We will call 192384576 the concatenated product of 192 and (1,2,3) -- -- The same can be achieved by starting with 9 and multiplying by 1, 2, 3, 4, and 5, giving the pandigital, 918273645, which is the concatenated product of 9 and (1,2,3,4,5). -- -- What is the largest 1 to 9 pandigital 9-digit number that can be formed as the concatenated product of an integer with (1,2, ... , n) where n > 1? import Data.List import Data.Ord main :: IO () main = print answer -- This is probably way more complex than it needs to be -- * map answerFor over 1..9 getting the pandigital series for [n*1], [n*1,n*2] -- * filter out the ns for which no series exist -- * concat the lists -- * get maximum 'n' from them -- * and show the pandigital it generates answer :: Int answer = read . snd . maximumBy (comparing fst) . concat . filter (not . null) $ map answerFor [1..9] -- Given an n find all the 9 pandigitals for 9..9999 * [1..n] answerFor :: Int -> [(Int,String)] answerFor n = filter ((""/=) . snd) $ map (try n) [9..9999] -- Try an x and see if 1x,2x..nx is nine digit pandigital -- If it is return a pair of it and the pandigital it generates -- Otherwise it and "" try :: Int -> Int -> (Int, String) try n x = if ninePan q then (x,q) else (x,"") where q = dropWhile (=='0') $ concatMap (show . (x*)) [1..n] ninePan r = length r == 9 && pandigital '9' r pandigital :: Char -> String -> Bool pandigital n xs = sort xs == ['1'..n]
ciderpunx/project_euler_in_haskell
euler038.hs
gpl-2.0
1,674
0
11
382
319
180
139
17
2
{-# LANGUAGE ScopedTypeVariables #-} module LevelTransSpec(main, spec) where import Control.Monad.State import Control.Monad.Error import Test.Hspec import Level import Level.Transformation import TestHelper import HspecHelper main :: IO () main = hspec spec spec :: Spec spec = describe "A Level Transformation" $ do let level = createLevel $ unlines [ "## " , " # " , "m " ] dwarf' = findDwarf 'm' level wall' = findWall (1, 0) level move' coord = ErrorT . return . move dwarf' (from2d coord) mine' coord = ErrorT . return . mine dwarf' (findWall coord level) failOnMissingItem' coord = ErrorT . return . failOnMissingItem dwarf' wall' (from2d coord) describe "A Move" $ do it "moves an actor in one step to an adjacent coordinate" $ do e <- runErrorT $ move' (1,2) >=> levelShouldBe [ "## " , " # " , " m " ] >=> move' (0,1) >=> levelShouldBe [ "## " , "m# " , " " ] $ level e `shouldSatisfy` isRight it "cannot be executed if the destination is blocked" $ do e <- runErrorT $ move' (1,1) level e `shouldSatisfy` isLeft describe "Mining" $ it "removes the mining target and places the actor on the empty field" $ do e <- runErrorT $ mine' (1,1) >=> levelShouldBe [ "## " , " m " , " " ] >=> mine' (0,0) >=> levelShouldBe [ "m# " , " " , " " ] $ level e `shouldSatisfy` isRight describe "Fail on item missing" $ do it "fails if the item is not on the specified location" $ do let e = failOnMissingItem dwarf' wall' (from2d (2,2)) level e `shouldSatisfy` isLeft it "works with alternative" $ do e <- runErrorT $ failOnMissingItem' (1, 0) level e `shouldSatisfy` isRight
svenkeidel/gnome-citadel
test/LevelTransSpec.hs
gpl-3.0
2,255
0
21
973
549
282
267
58
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE OverloadedStrings #-} module Ampersand.Output.ToPandoc.ChapterConceptualAnalysis where import Ampersand.Output.ToPandoc.SharedAmongChapters import Data.List (intersperse ) import qualified Data.Set as Set chpConceptualAnalysis :: Int -> FSpec -> (Blocks,[Picture]) chpConceptualAnalysis lev fSpec = ( -- *** Header *** xDefBlck fSpec ConceptualAnalysis <> -- *** Intro *** caIntro <> -- *** For all patterns, a section containing the conceptual analysis for that pattern *** caBlocks, pictures) where -- shorthand for easy localizing l :: LocalizedStr -> String l = localize (fsLang fSpec) caIntro :: Blocks caIntro = (case fsLang fSpec of Dutch -> para ( "Dit hoofdstuk beschrijft een formele taal, waarin functionele eisen ten behoeve van " <> (singleQuoted.str.name) fSpec <> " kunnen worden besproken en uitgedrukt. " <> "De formalisering dient om een bouwbare specificatie te verkrijgen. " <> "Een derde met voldoende deskundigheid kan op basis van dit hoofdstuk toetsen of de gemaakte afspraken " <> "overeenkomen met de formele regels en definities. " ) English -> para ( "This chapter defines the formal language, in which functional requirements of " <> (singleQuoted.str.name) fSpec <> " can be analysed and expressed." <> "The purpose of this formalisation is to obtain a buildable specification. " <> "This chapter allows an independent professional with sufficient background to check whether the agreements made " <> "correspond to the formal rules and definitions. " ) )<> purposes2Blocks (getOpts fSpec) (purposesDefinedIn fSpec (fsLang fSpec) fSpec) -- This explains the purpose of this context. caBlocks = mconcat (map caSection (vpatterns fSpec)) <>(case fsLang fSpec of Dutch -> para "De definities van concepten zijn te vinden in de index." <> header (lev+3) "Gedeclareerde relaties" <> para "Deze paragraaf geeft een opsomming van de gedeclareerde relaties met eigenschappen en betekenis." English -> para "The definitions of concepts can be found in the glossary." <> header (lev+3) "Declared relations" <> para "This section itemizes the declared relations with properties and purpose." ) <> definitionList (map caRelation (Set.elems $ vrels fSpec)) pictures = map pictOfPat (vpatterns fSpec) ++ map pictOfConcept (Set.elems $ concs fSpec) ++ map pictOfRule (Set.elems $ vrules fSpec) ----------------------------------------------------- -- the Picture that represents this pattern's conceptual graph pictOfPat :: Pattern -> Picture pictOfPat = makePicture fSpec . PTCDPattern pictOfRule :: Rule -> Picture pictOfRule = makePicture fSpec . PTCDRule pictOfConcept :: A_Concept -> Picture pictOfConcept = makePicture fSpec . PTCDConcept caSection :: Pattern -> Blocks caSection pat = -- new section to explain this pattern xDefBlck fSpec (XRefConceptualAnalysisPattern pat) -- The section starts with the reason why this pattern exists <> purposes2Blocks (getOpts fSpec) (purposesDefinedIn fSpec (fsLang fSpec) pat) -- followed by a conceptual model for this pattern <> ( case fsLang fSpec of Dutch -> -- announce the conceptual diagram para (hyperLinkTo (pictOfPat pat) <> " geeft een conceptueel diagram van dit pattern.") -- draw the conceptual diagram <>(xDefBlck fSpec . pictOfPat) pat English -> para (hyperLinkTo (pictOfPat pat) <> " shows a conceptual diagram of this pattern.") <>(xDefBlck fSpec . pictOfPat) pat ) <> ( -- now provide the text of this pattern. case map caRule . Set.elems $ invariants fSpec `Set.intersection` udefrules pat of [] -> mempty blocks -> (case fsLang fSpec of Dutch -> header (lev+3) "Regels" <> plain "Deze paragraaf geeft een opsomming van de regels met een verwijzing naar de gemeenschappelijke taal van de belanghebbenden ten behoeve van de traceerbaarheid." English -> header (lev+3) "Rules" <> plain "This section itemizes the rules with a reference to the shared language of stakeholders for the sake of traceability." ) <> definitionList blocks ) caRelation :: Relation -> (Inlines, [Blocks]) caRelation d = let purp = purposes2Blocks (getOpts fSpec) (purposesDefinedIn fSpec (fsLang fSpec) d) in ((xDefInln fSpec (XRefConceptualAnalysisRelation d) <> ": "<>(showMathWithSign d)) ,[ -- First the reason why the relation exists, if any, with its properties as fundamental parts of its being.. ( case ( isNull purp, fsLang fSpec) of (True , Dutch) -> plain ("De volgende " <> str(nladjs d) <> " is gedefinieerd ") (True , English) -> plain ("The following " <> str(ukadjs d) <> " has been defined ") (False, Dutch) -> purp <> plain ("Voor dat doel is de volgende " <> str(nladjs d) <> " gedefinieerd ") (False, English) -> purp <> plain ("For this purpose, the following " <> str(ukadjs d) <> " has been defined ") ) -- Then the relation of the relation with its properties and its intended meaning <> printMeaning (fsLang fSpec) d ]) ukadjs d = if Uni `elem` (properties d) && Tot `elem` (properties d) then commaEng "and" (map adj . Set.elems $ (properties d Set.\\ Set.fromList [Uni,Tot]))++" function" else commaEng "and" (map adj . Set.elems $ (properties d))++" relation" nladjs d = if Uni `elem` (properties d) && Tot `elem` (properties d) then commaNL "en" (map adj . Set.elems $ properties d Set.\\ Set.fromList [Uni,Tot])++" functie" else commaNL "en" (map adj . Set.elems $ properties d)++" relatie" adj = propFullName (fsLang fSpec) caRule :: Rule -> (Inlines, [Blocks]) caRule r = let purp = purposes2Blocks (getOpts fSpec) (purposesDefinedIn fSpec (fsLang fSpec) r) in ( mempty , [ -- First the reason why the rule exists, if any.. purp -- Then the rule as a requirement <> plain ( if isNull purp then str (l (NL "De ongedocumenteerde afspraak ", EN "The undocumented agreement ")) <> (hyperLinkTo . XRefSharedLangRule) r <> str (l (NL " bestaat: " ,EN " has been made: ")) else str (l (NL "Daarom bestaat afspraak ", EN "Therefore agreement ")) <> (hyperLinkTo . XRefSharedLangRule) r <> str (l (NL " : ", EN " exists: ")) ) <> printMeaning (fsLang fSpec) r -- then the formal rule <> plain ( str (l (NL "Dit is - gebruikmakend van relaties " ,EN "Using relations " )) <> mconcat (intersperse (str ", ") [ hyperLinkTo (XRefConceptualAnalysisRelation d) <> text (" ("++name d++")") | d<-Set.elems $ bindedRelationsIn r]) <> str (l (NL " - geformaliseerd als " ,EN ", this is formalized as ")) ) <> pandocEquationWithLabel fSpec (XRefConceptualAnalysisRule r) (showMath r) -- followed by a conceptual model for this rule <> para ( hyperLinkTo (pictOfRule r) <> str (l (NL " geeft een conceptueel diagram van deze regel." ,EN " shows a conceptual diagram of this rule.")) ) <> xDefBlck fSpec (pictOfRule r) ] )
AmpersandTarski/ampersand
src/Ampersand/Output/ToPandoc/ChapterConceptualAnalysis.hs
gpl-3.0
8,541
0
28
2,942
1,764
901
863
120
12
-- | BlastHTTP test script --runghc -package-db --ghc-arg=.cabal-sandbox/x86_64-linux-ghc-8.0.1-packages.conf.d/ BlastTabularHTTPTest.hs aeromonas.fa module Main where import System.Environment (getArgs) import System.Process import Text.ParserCombinators.Parsec import System.IO import System.Environment import Data.List import System.Directory import System.Process import Control.Monad import Data.Either.Unwrap import Bio.BlastHTTP import Biobase.Fasta.Streaming import Biobase.Fasta.Types import qualified Data.ByteString.Lazy.Char8 as L8 main = do args <- getArgs let input_file = (head args) putStrLn "Test:" inputFasta <- parseFastaFile input_file let blastQuery = BlastHTTPQuery (Just "ncbi") (Just "blastn") (Just "nt") inputFasta Nothing (Just (7200000000 ::Int)) blastOutput <- blastTabularHTTP blastQuery if isRight blastOutput then print (fromRight blastOutput) else print (fromLeft blastOutput)
eggzilla/BlastHTTP
BlastTabularHTTPTest.hs
gpl-3.0
950
0
13
131
227
123
104
25
2
{- teafree, a Haskell utility for tea addicts Copyright (C) 2013 Fabien Dubosson <fabien.dubosson@gmail.com> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} {-# LANGUAGE TemplateHaskell, TypeOperators #-} module Teafree.Core.Environment ( Environment , defaultEnvironment , get , set , modify , teas , families , quantityTo , temperatureTo ) where import Data.Label import Data.List as DL import Control.Monad import System.Directory import System.Environment (lookupEnv) import System.FilePath import Paths_teafree import Teafree.Core.Parsers import Teafree.Entity.Family as F import Teafree.Entity.Tea as Tea import Teafree.Entity.Units as U import Data.Text as T import Data.Text.IO as TIO default (T.Text) fclabels [d| data Environment = Environment { teas :: [Tea] , families :: [Family] , quantityTo :: U.Quantity -> U.Quantity , temperatureTo :: U.Temperature -> U.Temperature } |] defaultEnvironment :: Environment defaultEnvironment = Environment [] [] id id
StreakyCobra/teafree
src/Teafree/Core/Environment.hs
gpl-3.0
1,706
0
6
394
164
107
57
33
1
module GeneralSpecies (agents) where import Agent import Blackboard import Note import Interval import Voice import Data.Function (on) import Control.Monad import Control.Applicative import Control.Arrow import Data.Maybe (fromMaybe) agents :: [Agent] agents = [ beginPerfectConsonance , noAugDimCPIntervals , dontSkipMoreThan6 , noAug4Outline , endPerfectConsonance , fillInDim5OutlineAndOppStep ] toBool = fromMaybe False -- skipping hard rule 1 -- hard rule 2 noAugDimCPIntervals = makeHardRule op "General CP - no augmented or diminished intervals in CP." where op bb = let cp = goToTime (counterPoint bb) (timeToTestAt bb) notes = getBackN 2 =<< cp interval = liftM2 (#) (liftM (!!0) notes) (liftM (!!1) notes) isDim = toBool . liftM ((<Minor) . quality) $ interval isAug = toBool . liftM ((>Major) . quality) $ interval in (if isDim || isAug then failTest else passTest) bb dontSkipMoreThan6 = makeHardRule op "General CP - no skips larger than a sixth (except octave)." where op bb = let cp = goToTime (counterPoint bb) (timeToTestAt bb) notes = getBackN 2 =<< cp interval = liftM2 (#) (liftM (!!0) notes) (liftM (!!1) notes) tooBig = toBool . liftM ((> Span maj6) . Span) $ interval isOctv = toBool . liftM (== octv) $ interval in (if isOctv || not tooBig then passTest else failTest) bb -- hard rule 3 beginPerfectConsonance = makeHardRule op "General CP - start with perfect consonance." where op bb = let cfStart = getCurrentNote . front . cantusFirmus $ bb cpStart = getCurrentNote . front . counterPoint $ bb interval = liftM2 (#) cfStart cpStart isPerfectConsonance i = quality i == Perfect && simplify i `elem` [unison, perf5, octv] noteOk = toBool . liftM isPerfectConsonance $ interval atFirstNote = timeToTestAt bb == 0 in (if not atFirstNote || noteOk then passTest else failTest) bb endPerfectConsonance = flip makeHardRule "General CP - end with perfect consonance." $ \bb -> let atLastNote = durationOfCounterPoint bb == durationOfCantusFirmus bb lastCFNote = getCurrentNote <=< back1 . end . cantusFirmus $ bb lastCPNote = getCurrentNote <=< back1 . end . counterPoint $ bb interval = liftM2 (#) lastCFNote lastCPNote isPerfectConsonance i = quality i == Perfect && simplify i `elem` [unison, perf5, octv] noteOk = toBool . liftM isPerfectConsonance $ interval in (if not atLastNote || noteOk then passTest else failTest) bb -- hard rule 4 noAug4Outline = flip makeHardRule "General CP - no outlines (interval btw local extrema) of augmented fourths." $ \bb -> let cp = goToTime (counterPoint bb) (timeToTestAt bb) ext1 = cp >>= recentLocalExtreme ext2 = ext1 >>= recentLocalExtreme interval = liftM2 (#) (ext1 >>= getCurrentNote) (ext2 >>= getCurrentNote) isAug4 = toBool . liftM (==aug4) $ interval in (if isAug4 then failTest else passTest) bb fillInDim5OutlineAndOppStep = flip makeHardRule "General CP - an outline of dim5 must be completely filled in and followed by a step in the opposite direciton." $ \bb -> let cp = goToTime (counterPoint bb) (timeToTestAt bb) ext1 = cp >>= recentLocalExtreme ext2 = ext1 >>= recentLocalExtreme ext1Note = ext1 >>= getCurrentNote ext2Note = ext2 >>= getCurrentNote interval = liftM2 (#) ext1Note ext2Note isDim5 = toBool . liftM (==dim5) $ interval numBtw = fmap (subtract 1) $ liftM2 (-) (fmap numAfter ext2) (fmap numAfter ext1) lowerNote = liftM2 (min `on` Location) ext1Note ext2Note >>= \(Location note) -> Just note :: Maybe Note fillNotes = map (\n -> liftM (raise n) lowerNote) [1,2,3] :: [ Maybe Note ] intervening = do n <- numBtw start <- ext2 (_:notes) <- getForwardN (n+1) start return notes :: Maybe [Note] isFilled = toBool $ do interNotes <- intervening let f ml = liftM (`elem` (map Location interNotes)) ml let fillLocs = map (liftM Location) fillNotes return . and . map toBool . map f $ fillLocs followingNote = ext1 >>= forward1 >>= getCurrentNote isStep = toBool $ liftM2 (#-#) ext1Note followingNote >>= Just . (==2) . abs -- We don't need to test if we're stepping in the opposite direction because we must be; otherwise ext1 would not be an extreme point. in (if not isDim5 || (isFilled && isStep) then passTest else failTest) bb -- soft rule 1 moreStepsThanSkips = flip makeSoftRule "General CP - use steps for frequently than skips." $ \bb -> undefined -- soft rule 2 avoidMaj6Skips = flip makeSoftRule "General CP - avoid skipping a major sixth." $ \bb -> undefined avoidMin6SkipsDown = flip makeSoftRule "General CP - avoid skipping a minor sixth downwards." $ \bb -> undefined -- soft rule 3 precedeOrFollowSkipWithOppStep = flip makeSoftRule "General CP - prefer to precede and/or follow a skip with a step in opposite direction." $ \bb -> undefined -- soft rule 4 dontUseMoreThan2SuccSkips = flip makeSoftRule "General CP - do not use more than 2 skips in succession." $ \bb -> undefined -- soft rule 5 keep2SuccSkipsInSameDirSmall = flip makeSoftRule "General CP - if there are 2 successive skips in the same direction, keep them small (<4th)." $ \bb -> undefined -- soft rule 6 pyramidRule = flip makeSoftRule "General CP - when using skips and steps in the same direction, larger intervals should be below smaller ones." $ \bb -> undefined -- soft rule 7 avoidSkipToAndFromLocalHighOrLow = flip makeSoftRule "General CP - avoid skipping both to and from a temporary high or low point." $ \bb -> undefined -- skipping soft rule 8
yousufmsoliman/music
Source (Haskell)/GeneralSpecies.hs
gpl-3.0
5,964
0
20
1,502
1,538
821
717
-1
-1
{-# OPTIONS -Wall #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE KindSignatures #-} module FancyDomain where import Data.Sequence as Seq import Data.Monoid import Context import qualified Language as TM import Semantics import qualified NormalForms as NF ---------------------------------------------------- -- THE EVALUATION DOMAIN -- We opt for a well-scoped by construction approach which lets us -- avoid the back-and-forth motion bewteen de Bruijn levels / indices -- typical of name generation-based approaches. -- This is made possible by the typical Kripke structure of the BND -- construct taking into account all possible future extensions of -- the current scope. ---------------------------------------------------- data Dom (g :: Context) = NF (ActDom g) | NE (Var g) (Spine g) | BT data Elim (g :: Context) = APP (Dom g) | REC (Dom g) (Dom g) (Dom g) newtype Spine (g :: Context) = Spine { unSpine :: Seq (Elim g) } data ActDom (g :: Context) = BND (Binder g) (forall d. Renaming g d -> Dom d -> Dom d) | SUC (Dom g) | ZRO | NAT | SET data Binder (g :: Context) = LAM | PI (Dom g) instance Monoid (Spine g) where mempty = Spine empty mappend sp sp' = Spine $ unSpine sp >< unSpine sp' -- Renaming for the domain weakDom :: Renaming g d -> Dom g -> Dom d weakDom ren (NF ad) = NF $ weakActDom ren ad weakDom ren (NE v sp) = NE (ren v) $ weakSpine ren sp weakDom _ BT = BT weakActDom :: Renaming g d -> ActDom g -> ActDom d weakActDom ren (BND bd t) = BND (weakBinder ren bd) $ t . trans ren weakActDom ren (SUC n) = SUC $ weakDom ren n weakActDom _ ZRO = ZRO weakActDom _ NAT = NAT weakActDom _ SET = SET weakBinder :: Renaming g d -> Binder g -> Binder d weakBinder _ LAM = LAM weakBinder ren (PI a) = PI $ weakDom ren a weakElim :: Renaming g d -> Elim g -> Elim d weakElim ren (APP u) = APP $ weakDom ren u weakElim ren (REC ty s z) = REC (wk ty) (wk s) (wk z) where wk = weakDom ren weakSpine :: Renaming g d -> Spine g -> Spine d weakSpine ren = Spine . fmap (weakElim ren) . unSpine ---------------------------------------------------- -- EVALUATION ---------------------------------------------------- data BinderOrLet (g :: Context) = BINDER (Binder g) | LET (Dom g) domCUT :: Dom g -> Spine g -> Dom g domCUT (NE v sp) sp' = NE v $ sp <> sp' domCUT nf@(NF ad) sp = case viewl $ unSpine sp of EmptyL -> nf el :< sp' -> actCUT ad el (Spine sp') domCUT BT _ = BT actCUT :: ActDom g -> Elim g -> Spine g -> Dom g actCUT ZRO (REC _ _ z) = domCUT z actCUT (SUC n) r@(REC _ s _) = domCUT $ domCUT s $ Spine sp where sp = fromList [ APP n , APP $ domCUT n $ Spine $ singleton r ] actCUT (BND _ t) (APP el) = domCUT (t refl el) actCUT _ _ = const BT normalisation :: Semantics Dom Dom BinderOrLet Dom Elim Spine normalisation = Semantics { weak = weakDom , embed = \ v -> NE v $ Spine empty , var = id , cut = domCUT , ann = const , lam = BINDER LAM , piT = BINDER . PI , letx = LET , bnd = \ bdOrLet t -> case bdOrLet of LET v -> t refl v BINDER bd -> NF $ BND bd t , zro = NF ZRO , suc = NF . SUC , emb = id , nat = NF NAT , set = NF SET , app = APP , rec = REC , spine = Spine } ---------------------------------------------------- -- THE REIFICATION PROCESS ---------------------------------------------------- reflect :: Var g -> Dom g reflect v = NE v $ Spine empty reify :: Dom g -> NF.Nf g reify (NF d) = reifyAct d reify (NE v sp) = NF.Emb $ NF.Cut v $ NF.Spine $ fmap reifyArg $ unSpine sp reifyAct :: ActDom g -> NF.Nf g reifyAct (BND bd t) = NF.Bnd (reifyBinder bd) $ reify $ t (top refl) $ reflect Z reifyAct (SUC d) = NF.Suc $ reify d reifyAct ZRO = NF.Zro reifyAct NAT = NF.Nat reifyAct SET = NF.Set reifyBinder :: Binder g -> NF.Binder g reifyBinder LAM = NF.Lam reifyBinder (PI a) = NF.Pi $ reify a reifyArg :: Elim g -> NF.Elim g reifyArg (APP t) = NF.App $ reify t reifyArg (REC ty z s) = NF.Rec (reify ty) (reify z) (reify s) instance SContextI g => Show (Dom g) where show d = show $ reify d normInfer :: TM.Infer a -> NF.Nf a normInfer t = reify $ lemmaInfer normalisation t $ reflect normCheck :: TM.Check a -> NF.Nf a normCheck t = reify $ lemmaCheck normalisation t $ reflect
gallais/potpourri
haskell/nurules/FancyDomain.hs
gpl-3.0
4,487
0
12
1,186
1,768
904
864
106
2
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0"> <title>CHRIS/Proba Atmospheric Correction Tool Help</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view mergetype="javax.help.UniteAppendMerge"> <name>TOC</name> <label>Contents</label> <type>javax.help.TOCView</type> <data>toc.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine">JavaHelpSearch</data> </view> </helpset>
bcdev/chris-box
chris-atmospheric-correction/src/main/resources/doc/help/atmosphericcorrection.hs
gpl-3.0
800
54
45
167
291
147
144
-1
-1
module Abstat.Interface.Lattice where class (Eq t) => Lattice t where join :: t -> t -> t meet :: t -> t -> t top :: t bottom :: t cmpUsingJoin :: (Eq t, Lattice t) => t -> t -> Maybe Ordering cmpUsingJoin a b | a == b = Just EQ | otherwise = case a `join` b of x | x == a -> Just GT x | x == b -> Just LT _ -> Nothing cmpUsingMeet :: (Eq t, Lattice t) => t -> t -> Maybe Ordering cmpUsingMeet a b | a == b = Just EQ | otherwise = case a `meet` b of x | x == a -> Just LT x | x == b -> Just GT _ -> Nothing lfpFrom :: (Eq t) => t -> (t -> t) -> t lfpFrom initial fun = case fun initial of x | x == initial -> x x -> lfpFrom x fun
fpoli/abstat
src/Abstat/Interface/Lattice.hs
gpl-3.0
774
0
12
306
368
180
188
27
3
module Main where import Types import Objects import Locations import GameAction run :: Location -> IO () run curLoc = let locObjects = locationObjects curLoc locDescr = describeLocation curLoc objectsDescr = enumerateObjects locObjects fullDescr = locDescr ++ objectsDescr in do putStrLn fullDescr putStr "Enter command: " x <- getLine case (convertStringToAction x) of Quit -> putStrLn "Be seen you..." Investigate obj -> do putStrLn (investigate obj locObjects) run curLoc Look -> do putStrLn fullDescr run curLoc Go dir -> do putStrLn ("\nYou're going to " ++ show dir ++ ".\n") run (walk curLoc dir) conversionResult -> do putStrLn (evalAction conversionResult) putStrLn "End of turn.\n" run curLoc main = do putStrLn "Quest adventure on Haskell.\n" run Home
dskecse/Adv2Game
QuestMain.hs
gpl-3.0
908
0
18
260
255
115
140
34
5
-- | Different leaf types in the Sugar expressions. -- These don't contain more expressions in them. {-# LANGUAGE TemplateHaskell, DataKinds, GADTs, TypeFamilies, MultiParamTypeClasses #-} module Lamdu.Sugar.Types.Parts ( VarInfo(..), _VarNominal, _VarGeneric, _VarFunction, _VarRecord, _VarVariant , FuncApplyLimit(..), _UnlimitedFuncApply, _AtMostOneFuncApply , Literal(..), _LiteralNum, _LiteralBytes, _LiteralChar, _LiteralText , -- Annotations Annotation(..), _AnnotationVal, _AnnotationType, _AnnotationNone -- Node actions , DetachAction(..), _FragmentedAlready, _DetachAction , Delete(..), _SetToHole, _Delete, _CannotDelete , NodeActions(..), detach, delete, setToLiteral, extract, mReplaceParent, mApply , -- Let ExtractDestination(..) , -- TaggedList TaggedList(..), tlAddFirst, tlItems , TaggedSwappableItem(..), tsiItem, tsiSwapWithPrevious , TaggedListBody(..), tlHead, tlTail , TaggedItem(..), tiTag, tiDelete, tiValue, tiAddAfter , -- Binders LhsNames(..), _LhsVar, _LhsRecord , FuncParam(..), fpAnnotation, fpUsages, fpVarInfo , NullParamActions(..), npDeleteLambda , Var(..), vTag, vAddPrev, vAddNext, vDelete, vIsNullParam, vParam , LhsField(..), fParam, fSubFields , AddParam(..), _AddNext, _NeedToPickTagToAddNext , -- Expressions Payload(..), plEntityId, plAnnotation, plActions, plHiddenEntityIds, plParenInfo , ClosedCompositeActions(..), closedCompositeOpen , PunnedVar(..), pvVar, pvTagEntityId , NullaryInject(..), iInject, iContent , Option(..), optionExpr, optionPick, optionTypeMatch, optionMNewTag , Query(..), qLangInfo, qTagSuffixes, qSearchTerm , QueryLangInfo(..), qLangId, qLangDir, qCodeTexts, qUITexts, qNameTexts , hasQueryLangInfo , TaggedVarId(..), TagSuffixes , Expr , ParenInfo(..), piNeedParens, piMinOpPrec ) where import qualified Control.Lens as Lens import Control.Monad.Unit (Unit) import Data.Kind (Type) import Data.UUID.Types (UUID) import GUI.Momentu.Direction (Layout) import Hyper (makeHTraversableAndBases, makeHMorph) import qualified Lamdu.Calc.Type as T import qualified Lamdu.I18N.Code as Texts import qualified Lamdu.I18N.CodeUI as Texts import qualified Lamdu.I18N.Name as Texts import Lamdu.I18N.LangId (LangId) import Lamdu.Sugar.Internal.EntityId (EntityId) import Lamdu.Sugar.Types.GetVar import Lamdu.Sugar.Types.Tag import qualified Lamdu.Sugar.Types.Type as SugarType import Lamdu.Prelude type Expr e v name (i :: Type -> Type) o = Annotated (Payload v o) # e v name i o -- Can a lambda be called more than once? -- Used to avoid showing scope selector presentations for case alternative lambdas. data FuncApplyLimit = UnlimitedFuncApply | AtMostOneFuncApply deriving (Eq, Ord, Generic) data Annotation v name = AnnotationType (Annotated EntityId # SugarType.Type name Unit) | AnnotationVal v | AnnotationNone deriving Generic data AddParam name i o = AddNext (i (TagChoice name o)) | -- When the param has anon tag one can't add another one, -- contains the EntityId of the param requiring tag. NeedToPickTagToAddNext EntityId deriving Generic newtype NullParamActions o = NullParamActions { _npDeleteLambda :: o () } deriving stock Generic data FuncParam v = FuncParam -- TODO: Better name { _fpAnnotation :: v , _fpUsages :: [EntityId] , _fpVarInfo :: VarInfo } deriving (Generic, Functor, Foldable, Traversable) data ExtractDestination = ExtractToLet EntityId | ExtractToDef EntityId data DetachAction o = FragmentedAlready EntityId -- Already a fragment, its expr or hole | DetachAction (o EntityId) -- Detach me deriving Generic data Delete m = SetToHole (m EntityId) | -- Changes the structure around the hole to remove the hole. -- For example (f _) becomes (f) or (2 + _) becomes 2 Delete (m EntityId) | CannotDelete deriving Generic data NodeActions o = NodeActions { _detach :: DetachAction o , _delete :: Delete o , _setToLiteral :: Literal Identity -> o EntityId , _extract :: o ExtractDestination , _mReplaceParent :: Maybe (o EntityId) , _mApply :: Maybe (o EntityId) } deriving Generic data TaggedItem name i o a = TaggedItem { _tiTag :: TagRef name i o , _tiDelete :: o () , _tiAddAfter :: i (TagChoice name o) , _tiValue :: a } deriving (Generic, Functor, Foldable, Traversable) data TaggedSwappableItem name i o a = TaggedSwappableItem { _tsiItem :: TaggedItem name i o a , _tsiSwapWithPrevious :: o () } deriving (Generic, Functor, Foldable, Traversable) data TaggedListBody name i o a = TaggedListBody { _tlHead :: TaggedItem name i o a -- The 2nd tagged item onwards can be swapped with their previous item , _tlTail :: [TaggedSwappableItem name i o a] } deriving (Generic, Functor, Foldable, Traversable) data TaggedList name i o a = TaggedList { _tlAddFirst :: i (TagChoice name o) , _tlItems :: Maybe (TaggedListBody name i o a) } deriving (Generic, Functor, Foldable, Traversable) data Var name i o v = Var { _vParam :: FuncParam v , _vTag :: OptionalTag name i o , _vAddPrev :: AddParam name i o , _vAddNext :: AddParam name i o , _vDelete :: o () , _vIsNullParam :: Bool } deriving (Generic, Functor, Foldable, Traversable) -- TODO: Is there a standard term for this? data LhsField name v = LhsField { _fParam :: FuncParam v , _fSubFields :: Maybe [(Tag name, LhsField name v)] } deriving (Generic, Functor, Foldable, Traversable) data LhsNames name i o v = LhsVar (Var name i o v) | LhsRecord (TaggedList name i o (LhsField name v)) deriving (Generic, Functor, Foldable, Traversable) -- VarInfo is used for: -- * Differentiating Mut actions so UI can suggest executing them -- * Name pass giving parameters names according to types data VarInfo = VarNominal (SugarType.TId T.Tag Unit) | VarGeneric | VarFunction | VarRecord | VarUnit | VarVariant | VarVoid deriving (Generic, Eq) data Payload v o = Payload { _plAnnotation :: v , _plActions :: NodeActions o , _plEntityId :: EntityId , _plParenInfo :: !ParenInfo , _plHiddenEntityIds :: [EntityId] } deriving Generic newtype ClosedCompositeActions o = ClosedCompositeActions { _closedCompositeOpen :: o EntityId } deriving stock Generic data Literal f = LiteralNum (f Double) | LiteralBytes (f ByteString) | LiteralChar (f Char) | LiteralText (f Text) deriving Generic data NullaryInject name i o k = NullaryInject { _iInject :: k :# Const (TagRef name i o) , -- Child represents the empty record, and has action to add an item _iContent :: k :# Const (i (TagChoice name o)) } deriving Generic data PunnedVar name o k = PunnedVar { _pvVar :: k :# Const (GetVar name o) , _pvTagEntityId :: EntityId } deriving Generic data ParenInfo = ParenInfo { _piMinOpPrec :: !Int , _piNeedParens :: !Bool } deriving (Eq, Show, Generic) data Option t name i o = Option { _optionExpr :: Expr t (Annotation () name) name i o , _optionPick :: o () , -- Whether option expr fits the destination or will it be fragmented? -- Note that for fragments, this doesn't indicate whether the emplaced fragmented expr -- within stays fragmented. _optionTypeMatch :: Bool , -- Whether option includes creation of new tag for the given search string _optionMNewTag :: Maybe T.Tag } deriving Generic data QueryLangInfo = QueryLangInfo { _qLangId :: LangId , _qLangDir :: Layout , _qCodeTexts :: Texts.Code Text , _qUITexts :: Texts.CodeUI Text , _qNameTexts :: Texts.Name Text } hasQueryLangInfo :: _ => a -> QueryLangInfo hasQueryLangInfo env = QueryLangInfo (env ^. has) (env ^. has) (env ^. has) (env ^. has) (env ^. has) -- Like InternalName, but necessarily with a context and non-anonymous tag data TaggedVarId = TaggedVarId { _tvCtx :: UUID -- InternalName's context , _tvTag :: T.Tag -- InternalName's tag } deriving (Eq, Ord, Show, Generic) type TagSuffixes = Map TaggedVarId Int data Query = Query { _qLangInfo :: QueryLangInfo , _qTagSuffixes :: TagSuffixes , _qSearchTerm :: Text } traverse Lens.makeLenses [ ''ClosedCompositeActions, ''FuncParam, ''LhsField, ''NodeActions , ''NullParamActions, ''NullaryInject, ''Option, ''ParenInfo, ''Payload, ''PunnedVar , ''Query, ''QueryLangInfo , ''TaggedList, ''TaggedListBody, ''TaggedItem, ''TaggedSwappableItem, ''Var ] <&> concat traverse Lens.makePrisms [ ''AddParam, ''Annotation, ''Delete, ''DetachAction , ''FuncApplyLimit, ''LhsNames, ''Literal, ''VarInfo ] <&> concat traverse makeHTraversableAndBases [''NullaryInject, ''PunnedVar] <&> concat makeHMorph ''NullaryInject
lamdu/lamdu
src/Lamdu/Sugar/Types/Parts.hs
gpl-3.0
9,037
0
14
1,966
2,268
1,374
894
-1
-1
module C where c :: Int c = 5
ktvoelker/hjc
example/C.hs
gpl-3.0
33
0
4
12
14
9
5
3
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.TaskQueue.Tasks.Update -- Copyright : (c) 2015-2016 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) -- -- Update tasks that are leased out of a TaskQueue. -- -- /See:/ <https://developers.google.com/appengine/docs/python/taskqueue/rest TaskQueue API Reference> for @taskqueue.tasks.update@. module Network.Google.Resource.TaskQueue.Tasks.Update ( -- * REST Resource TasksUpdateResource -- * Creating a Request , tasksUpdate , TasksUpdate -- * Request Lenses , tuTaskQueue , tuProject , tuPayload , tuTask , tuNewLeaseSeconds ) where import Network.Google.Prelude import Network.Google.TaskQueue.Types -- | A resource alias for @taskqueue.tasks.update@ method which the -- 'TasksUpdate' request conforms to. type TasksUpdateResource = "taskqueue" :> "v1beta2" :> "projects" :> Capture "project" Text :> "taskqueues" :> Capture "taskqueue" Text :> "tasks" :> Capture "task" Text :> QueryParam "newLeaseSeconds" (Textual Int32) :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Task :> Post '[JSON] Task -- | Update tasks that are leased out of a TaskQueue. -- -- /See:/ 'tasksUpdate' smart constructor. data TasksUpdate = TasksUpdate' { _tuTaskQueue :: !Text , _tuProject :: !Text , _tuPayload :: !Task , _tuTask :: !Text , _tuNewLeaseSeconds :: !(Textual Int32) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TasksUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tuTaskQueue' -- -- * 'tuProject' -- -- * 'tuPayload' -- -- * 'tuTask' -- -- * 'tuNewLeaseSeconds' tasksUpdate :: Text -- ^ 'tuTaskQueue' -> Text -- ^ 'tuProject' -> Task -- ^ 'tuPayload' -> Text -- ^ 'tuTask' -> Int32 -- ^ 'tuNewLeaseSeconds' -> TasksUpdate tasksUpdate pTuTaskQueue_ pTuProject_ pTuPayload_ pTuTask_ pTuNewLeaseSeconds_ = TasksUpdate' { _tuTaskQueue = pTuTaskQueue_ , _tuProject = pTuProject_ , _tuPayload = pTuPayload_ , _tuTask = pTuTask_ , _tuNewLeaseSeconds = _Coerce # pTuNewLeaseSeconds_ } tuTaskQueue :: Lens' TasksUpdate Text tuTaskQueue = lens _tuTaskQueue (\ s a -> s{_tuTaskQueue = a}) -- | The project under which the queue lies. tuProject :: Lens' TasksUpdate Text tuProject = lens _tuProject (\ s a -> s{_tuProject = a}) -- | Multipart request metadata. tuPayload :: Lens' TasksUpdate Task tuPayload = lens _tuPayload (\ s a -> s{_tuPayload = a}) tuTask :: Lens' TasksUpdate Text tuTask = lens _tuTask (\ s a -> s{_tuTask = a}) -- | The new lease in seconds. tuNewLeaseSeconds :: Lens' TasksUpdate Int32 tuNewLeaseSeconds = lens _tuNewLeaseSeconds (\ s a -> s{_tuNewLeaseSeconds = a}) . _Coerce instance GoogleRequest TasksUpdate where type Rs TasksUpdate = Task type Scopes TasksUpdate = '["https://www.googleapis.com/auth/taskqueue", "https://www.googleapis.com/auth/taskqueue.consumer"] requestClient TasksUpdate'{..} = go _tuProject _tuTaskQueue _tuTask (Just _tuNewLeaseSeconds) (Just AltJSON) _tuPayload taskQueueService where go = buildClient (Proxy :: Proxy TasksUpdateResource) mempty
rueshyna/gogol
gogol-taskqueue/gen/Network/Google/Resource/TaskQueue/Tasks/Update.hs
mpl-2.0
4,211
0
18
1,095
642
376
266
97
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchDelete -- Copyright : (c) 2015-2016 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) -- -- Begins executing a batch delete jobs operation. -- -- /See:/ <https://cloud.google.com/talent-solution/job-search/docs/ Cloud Talent Solution API Reference> for @jobs.projects.tenants.jobs.batchDelete@. module Network.Google.Resource.Jobs.Projects.Tenants.Jobs.BatchDelete ( -- * REST Resource ProjectsTenantsJobsBatchDeleteResource -- * Creating a Request , projectsTenantsJobsBatchDelete , ProjectsTenantsJobsBatchDelete -- * Request Lenses , ptjbdParent , ptjbdXgafv , ptjbdUploadProtocol , ptjbdAccessToken , ptjbdUploadType , ptjbdPayload , ptjbdCallback ) where import Network.Google.Jobs.Types import Network.Google.Prelude -- | A resource alias for @jobs.projects.tenants.jobs.batchDelete@ method which the -- 'ProjectsTenantsJobsBatchDelete' request conforms to. type ProjectsTenantsJobsBatchDeleteResource = "v4" :> Capture "parent" Text :> "jobs:batchDelete" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BatchDeleteJobsRequest :> Post '[JSON] Operation -- | Begins executing a batch delete jobs operation. -- -- /See:/ 'projectsTenantsJobsBatchDelete' smart constructor. data ProjectsTenantsJobsBatchDelete = ProjectsTenantsJobsBatchDelete' { _ptjbdParent :: !Text , _ptjbdXgafv :: !(Maybe Xgafv) , _ptjbdUploadProtocol :: !(Maybe Text) , _ptjbdAccessToken :: !(Maybe Text) , _ptjbdUploadType :: !(Maybe Text) , _ptjbdPayload :: !BatchDeleteJobsRequest , _ptjbdCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsTenantsJobsBatchDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'ptjbdParent' -- -- * 'ptjbdXgafv' -- -- * 'ptjbdUploadProtocol' -- -- * 'ptjbdAccessToken' -- -- * 'ptjbdUploadType' -- -- * 'ptjbdPayload' -- -- * 'ptjbdCallback' projectsTenantsJobsBatchDelete :: Text -- ^ 'ptjbdParent' -> BatchDeleteJobsRequest -- ^ 'ptjbdPayload' -> ProjectsTenantsJobsBatchDelete projectsTenantsJobsBatchDelete pPtjbdParent_ pPtjbdPayload_ = ProjectsTenantsJobsBatchDelete' { _ptjbdParent = pPtjbdParent_ , _ptjbdXgafv = Nothing , _ptjbdUploadProtocol = Nothing , _ptjbdAccessToken = Nothing , _ptjbdUploadType = Nothing , _ptjbdPayload = pPtjbdPayload_ , _ptjbdCallback = Nothing } -- | Required. The resource name of the tenant under which the job is -- created. The format is \"projects\/{project_id}\/tenants\/{tenant_id}\". -- For example, \"projects\/foo\/tenants\/bar\". The parent of all of the -- jobs specified in \`names\` must match this field. ptjbdParent :: Lens' ProjectsTenantsJobsBatchDelete Text ptjbdParent = lens _ptjbdParent (\ s a -> s{_ptjbdParent = a}) -- | V1 error format. ptjbdXgafv :: Lens' ProjectsTenantsJobsBatchDelete (Maybe Xgafv) ptjbdXgafv = lens _ptjbdXgafv (\ s a -> s{_ptjbdXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). ptjbdUploadProtocol :: Lens' ProjectsTenantsJobsBatchDelete (Maybe Text) ptjbdUploadProtocol = lens _ptjbdUploadProtocol (\ s a -> s{_ptjbdUploadProtocol = a}) -- | OAuth access token. ptjbdAccessToken :: Lens' ProjectsTenantsJobsBatchDelete (Maybe Text) ptjbdAccessToken = lens _ptjbdAccessToken (\ s a -> s{_ptjbdAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). ptjbdUploadType :: Lens' ProjectsTenantsJobsBatchDelete (Maybe Text) ptjbdUploadType = lens _ptjbdUploadType (\ s a -> s{_ptjbdUploadType = a}) -- | Multipart request metadata. ptjbdPayload :: Lens' ProjectsTenantsJobsBatchDelete BatchDeleteJobsRequest ptjbdPayload = lens _ptjbdPayload (\ s a -> s{_ptjbdPayload = a}) -- | JSONP ptjbdCallback :: Lens' ProjectsTenantsJobsBatchDelete (Maybe Text) ptjbdCallback = lens _ptjbdCallback (\ s a -> s{_ptjbdCallback = a}) instance GoogleRequest ProjectsTenantsJobsBatchDelete where type Rs ProjectsTenantsJobsBatchDelete = Operation type Scopes ProjectsTenantsJobsBatchDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/jobs"] requestClient ProjectsTenantsJobsBatchDelete'{..} = go _ptjbdParent _ptjbdXgafv _ptjbdUploadProtocol _ptjbdAccessToken _ptjbdUploadType _ptjbdCallback (Just AltJSON) _ptjbdPayload jobsService where go = buildClient (Proxy :: Proxy ProjectsTenantsJobsBatchDeleteResource) mempty
brendanhay/gogol
gogol-jobs/gen/Network/Google/Resource/Jobs/Projects/Tenants/Jobs/BatchDelete.hs
mpl-2.0
5,807
0
17
1,268
786
460
326
118
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Tasks.Tasks.Move -- Copyright : (c) 2015-2016 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) -- -- Moves the specified task to another position in the task list. This can -- include putting it as a child task under a new parent and\/or move it to -- a different position among its sibling tasks. -- -- /See:/ <https://developers.google.com/google-apps/tasks/firstapp Tasks API Reference> for @tasks.tasks.move@. module Network.Google.Resource.Tasks.Tasks.Move ( -- * REST Resource TasksMoveResource -- * Creating a Request , tasksMove , TasksMove -- * Request Lenses , tmParent , tmTaskList , tmTask , tmPrevious ) where import Network.Google.AppsTasks.Types import Network.Google.Prelude -- | A resource alias for @tasks.tasks.move@ method which the -- 'TasksMove' request conforms to. type TasksMoveResource = "tasks" :> "v1" :> "lists" :> Capture "tasklist" Text :> "tasks" :> Capture "task" Text :> "move" :> QueryParam "parent" Text :> QueryParam "previous" Text :> QueryParam "alt" AltJSON :> Post '[JSON] Task -- | Moves the specified task to another position in the task list. This can -- include putting it as a child task under a new parent and\/or move it to -- a different position among its sibling tasks. -- -- /See:/ 'tasksMove' smart constructor. data TasksMove = TasksMove' { _tmParent :: !(Maybe Text) , _tmTaskList :: !Text , _tmTask :: !Text , _tmPrevious :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TasksMove' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'tmParent' -- -- * 'tmTaskList' -- -- * 'tmTask' -- -- * 'tmPrevious' tasksMove :: Text -- ^ 'tmTaskList' -> Text -- ^ 'tmTask' -> TasksMove tasksMove pTmTaskList_ pTmTask_ = TasksMove' { _tmParent = Nothing , _tmTaskList = pTmTaskList_ , _tmTask = pTmTask_ , _tmPrevious = Nothing } -- | New parent task identifier. If the task is moved to the top level, this -- parameter is omitted. Optional. tmParent :: Lens' TasksMove (Maybe Text) tmParent = lens _tmParent (\ s a -> s{_tmParent = a}) -- | Task list identifier. tmTaskList :: Lens' TasksMove Text tmTaskList = lens _tmTaskList (\ s a -> s{_tmTaskList = a}) -- | Task identifier. tmTask :: Lens' TasksMove Text tmTask = lens _tmTask (\ s a -> s{_tmTask = a}) -- | New previous sibling task identifier. If the task is moved to the first -- position among its siblings, this parameter is omitted. Optional. tmPrevious :: Lens' TasksMove (Maybe Text) tmPrevious = lens _tmPrevious (\ s a -> s{_tmPrevious = a}) instance GoogleRequest TasksMove where type Rs TasksMove = Task type Scopes TasksMove = '["https://www.googleapis.com/auth/tasks"] requestClient TasksMove'{..} = go _tmTaskList _tmTask _tmParent _tmPrevious (Just AltJSON) appsTasksService where go = buildClient (Proxy :: Proxy TasksMoveResource) mempty
rueshyna/gogol
gogol-apps-tasks/gen/Network/Google/Resource/Tasks/Tasks/Move.hs
mpl-2.0
3,950
0
17
992
551
327
224
79
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Gmail.Users.Settings.Delegates.Get -- Copyright : (c) 2015-2016 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) -- -- Gets the specified delegate. Note that a delegate user must be referred -- to by their primary email address, and not an email alias. This method -- is only available to service account clients that have been delegated -- domain-wide authority. -- -- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.delegates.get@. module Network.Google.Resource.Gmail.Users.Settings.Delegates.Get ( -- * REST Resource UsersSettingsDelegatesGetResource -- * Creating a Request , usersSettingsDelegatesGet , UsersSettingsDelegatesGet -- * Request Lenses , usdgXgafv , usdgUploadProtocol , usdgAccessToken , usdgUploadType , usdgUserId , usdgDelegateEmail , usdgCallback ) where import Network.Google.Gmail.Types import Network.Google.Prelude -- | A resource alias for @gmail.users.settings.delegates.get@ method which the -- 'UsersSettingsDelegatesGet' request conforms to. type UsersSettingsDelegatesGetResource = "gmail" :> "v1" :> "users" :> Capture "userId" Text :> "settings" :> "delegates" :> Capture "delegateEmail" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Delegate -- | Gets the specified delegate. Note that a delegate user must be referred -- to by their primary email address, and not an email alias. This method -- is only available to service account clients that have been delegated -- domain-wide authority. -- -- /See:/ 'usersSettingsDelegatesGet' smart constructor. data UsersSettingsDelegatesGet = UsersSettingsDelegatesGet' { _usdgXgafv :: !(Maybe Xgafv) , _usdgUploadProtocol :: !(Maybe Text) , _usdgAccessToken :: !(Maybe Text) , _usdgUploadType :: !(Maybe Text) , _usdgUserId :: !Text , _usdgDelegateEmail :: !Text , _usdgCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'UsersSettingsDelegatesGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usdgXgafv' -- -- * 'usdgUploadProtocol' -- -- * 'usdgAccessToken' -- -- * 'usdgUploadType' -- -- * 'usdgUserId' -- -- * 'usdgDelegateEmail' -- -- * 'usdgCallback' usersSettingsDelegatesGet :: Text -- ^ 'usdgDelegateEmail' -> UsersSettingsDelegatesGet usersSettingsDelegatesGet pUsdgDelegateEmail_ = UsersSettingsDelegatesGet' { _usdgXgafv = Nothing , _usdgUploadProtocol = Nothing , _usdgAccessToken = Nothing , _usdgUploadType = Nothing , _usdgUserId = "me" , _usdgDelegateEmail = pUsdgDelegateEmail_ , _usdgCallback = Nothing } -- | V1 error format. usdgXgafv :: Lens' UsersSettingsDelegatesGet (Maybe Xgafv) usdgXgafv = lens _usdgXgafv (\ s a -> s{_usdgXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). usdgUploadProtocol :: Lens' UsersSettingsDelegatesGet (Maybe Text) usdgUploadProtocol = lens _usdgUploadProtocol (\ s a -> s{_usdgUploadProtocol = a}) -- | OAuth access token. usdgAccessToken :: Lens' UsersSettingsDelegatesGet (Maybe Text) usdgAccessToken = lens _usdgAccessToken (\ s a -> s{_usdgAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). usdgUploadType :: Lens' UsersSettingsDelegatesGet (Maybe Text) usdgUploadType = lens _usdgUploadType (\ s a -> s{_usdgUploadType = a}) -- | User\'s email address. The special value \"me\" can be used to indicate -- the authenticated user. usdgUserId :: Lens' UsersSettingsDelegatesGet Text usdgUserId = lens _usdgUserId (\ s a -> s{_usdgUserId = a}) -- | The email address of the user whose delegate relationship is to be -- retrieved. usdgDelegateEmail :: Lens' UsersSettingsDelegatesGet Text usdgDelegateEmail = lens _usdgDelegateEmail (\ s a -> s{_usdgDelegateEmail = a}) -- | JSONP usdgCallback :: Lens' UsersSettingsDelegatesGet (Maybe Text) usdgCallback = lens _usdgCallback (\ s a -> s{_usdgCallback = a}) instance GoogleRequest UsersSettingsDelegatesGet where type Rs UsersSettingsDelegatesGet = Delegate type Scopes UsersSettingsDelegatesGet = '["https://mail.google.com/", "https://www.googleapis.com/auth/gmail.modify", "https://www.googleapis.com/auth/gmail.readonly", "https://www.googleapis.com/auth/gmail.settings.basic"] requestClient UsersSettingsDelegatesGet'{..} = go _usdgUserId _usdgDelegateEmail _usdgXgafv _usdgUploadProtocol _usdgAccessToken _usdgUploadType _usdgCallback (Just AltJSON) gmailService where go = buildClient (Proxy :: Proxy UsersSettingsDelegatesGetResource) mempty
brendanhay/gogol
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/Delegates/Get.hs
mpl-2.0
5,979
0
20
1,383
797
468
329
120
1
{-# LANGUAGE RecordWildCards #-} module Network.Riak.Request where import Network.Riak.Message import Network.Riak.Types import Data.ByteString newtype ReturnBody = ReturnBody {returnBody :: Bool} getRequest :: KVOpts -> Message getRequest KVOpts {..} = GetRequest { getBucket = bucket , getKey = key , getR = Nothing , getPR = Nothing , basic_quorom = Nothing , notfound_ok = Nothing , if_modified = Nothing , getHead = Nothing , deleted_vclock = Nothing , getTimeout = Nothing , getSloppyQuorom = Nothing , n_val = Nothing , getBucketType = Nothing } putRequest :: ByteString -> Metadata -> ReturnBody -> KVOpts -> VClock -> Message putRequest value metadata ReturnBody{..} KVOpts{..} VClock{..} = PutRequest { putBucket = bucket , putKey = Just key , putVclock = vclock , putContent = encodeContent value metadata , putW = Nothing , putDW = Nothing , return_body = Just returnBody , putPW = Nothing , if_not_modified = Nothing , if_none_match = Nothing , return_head = Nothing , putTimeout = Nothing , asis = Nothing , putSloppyQuorom = Nothing , putNVal = Nothing , putBucketType = encodeBucketType bucketType } deleteRequest :: KVOpts -> VClock -> Message deleteRequest KVOpts{..} VClock{..} = DeleteRequest { delBucket = bucket , delKey = key , rw = Nothing , delVclock = vclock , delR = Nothing , delW = Nothing , delPR = Nothing , delPW = Nothing , delDW = Nothing , delTimeout = Nothing , delSloppyQuorom = Nothing , delNVal = Nothing , delBucketType = encodeBucketType bucketType } encodeBucketType :: BucketType -> Maybe ByteString encodeBucketType Default = Nothing enocdeBucketType (BucketType bucketType) = Just bucketType encodeContent :: ByteString -> Metadata -> Content encodeContent value Metadata{..} = Content{ value = value , content_type = contentType , charset = charset , content_encoding = contentEncoding , vtag = Nothing , links = [] , last_mod = Nothing , last_mod_usecs = Nothing , usermeta = [] , indexes = [] , deleted = Nothing }
ian-mi/haskell-riak-client
Network/Riak/Request.hs
apache-2.0
2,941
0
9
1,290
570
344
226
69
1
module Miscellaneous.A338887 (a338887) where import Helpers.Primes (divisors) import Data.Set (Set) import qualified Data.Set as Set a338887 :: Integer -> Int a338887 n = Set.size $ Set.fromList [x + y * z | z <- [1..n-1], x <- divisors $ n - z, y <- [(n - z) `div` x]]
peterokagey/haskellOEIS
src/Miscellaneous/A338887.hs
apache-2.0
271
0
13
50
135
76
59
6
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE OverloadedStrings #-} {- | CouchDB database methods. > runCouch def {couchDB="my_db"} $ couchPutDb > runCouch def {couchDB="my_new_db"} $ couchPutDb -} module Database.CouchDB.Conduit.DB ( -- * Methods couchPutDB, couchPutDB_, couchDeleteDB, -- * Security couchSecureDB, -- * Replication couchReplicateDB ) where import Control.Monad (void) import qualified Data.ByteString as B import qualified Data.Aeson as A import qualified Network.HTTP.Conduit as H import qualified Network.HTTP.Types as HT import Database.CouchDB.Conduit.Internal.Connection (MonadCouch(..), Path, mkPath) import Database.CouchDB.Conduit.LowLevel (couch, couch', protect, protect') -- | Create CouchDB database. couchPutDB :: MonadCouch m => Path -- ^ Database -> m () couchPutDB db = void $ couch HT.methodPut (mkPath [db]) [] [] (H.RequestBodyBS B.empty) protect' -- | \"Don't care\" version of couchPutDb. Create CouchDB database only in its -- absence. For this it handles @412@ responses. couchPutDB_ :: MonadCouch m => Path -- ^ Database -> m () couchPutDB_ db = void $ couch HT.methodPut (mkPath [db]) [] [] (H.RequestBodyBS B.empty) (protect [200, 201, 202, 304, 412] return) -- | Delete a database. couchDeleteDB :: MonadCouch m => Path -- ^ Database -> m () couchDeleteDB db = void $ couch HT.methodDelete (mkPath [db]) [] [] (H.RequestBodyBS B.empty) protect' -- | Maintain DB security. couchSecureDB :: MonadCouch m => Path -- ^ Database -> [B.ByteString] -- ^ Admin roles -> [B.ByteString] -- ^ Admin names -> [B.ByteString] -- ^ Readers roles -> [B.ByteString] -- ^ Readers names -> m () couchSecureDB db adminRoles adminNames readersRoles readersNames = void $ couch HT.methodPut (mkPath [db, "_security"]) [] [] reqBody protect' where reqBody = H.RequestBodyLBS $ A.encode $ A.object [ "admins" A..= A.object [ "roles" A..= adminRoles, "names" A..= adminNames ], "readers" A..= A.object [ "roles" A..= readersRoles, "names" A..= readersNames ] ] -- | Database replication. -- -- See <http://guide.couchdb.org/editions/1/en/api.html#replication> for -- details. couchReplicateDB :: MonadCouch m => B.ByteString -- ^ Source database. Path or URL -> B.ByteString -- ^ Target database. Path or URL -> Bool -- ^ Target creation flag -> Bool -- ^ Continuous flag -> Bool -- ^ Cancel flag -> m () couchReplicateDB source target createTarget continuous cancel = void $ couch' HT.methodPost (const "/_replicate") [] [] reqBody protect' where reqBody = H.RequestBodyLBS $ A.encode $ A.object [ "source" A..= source, "target" A..= target, "create_target" A..= createTarget, "continuous" A..= continuous, "cancel" A..= cancel ]
lostbean/neo4j-conduit
src/Database/CouchDB/Conduit/DB.hs
bsd-2-clause
3,498
0
13
1,225
728
407
321
68
1
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} module Bug1103 where import Data.Kind data family Foo1 :: Type -> Type data instance Foo1 Bool = Foo1Bool data instance Foo1 (Maybe a) data family Foo2 :: k -> Type data instance Foo2 Bool = Foo2Bool data instance Foo2 (Maybe a) data instance Foo2 :: Char -> Type data instance Foo2 :: (Char -> Char) -> Type where data family Foo3 :: k data instance Foo3 data instance Foo3 Bool = Foo3Bool data instance Foo3 (Maybe a) data instance Foo3 :: Char -> Type data instance Foo3 :: (Char -> Char) -> Type where
haskell/haddock
html-test/src/Bug1103.hs
bsd-2-clause
652
0
7
124
190
110
80
-1
-1
module Main where import Sound.Fluent main = runFluent
hanshoglund/fluent
Main.hs
bsd-3-clause
57
0
4
10
14
9
5
3
1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE UnicodeSyntax #-} module Dir.Create ( createDir ) where import Database.HDBC (fromSql, toSql) import System.Fuse import System.Posix.Types (FileMode) import DB.Base import DB.Read import DB.Write import Debug (dbg) import Parse (parseDirPath) import Stat.Base (dirStat) dummyFileName ∷ String dummyFileName = ".dummy" {- | Create new tags (as necessary) for dirs in path. -} createDir ∷ DB → FilePath → FileMode → IO Errno createDir db filePath mode = do dbg $ "createDir w/ path: " ++ filePath case parseDirPath filePath of [] → return eNOENT tagNames → do -- Create a dummy file to inhabit it. (Don't display it.) dummyFileId ← findOrCreateDummyFileId db -- Create FileTag for each of tagNames. -- FIXME: use newDirStat tagIds ← mapM (findOrCreateTagId db) tagNames mapM_ (ensureFileTag db dummyFileId) tagIds return eOK newDirStat ∷ FileMode → IO FileStat newDirStat mode = do ctx ← getFuseContext return $ (dirStat ctx) { statFileMode = mode } findOrCreateTagId ∷ DB → TagName → IO TagId findOrCreateTagId db tagName = do maybeTagEntity ← tagEntityNamed db tagName case maybeTagEntity of Just te → return $ tagId te Nothing → do mkTag db (Tag tagName) findOrCreateTagId db tagName findOrCreateDummyFileId ∷ DB → IO FileId findOrCreateDummyFileId db = do maybeFileEntity ← fileEntityNamed db dummyFileName case maybeFileEntity of Just fe → return $ fileId fe Nothing → do mkFile db (File dummyFileName "") findOrCreateDummyFileId db
marklar/TagFS
src/Dir/Create.hs
bsd-3-clause
1,851
0
15
546
437
217
220
48
2
module Data.LanguageTag.Types where import Data.Text(Text) import Data.ISO639(Language) import Data.ISO3166(Country) {- from RFC 1766 § 2: 2. The Language tag The language tag is composed of 1 or more parts: A primary language tag and a (possibly empty) series of subtags. The syntax of this tag in RFC-822 EBNF is: Language-Tag = Primary-tag *( "-" Subtag ) Primary-tag = 1*8ALPHA Subtag = 1*8ALPHA Whitespace is not allowed within the tag. -} {- We'll compose a Language tag of a 'PrimaryTag', and a 'FirstSubTag', since primary and the first subtag have rules arround their construction. all constructors of 'FirstSubTag' should contain an array of 'SubTag's to hold all subsequent SubTags. -} data LanguageTag = LanguageTag PrimaryTag (Maybe FirstSubTag) deriving (Eq, Show) {- from RFC 1766 § 2: In the primary language tag: - All 2-letter tags are interpreted according to ISO standard 639, "Code for the representation of names of languages" [ISO 639]. - The value "i" is reserved for IANA-defined registrations - The value "x" is reserved for private use. Subtags of "x" will not be registered by the IANA. - Other values cannot be assigned except by updating this standard. The reason for reserving all other tags is to be open towards new revisions of ISO 639; the use of "i" and "x" is the minimum we can do here to be able to extend the mechanism to meet our requirements. -} data PrimaryTag = ISO639Tag Language | IANADefinedTag | PrivateTag deriving (Eq, Show) {- from RFC 1766 § 2: In the first subtag: - All 2-letter codes are interpreted as ISO 3166 alpha-2 country codes denoting the area in which the language is used. - Codes of 3 to 8 letters may be registered with the IANA by anyone who feels a need for it, according to the rules in chapter 5 of this document. The information in the subtag may for instance be: - Country identification, such as en-US (this usage is described in ISO 639) - Dialect or variant information, such as no-nynorsk or en- cockney - Languages not listed in ISO 639 that are not variants of any listed language, which can be registered with the i- prefix, such as i-cherokee - Script variations, such as az-arabic and az-cyrillic -} data FirstSubTag = ISO3166Alpha2Tag Country [SubTag] | IANARegisteredTag Text [SubTag] deriving (Eq, Show) {- from RFC 1766 § 2: In the second and subsequent subtag, any value can be registered. -} newtype SubTag = SubTag Text deriving (Eq, Show)
necrobious/language-tag
src/Data/LanguageTag/Types.hs
bsd-3-clause
2,766
0
8
746
150
89
61
13
0
-- (c) 2007 Andy Gill -- Main driver for Hpc module Trace.Haptics.Main where import Data.Version import Trace.Haptics.Combine import Trace.Haptics.Draft import Trace.Haptics.Flags import Trace.Haptics.Markup import Trace.Haptics.Overlay import Trace.Haptics.Report import Trace.Haptics.ShowTix import Paths_haptics import System.Console.GetOpt import System.Environment import System.Exit helpList :: IO () helpList = putStrLn $ "Usage: hpc COMMAND ...\n\n" ++ section "Commands" help ++ section "Reporting Coverage" reporting ++ section "Processing Coverage files" processing ++ section "Coverage Overlays" overlays ++ section "Others" other ++ "" where help = ["help"] reporting = ["report", "markup"] overlays = ["overlay", "draft"] processing = ["sum", "combine", "map"] other = [ name hook | hook <- hooks , name hook `notElem` concat [help, reporting, processing, overlays] ] section :: String -> [String] -> String section _ [] = "" section msg cmds = msg ++ ":\n" ++ unlines [ take 14 (" " ++ cmd ++ repeat ' ') ++ summary hook | cmd <- cmds , hook <- hooks , name hook == cmd ] dispatch :: [String] -> IO () dispatch [] = do helpList exitSuccess dispatch (txt : args0) = case lookup txt hooks' of Just plugin -> parse plugin args0 _ -> parse help_plugin (txt : args0) where parse plugin args = case getOpt Permute (options plugin []) args of (_, _, errs) | not (null errs) -> do putStrLn "hpc failed:" sequence_ [ putStr (" " ++ err) | err <- errs ] putStrLn "\n" command_usage plugin exitFailure (o, ns, _) -> do let flags = final_flags plugin $ foldr ($) ( init_flags plugin) o implementation plugin flags ns main :: IO () main = getArgs >>= dispatch hooks :: [Plugin] hooks = [ help_plugin , report_plugin , markup_plugin , sum_plugin , combine_plugin , map_plugin , showtix_plugin , overlay_plugin , draft_plugin , version_plugin ] hooks' :: [(String, Plugin)] hooks' = [(name hook, hook) | hook <- hooks] help_plugin :: Plugin help_plugin = Plugin { name = "help" , usage = "[<HPC_COMMAND>]" , summary = "Display help for hpc or a single command" , options = help_options , implementation = help_main , init_flags = default_flags , final_flags = default_final_flags } help_main :: Flags -> [String] -> IO () help_main _ [] = do helpList exitSuccess help_main _ (sub_txt : _) = case lookup sub_txt hooks' of Nothing -> do putStrLn $ "no such hpc command : " ++ sub_txt exitFailure Just plugin' -> do command_usage plugin' exitSuccess help_options :: FlagOptSeq help_options = id version_plugin :: Plugin version_plugin = Plugin { name = "version" , usage = "" , summary = "Display version for hpc" , options = id , implementation = version_main , init_flags = default_flags , final_flags = default_final_flags } version_main :: Flags -> [String] -> IO () version_main _ _ = putStrLn ("hpc tools, version " ++ showVersion version)
Javran/haptics
src/Trace/Haptics/Main.hs
bsd-3-clause
3,349
0
18
965
963
518
445
118
3
{-# LANGUAGE DeriveFunctor, TemplateHaskell #-} module Part ( XY(..), Error(..), Result, Parser, parse, try, char, string, ) where -- General import Control.Applicative import Control.Monad import Data.Monoid -- Lists import Data.List (intercalate) -- Lenses import Lens.Micro import Lens.Micro.TH -- Text import Text.Printf -- Lists import Data.List (stripPrefix) data XY = XY { x, y :: Int } deriving (Show) instance Monoid XY where mempty = XY 0 0 mappend p1 p2 = XY { x = x p1 + x p2, y = y p1 + y p2 } xy0 :: XY xy0 = mempty data Error = Expected { errorExpected :: [String], errorBut :: Maybe String } | Message { errorMessage :: String } deriving (Show) makeLensesFor [("errorExpected", "_errorExpected"), ("errorBut", "_errorBut"), ("errorMessage", "_errorMessage")] ''Error showError :: Error -> String showError (Expected xs but) = "expected " ++ or'ed ++ maybe "" (", but " ++) but where or'ed = case xs of [] -> error "Path.showError: empty list of expected things" [x] -> x xs -> intercalate ", " (init xs) ++ " or " ++ last xs showError (Message msg) = msg type Result a = Either (XY, Error) (a, String) data Parser a = Parser {runParser :: String -> (XY, Result a)} deriving (Functor) makeLensesFor [("runParser", "_Parser")] ''Parser _parserResult :: ASetter (Parser a) (Parser b) (XY, Result a) (XY, Result b) _parserResult = _Parser.mapped _shift :: Lens' (XY, Result a) XY _shift = _1 _error :: Traversal' (XY, Result a) Error _error = _2._Left._2 _errorPosition :: Traversal' (XY, Result a) XY _errorPosition = _2._Left._1 instance Applicative Parser where pure = return (<*>) = ap instance Monad Parser where fail s = Parser $ \_ -> (xy0, Left (xy0, Message s)) return x = Parser $ \s -> (xy0, Right (x, s)) Parser sa >>= fb = Parser $ \s -> case sa s of (pa, Left err) -> (pa, Left err) (pa, Right (a, s')) -> let Parser sb = fb a in sb s' -- have to update position & _shift %~ (<> pa) -- as well as error position (if exists) & _errorPosition %~ (<> pa) instance Alternative Parser where empty = fail "empty" Parser sa <|> Parser sb = Parser $ \s -> case sa s of (pa, Right x) -> (pa, Right x) -- If the parser hasn't consumed any input, we try the other parser. (XY 0 0, Left _) -> sb s -- Otherwise, we report the error – we don't do backtracking. (pa, Left err) -> (pa, Left err) instance MonadPlus Parser where mzero = fail "mzero" mplus = (<|>) parse :: Parser a -> String -> Either (XY, Error) a parse (Parser sa) s = case sa s of (pa, Left err) -> Left err (_, Right (a, _)) -> Right a try :: Parser a -> Parser a try = set (_parserResult._shift) xy0 -- parsers char :: Char -> Parser Char char c = Parser $ \inp -> case inp of [] -> (xy0, Left (xy0, errEOF)) (x:xs) | x /= c -> (xy0, Left (xy0, errUnexpected x)) | otherwise -> (XY 1 0, Right (c, xs)) where errEOF = Expected [show c] (Just "string has ended") errUnexpected x = Expected [show c] (Just ("got " ++ show x)) string :: String -> Parser String string s = Parser $ \inp -> case stripPrefix s inp of Nothing | null inp -> (xy0, Left (xy0, errEOF)) | otherwise -> (xy0, Left (xy0, errUnexpected)) Just xs -> (XY (length s) 0, Right (s, xs)) where errEOF = Expected [show s] (Just "string has ended") errUnexpected = Expected [show s] Nothing
aelve/part
src/Part.hs
bsd-3-clause
3,694
0
17
1,058
1,438
774
664
-1
-1
{-# OPTIONS_GHC -F -pgmF doctest-discover -optF tests/doctest-config.json #-}
aelve/fmt
tests/doctests.hs
bsd-3-clause
78
0
2
8
3
2
1
1
0
module Main ( main ) where import Test.Tasty ( TestTree, defaultMain, testGroup ) import SingletonsTestSuiteUtils ( compileAndDumpStdTest, compileAndDumpTest , testCompileAndDumpGroup, ghcOpts -- , cleanFiles ) main :: IO () main = do -- cleanFiles We really need to parallelize the testsuite. defaultMain tests tests :: TestTree tests = testGroup "Testsuite" $ [ testCompileAndDumpGroup "Singletons" [ compileAndDumpStdTest "Nat" , compileAndDumpStdTest "Empty" , compileAndDumpStdTest "Maybe" , compileAndDumpStdTest "BoxUnBox" , compileAndDumpStdTest "Operators" , compileAndDumpStdTest "HigherOrder" , compileAndDumpStdTest "Contains" , compileAndDumpStdTest "AsPattern" , compileAndDumpStdTest "DataValues" , compileAndDumpStdTest "EqInstances" , compileAndDumpStdTest "CaseExpressions" , compileAndDumpStdTest "Star" , compileAndDumpStdTest "ReturnFunc" , compileAndDumpStdTest "Lambdas" , compileAndDumpStdTest "LambdasComprehensive" , compileAndDumpStdTest "Error" , compileAndDumpStdTest "TopLevelPatterns" , compileAndDumpStdTest "LetStatements" , compileAndDumpStdTest "LambdaCase" , compileAndDumpStdTest "Sections" , compileAndDumpStdTest "PatternMatching" , compileAndDumpStdTest "Records" , compileAndDumpStdTest "T29" , compileAndDumpStdTest "T33" , compileAndDumpStdTest "T54" , compileAndDumpStdTest "Classes" , compileAndDumpStdTest "Classes2" , compileAndDumpStdTest "FunDeps" , compileAndDumpStdTest "T78" , compileAndDumpStdTest "OrdDeriving" , compileAndDumpStdTest "BoundedDeriving" , compileAndDumpStdTest "BadBoundedDeriving" , compileAndDumpStdTest "EnumDeriving" , compileAndDumpStdTest "BadEnumDeriving" , compileAndDumpStdTest "Fixity" , compileAndDumpStdTest "Undef" , compileAndDumpStdTest "T124" , compileAndDumpStdTest "T136" , compileAndDumpStdTest "T136b" , compileAndDumpStdTest "T153" , compileAndDumpStdTest "T157" , compileAndDumpStdTest "T159" , compileAndDumpStdTest "T167" , compileAndDumpStdTest "T145" , compileAndDumpStdTest "PolyKinds" , compileAndDumpStdTest "PolyKindsApp" , compileAndDumpStdTest "T166" ], testCompileAndDumpGroup "Promote" [ compileAndDumpStdTest "Constructors" , compileAndDumpStdTest "GenDefunSymbols" , compileAndDumpStdTest "Newtypes" , compileAndDumpStdTest "Pragmas" , compileAndDumpStdTest "Prelude" ], testGroup "Database client" [ compileAndDumpTest "GradingClient/Database" ghcOpts , compileAndDumpTest "GradingClient/Main" ghcOpts ], testCompileAndDumpGroup "InsertionSort" [ compileAndDumpStdTest "InsertionSortImp" ] ]
int-index/singletons
tests/SingletonsTestSuite.hs
bsd-3-clause
2,893
0
9
627
448
231
217
70
1
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} module Juno.Types.Message.REV ( Revolution(..), revClientId, revLeaderId, revRequestId, revProvenance ) where import Control.Lens import Data.Serialize (Serialize) import qualified Data.Serialize as S import Data.Thyme.Time.Core () import GHC.Generics import Juno.Types.Base import Juno.Types.Message.Signed data Revolution = Revolution { _revClientId :: !NodeID , _revLeaderId :: !NodeID , _revRequestId :: !RequestId , _revProvenance :: !Provenance } deriving (Show, Eq, Generic) makeLenses ''Revolution newtype REVWire = REVWire (NodeID,NodeID,RequestId) deriving (Show, Generic) instance Serialize REVWire instance WireFormat Revolution where toWire nid pubKey privKey Revolution{..} = case _revProvenance of NewMsg -> let bdy = S.encode $ REVWire (_revClientId,_revLeaderId,_revRequestId) sig = sign bdy privKey pubKey dig = Digest nid sig pubKey REV in SignedRPC dig bdy ReceivedMsg{..} -> SignedRPC _pDig _pOrig fromWire !ts !ks s@(SignedRPC !dig !bdy) = case verifySignedRPC ks s of Left !err -> Left $! err Right () -> if _digType dig /= REV then error $ "Invariant Failure: attempting to decode " ++ show (_digType dig) ++ " with REVWire instance" else case S.decode bdy of Left !err -> Left $! "Failure to decode REVWire: " ++ err Right (REVWire (cid,lid,rid)) -> Right $! Revolution cid lid rid $ ReceivedMsg dig bdy ts {-# INLINE toWire #-} {-# INLINE fromWire #-}
haroldcarr/juno
src/Juno/Types/Message/REV.hs
bsd-3-clause
1,636
0
16
342
466
249
217
47
0
module AST.Axiom( Axiom(..) ) where import Data.List(intercalate) import AST.Term import AST.Judgement data Axiom = Axiom { name :: Name, stab :: Stab, forallVars :: [(MetaVar, Sort)], premise :: [Judgement], conclusion :: Judgement } instance Show Axiom where show (Axiom nm st forall prem concl) = concat [ f st, nm, " =\n ", showCtx (\ (mv, s) -> show mv ++ ": " ++ show s) forall, "\n ", showCtx show prem, " |--- ", show concl, "\n"] where f Nothing = "" f (Just st') = "[" ++ intercalate "," (show <$> st') ++ "]\n" --
esengie/fpl-exploration-tool
src/specLang/AST/Axiom.hs
bsd-3-clause
606
0
13
178
235
133
102
19
0
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TupleSections #-} {-# LANGUAGE ViewPatterns #-} -- | Build the project. module Stack.Build (build ,withLoadPackage ,mkBaseConfigOpts ,queryBuildInfo ,splitObjsWarning ,CabalVersionException(..)) where import Control.Monad import Control.Monad.IO.Unlift import Control.Monad.Logger import Control.Monad.Reader (MonadReader) import Data.Aeson (Value (Object, Array), (.=), object) import Data.Function import qualified Data.HashMap.Strict as HM import Data.List ((\\)) import Data.List.Extra (groupSort) import Data.List.NonEmpty (NonEmpty(..)) import qualified Data.List.NonEmpty as NE import qualified Data.Map as Map import Data.Map.Strict (Map) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import Data.String import Data.Text (Text) import qualified Data.Text as T import Data.Text.Encoding (decodeUtf8) import qualified Data.Text.IO as TIO import Data.Text.Read (decimal) import Data.Typeable (Typeable) import qualified Data.Vector as V import qualified Data.Yaml as Yaml import Path import Prelude hiding (writeFile) import Stack.Build.ConstructPlan import Stack.Build.Execute import Stack.Build.Haddock import Stack.Build.Installed import Stack.Build.Source import Stack.Build.Target import Stack.Fetch as Fetch import Stack.Package import Stack.PackageLocation (loadSingleRawCabalFile) import Stack.Types.Build import Stack.Types.BuildPlan import Stack.Types.Config import Stack.Types.FlagName import Stack.Types.Package import Stack.Types.PackageIdentifier import Stack.Types.PackageName import Stack.Types.StackT import Stack.Types.StringError import Stack.Types.Version #ifdef WINDOWS import Stack.Types.Compiler #endif import System.FileLock (FileLock, unlockFile) #ifdef WINDOWS import System.Win32.Console (setConsoleCP, setConsoleOutputCP, getConsoleCP, getConsoleOutputCP) #endif -- | Build. -- -- If a buildLock is passed there is an important contract here. That lock must -- protect the snapshot, and it must be safe to unlock it if there are no further -- modifications to the snapshot to be performed by this build. build :: (StackM env m, HasEnvConfig env) => (Set (Path Abs File) -> IO ()) -- ^ callback after discovering all local files -> Maybe FileLock -> BuildOptsCLI -> m () build setLocalFiles mbuildLk boptsCli = fixCodePage $ do bopts <- view buildOptsL let profiling = boptsLibProfile bopts || boptsExeProfile bopts let symbols = not (boptsLibStrip bopts || boptsExeStrip bopts) menv <- getMinimalEnvOverride (targets, mbp, locals, extraToBuild, sourceMap) <- loadSourceMapFull NeedTargets boptsCli -- Set local files, necessary for file watching stackYaml <- view stackYamlL liftIO $ setLocalFiles $ Set.insert stackYaml $ Set.unions $ map lpFiles locals (installedMap, globalDumpPkgs, snapshotDumpPkgs, localDumpPkgs) <- getInstalled menv GetInstalledOpts { getInstalledProfiling = profiling , getInstalledHaddock = shouldHaddockDeps bopts , getInstalledSymbols = symbols } sourceMap baseConfigOpts <- mkBaseConfigOpts boptsCli plan <- withLoadPackage $ \loadPackage -> constructPlan mbp baseConfigOpts locals extraToBuild localDumpPkgs loadPackage sourceMap installedMap (boptsCLIInitialBuildSteps boptsCli) allowLocals <- view $ configL.to configAllowLocals unless allowLocals $ case justLocals plan of [] -> return () localsIdents -> throwM $ LocalPackagesPresent localsIdents -- If our work to do is all local, let someone else have a turn with the snapshot. -- They won't damage what's already in there. case (mbuildLk, allLocal plan) of -- NOTE: This policy is too conservative. In the future we should be able to -- schedule unlocking as an Action that happens after all non-local actions are -- complete. (Just lk,True) -> do $logDebug "All installs are local; releasing snapshot lock early." liftIO $ unlockFile lk _ -> return () checkCabalVersion warnAboutSplitObjs bopts warnIfExecutablesWithSameNameCouldBeOverwritten locals plan when (boptsPreFetch bopts) $ preFetch plan if boptsCLIDryrun boptsCli then printPlan plan else executePlan menv boptsCli baseConfigOpts locals globalDumpPkgs snapshotDumpPkgs localDumpPkgs installedMap targets plan -- | If all the tasks are local, they don't mutate anything outside of our local directory. allLocal :: Plan -> Bool allLocal = all (== Local) . map taskLocation . Map.elems . planTasks justLocals :: Plan -> [PackageIdentifier] justLocals = map taskProvides . filter ((== Local) . taskLocation) . Map.elems . planTasks checkCabalVersion :: (StackM env m, HasEnvConfig env) => m () checkCabalVersion = do allowNewer <- view $ configL.to configAllowNewer cabalVer <- view cabalVersionL -- https://github.com/haskell/cabal/issues/2023 when (allowNewer && cabalVer < $(mkVersion "1.22")) $ throwM $ CabalVersionException $ "Error: --allow-newer requires at least Cabal version 1.22, but version " ++ versionString cabalVer ++ " was found." newtype CabalVersionException = CabalVersionException { unCabalVersionException :: String } deriving (Typeable) instance Show CabalVersionException where show = unCabalVersionException instance Exception CabalVersionException -- | See https://github.com/commercialhaskell/stack/issues/1198. warnIfExecutablesWithSameNameCouldBeOverwritten :: MonadLogger m => [LocalPackage] -> Plan -> m () warnIfExecutablesWithSameNameCouldBeOverwritten locals plan = do $logDebug "Checking if we are going to build multiple executables with the same name" forM_ (Map.toList warnings) $ \(exe,(toBuild,otherLocals)) -> do let exe_s | length toBuild > 1 = "several executables with the same name:" | otherwise = "executable" exesText pkgs = T.intercalate ", " ["'" <> packageNameText p <> ":" <> exe <> "'" | p <- pkgs] ($logWarn . T.unlines . concat) [ [ "Building " <> exe_s <> " " <> exesText toBuild <> "." ] , [ "Only one of them will be available via 'stack exec' or locally installed." | length toBuild > 1 ] , [ "Other executables with the same name might be overwritten: " <> exesText otherLocals <> "." | not (null otherLocals) ] ] where -- Cases of several local packages having executables with the same name. -- The Map entries have the following form: -- -- executable name: ( package names for executables that are being built -- , package names for other local packages that have an -- executable with the same name -- ) warnings :: Map Text ([PackageName],[PackageName]) warnings = Map.mapMaybe (\(pkgsToBuild,localPkgs) -> case (pkgsToBuild,NE.toList localPkgs \\ NE.toList pkgsToBuild) of (_ :| [],[]) -> -- We want to build the executable of single local package -- and there are no other local packages with an executable of -- the same name. Nothing to warn about, ignore. Nothing (_,otherLocals) -> -- We could be here for two reasons (or their combination): -- 1) We are building two or more executables with the same -- name that will end up overwriting each other. -- 2) In addition to the executable(s) that we want to build -- there are other local packages with an executable of the -- same name that might get overwritten. -- Both cases warrant a warning. Just (NE.toList pkgsToBuild,otherLocals)) (Map.intersectionWith (,) exesToBuild localExes) exesToBuild :: Map Text (NonEmpty PackageName) exesToBuild = collect [ (exe,pkgName) | (pkgName,task) <- Map.toList (planTasks plan) , isLocal task , exe <- (Set.toList . exeComponents . lpComponents . taskLP) task ] where isLocal Task{taskType = (TTLocal _)} = True isLocal _ = False taskLP Task{taskType = (TTLocal lp)} = lp taskLP _ = error "warnIfExecutablesWithSameNameCouldBeOverwritten/taskLP: task isn't local" localExes :: Map Text (NonEmpty PackageName) localExes = collect [ (exe,packageName pkg) | pkg <- map lpPackage locals , exe <- Set.toList (packageExes pkg) ] collect :: Ord k => [(k,v)] -> Map k (NonEmpty v) collect = Map.map NE.fromList . Map.fromDistinctAscList . groupSort warnAboutSplitObjs :: MonadLogger m => BuildOpts -> m () warnAboutSplitObjs bopts | boptsSplitObjs bopts = do $logWarn $ "Building with --split-objs is enabled. " <> T.pack splitObjsWarning warnAboutSplitObjs _ = return () splitObjsWarning :: String splitObjsWarning = unwords [ "Note that this feature is EXPERIMENTAL, and its behavior may be changed and improved." , "You will need to clean your workdirs before use. If you want to compile all dependencies" , "with split-objs, you will need to delete the snapshot (and all snapshots that could" , "reference that snapshot)." ] -- | Get the @BaseConfigOpts@ necessary for constructing configure options mkBaseConfigOpts :: (MonadIO m, MonadReader env m, HasEnvConfig env, MonadThrow m) => BuildOptsCLI -> m BaseConfigOpts mkBaseConfigOpts boptsCli = do bopts <- view buildOptsL snapDBPath <- packageDatabaseDeps localDBPath <- packageDatabaseLocal snapInstallRoot <- installationRootDeps localInstallRoot <- installationRootLocal packageExtraDBs <- packageDatabaseExtra return BaseConfigOpts { bcoSnapDB = snapDBPath , bcoLocalDB = localDBPath , bcoSnapInstallRoot = snapInstallRoot , bcoLocalInstallRoot = localInstallRoot , bcoBuildOpts = bopts , bcoBuildOptsCLI = boptsCli , bcoExtraDBs = packageExtraDBs } -- | Provide a function for loading package information from the package index withLoadPackage :: (StackM env m, HasEnvConfig env) => ((PackageLocationIndex FilePath -> Map FlagName Bool -> [Text] -> IO Package) -> m a) -> m a withLoadPackage inner = do econfig <- view envConfigL menv <- getMinimalEnvOverride root <- view projectRootL run <- askRunIO withCabalLoader $ \loadFromIndex -> inner $ \loc flags ghcOptions -> do bs <- run $ loadSingleRawCabalFile loadFromIndex menv root loc (_warnings,pkg) <- readPackageBS (depPackageConfig econfig flags ghcOptions) bs return pkg where -- | Package config to be used for dependencies depPackageConfig :: EnvConfig -> Map FlagName Bool -> [Text] -> PackageConfig depPackageConfig econfig flags ghcOptions = PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = flags , packageConfigGhcOptions = ghcOptions , packageConfigCompilerVersion = view actualCompilerVersionL econfig , packageConfigPlatform = view platformL econfig } -- | Set the code page for this process as necessary. Only applies to Windows. -- See: https://github.com/commercialhaskell/stack/issues/738 #ifdef WINDOWS fixCodePage :: (StackM env m, HasBuildConfig env, HasEnvConfig env) => m a -> m a fixCodePage inner = do mcp <- view $ configL.to configModifyCodePage ghcVersion <- view $ actualCompilerVersionL.to getGhcVersion if mcp && ghcVersion < $(mkVersion "7.10.3") then fixCodePage' -- GHC >=7.10.3 doesn't need this code page hack. else inner where fixCodePage' = do origCPI <- liftIO getConsoleCP origCPO <- liftIO getConsoleOutputCP let setInput = origCPI /= expected setOutput = origCPO /= expected fixInput | setInput = bracket_ (liftIO $ do setConsoleCP expected) (liftIO $ setConsoleCP origCPI) | otherwise = id fixOutput | setOutput = bracket_ (liftIO $ do setConsoleOutputCP expected) (liftIO $ setConsoleOutputCP origCPO) | otherwise = id case (setInput, setOutput) of (False, False) -> return () (True, True) -> warn "" (True, False) -> warn " input" (False, True) -> warn " output" fixInput $ fixOutput inner expected = 65001 -- UTF-8 warn typ = $logInfo $ T.concat [ "Setting" , typ , " codepage to UTF-8 (65001) to ensure correct output from GHC" ] #else fixCodePage :: a -> a fixCodePage = id #endif -- | Query information about the build and print the result to stdout in YAML format. queryBuildInfo :: (StackM env m, HasEnvConfig env) => [Text] -- ^ selectors -> m () queryBuildInfo selectors0 = rawBuildInfo >>= select id selectors0 >>= liftIO . TIO.putStrLn . decodeUtf8 . Yaml.encode where select _ [] value = return value select front (sel:sels) value = case value of Object o -> case HM.lookup sel o of Nothing -> err "Selector not found" Just value' -> cont value' Array v -> case decimal sel of Right (i, "") | i >= 0 && i < V.length v -> cont $ v V.! i | otherwise -> err "Index out of range" _ -> err "Encountered array and needed numeric selector" _ -> err $ "Cannot apply selector to " ++ show value where cont = select (front . (sel:)) sels err msg = errorString $ msg ++ ": " ++ show (front [sel]) -- | Get the raw build information object rawBuildInfo :: (StackM env m, HasEnvConfig env) => m Value rawBuildInfo = do (locals, _sourceMap) <- loadSourceMap NeedTargets defaultBuildOptsCLI return $ object [ "locals" .= Object (HM.fromList $ map localToPair locals) ] where localToPair lp = (T.pack $ packageNameString $ packageName p, value) where p = lpPackage lp value = object [ "version" .= packageVersion p , "path" .= toFilePath (lpDir lp) ]
martin-kolinek/stack
src/Stack/Build.hs
bsd-3-clause
15,981
0
20
4,905
3,242
1,713
1,529
269
6
module Network.Nylas ( module Network.Nylas.Client , module Network.Nylas.Types ) where import Network.Nylas.Client import Network.Nylas.Types
bts/nylas-hs
src/Network/Nylas.hs
bsd-3-clause
185
0
5
56
34
23
11
5
0
{-# LANGUAGE QuasiQuotes #-} import LiquidHaskell import Control.Applicative import Language.Haskell.Liquid.Prelude goo x = [x] xs = goo (choose 0) nullity :: [a] -> Int nullity [] = 0 nullity (x:_) = 1 prop2 = liquidAssertB (1 == nullity xs)
spinda/liquidhaskell
tests/gsoc15/unknown/pos/meas1.hs
bsd-3-clause
256
1
8
52
100
53
47
10
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} -- | Home/landing page. module HL.View.Home where import HL.Types import HL.View import HL.View.Code import HL.View.Home.Features import HL.View.Home.Whyhaskell import HL.View.Template import System.Random -- | Home view. homeV :: SnippetInfo -> View App () homeV snippets = skeleton "Haskell Language" (linkcss "https://fonts.googleapis.com/css?family=Ubuntu:700") (do url <- lift (asks pageRender) navigation True header snippets url whyhaskell when False (community url) when False features when False (try url) sponsors events div_ [class_ "mobile"] $ (navigation False)) (scripts [js_jquery_console_js, js_tryhaskell_js, js_tryhaskell_pages_js]) -- | Top header section with the logo and code sample. header :: SnippetInfo -> (Route App -> Text) -> View App () header snippetInfo url = div_ [class_ "header"] $ (container_ (row_ (do span6_ [class_ "col-md-6"] (div_ [class_ "branding"] (do branding summation)) span6_ [class_ "col-md-6"] (div_ [class_ "branding"] (do tag snippet))))) where branding = span_ [class_ "name", background url img_logo_png] "Haskell" summation = span_ [class_ "summary"] "An advanced purely-functional programming language" tag = span_ [class_ "tag"] "Declarative, statically typed code." snippet = maybe (p_ (toHtml (show index))) sample (lookup index (zip [0 ..] (siSnippets snippetInfo))) index = fst (randomR (0, (length (siSnippets snippetInfo)) - 1) (mkStdGen (siSeed snippetInfo))) -- | Show a sample code. sample :: Snippet -> View App () sample snippet = div_ [class_ "code-sample", title_ (snippetTitle snippet)] (haskellPre (snippetCode snippet)) -- | Try Haskell section. try :: (Route App -> Text) -> View App () try _ = div_ [class_ "try", onclick_ "tryhaskell.controller.inner.click()"] (container_ (row_ (do span6_ [class_ "col-md-6"] repl span6_ [class_ "col-md-6", id_ "guide"] (return ())))) where repl = do h2_ "Try it" noscript_ (span6_ (div_ [class_ "alert alert-warning"] "Try Haskell requires JavaScript to be enabled.")) span6_ [hidden_ "", id_ "cookie-warning"] (div_ [class_ "alert alert-warning"] "Try Haskell requires cookies to be enabled.") div_ [id_ "console"] (return ()) -- | Community section. -- TOOD: Should contain a list of thumbnail videos. See mockup. community :: (Route App -> Text) -> View App () community url = div_ [id_ "community-wrapper"] (do div_ [class_ "community", background url img_community_jpg] (do container_ [id_ "tagline"] (row_ (span8_ [class_ "col-md-8"] (do h1_ "An open source community effort for over 20 years" p_ [class_ "learn-more"] (a_ [href_ (url CommunityR)] "Learn more")))))) -- | Events section. -- TODO: Take events section from Haskell News? events :: View App () events = return () -- | List of sponsors. sponsors :: View App () sponsors = div_ [class_ "sponsors"] $ container_ $ do row_ (span6_ [class_ "col-md-6"] (h1_ "Sponsors")) row_ (do span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "https://www.fpcomplete.com/"] "FP Complete") " The leading commercial provider of Haskell consulting")) span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "http://haskellbook.com/"] "Haskell Programming from First Principles") " Think learning Haskell is difficult? It doesn't have to be.")))
haskell-lang/haskell-lang
src/HL/View/Home.hs
bsd-3-clause
4,630
0
27
1,808
1,115
549
566
107
1
module Test where import System.IO import System.Random import System.IO.Unsafe import Data.List import Data.Char import Data.Tuple import AffineDecode import AffineEncode import Atbash import CaesarEncode import CaesarDecode import MorseEncode import MorseDecode --import RSAEncode --import SubstitutionEncode import VigenereEncode import VigenereDecode --import PlayFair repeater :: String -> String repeater t = t ++ repeater t cleaner :: Char -> Char cleaner x | isAlpha x || x=='\'' = x | True = ' ' randomStr :: Int -> String randomStr t = take t $ randomRs ('a','z') $ unsafePerformIO newStdGen randomNs :: Int -> [Int] randomNs t = take t $ randomRs (1,1000) $ unsafePerformIO newStdGen main = do data1 <- hGetContents =<< openFile "dict/american-english" ReadMode data2 <- hGetContents =<< openFile "dict/cracklib-small" ReadMode let bigData = sort $ (words $ map cleaner data1) ++ (words $ map cleaner data2) putStrLn "AFFINE" let numberA = head $ randomNs 1 let numberB = head $ randomNs 1 print numberA print numberB let myAffineString = randomStr 10 putStrLn myAffineString putStrLn "AFFINE ENCODE" let myAffineEncode = affineEncode numberA numberB myAffineString putStrLn $ myAffineEncode putStrLn "AFFINE DECODE" let myAffineDecode = affineDecode numberA numberB myAffineEncode putStrLn $ myAffineDecode putStrLn "ATBASH" --let numberA = head $ randomNs 1 --let numberB = head $ randomNs 1 --print numberA --print numberB let myAtbashString = randomStr 10 putStrLn myAtbashString putStrLn "ATBASH ENCODE" let myAtbashEncode = atbash myAtbashString putStrLn $ myAtbashEncode putStrLn "AFFINE DECODE" let myAtbashDecode = atbash myAtbashEncode putStrLn $ myAtbashDecode putStrLn "CAESAR" let numberC = head $ randomNs 1 --let numberB = head $ randomNs 1 print numberC --print numberB let myCaesarString = randomStr 10 putStrLn myCaesarString putStrLn "CAESAR ENCODE" let myCaesarEncode = caesarEncode numberC myCaesarString putStrLn $ myCaesarEncode putStrLn "CAESAR DECODE" let myCaesarDecode = caesarDecode numberC myCaesarEncode putStrLn $ myCaesarDecode putStrLn "CAESAR" let numberC = head $ randomNs 1 --let numberB = head $ randomNs 1 print numberC --print numberB let myCaesarString = randomStr 10 putStrLn myCaesarString putStrLn "CAESAR ENCODE" let myCaesarEncode = caesarEncode numberC myCaesarString putStrLn $ myCaesarEncode putStrLn "CAESAR DECODE" let myCaesarDecode = caesarDecode numberC myCaesarEncode putStrLn $ myCaesarDecode putStrLn "MORSE" --let numberC = head $ randomNs 1 --let numberB = head $ randomNs 1 --print numberC --print numberB let myMorseString = randomStr 10 putStrLn myMorseString putStrLn "MORSE ENCODE" let myMorseEncode = morseEncode myMorseString putStrLn $ myMorseEncode putStrLn "MORSE DECODE" let myMorseDecode = morseDecode $ words myMorseEncode putStrLn $ myMorseDecode putStrLn "VIGENERE" let rkey = randomStr 3 --let numberB = head $ randomNs 1 putStrLn rkey let key = repeater rkey --print numberB let myVigenereString = randomStr 10 putStrLn myVigenereString putStrLn "VIGENERE ENCODE" let myVigenereEncode = vigenereEncode key myVigenereString putStrLn $ myCaesarEncode putStrLn "VIGENERE DECODE" let myVigenereDecode = vigenereDecode key myVigenereEncode putStrLn $ myVigenereDecode {- main = do putStrLn randomStr putStrLn randomStr raw <-getLine let raw2 = words $ map cleaner raw putStrLn (decrypt bigData raw2) putStrLn "Abhinav" -}
abhinav-mehta/CipherSolver
src/Test.hs
bsd-3-clause
3,564
27
14
630
922
421
501
95
1
{-#LANGUAGE GADTs, StandaloneDeriving, GeneralizedNewtypeDeriving #-} module Genome.Dna.Dna where import Data.List (sort) import Data.Set (Set) import Data.Sequence (Seq) import Data.Sequence ((><), (<|), (|>)) import qualified Data.Foldable as Foldable import Test.QuickCheck (Gen, choose, elements, generate, vectorOf) import Test.QuickCheck.Arbitrary (Arbitrary, arbitrary) import Util.Util (hamdist import Genome.Data.FrequencyArray (Lexicord, lexord, lexval, listlexord, listlexval) {- Ix is used to map a contiguous subrange of values in type onto integers. It is used primarily for array indexing (see the array package). Ix uses row-major order. -} import Data.Ix {- Foreign.Storable provides most elementary support for marshalling and is part of the language-independent portion of the Foreign Function Interface (FFI), and will normally be imported via the Foreign module -} import Foreign.Storable import qualified Data.Set as Set import Data.Word invalidPos :: Int invalidPos = -1 class Ord a => Base a where bases :: [a] indexed :: Int -> a --to use in random generation complement :: a -> a invalidElem :: a valid :: a -> Bool valid x = elem x bases symbol :: a -> Char instance Base Char where bases = ['A', 'C', 'G', 'T', 'N', 'a', 'c', 'g', 't'] indexed 0 = 'A' indexed 1 = 'C' indexed 2 = 'G' indexed 3 = 'T' indexed _ = 'N' complement c = case c of 'A' -> 'T' 'a' -> 't' 'C' -> 'G' 'c' -> 'g' 'G' -> 'C' 'g' -> 'c' 'T' -> 'A' 't' -> 'a' 'N' -> 'N' 'n' -> 'n' _ -> c invalidElem = 'N' symbol c = c instance Base Int where bases = [0, 1, 2, 3, 4] indexed i = if (i < 0) then 4 else min i 4 complement c = case c of 0 -> 3 1 -> 2 2 -> 1 3 -> 0 4 -> 4 _ -> c invalidElem = 4 symbol c = case c of 0 -> 'A' 1 -> 'C' 2 -> 'G' 3 -> 'T' data Sense = Reverse | Forward deriving (Eq, Ord, Show, Read) anti :: Sense -> Sense anti Reverse = Forward anti Forward = Reverse reverseComplement :: Base a => [a] -> [a] reverseComplement = foldl (\rs x -> (complement x):rs) [] isBase :: Char -> Bool isBase c = c == 'A' || c == 'C' || c == 'G' || c == 'T' isDNA :: String -> Bool isDNA seq = all isBase seq class WithBaseSeq b where bseq :: Base a => (b a) -> [a] newtype Nucleotide = Nuc {unNuc :: Word8} deriving ( Eq, Ord, Enum, Ix, Storable ) instance Bounded Nucleotide where minBound = Nuc 0 maxBound = Nuc 15 instance Show Nucleotide where show (Nuc x) | x == 0 = "-" | x == 1 = "A" | x == 2 = "C" | x == 4 = "G" | x == 8 = "T" | x == 15 = "N" | otherwise = "X" gap, _A_, _C_, _G_, _T_, _N_ :: Nucleotide gap = Nuc 0 _A_ = Nuc 1 _C_ = Nuc 2 _G_ = Nuc 4 _T_ = Nuc 8 _N_ = Nuc 15 instance Base Nucleotide where bases = [_A_, _C_, _G_, _T_, _N_] indexed 0 = gap indexed 1 = _A_ indexed 2 = _C_ indexed 3 = _G_ indexed 4 = _T_ indexed _ = _N_ complement (Nuc 0) = Nuc 0 complement (Nuc 1) = Nuc 8 complement (Nuc 2) = Nuc 4 complement (Nuc 4) = Nuc 2 complement (Nuc 8) = Nuc 1 complement (Nuc 15) = Nuc 15 complement x = x invalidElem = Nuc 15 symbol (Nuc 0) = '-' symbol (Nuc 1) = 'A' symbol (Nuc 2) = 'C' symbol (Nuc 4) = 'G' symbol (Nuc 8) = 'T' symbol (Nuc 15) = 'N' symbol x = 'X' type DnaSeq = Seq Nucleotide instance Arbitrary Nucleotide where arbitrary = do x <- choose (0, 3) :: Gen Int return (Nuc (2 ^ x)) dnaString :: (Base b) => [b] -> String dnaString [] = "" dnaString (b:bs) = (symbol b) : (dnaString bs) randNuc0 = elements [gap, _A_, _C_, _G_, _T_] randNuc = elements [_A_, _C_, _G_, _T_] randomDna :: Int -> Gen [Nucleotide] randomDna k = vectorOf k randNuc --for frequency arrays instance Lexicord Char where lexord 'A' = 0 lexord 'C' =1 lexord 'G' = 2 lexord 'T' = 3 lexord _ = -1 lexval 0 = 'A' lexval 1 = 'C' lexval 2 = 'G' lexval 3 = 'T' lexval _ = 'N' instance Lexicord Nucleotide where lexord (Nuc 1) = 0 lexord (Nuc 2) = 1 lexord (Nuc 4) = 2 lexord (Nuc 8) = 3 lexord _ = -1 lexval 0 = _A_ lexval 1 = _C_ lexval 2 = _G_ lexval 3 = _T_ lexval _ = _N_
visood/bioalgo
src/lib/Genome/Dna/Dna.hs
bsd-3-clause
4,368
17
12
1,279
1,446
825
621
-1
-1
-- Tahin -- Copyright (C) 2015-2016 Moritz Schulte <mtesseract@silverratio.net> {-# LANGUAGE OverloadedStrings #-} module Crypto.Tahin ( TahinPassword , TahinMasterPassword , TahinIdentifier , TahinTransformer , tahin ) where import qualified Data.ByteString.Base64 as B64 import qualified Data.ByteString.Char8 as BS8 import qualified Data.Text as T import qualified Data.Text.Encoding as TE import Data.Text (Text) -- | TahinMasterPassword is used for holding a master password. type TahinMasterPassword = Text -- | TahinPassword is used for passwords generated by Tahin. type TahinPassword = Text -- | A TahinIdentifier is used for holding a '(service) identifier'. type TahinIdentifier = Text -- | A 'TahinTransformer' is a function mapping a -- 'TahinMasterPassword' together with a 'TahinIdentifier' to a -- 'TahinPassword'. type TahinTransformer = TahinMasterPassword -> TahinIdentifier -> TahinPassword ------------------------- -- Main tahin function -- ------------------------- -- | Given a hash function and a maximum length, return a -- 'TahinTransformer'. tahin :: (BS8.ByteString -> BS8.ByteString) -> Int -> TahinTransformer tahin hash len = curry (T.take len . TE.decodeUtf8 . B64.encode . hash . TE.encodeUtf8 . intercal) where intercal (pw, identifier) = T.intercalate " " [pw, identifier]
mtesseract/tahin
src/Crypto/Tahin.hs
bsd-3-clause
1,426
0
13
294
214
134
80
19
1
module AbstractInterpreter.PatternMatcher where {- This module defines pattern matching over abstract sets -} import TypeSystem import Utils.Utils import Utils.ToString import Utils.Unification import Graphs.UnionFind import AbstractInterpreter.AbstractSet import AbstractInterpreter.Assignment import AbstractInterpreter.Constraints import qualified Data.Map as M import Data.Map (Map, (!), intersection, union, empty, singleton, keys) import Data.List as L import Data.Maybe import Data.Tuple import Control.Arrow ((&&&)) import Control.Monad patternMatch :: Syntax -> Expression -> AbstractSet -> [Assignments] patternMatch _ MCall{} _ = returnE patternMatch r (MVar _ v) as = assign v as patternMatch r (MParseTree (MLiteral _ _ s1)) (ConcreteLiteral _ s2) | s1 == s2 = returnE | otherwise = returnF $ "Not the same literal: "++s1++ " /= " ++ s2 patternMatch r (MParseTree (MInt _ _ s1)) (ConcreteInt _ n) = returnE patternMatch r (MParseTree (PtSeq _ mi pts)) pt = patternMatch r (MSeq mi (pts |> MParseTree)) pt patternMatch r s1@(MSeq _ seq1) s2@(AsSeq _ _ seq2) | length seq1 /= length seq2 = returnF $ "Sequence lengths are not the same: "++toParsable s1 ++ " /= "++toParsable s2 | otherwise = do somePossibleMatch <- zip seq1 seq2 |+> uncurry (patternMatch r) mergeAssgnss r somePossibleMatch patternMatch r ascr@(MAscription as expr') expr | alwaysIsA r (typeOf expr) as = patternMatch r expr' expr | mightContainA r as (typeOf expr) = do possExpr <- unfold r expr & filter isEveryPossible patternMatch r ascr possExpr | otherwise = returnF $ "Failed ascription: "++show expr ++" is not a "++show as patternMatch syntax evalCtx@(MEvalContext tp name hole) value = do -- first of all, the current expression should (be able to) contain the sub expression -- this sub-expression (hole) is always a complete expression; thus we search a 'EveryPossible' within our asseq. (The eventually unfolded input) let neededType = typeOf hole value' <- unfoldFull syntax value -- contexts only work within another expression, so we already unfold. (Searchmatches might unfold more) (match, pths) <- searchMatches syntax neededType [] value' pth <- pths -- we calculate assignments induced by the hole-expression... let replacedExpr = getAsAt match pth -- the subexpression that is thrown away let holeName = getName replacedExpr let holeType = typeOf replacedExpr holeAssignment <- patternMatch syntax hole (generateAbstractSet syntax (holeName++"$") holeType) -- and calculate the form of the hole let hole' = evalExpr M.empty {-functions are not possible in the patterns anyway-} holeAssignment hole & either error id let match' = replaceAS match pth hole' let ctxAssignment = M.singleton name (match', Just pth) mergeAssgns syntax holeAssignment ctxAssignment patternMatch r pat as@EveryPossible{} = do choice <- unfold r as patternMatch r pat choice patternMatch _ pat as = [] {- Consider x ::= a b | c b | d b ::= "B" z Given x["B" z], we want to search a possible unfolding of x, containing the possible sets, e.g. [(a b, [1]), (c b, [1]) -} searchMatches :: Syntax -> TypeName -> [TypeName] -> AbstractSet -> [(AbstractSet, [Path])] searchMatches syntax neededType noExpand as@(EveryPossible _ _ t) | alwaysIsA syntax t neededType = return (as, [[]]) | t `elem` noExpand = [] | otherwise = do as' <- unfold syntax as searchMatches syntax neededType (t:noExpand) as' searchMatches syntax neededType noExpand (AsSeq gen i seq) = do seq' <- mapi seq |> (\(i, as) -> if isEveryPossible as && (typeOf as & mightContainA syntax neededType) then searchMatches syntax neededType noExpand as ||>> (|> (i:)) else [(as, [])]) & allCombinations :: [[ (AbstractSet, [Path]) ]] let (seq'', pthss) = unzip seq' :: ([AbstractSet], [ [Path] ]) return (AsSeq gen i seq'', concat pthss) searchMatches _ _ _ _ = [] ------------------------ Tools --------------------------------------------- returnE = [empty] assign n v = [singleton n (v, Nothing)] -- error messages. Might actually be used somewhere in the future returnF str = []
pietervdvn/ALGT
src/AbstractInterpreter/PatternMatcher.hs
bsd-3-clause
4,169
107
16
769
1,366
703
663
81
2
{-# language CPP #-} -- | = Name -- -- VK_EXT_shader_subgroup_ballot - device extension -- -- == VK_EXT_shader_subgroup_ballot -- -- [__Name String__] -- @VK_EXT_shader_subgroup_ballot@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 65 -- -- [__Revision__] -- 1 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- [__Deprecation state__] -- -- - /Deprecated/ by -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#versions-1.2-new-features Vulkan 1.2> -- -- [__Contact__] -- -- - Daniel Koch -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_shader_subgroup_ballot] @dgkoch%0A<<Here describe the issue or question you have about the VK_EXT_shader_subgroup_ballot extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2016-11-28 -- -- [__IP Status__] -- No known IP claims. -- -- [__Interactions and External Dependencies__] -- -- - This extension requires -- <https://htmlpreview.github.io/?https://github.com/KhronosGroup/SPIRV-Registry/blob/master/extensions/KHR/SPV_KHR_shader_ballot.html SPV_KHR_shader_ballot> -- -- - This extension provides API support for -- <https://www.khronos.org/registry/OpenGL/extensions/ARB/ARB_shader_ballot.txt GL_ARB_shader_ballot> -- -- [__Contributors__] -- -- - Jeff Bolz, NVIDIA -- -- - Neil Henning, Codeplay -- -- - Daniel Koch, NVIDIA Corporation -- -- == Description -- -- This extension adds support for the following SPIR-V extension in -- Vulkan: -- -- - @SPV_KHR_shader_ballot@ -- -- This extension provides the ability for a group of invocations, which -- execute in parallel, to do limited forms of cross-invocation -- communication via a group broadcast of a invocation value, or broadcast -- of a bitarray representing a predicate value from each invocation in the -- group. -- -- This extension provides access to a number of additional built-in shader -- variables in Vulkan: -- -- - @SubgroupEqMaskKHR@, containing the subgroup mask of the current -- subgroup invocation, -- -- - @SubgroupGeMaskKHR@, containing the subgroup mask of the invocations -- greater than or equal to the current invocation, -- -- - @SubgroupGtMaskKHR@, containing the subgroup mask of the invocations -- greater than the current invocation, -- -- - @SubgroupLeMaskKHR@, containing the subgroup mask of the invocations -- less than or equal to the current invocation, -- -- - @SubgroupLtMaskKHR@, containing the subgroup mask of the invocations -- less than the current invocation, -- -- - @SubgroupLocalInvocationId@, containing the index of an invocation -- within a subgroup, and -- -- - @SubgroupSize@, containing the maximum number of invocations in a -- subgroup. -- -- Additionally, this extension provides access to the new SPIR-V -- instructions: -- -- - @OpSubgroupBallotKHR@, -- -- - @OpSubgroupFirstInvocationKHR@, and -- -- - @OpSubgroupReadInvocationKHR@, -- -- When using GLSL source-based shader languages, the following variables -- and shader functions from GL_ARB_shader_ballot can map to these SPIR-V -- built-in decorations and instructions: -- -- - @in uint64_t gl_SubGroupEqMaskARB;@ → @SubgroupEqMaskKHR@, -- -- - @in uint64_t gl_SubGroupGeMaskARB;@ → @SubgroupGeMaskKHR@, -- -- - @in uint64_t gl_SubGroupGtMaskARB;@ → @SubgroupGtMaskKHR@, -- -- - @in uint64_t gl_SubGroupLeMaskARB;@ → @SubgroupLeMaskKHR@, -- -- - @in uint64_t gl_SubGroupLtMaskARB;@ → @SubgroupLtMaskKHR@, -- -- - @in uint gl_SubGroupInvocationARB;@ → @SubgroupLocalInvocationId@, -- -- - @uniform uint gl_SubGroupSizeARB;@ → @SubgroupSize@, -- -- - @ballotARB@() → @OpSubgroupBallotKHR@, -- -- - @readFirstInvocationARB@() → @OpSubgroupFirstInvocationKHR@, and -- -- - @readInvocationARB@() → @OpSubgroupReadInvocationKHR@. -- -- == Deprecated by Vulkan 1.2 -- -- Most of the functionality in this extension is superseded by the core -- Vulkan 1.1 -- <VkPhysicalDeviceSubgroupProperties.html subgroup operations>. However, -- Vulkan 1.1 required the @OpGroupNonUniformBroadcast@ “Id” to be -- constant. This restriction was removed in Vulkan 1.2 with the addition -- of the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#features-subgroupBroadcastDynamicId subgroupBroadcastDynamicId> -- feature. -- -- == New Enum Constants -- -- - 'EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME' -- -- - 'EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION' -- -- == New Built-In Variables -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgeq SubgroupEqMaskKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgge SubgroupGeMaskKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sggt SubgroupGtMaskKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgle SubgroupLeMaskKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sglt SubgroupLtMaskKHR> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgli SubgroupLocalInvocationId> -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#interfaces-builtin-variables-sgs SubgroupSize> -- -- == New SPIR-V Capabilities -- -- - <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#spirvenv-capabilities-table-SubgroupBallotKHR SubgroupBallotKHR> -- -- == Version History -- -- - Revision 1, 2016-11-28 (Daniel Koch) -- -- - Initial draft -- -- == See Also -- -- No cross-references are available -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_shader_subgroup_ballot Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_EXT_shader_subgroup_ballot ( EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION , pattern EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION , EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME , pattern EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME ) where import Data.String (IsString) type EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION = 1 -- No documentation found for TopLevel "VK_EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION" pattern EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION :: forall a . Integral a => a pattern EXT_SHADER_SUBGROUP_BALLOT_SPEC_VERSION = 1 type EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME = "VK_EXT_shader_subgroup_ballot" -- No documentation found for TopLevel "VK_EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME" pattern EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_SHADER_SUBGROUP_BALLOT_EXTENSION_NAME = "VK_EXT_shader_subgroup_ballot"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_EXT_shader_subgroup_ballot.hs
bsd-3-clause
7,437
0
8
1,189
292
246
46
-1
-1
{-# LANGUAGE OverloadedStrings, FlexibleInstances #-} module Json where import Network import Control.Monad import System.IO(Handle, hFlush, hPutChar) import Data.Aeson import qualified Data.Aeson.Generic as GJ import Data.Maybe import Data.Data import Data.Typeable import qualified Data.ByteString.Lazy.Char8 as L send :: ToJSON a => Handle -> String -> a -> IO () send h msgType msgData = do let json = encode $ object ["msgType" .= msgType, "data" .= msgData] L.hPut h $ json hPutChar h '\n' hFlush h --putStrLn $ ">> " ++ (show json) instance FromJSON (String, Value) where parseJSON (Object v) = do msgType <- v .: "msgType" msgData <- v .: "data" return (msgType, msgData) parseJSON x = fail $ "Not an JSON object: " ++ (show x)
timorantalaiho/pong11
src/Json.hs
bsd-3-clause
777
0
13
157
250
134
116
23
1
module Main where import Console.ConsoleRunner (setUpGame, play) main :: IO () main = do putStrLn $ "Welcome To Tic Tac Toe!" config <- setUpGame play config
jcg3challenges/haskell_ttt
app/Main.hs
bsd-3-clause
169
0
7
37
52
27
25
7
1
module PolyGraph.Common.RecursionHelpers ( HashTable, memo, noReentry, handleReentry, dumpMemoStore, RecursionHandler (..) ) where --exports everything, terrible programmer import Control.Monad (forM) import qualified Control.Monad.ST as St import Data.Hashable (Hashable) import qualified Data.HashTable.ST.Cuckoo as C import qualified Data.HashTable.Class as H data RecursionHandler m a b = RecursionHandler { handle :: (a -> m b) -> a -> m b } -- memo helpers use ST Monad type HashTable s k v = C.HashTable s k v -- passing ST.pure hash allows for better hash sharing memo :: (Eq a, Hashable a) => HashTable s a b -> (a -> St.ST s b) -> (a -> St.ST s b) memo ht f a = do maybe_b <- H.lookup ht a b <- case maybe_b of Nothing -> f a Just _b -> return _b case maybe_b of Nothing -> H.insert ht a b _ -> return () return b -- -- result function returns f1 (second fn arg) function result on first call and f2 (first fn arg) afterwords -- this is a re-entry handler -- handleReentry :: (Eq a, Hashable a) => HashTable s a Bool -> (a -> St.ST s b) -> (a -> St.ST s b) -> (a -> St.ST s b) handleReentry ht handler f a = do maybe_b <- H.lookup ht a H.insert ht a True case maybe_b of Nothing -> f a Just _ -> handler a noReentry :: (Eq a, Hashable a) => HashTable s a Bool -> (a -> St.ST s b) -> (a -> St.ST s b) noReentry ht = handleReentry ht (\_ -> fail "reentry-detected") {- noReentry ht f a = do maybe_b <- H.lookup ht a H.insert ht a True case maybe_b of Nothing -> f a Just x -> fail ("re-entry detected") -} dumpMemoStore :: (Eq a, Hashable a) => HashTable s a b -> St.ST s [(a,b)] dumpMemoStore h = do H.foldM (\list el -> return (el: list)) [] h -- TESTS --- -- TMemoExperiments have code that traces _fib :: Int -> St.ST s Int _fib 0 = return 0 _fib 1 = return 1 _fib i = do f1 <- _fib (i-1) f2 <- _fib (i-2) return (f1 + f2) _fibX :: HashTable s Int Int -> Int -> St.ST s Int _fibX _ 0 = return 0 _fibX _ 1 = return 1 _fibX h i = do f1 <- memo h (_fibX h) $ (i-1) f2 <- memo h (_fibX h) $ (i-2) return (f1 + f2) _runFib :: Int -> St.ST s Int _runFib i = do ht <- H.new:: St.ST s (HashTable s Int Int) f <- _fibX ht i return f _fibY :: HashTable s Int Bool -> HashTable s Int Int -> Int -> St.ST s Int _fibY _ _ 0 = return 0 _fibY _ _ 1 = return 1 _fibY h0 h i = do f1 <- ((memo h) . (noReentry h0)) (_fibY h0 h) $ (i-1) f2 <- ((memo h) . (noReentry h0)) (_fibY h0 h) $ (i-2) return (f1 + f2) _runFibY :: Int -> St.ST s Int _runFibY i = do ht0 <- H.new :: St.ST s (HashTable s Int Bool) ht <- H.new:: St.ST s (HashTable s Int Int) f <- _fibY ht0 ht i return f {- _regFibIO n = St.stToIO $ _fib n _fastFibIO n = St.stToIO (_runFib n) _regFib n = St.runST $ _fib n _fastFib n = St.runST (_runFib n) -} _compareFibs :: Int -> IO ([(Int, Int)]) _compareFibs n = St.stToIO ( do forM [1..n] (\i -> do slow <- _fib i fast <- _runFib i return (slow, fast) )) -- runST cannot be run compaints about purity loss -- can be used with stToIO only
rpeszek/GraphPlay
src/PolyGraph/Common/RecursionHelpers.hs
bsd-3-clause
3,444
0
15
1,115
1,316
665
651
77
3
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MagicHash #-} module Sky.Ideas.Choice where import GHC.Integer.Logarithms (integerLog2#) import GHC.Exts( Int( I# ) ) {- Try to do something like "Enumerable" or "Enum" Useful for generating stuff. -} ilog2 :: Integer -> Integer ilog2 i = toInteger (I# (integerLog2# i)) ---------------------------------------------------------------------------------------------------- data CH = CH { _i :: Integer, _n :: Integer, _m :: Integer } instance Show CH where show (CH i n m) = show (i,n,m) chooseIofN :: Integer -> Integer -> CH chooseIofN i n | i >= n = error "i >= n" chooseIofN i n = CH i n 1 cof :: Integer -> Integer -> CH cof = chooseIofN entropyLeft :: CH -> Integer entropyLeft (CH i n m) = quot n m bitsLeft :: CH -> Integer bitsLeft (CH i n m) = -- ilog2 (n / m) = (ilog2 n) - (ilog2 m) (ilog2 n) - (ilog2 m) combine :: CH -> CH -> CH combine (CH i0 n0 m0) (CH i1 n1 m1) = CH i n m where i = i0 * m + i1 * n0 * m1 n = n0 * n1 m = m0 * m1 extract :: Integer -> CH -> (Integer, CH) extract c (CH i0 n0 m0) = (i, CH i1 n1 m1) where g = gcd n0 c c' = c `quot` g (i, i1') = quotRem (c * i0) n0 i1 = i1' * c' n1 = n0 `quot` g m1 = m0 * c' c0of1 :: CH c0of1 = 0 `cof` 1 c0of2 :: CH c0of2 = 0 `cof` 2 c1of2 :: CH c1of2 = 1 `cof` 2 {- ---------------------------------------------------------------------------------------------------- combineChoice (i,imax) (j,jmax) = (i + j * imax, imax * jmax) partialChoice (i,imax) max | max > imax = error $ "Not enough entropy" partialChoice (i,imax) max ---------------------------------------------------------------------------------------------------- data EntropyAmount = FiniteEntropy Integer | InfiniteEntropy -- Much like RNGs, but has well defined ranges, entropy might be finite! class EntropySource e where entropyLeft :: e -> EntropyAmount -- = -- fu sublime -- | Uniformly choose an integer in range [0..max[ chooseFiniteInteger :: Integer -> e -> (Maybe Integer, e) -- = -- fu sublime -- | Uniformly choose an int in range [0..max[ chooseFiniteInt :: Int -> e -> (Maybe Int, e) chooseFiniteInt max entropy = (fmap fromIntegral i, e') where (i, e') = chooseInteger (toInteger max) class Choosable a where entropyRequired :: Proxy a -> EntropyAmount -- = -- fu sublime choose :: EntropySource e => e -> (Maybe a, e) -- = -- fu sublime chooseFinite :: EntropySource e => a -> e -> (Maybe a, e) -- = -- fu sublime --chooseFinite max entropy ---------------------------------------------------------------------------------------------------- newtype FiniteEntropySource = FiniteEntropySource { _remainder :: Integer , _remainMax :: Integer , _source :: [Bool] } instance EntropySource FiniteEntropySource where entropyAmount (FiniteEntropySource r rmax source) = 2 ^ length source + rmax chooseFiniteInteger ---------------------------------------------------------------------------------------------------- instance Chooseable () where entropyRequired Proxy = FiniteEntropy 0 choose entropy = (Just (), entropy) chooseFinite () entropy = (Just (), entropy) instance Chooseable a => Chooseable [a] where -}
xicesky/sky-haskell-playground
src/Sky/Ideas/Choice.hs
bsd-3-clause
3,359
0
10
732
549
302
247
40
1
module Hrpg.Framework.Mobs.MobType ( MobType (..) ) where import Data.Text import Hrpg.Framework.Items.LootTable import Hrpg.Framework.Level import Hrpg.Framework.Stats data MobType = MobType { mobTypeId :: Int , mobTypeName :: Text , mobTypeMinLevel :: Level , mobTypeMaxLevel :: Level , mobTypeBaseStats :: Stats , mobTypeMaxHp :: Int , mobTypeLootTable :: Maybe LootTable } deriving Show
cwmunn/hrpg
src/Hrpg/Framework/Mobs/MobType.hs
bsd-3-clause
458
0
9
118
98
64
34
15
0
{-# LANGUAGE RecordWildCards #-} -- | A persistent version of the Ghci session, encoding lots of semantics on top. -- Not suitable for calling multithreaded. module Session( Session, withSession, sessionStart, sessionRestart, sessionReload, sessionExecAsync, ) where import Language.Haskell.Ghcid import Language.Haskell.Ghcid.Util import Data.IORef import System.Time.Extra import System.Process import Control.Exception.Extra import Control.Concurrent.Extra import Control.Monad.Extra import Data.Maybe import Data.List.Extra import Control.Applicative import Prelude data Session = Session {ghci :: IORef (Maybe Ghci) -- ^ The Ghci session, or Nothing if there is none ,command :: IORef (Maybe String) -- ^ The last command passed to sessionStart ,warnings :: IORef [Load] -- ^ The warnings from the last load ,running :: Var Bool -- ^ Am I actively running an async command } -- | Ensure an action runs off the main thread, so can't get hit with Ctrl-C exceptions. -- Disabled because it plays havoc with tests and cleaning up quickly enough. ctrlC :: IO a -> IO a ctrlC = id -- join . onceFork -- | The function 'withSession' expects to be run on the main thread, -- but the inner function will not. This ensures Ctrl-C is handled -- properly and any spawned Ghci processes will be aborted. withSession :: (Session -> IO a) -> IO a withSession f = do ghci <- newIORef Nothing command <- newIORef Nothing warnings <- newIORef [] running <- newVar False ctrlC (f Session{..}) `finally` do modifyVar_ running $ const $ return False whenJustM (readIORef ghci) $ \v -> do writeIORef ghci Nothing ctrlC $ kill v -- | Kill. Wait just long enough to ensure you've done the job, but not to see the results. kill :: Ghci -> IO () kill ghci = ignore $ do timeout 5 $ quit ghci terminateProcess $ process ghci -- | Spawn a new Ghci process at a given command line. Returns the load messages, plus -- the list of files that were observed (both those loaded and those that failed to load). sessionStart :: Session -> String -> IO ([Load], [FilePath]) sessionStart Session{..} cmd = do modifyVar_ running $ const $ return False writeIORef command $ Just cmd val <- readIORef ghci whenJust val $ void . forkIO . kill writeIORef ghci Nothing outStrLn $ "Loading " ++ cmd ++ " ..." (v, messages) <- startGhci cmd Nothing $ const outStrLn writeIORef ghci $ Just v messages <- return $ mapMaybe tidyMessage messages writeIORef warnings [m | m@Message{..} <- messages, loadSeverity == Warning] return (messages, nubOrd $ map loadFile messages) -- | Call 'sessionStart' at the previous command. sessionRestart :: Session -> IO ([Load], [FilePath]) sessionRestart session@Session{..} = do Just cmd <- readIORef command sessionStart session cmd -- | Reload, returning the same information as 'sessionStart'. In particular, any -- information that GHCi doesn't repeat (warnings from loaded modules) will be -- added back in. sessionReload :: Session -> IO ([Load], [FilePath]) sessionReload session@Session{..} = do -- kill anything async, set stuck if you didn't succeed old <- modifyVar running $ \b -> return (False, b) stuck <- if not old then return False else do Just ghci <- readIORef ghci fmap isNothing $ timeout 5 $ interrupt ghci if stuck then sessionRestart session else do -- actually reload Just ghci <- readIORef ghci messages <- mapMaybe tidyMessage <$> reload ghci loaded <- map snd <$> showModules ghci let reloaded = nubOrd $ filter (/= "") $ map loadFile messages warn <- readIORef warnings -- only keep old warnings from files that are still loaded, but did not reload let validWarn w = loadFile w `elem` loaded && loadFile w `notElem` reloaded -- newest warnings always go first, so the file you hit save on most recently has warnings first messages <- return $ messages ++ filter validWarn warn writeIORef warnings [m | m@Message{..} <- messages, loadSeverity == Warning] return (messages, nubOrd $ loaded ++ reloaded) -- | Run an exec operation asynchronously. Should not be a @:reload@ or similar. -- Will be automatically aborted if it takes too long. Only fires done if not aborted. -- Argument to done is the final stderr line. sessionExecAsync :: Session -> String -> (String -> IO ()) -> IO () sessionExecAsync Session{..} cmd done = do Just ghci <- readIORef ghci stderr <- newIORef "" modifyVar_ running $ const $ return True caller <- myThreadId void $ flip forkFinally (either (throwTo caller) (const $ return ())) $ do execStream ghci cmd $ \strm msg -> when (msg /= "*** Exception: ExitSuccess") $ do when (strm == Stderr) $ writeIORef stderr msg outStrLn msg old <- modifyVar running $ \b -> return (False, b) -- don't fire Done if someone interrupted us stderr <- readIORef stderr when old $ done stderr -- | Ignore entirely pointless messages and remove unnecessary lines. tidyMessage :: Load -> Maybe Load tidyMessage Message{loadSeverity=Warning, loadMessage=[_,x]} | x == " -O conflicts with --interactive; -O ignored." = Nothing tidyMessage m@Message{..} = Just m{loadMessage = filter (\x -> not $ any (`isPrefixOf` x) bad) loadMessage} where bad = [" except perhaps to import instances from" ," To import instances alone, use: import "] tidyMessage x = Just x
JPMoresmau/ghcid
src/Session.hs
bsd-3-clause
5,652
0
18
1,320
1,415
708
707
94
3
-------------------------------------------------------------------- -- | -- Module : Main -- Copyright : (c) Stephen Diehl 2013 -- License : MIT -- Maintainer: stephen.m.diehl@gmail.com -- Stability : experimental -- Portability: non-portable -- -------------------------------------------------------------------- module Main where import Parser import Codegen import Emit import Control.Monad.Trans import System.IO import System.Environment import System.Console.Haskeline import qualified LLVM.General.AST as AST initModule :: AST.Module initModule = emptyModule "my cool jit" process :: AST.Module -> String -> IO (Maybe AST.Module) process modo source = do let res = parseToplevel source case res of Left err -> print err >> return Nothing Right ex -> do ast <- codegen modo ex return $ Just ast processFile :: String -> IO (Maybe AST.Module) processFile fname = readFile fname >>= process initModule repl :: IO () repl = runInputT defaultSettings (loop initModule) where loop :: AST.Module -> InputT IO () loop mod = do minput <- getInputLine "ready> " case minput of Nothing -> outputStrLn "Goodbye." Just input -> do modn <- lift $ process mod input case modn of Just modn -> loop modn Nothing -> loop mod main :: IO () main = do args <- getArgs case args of [] -> repl [fname] -> processFile fname >> return ()
TorosFanny/kaleidoscope
src/chapter7/Main.hs
mit
1,445
0
17
322
403
202
201
39
3
module Category.TypedGraphRule.FindMorphism () where import Abstract.Category import Abstract.Category.FindMorphism import Abstract.Rewriting.DPO import Category.TypedGraph () import Category.TypedGraphRule.Category instance FindMorphism (RuleMorphism n e) where -- | A match between two first-order rules (desconsidering the NACs) findMorphisms cls' p1 p2 = [ ruleMorphism p1 p2 fL fK fR | fK <- findMorphisms cls (interfaceObject p1) (interfaceObject p2) , fL <- findSpanCommuters cls (leftMorphism p1) (leftMorphism p2 <&> fK) , fR <- findSpanCommuters cls (rightMorphism p1) (rightMorphism p2 <&> fK) ] where cls = toFstOrderMorphismClass cls' induceSpanMorphism = error "induceSpanMorphism not implemented for RuleMorphism" -- Given span (p2 <-f- p1 -g-> p3), returns a list of (h : p2 -> p3) with (h <&> f = g) findSpanCommuters cls' f g = [ ruleMorphism p2 p3 hL hK hR | hK <- findSpanCommuters cls (mappingInterface f) (mappingInterface g) , hL <- findSpanCommuters cls (leftMorphism p2) (leftMorphism p3 <&> hK) , hL <&> fL == gL , hR <- findSpanCommuters cls (rightMorphism p2) (rightMorphism p3 <&> hK) , hR <&> fR == gR ] where (p2, p3) = (codomain f, codomain g) (fL, fR) = (mappingLeft f, mappingRight f) (gL, gR) = (mappingLeft g, mappingRight g) cls = toFstOrderMorphismClass cls' -- Given cospan (p2 -f-> p1 <-g- p3), returns a list of (h : p2 -> p3) with (f = g <&> h) findCospanCommuters cls' f g = [ ruleMorphism p2 p3 hL hK hR | hK <- findCospanCommuters cls (mappingInterface f) (mappingInterface g) , hL <- findSpanCommuters cls (leftMorphism p2) (leftMorphism p3 <&> hK) , fL == gL <&> hL , hR <- findSpanCommuters cls (rightMorphism p2) (rightMorphism p3 <&> hK) , fR == gR <&> hR ] where (p2, p3) = (domain f, domain g) (fL, fR) = (mappingLeft f, mappingRight f) (gL, gR) = (mappingLeft g, mappingRight g) cls = toFstOrderMorphismClass cls'
rodrigo-machado/verigraph
src/library/Category/TypedGraphRule/FindMorphism.hs
gpl-3.0
2,132
0
12
564
635
327
308
36
0
-- Copyright (C) 2017 Red Hat, Inc. -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public -- License along with this library; if not, see <http://www.gnu.org/licenses/>. import Control.Monad(forM_) import System.Environment(getArgs) import System.Exit(exitFailure) import BDCS.Version import Utils.GetOpt(commandLineArgs) import Utils.Subcommands(runSubcommand) -- A mapping from a subcommand name to a brief description of what it does. knownSubcommands :: [(String, String)] knownSubcommands = [ ("groups", "List groups (RPM packages, etc.) in the content store"), ("ls", "List files in the content store"), ("nevras", "List NEVRAs of RPM packages in the content store") ] usage :: IO () usage = do printVersion "inspect" putStrLn "Usage: inspect output.db repo subcommand [args ...]" putStrLn "- output.db is the path to a metadata database" putStrLn "- repo is the path to a content store repo" putStrLn "- subcommands:" forM_ knownSubcommands $ \(cmd, help) -> putStrLn $ " " ++ cmd ++ " - " ++ help exitFailure main :: IO () main = commandLineArgs <$> getArgs >>= \case Just (db, repo, subcmd:args) -> runSubcommand "inspect-" subcmd ([db, repo] ++ args) knownSubcommands usage _ -> usage
atodorov/bdcs
src/tools/inspect/inspect.hs
lgpl-2.1
1,816
4
12
357
280
157
123
-1
-1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="az-AZ"> <title>Form Handler | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/formhandler/src/main/javahelp/org/zaproxy/zap/extension/formhandler/resources/help_az_AZ/helpset_az_AZ.hs
apache-2.0
974
85
52
160
398
210
188
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE ScopedTypeVariables #-} -- | Introduce simple theta joins. module Database.DSH.CL.Opt.ThetaJoin ( thetajoinR ) where import qualified Data.Set as S import Database.DSH.CL.Kure import Database.DSH.CL.Lang import Database.DSH.CL.Opt.Auxiliary import qualified Database.DSH.CL.Primitives as P import Database.DSH.Common.Lang -------------------------------------------------------------------------------- -- Introduce simple theta joins tuplifyCont :: S.Set Ident -> (Ident, Expr) -> (Ident, Expr) -> NL Qual -> (NL Qual, Expr -> Expr) tuplifyCont scopeNames (x, xs) (y, ys) qs = tuplifyCompContE scopeNames x (x, xt) (y, yt) qs where xt = elemT $ typeOf xs yt = elemT $ typeOf ys tuplify :: S.Set Ident -> (Ident, Expr) -> (Ident, Expr) -> Expr -> Expr tuplify scopeNames (x, xs) (y, ys) = tuplifyE scopeNames x (x, xt) (y, yt) where xt = elemT $ typeOf xs yt = elemT $ typeOf ys thetajoinQualsT :: TransformC CL (NL Qual, Expr -> Expr) thetajoinQualsT = readerT $ \e -> case e of QualsCL (BindQ x xs :* BindQ y ys :* GuardQ p :* qs) -> do guardM $ x /= y -- xs and ys generators must be independent guardM $ x `notElem` freeVars ys -- The predicate must be a join predicate joinConjunct <- constT $ splitJoinPredM x y p scopeNames <- inScopeNamesT let joinGen = BindQ x (P.thetajoin xs ys (singlePred joinConjunct)) (qs', substCont) = tuplifyCont scopeNames (x, xs) (y, ys) qs return (joinGen :* qs', substCont) QualsCL (BindQ x xs :* BindQ y ys :* S (GuardQ p)) -> do guardM $ x /= y -- xs and ys generators must be independent guardM $ x `notElem` freeVars ys -- The predicate must be a join predicate joinConjunct <- constT $ splitJoinPredM x y p scopeNames <- inScopeNamesT let joinGen = BindQ x (P.thetajoin xs ys (singlePred joinConjunct)) substCont = tuplify scopeNames (x, xs) (y, ys) return (S joinGen, substCont) QualsCL (q :* _) -> do (qs', substCont) <- childT QualsTail thetajoinQualsT pure (q :* qs', substCont) _ -> fail "no match" thetajoinR :: [Expr] -> [Expr] -> TransformC CL (CL, [Expr], [Expr]) thetajoinR currentGuards testedGuards = do Comp t h _ <- promoteT idR (qs', substCont) <- childT CompQuals thetajoinQualsT pure ( inject $ Comp t (substCont h) qs' , map substCont currentGuards , map substCont testedGuards )
ulricha/dsh
src/Database/DSH/CL/Opt/ThetaJoin.hs
bsd-3-clause
2,744
0
19
828
866
460
406
50
4
----------------------------------------------------------------------------- -- | -- Module : System.Taffybar.Widget.XDGMenu.MenuWidget -- Copyright : 2017 Ulf Jasper -- License : BSD3-style (see LICENSE) -- -- Maintainer : Ulf Jasper <ulf.jasper@web.de> -- Stability : unstable -- Portability : unportable -- -- MenuWidget provides a hierachical GTK menu containing all -- applicable desktop entries found on the system. The menu is built -- according to the version 1.1 of the XDG "Desktop Menu -- Specification", see -- https://specifications.freedesktop.org/menu-spec/menu-spec-1.1.html ----------------------------------------------------------------------------- module System.Taffybar.Widget.XDGMenu.MenuWidget ( -- * Usage -- $usage menuWidgetNew ) where import Control.Monad import Control.Monad.IO.Class import qualified Data.Text as T import GI.Gtk hiding (Menu, imageMenuItemNew) import System.Log.Logger import System.Process import System.Taffybar.Widget.Generic.AutoSizeImage import System.Taffybar.Widget.Util import System.Taffybar.Widget.XDGMenu.Menu -- $usage -- -- In order to use this widget add the following line to your -- @taffybar.hs@ file: -- -- > import System.Taffybar.Widget.XDGMenu.MenuWidget -- > main = do -- > let menu = menuWidgetNew $ Just "PREFIX-" -- -- The menu will look for a file named "PREFIX-applications.menu" in the -- (subdirectory "menus" of the) directories specified by the environment -- variables XDG_CONFIG_HOME and XDG_CONFIG_DIRS. (If XDG_CONFIG_HOME is not set -- or empty then $HOME/.config is used, if XDG_CONFIG_DIRS is not set or empty -- then "/etc/xdg" is used). If no prefix is given (i.e. if you pass Nothing) -- then the value of the environment variable XDG_MENU_PREFIX is used, if it is -- set. If taffybar is running inside a desktop environment like Mate, Gnome, -- XFCE etc. the environment variables XDG_CONFIG_DIRS and XDG_MENU_PREFIX -- should be set and you may create the menu like this: -- -- > let menu = menuWidgetNew Nothing -- -- Now you can use @menu@ as any other Taffybar widget. logHere :: Priority -> String -> IO () logHere = logM "System.Taffybar.Widget.XDGMenu.MenuWidget" -- | Add a desktop entry to a gtk menu by appending a gtk menu item. addItem :: (IsMenuShell msc) => msc -- ^ GTK menu -> MenuEntry -- ^ Desktop entry -> IO () addItem ms de = do item <- imageMenuItemNew (feName de) (getImageForMaybeIconName (feIcon de)) setWidgetTooltipText item (feComment de) menuShellAppend ms item _ <- onMenuItemActivate item $ do let cmd = feCommand de logHere DEBUG $ "Launching '" ++ cmd ++ "'" _ <- spawnCommand cmd return () return () -- | Add an xdg menu to a gtk menu by appending gtk menu items and submenus. addMenu :: (IsMenuShell msc) => msc -- ^ A GTK menu -> Menu -- ^ A menu object -> IO () addMenu ms fm = do let subMenus = fmSubmenus fm items = fmEntries fm when (not (null items) || not (null subMenus)) $ do item <- imageMenuItemNew (T.pack $ fmName fm) (getImageForMaybeIconName (T.pack <$> fmIcon fm)) menuShellAppend ms item subMenu <- menuNew menuItemSetSubmenu item (Just subMenu) mapM_ (addMenu subMenu) subMenus mapM_ (addItem subMenu) items -- | Create a new XDG Menu Widget. menuWidgetNew :: MonadIO m => Maybe String -- ^ menu name, must end with a dash, e.g. "mate-" or "gnome-" -> m GI.Gtk.Widget menuWidgetNew mMenuPrefix = liftIO $ do mb <- menuBarNew m <- buildMenu mMenuPrefix addMenu mb m widgetShowAll mb toWidget mb
teleshoes/taffybar
src/System/Taffybar/Widget/XDGMenu/MenuWidget.hs
bsd-3-clause
3,677
0
16
753
580
309
271
54
1
-- Copyright (c) 2014-present, Facebook, Inc. -- All rights reserved. -- -- This source code is distributed under the terms of a BSD license, -- found in the LICENSE file. {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE RecordWildCards #-} module MockTAO ( Id(..), initGlobalState, assocRangeId2s, friendsAssoc, friendsOf, ) where import Data.Hashable import Data.Map (Map) import Data.Typeable import Prelude () import qualified Data.Map as Map import qualified Data.Text as Text import Haxl.Prelude import Haxl.Core import TestTypes -- ----------------------------------------------------------------------------- -- Minimal mock TAO data TAOReq a where AssocRangeId2s :: Id -> Id -> TAOReq [Id] deriving Typeable deriving instance Show (TAOReq a) deriving instance Eq (TAOReq a) instance ShowP TAOReq where showp = show instance Hashable (TAOReq a) where hashWithSalt s (AssocRangeId2s a b) = hashWithSalt s (a,b) instance StateKey TAOReq where data State TAOReq = TAOState { future :: Bool } instance DataSourceName TAOReq where dataSourceName _ = "MockTAO" instance DataSource UserEnv TAOReq where fetch TAOState{..} _flags _user | future = FutureFetch $ return . mapM_ doFetch | otherwise = SyncFetch $ mapM_ doFetch initGlobalState :: Bool -> IO (State TAOReq) initGlobalState future = return TAOState { future=future } doFetch :: BlockedFetch TAOReq -> IO () doFetch (BlockedFetch req@(AssocRangeId2s a b) r) = case Map.lookup (a, b) assocs of Nothing -> putFailure r . NotFound . Text.pack $ show req Just result -> putSuccess r result assocs :: Map (Id,Id) [Id] assocs = Map.fromList [ ((friendsAssoc, 1), [5..10]), ((friendsAssoc, 2), [7..12]), ((friendsAssoc, 3), [10..15]), ((friendsAssoc, 4), [15..19]) ] friendsAssoc :: Id friendsAssoc = 167367433327742 assocRangeId2s :: Id -> Id -> Haxl [Id] assocRangeId2s a b = dataFetch (AssocRangeId2s a b) friendsOf :: Id -> Haxl [Id] friendsOf = assocRangeId2s friendsAssoc
simonmar/Haxl
tests/MockTAO.hs
bsd-3-clause
2,247
0
11
386
632
353
279
59
2
import Test.Tasty import Test.Tasty.Hspec import Bake.Test.GCSpec main = testSpec "Bake" gcSpec >>= defaultMain
capital-match/bake
test/bake-test.hs
bsd-3-clause
113
0
6
14
32
18
14
4
1
{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE DeriveGeneric #-} {-# OPTIONS_HADDOCK hide #-} module Graphics.Vty.Image.Internal where import Graphics.Vty.Attributes import Graphics.Text.Width import GHC.Generics import Control.DeepSeq #if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup (Semigroup(..)) #endif import qualified Data.Text.Lazy as TL -- | A display text is a Data.Text.Lazy type DisplayText = TL.Text clipText :: DisplayText -> Int -> Int -> DisplayText clipText txt leftSkip rightClip = -- CPS would clarify this I think let (toDrop,padPrefix) = clipForCharWidth leftSkip txt 0 txt' = if padPrefix then TL.cons '…' (TL.drop (toDrop+1) txt) else TL.drop toDrop txt (toTake,padSuffix) = clipForCharWidth rightClip txt' 0 txt'' = TL.append (TL.take toTake txt') (if padSuffix then TL.singleton '…' else TL.empty) -- Note: some characters and zero-width and combining characters -- combine to the left, so keep taking characters even if the -- width is zero. clipForCharWidth w t n | TL.null t = (n, False) | w < cw = (n, w /= 0) | otherwise = clipForCharWidth (w - cw) (TL.tail t) (n + 1) where cw = safeWcwidth (TL.head t) in txt'' -- | This is the internal representation of Images. Use the constructors -- in "Graphics.Vty.Image" to create instances. -- -- Images are: -- -- * a horizontal span of text -- -- * a horizontal or vertical join of two images -- -- * a two dimensional fill of the 'Picture's background character -- -- * a cropped image -- -- * an empty image of no size or content. data Image = -- | A horizontal text span has a row height of 1. HorizText { attr :: Attr -- | The text to display. The display width of the text is always -- outputWidth. , displayText :: DisplayText -- | The number of display columns for the text. , outputWidth :: Int -- | the number of characters in the text. , charWidth :: Int } -- | A horizontal join can be constructed between any two images. -- However a HorizJoin instance is required to be between two images -- of equal height. The horizJoin constructor adds background fills -- to the provided images that assure this is true for the HorizJoin -- value produced. | HorizJoin { partLeft :: Image , partRight :: Image , outputWidth :: Int -- ^ imageWidth partLeft == imageWidth partRight. Always > 0 , outputHeight :: Int -- ^ imageHeight partLeft == imageHeight partRight. Always > 0 } -- | A veritical join can be constructed between any two images. -- However a VertJoin instance is required to be between two images -- of equal width. The vertJoin constructor adds background fills -- to the provides images that assure this is true for the VertJoin -- value produced. | VertJoin { partTop :: Image , partBottom :: Image , outputWidth :: Int -- ^ imageWidth partTop == imageWidth partBottom. always > 0 , outputHeight :: Int -- ^ imageHeight partTop == imageHeight partBottom. always > 1 } -- | A background fill will be filled with the background char. The -- background char is defined as a property of the Picture this -- Image is used to form. | BGFill { outputWidth :: Int -- ^ always > 0 , outputHeight :: Int -- ^ always > 0 } -- | Crop an image horizontally to a size by reducing the size from -- the right. | CropRight { croppedImage :: Image -- | Always < imageWidth croppedImage > 0 , outputWidth :: Int , outputHeight :: Int -- ^ imageHeight croppedImage } -- | Crop an image horizontally to a size by reducing the size from -- the left. | CropLeft { croppedImage :: Image -- | Always < imageWidth croppedImage > 0 , leftSkip :: Int -- | Always < imageWidth croppedImage > 0 , outputWidth :: Int , outputHeight :: Int } -- | Crop an image vertically to a size by reducing the size from -- the bottom | CropBottom { croppedImage :: Image -- | imageWidth croppedImage , outputWidth :: Int -- | height image is cropped to. Always < imageHeight croppedImage > 0 , outputHeight :: Int } -- | Crop an image vertically to a size by reducing the size from -- the top | CropTop { croppedImage :: Image -- | Always < imageHeight croppedImage > 0 , topSkip :: Int -- | imageWidth croppedImage , outputWidth :: Int -- | Always < imageHeight croppedImage > 0 , outputHeight :: Int } -- | The empty image -- -- The combining operators identity constant. -- EmptyImage <|> a = a -- EmptyImage <-> a = a -- -- Any image of zero size equals the empty image. | EmptyImage deriving (Eq, Generic, Show, Read) -- | pretty print just the structure of an image. ppImageStructure :: Image -> String ppImageStructure = go 0 where go indent img = tab indent ++ pp indent img tab indent = concat $ replicate indent " " pp _ (HorizText {outputWidth}) = "HorizText(" ++ show outputWidth ++ ")" pp _ (BGFill {outputWidth, outputHeight}) = "BGFill(" ++ show outputWidth ++ "," ++ show outputHeight ++ ")" pp i (HorizJoin {partLeft = l, partRight = r, outputWidth = c}) = "HorizJoin(" ++ show c ++ ")\n" ++ go (i+1) l ++ "\n" ++ go (i+1) r pp i (VertJoin {partTop = t, partBottom = b, outputWidth = c, outputHeight = r}) = "VertJoin(" ++ show c ++ ", " ++ show r ++ ")\n" ++ go (i+1) t ++ "\n" ++ go (i+1) b pp i (CropRight {croppedImage, outputWidth, outputHeight}) = "CropRight(" ++ show outputWidth ++ "," ++ show outputHeight ++ ")\n" ++ go (i+1) croppedImage pp i (CropLeft {croppedImage, leftSkip, outputWidth, outputHeight}) = "CropLeft(" ++ show leftSkip ++ "->" ++ show outputWidth ++ "," ++ show outputHeight ++ ")\n" ++ go (i+1) croppedImage pp i (CropBottom {croppedImage, outputWidth, outputHeight}) = "CropBottom(" ++ show outputWidth ++ "," ++ show outputHeight ++ ")\n" ++ go (i+1) croppedImage pp i (CropTop {croppedImage, topSkip, outputWidth, outputHeight}) = "CropTop("++ show outputWidth ++ "," ++ show topSkip ++ "->" ++ show outputHeight ++ ")\n" ++ go (i+1) croppedImage pp _ EmptyImage = "EmptyImage" instance NFData Image where rnf EmptyImage = () rnf (CropRight i w h) = i `deepseq` w `seq` h `seq` () rnf (CropLeft i s w h) = i `deepseq` s `seq` w `seq` h `seq` () rnf (CropBottom i w h) = i `deepseq` w `seq` h `seq` () rnf (CropTop i s w h) = i `deepseq` s `seq` w `seq` h `seq` () rnf (BGFill w h) = w `seq` h `seq` () rnf (VertJoin t b w h) = t `deepseq` b `deepseq` w `seq` h `seq` () rnf (HorizJoin l r w h) = l `deepseq` r `deepseq` w `seq` h `seq` () rnf (HorizText a s w cw) = a `seq` s `deepseq` w `seq` cw `seq` () -- | The width of an Image. This is the number display columns the image -- will occupy. imageWidth :: Image -> Int imageWidth HorizText { outputWidth = w } = w imageWidth HorizJoin { outputWidth = w } = w imageWidth VertJoin { outputWidth = w } = w imageWidth BGFill { outputWidth = w } = w imageWidth CropRight { outputWidth = w } = w imageWidth CropLeft { outputWidth = w } = w imageWidth CropBottom { outputWidth = w } = w imageWidth CropTop { outputWidth = w } = w imageWidth EmptyImage = 0 -- | The height of an Image. This is the number of display rows the -- image will occupy. imageHeight :: Image -> Int imageHeight HorizText {} = 1 imageHeight HorizJoin { outputHeight = h } = h imageHeight VertJoin { outputHeight = h } = h imageHeight BGFill { outputHeight = h } = h imageHeight CropRight { outputHeight = h } = h imageHeight CropLeft { outputHeight = h } = h imageHeight CropBottom { outputHeight = h } = h imageHeight CropTop { outputHeight = h } = h imageHeight EmptyImage = 0 -- | Append in the 'Semigroup' instance is equivalent to '<->'. instance Semigroup Image where (<>) = vertJoin -- | Append in the 'Monoid' instance is equivalent to '<->'. instance Monoid Image where mempty = EmptyImage #if !(MIN_VERSION_base(4,11,0)) mappend = (<>) #endif -- | combines two images side by side -- -- Combines text chunks where possible. Assures outputWidth and -- outputHeight properties are not violated. -- -- The result image will have a width equal to the sum of the two images -- width. And the height will equal the largest height of the two -- images. The area not defined in one image due to a height missmatch -- will be filled with the background pattern. horizJoin :: Image -> Image -> Image horizJoin EmptyImage i = i horizJoin i EmptyImage = i horizJoin i0@(HorizText a0 t0 w0 cw0) i1@(HorizText a1 t1 w1 cw1) | a0 == a1 = HorizText a0 (TL.append t0 t1) (w0 + w1) (cw0 + cw1) -- assumes horiz text height is always 1 | otherwise = HorizJoin i0 i1 (w0 + w1) 1 horizJoin i0 i1 -- If the images are of the same height then no padding is required | h0 == h1 = HorizJoin i0 i1 w h0 -- otherwise one of the images needs to be padded to the right size. | h0 < h1 -- Pad i0 = let padAmount = h1 - h0 in HorizJoin (VertJoin i0 (BGFill w0 padAmount) w0 h1) i1 w h1 | h0 > h1 -- Pad i1 = let padAmount = h0 - h1 in HorizJoin i0 (VertJoin i1 (BGFill w1 padAmount) w1 h0) w h0 where w0 = imageWidth i0 w1 = imageWidth i1 w = w0 + w1 h0 = imageHeight i0 h1 = imageHeight i1 horizJoin _ _ = error "horizJoin applied to undefined values." -- | combines two images vertically -- -- The result image will have a height equal to the sum of the heights -- of both images. The width will equal the largest width of the two -- images. The area not defined in one image due to a width missmatch -- will be filled with the background pattern. vertJoin :: Image -> Image -> Image vertJoin EmptyImage i = i vertJoin i EmptyImage = i vertJoin i0 i1 -- If the images are of the same width then no background padding is -- required | w0 == w1 = VertJoin i0 i1 w0 h -- Otherwise one of the images needs to be padded to the size of the -- other image. | w0 < w1 = let padAmount = w1 - w0 in VertJoin (HorizJoin i0 (BGFill padAmount h0) w1 h0) i1 w1 h | w0 > w1 = let padAmount = w0 - w1 in VertJoin i0 (HorizJoin i1 (BGFill padAmount h1) w0 h1) w0 h where w0 = imageWidth i0 w1 = imageWidth i1 h0 = imageHeight i0 h1 = imageHeight i1 h = h0 + h1 vertJoin _ _ = error "vertJoin applied to undefined values."
jtdaugherty/vty
src/Graphics/Vty/Image/Internal.hs
bsd-3-clause
11,015
0
14
3,029
2,529
1,402
1,127
161
9
{-# LANGUAGE PatternSignatures, FlexibleContexts #-} module Main where import Foreign.Salsa import Bindings import Control.Monad import Data.Array import Data.Maybe loadXaml :: Coercible (Obj Object_) a => String -> IO a loadXaml xamlPath = do uri <- new _Uri (xamlPath, _UriKind # _relative_) streamInfo <- _Application # _getRemoteStream (uri) xamlReader <- new _XamlReader () stream <- get streamInfo _Stream get streamInfo _Stream >>= \s -> xamlReader # _loadAsync s >>= cast -- | @'neighbors' states cell@ is the number of alive cells adjacent to @cell@ in @states@. neighbors :: Array (Int,Int) Bool -> (Int,Int) -> Int neighbors states (row,col) = length $ filter (== True) [ states ! cell | cell <- neighborCells ] where neighborCells = [ wrap (r,c) | r <- [row-1..row+1], c <- [col-1..col+1], wrap (r,c) /= (row,col) ] wrap (r,c) = (r `mod` (maxRow+1), c `mod` (maxCol+1)) (_, (maxRow,maxCol)) = bounds states step :: Array (Int,Int) (Obj ToggleButton_) -> IO () step buttons = do buttonStates <- mapM (\b -> get b _IsChecked) (elems buttons) let states = listArray (bounds buttons) (map fromJust buttonStates) sequence_ $ do cell <- indices states let state' = case neighbors states cell of 2 -> Nothing -- unchanged 3 -> Just True -- comes to life otherwise -> Just False -- dies case state' of Nothing -> mzero otherwise -> return $ set (buttons ! cell) [ _IsChecked :== state' ] main :: IO () main = withCLR $ do win :: Obj Window_ <- loadXaml "/Conway.xaml" -- Build an array of toggle buttons in 'grid' grid :: Obj UniformGrid_ <- win # _findName ("grid") >>= cast let (rows,cols) = (12,20) set grid [_Columns :== fromIntegral cols] buttonList <- sequence $ replicate (rows * cols) $ do b <- new _ToggleButton () get grid _Children >>=# _add (b) return b let buttons = listArray ((0,0),(rows-1,cols-1)) buttonList timer <- new _DispatcherTimer () set timer [_Tick :+> delegate _EventHandler (\_ _ -> step buttons), _Interval :=> _TimeSpan # _fromSeconds (0.1::Double)] runButton :: Obj ToggleButton_ <- win # _findName ("runButton") >>= cast set runButton [_Click :+> delegate _RoutedEventHandler (\_ _ -> do Just run <- get runButton _IsChecked if run then timer # _start () else timer # _stop ())] clearButton :: Obj Button_ <- win # _findName ("clearButton") >>= cast set clearButton [_Click :+> delegate _RoutedEventHandler (\_ _ -> mapM_ (flip set [ _IsChecked :== Just False ]) (elems buttons))] exitButton :: Obj Button_ <- win # _findName ("exitButton") >>= cast set exitButton [_Click :+> delegate _RoutedEventHandler (\_ _ -> win # _close_)] app <- new _Application () app # _run (win) return () -- vim:set sw=4 ts=4 expandtab:
unfoldr/Salsa
Samples/Conway/Conway.hs
bsd-3-clause
3,146
0
19
928
1,146
574
572
62
4
-- | This module provides an API for turning "markup" values into -- widgets. This module uses the Data.Text.Markup interface in this -- package to assign attributes to substrings in a text string; to -- manipulate markup using (for example) syntax highlighters, see that -- module. module Brick.Markup ( Markup , markup , (@?) , GetAttr(..) ) where import Control.Lens ((.~), (&), (^.)) import Control.Monad (forM) import qualified Data.Text as T import Data.Text.Markup import Data.Default (def) import Graphics.Vty (Attr, horizCat, string) import Brick.Widgets.Core import Brick.AttrMap -- | A type class for types that provide access to an attribute in the -- rendering monad. You probably won't need to instance this. class GetAttr a where -- | Where to get the attribute for this attribute metadata. getAttr :: a -> RenderM Attr instance GetAttr Attr where getAttr a = do c <- getContext return $ mergeWithDefault a (c^.ctxAttrMapL) instance GetAttr AttrName where getAttr = lookupAttrName -- | Build a piece of markup from text with an assigned attribute name. -- When the markup is rendered, the attribute name will be looked up in -- the rendering context's 'AttrMap' to determine the attribute to use -- for this piece of text. (@?) :: T.Text -> AttrName -> Markup AttrName (@?) = (@@) -- | Build a widget from markup. markup :: (Eq a, GetAttr a) => Markup a -> Widget markup m = Widget Fixed Fixed $ do let pairs = markupToList m imgs <- forM pairs $ \(t, aSrc) -> do a <- getAttr aSrc return $ string a $ T.unpack t return $ def & imageL .~ horizCat imgs
FranklinChen/brick
src/Brick/Markup.hs
bsd-3-clause
1,660
0
15
362
355
201
154
31
1