code
stringlengths
2
1.05M
repo_name
stringlengths
5
101
path
stringlengths
4
991
language
stringclasses
3 values
license
stringclasses
5 values
size
int64
2
1.05M
module Arp (doArp, main) where import Control.Concurrent import qualified Data.Map as Map import Data.ByteString.Lazy (ByteString) import Data.Word import Frenetic.NetCore import Frenetic.NetworkFrames (arpReply) import MacLearning (learningSwitch) import System.Log.Logger type IpMap = Map.Map IPAddress EthernetAddress -- See RFC 826 for ARP specification -- Note that the OpenFlow spec uses the Nw* fields for both IP packets and ARP -- packets, which is how nwProto matches the ARP query/reply field. -- Ethertype for ARP packets isArp = DlTyp 0x0806 -- Numbers from ARP protocol isQuery = isArp <&&> NwProto 1 isReply = isArp <&&> NwProto 2 known ips = prOr . map (\ip -> NwDst (IPAddressPrefix ip 32)) $ Map.keys ips -- |Maybe produce a reply packet from an ARP request. -- Try to look up the IP address in the lookup table. If there's an associated -- MAC address, build an ARP reply packet, otherwise return Nothing. It's -- possible that we get a malformed packet that doesn't have one or more of the -- IP src or dst fields, in which case also return Nothing. handleQuery :: LocPacket -> IpMap -> Maybe (Loc, ByteString) handleQuery (Loc switch port, Packet {..}) ips = case pktNwDst of Nothing -> Nothing Just toIp -> case Map.lookup toIp ips of Nothing -> Nothing Just toMac -> case pktNwSrc of Nothing -> Nothing Just fromIp -> Just (Loc switch port, arpReply toMac (ipAddressToWord32 toIp) pktDlSrc (ipAddressToWord32 fromIp)) -- |Maybe produce a new IP address map from an ARP reply. -- Try to parse the packet, and if you can, and it's a new mapping, return the -- new map. Otherwise, return Nothing to signal that we didn't learn something -- new so it's not necessary to update the policy. handleReply :: LocPacket -> IpMap -> Maybe IpMap handleReply (Loc switch _, packet) ips = let fromMac = pktDlSrc packet in case pktNwSrc packet of Nothing -> Nothing Just fromIp -> -- If we already know about the MAC address of the reply, do nothing. if Map.member fromIp ips then Nothing -- Otherwise, update the IP address map else Just (Map.insert fromIp fromMac ips) -- |Use the controller as an ARP cache with an underlying routing policy. -- This is parameterized on a channel that yields policies that provide basic -- host-to-host connectivity. The simplest implementation simplhy floods -- packets, but more sophisticated options might include a learning switch, or a -- topology-based shortest path approach. doArp :: Chan Policy -> IO (Chan Policy) doArp routeChan = do (queryChan, queryAction) <- getPkts (replyChan, replyAction) <- getPkts dataChan <- select queryChan replyChan allChan <- select routeChan dataChan packetOutChan <- newChan policyOutChan <- newChan -- The overall architecture of the loop: -- * allChan aggregates everything that may cause us to update. It's either -- ** A new routing policy for the underlying connectivity, -- ** An ARP query packet, or -- ** An ARP reply packet. -- -- During the loop, we need to track two pieces of data: -- * The current underlying connectivity policy, which may be Nothing if we -- haven't learned one yet, and -- * A map from IP addresses to MAC addresses, which stores the ARP lookups -- which we already know about. -- -- Ultimately, we need to generate a new routing and packet query policy that -- routes the ARP packets we're not going to handle, plus installs the packet -- receiving actions to query the packets we want to either reply to or learn -- from. let buildPolicy route ips = route' <+> query <+> reply <+> SendPackets packetOutChan where -- First, we define whether we can reply to a particular packet as -- whether it is an ARP query (thus, it wants a reply) for an IP address -- which we've already learned the MAC address for. canReply = isQuery <&&> known ips -- We want to provide connectivity for all packets except the ones we're -- going to reply to directly. We want to drop those because we're -- going to handle them, so there's no use in them reaching other hosts. route' = route <%> Not canReply -- The corollary to this is that we need to query all the packets that -- we can reply to so that the controller can send an ARP packet their -- way. query = canReply ==> queryAction -- We also want to spy on (but not impede forwarding of) ARP reply -- packets so that we can learn the sender's IP and MAC addresses, -- letting us reply from the controller next time. reply = isReply <&&> Not (known ips) ==> replyAction let loop mRoute ips = do update <- readChan allChan case update of Left route -> do -- If we get a new connectivity policy in, we recompile our overall -- policy, send that out, and recurse on the new route. infoM "ARP" "Got new routing policy for ARP" writeChan policyOutChan (buildPolicy route ips) loop (Just route) ips Right arpData -> case mRoute of -- If we don't have a routing policy yet, we're not even providing -- connectivity, so it's probably a spurious packet and we can just -- ignore it. Nothing -> loop Nothing ips Just route -> case arpData of Left query -> -- If we get an ARP query, try to form a response to it. If -- we can, send the packet out, otherwise do nothing. Either -- way, recurse. case handleQuery query ips of Nothing -> loop mRoute ips Just packet -> do infoM "ARP" $ "Sending ARP reply: " ++ show packet writeChan packetOutChan packet loop mRoute ips Right reply -> -- If we get an ARP reply, try to learn from it. If we -- learned a new mapping, update the routing and query policy -- to reflect the fact that we're going to handle these -- packets in the future and recurse on the new mapping. -- Otherwise, just recurse. case handleReply reply ips of Nothing -> loop mRoute ips Just ips' -> do infoM "ARP" $ "Learned ARP route from " ++ show reply writeChan policyOutChan (buildPolicy route ips') loop mRoute ips' forkIO (loop Nothing Map.empty) return policyOutChan -- |Runs ARP on top of a learning switch to gradually learn both routes and the -- ARP table. Provides both regular connectivity and synthetic ARP replies. main addr = do lsChan <- learningSwitch policyChan <- doArp lsChan dynController addr policyChan
frenetic-lang/netcore-1.0
examples/Arp.hs
Haskell
bsd-3-clause
7,162
{-# LANGUAGE GADTs, DataKinds, TypeFamilies #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell#-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module QueryAlgebras where import Types import Control.Error import Control.Monad.Free import Data.Singletons.TH data VFCrudable = UserCrud | MediaCrud | VfileCrud | MediaVfileCrud | CommentCrud CommentType deriving (Show) genSingletons [ ''VFCrudable ] type family NewData (c :: VFCrudable) :: * where NewData 'UserCrud = UserNew NewData 'MediaCrud = MediaNew NewData 'VfileCrud = VfileNew NewData 'MediaVfileCrud = MediaVfileNew NewData ('CommentCrud ct) = CommentNew ct type family BaseData (c :: VFCrudable) :: * where BaseData 'UserCrud = UserBase BaseData 'MediaCrud = MediaBase 'DB BaseData 'VfileCrud = VfileBase 'DB BaseData 'MediaVfileCrud = MediaVfileBase 'DB BaseData ('CommentCrud ct) = CommentBase ct 'DB type family ReadData (c :: VFCrudable) :: * where ReadData 'UserCrud = UserId ReadData 'MediaCrud = MediaId ReadData 'VfileCrud = VfileId ReadData 'MediaVfileCrud = MVFIdentifier ReadData ('CommentCrud ct) = CommentIdentifier ct -------------------------------------------------------------------------------- -- | Basic PG-CRUD operations -------------------------------------------------------------------------------- data PGCrudF next :: * where CreatePG :: Sing (c :: VFCrudable) -> NewData c -> (Either VfilesError (BaseData c) -> next) -> PGCrudF next ReadPG :: Sing (c :: VFCrudable) -> ReadData c -> (Either VfilesError (BaseData c) -> next) -> PGCrudF next UpdatePG :: Sing (c :: VFCrudable) -> BaseData c -> (Either VfilesError () -> next) -> PGCrudF next DeletePG :: Sing (c :: VFCrudable) -> ReadData c -> (Either VfilesError () -> next) -> PGCrudF next instance Functor PGCrudF where fmap f (CreatePG c n next) = CreatePG c n $ f . next fmap f (ReadPG c i next) = ReadPG c i $ f . next fmap f (UpdatePG c b next) = UpdatePG c b $ f . next fmap f (DeletePG c i next) = DeletePG c i $ f . next type PGCrud = ExceptT VfilesError (Free PGCrudF) -------------------------------------------------------------------------------- -- | Smart PG-CRUD Constructors -------------------------------------------------------------------------------- createPG :: Sing (c :: VFCrudable) -> NewData c -> PGCrud (BaseData c) createPG c n = ExceptT . Free $ CreatePG c n Pure readPG :: Sing (c :: VFCrudable) -> ReadData c -> PGCrud (BaseData c) readPG c n = ExceptT . Free $ ReadPG c n Pure updatePG :: Sing (c :: VFCrudable) -> BaseData c -> PGCrud () updatePG c n = ExceptT . Free $ UpdatePG c n Pure deletePG :: Sing (c :: VFCrudable) -> ReadData c -> PGCrud () deletePG c n = ExceptT . Free $ DeletePG c n Pure -------------------------------------------------------------------------------- -- | PG-CRUD Permissions -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- | Basic Neo-CRUD operations -------------------------------------------------------------------------------- data NeoCrudF next :: * where CreateNeo :: Sing (c :: VFCrudable) -> BaseData c -> (Either VfilesError () -> next) -> NeoCrudF next UpdateNeo :: Sing (c :: VFCrudable) -> BaseData c -> (Either VfilesError () -> next) -> NeoCrudF next DeleteNeo :: Sing (c :: VFCrudable) -> ReadData c -> (Either VfilesError () -> next) -> NeoCrudF next instance Functor NeoCrudF where fmap f (CreateNeo c n next) = CreateNeo c n $ f . next fmap f (UpdateNeo c b next) = UpdateNeo c b $ f . next fmap f (DeleteNeo c i next) = DeleteNeo c i $ f . next type NeoCrud = ExceptT VfilesError (Free NeoCrudF) -------------------------------------------------------------------------------- -- | Smart Neo-CRUD Constructors -------------------------------------------------------------------------------- createNeo :: Sing (c :: VFCrudable) -> BaseData c -> NeoCrud () createNeo c n = ExceptT . Free $ CreateNeo c n Pure updateNeo :: Sing (c :: VFCrudable) -> BaseData c -> NeoCrud () updateNeo c n = ExceptT . Free $ UpdateNeo c n Pure deleteNeo :: Sing (c :: VFCrudable) -> ReadData c -> NeoCrud () deleteNeo c n = ExceptT . Free $ DeleteNeo c n Pure -------------------------------------------------------------------------------- -- | Composite Query Algebra -------------------------------------------------------------------------------- data VFCrudF a = InPGCrud (PGCrudF a) | InNeoCrud (NeoCrudF a) instance Functor VFCrudF where fmap f (InPGCrud a) = InPGCrud (fmap f a) fmap f (InNeoCrud a) = InNeoCrud (fmap f a) type VFCrud = ExceptT VfilesError (Free VFCrudF) class Monad m => MonadPGCrud m where liftPG :: forall a. PGCrud a -> m a instance MonadPGCrud VFCrud where liftPG = mapExceptT $ hoistFree InPGCrud class Monad m => MonadNeoCrud m where liftNeo :: forall a. NeoCrud a -> m a instance MonadNeoCrud VFCrud where liftNeo = mapExceptT $ hoistFree InNeoCrud
martyall/freeapi
src/QueryAlgebras.hs
Haskell
bsd-3-clause
5,384
-- The @FamInst@ type: family instance heads {-# LANGUAGE CPP, GADTs #-} module FamInst ( FamInstEnvs, tcGetFamInstEnvs, checkFamInstConsistency, tcExtendLocalFamInstEnv, tcLookupFamInst, tcLookupDataFamInst, tcLookupDataFamInst_maybe, tcInstNewTyCon_maybe, tcTopNormaliseNewTypeTF_maybe, newFamInst ) where import HscTypes import FamInstEnv import InstEnv( roughMatchTcs ) import Coercion hiding ( substTy ) import TcEvidence import LoadIface import TcRnMonad import TyCon import CoAxiom import DynFlags import Module import Outputable import UniqFM import FastString import Util import RdrName import DataCon ( dataConName ) import Maybes import TcMType import TcType import Name import Control.Monad import Data.Map (Map) import qualified Data.Map as Map import Control.Arrow ( first, second ) #include "HsVersions.h" {- ************************************************************************ * * Making a FamInst * * ************************************************************************ -} -- All type variables in a FamInst must be fresh. This function -- creates the fresh variables and applies the necessary substitution -- It is defined here to avoid a dependency from FamInstEnv on the monad -- code. newFamInst :: FamFlavor -> CoAxiom Unbranched -> TcRnIf gbl lcl FamInst -- Freshen the type variables of the FamInst branches -- Called from the vectoriser monad too, hence the rather general type newFamInst flavor axiom@(CoAxiom { co_ax_branches = FirstBranch branch , co_ax_tc = fam_tc }) | CoAxBranch { cab_tvs = tvs , cab_lhs = lhs , cab_rhs = rhs } <- branch = do { (subst, tvs') <- freshenTyVarBndrs tvs ; return (FamInst { fi_fam = tyConName fam_tc , fi_flavor = flavor , fi_tcs = roughMatchTcs lhs , fi_tvs = tvs' , fi_tys = substTys subst lhs , fi_rhs = substTy subst rhs , fi_axiom = axiom }) } {- ************************************************************************ * * Optimised overlap checking for family instances * * ************************************************************************ For any two family instance modules that we import directly or indirectly, we check whether the instances in the two modules are consistent, *unless* we can be certain that the instances of the two modules have already been checked for consistency during the compilation of modules that we import. Why do we need to check? Consider module X1 where module X2 where data T1 data T2 type instance F T1 b = Int type instance F a T2 = Char f1 :: F T1 a -> Int f2 :: Char -> F a T2 f1 x = x f2 x = x Now if we import both X1 and X2 we could make (f2 . f1) :: Int -> Char. Notice that neither instance is an orphan. How do we know which pairs of modules have already been checked? Any pair of modules where both modules occur in the `HscTypes.dep_finsts' set (of the `HscTypes.Dependencies') of one of our directly imported modules must have already been checked. Everything else, we check now. (So that we can be certain that the modules in our `HscTypes.dep_finsts' are consistent.) -} -- The optimisation of overlap tests is based on determining pairs of modules -- whose family instances need to be checked for consistency. -- data ModulePair = ModulePair Module Module -- canonical order of the components of a module pair -- canon :: ModulePair -> (Module, Module) canon (ModulePair m1 m2) | m1 < m2 = (m1, m2) | otherwise = (m2, m1) instance Eq ModulePair where mp1 == mp2 = canon mp1 == canon mp2 instance Ord ModulePair where mp1 `compare` mp2 = canon mp1 `compare` canon mp2 instance Outputable ModulePair where ppr (ModulePair m1 m2) = angleBrackets (ppr m1 <> comma <+> ppr m2) -- Sets of module pairs -- type ModulePairSet = Map ModulePair () listToSet :: [ModulePair] -> ModulePairSet listToSet l = Map.fromList (zip l (repeat ())) checkFamInstConsistency :: [Module] -> [Module] -> TcM () checkFamInstConsistency famInstMods directlyImpMods = do { dflags <- getDynFlags ; (eps, hpt) <- getEpsAndHpt ; let { -- Fetch the iface of a given module. Must succeed as -- all directly imported modules must already have been loaded. modIface mod = case lookupIfaceByModule dflags hpt (eps_PIT eps) mod of Nothing -> panic "FamInst.checkFamInstConsistency" Just iface -> iface ; hmiModule = mi_module . hm_iface ; hmiFamInstEnv = extendFamInstEnvList emptyFamInstEnv . md_fam_insts . hm_details ; hpt_fam_insts = mkModuleEnv [ (hmiModule hmi, hmiFamInstEnv hmi) | hmi <- eltsUFM hpt] ; groups = map (dep_finsts . mi_deps . modIface) directlyImpMods ; okPairs = listToSet $ concatMap allPairs groups -- instances of okPairs are consistent ; criticalPairs = listToSet $ allPairs famInstMods -- all pairs that we need to consider ; toCheckPairs = Map.keys $ criticalPairs `Map.difference` okPairs -- the difference gives us the pairs we need to check now } ; mapM_ (check hpt_fam_insts) toCheckPairs } where allPairs [] = [] allPairs (m:ms) = map (ModulePair m) ms ++ allPairs ms check hpt_fam_insts (ModulePair m1 m2) = do { env1 <- getFamInsts hpt_fam_insts m1 ; env2 <- getFamInsts hpt_fam_insts m2 ; mapM_ (checkForConflicts (emptyFamInstEnv, env2)) (famInstEnvElts env1) } getFamInsts :: ModuleEnv FamInstEnv -> Module -> TcM FamInstEnv getFamInsts hpt_fam_insts mod | Just env <- lookupModuleEnv hpt_fam_insts mod = return env | otherwise = do { _ <- initIfaceTcRn (loadSysInterface doc mod) ; eps <- getEps ; return (expectJust "checkFamInstConsistency" $ lookupModuleEnv (eps_mod_fam_inst_env eps) mod) } where doc = ppr mod <+> ptext (sLit "is a family-instance module") {- ************************************************************************ * * Lookup * * ************************************************************************ Look up the instance tycon of a family instance. The match may be ambiguous (as we know that overlapping instances have identical right-hand sides under overlapping substitutions - see 'FamInstEnv.lookupFamInstEnvConflicts'). However, the type arguments used for matching must be equal to or be more specific than those of the family instance declaration. We pick one of the matches in case of ambiguity; as the right-hand sides are identical under the match substitution, the choice does not matter. Return the instance tycon and its type instance. For example, if we have tcLookupFamInst 'T' '[Int]' yields (':R42T', 'Int') then we have a coercion (ie, type instance of family instance coercion) :Co:R42T Int :: T [Int] ~ :R42T Int which implies that :R42T was declared as 'data instance T [a]'. -} tcLookupFamInst :: FamInstEnvs -> TyCon -> [Type] -> Maybe FamInstMatch tcLookupFamInst fam_envs tycon tys | not (isOpenFamilyTyCon tycon) = Nothing | otherwise = case lookupFamInstEnv fam_envs tycon tys of match : _ -> Just match [] -> Nothing -- | If @co :: T ts ~ rep_ty@ then: -- -- > instNewTyCon_maybe T ts = Just (rep_ty, co) -- -- Checks for a newtype, and for being saturated -- Just like Coercion.instNewTyCon_maybe, but returns a TcCoercion tcInstNewTyCon_maybe :: TyCon -> [TcType] -> Maybe (TcType, TcCoercion) tcInstNewTyCon_maybe tc tys = fmap (second TcCoercion) $ instNewTyCon_maybe tc tys -- | Like 'tcLookupDataFamInst_maybe', but returns the arguments back if -- there is no data family to unwrap. -- Returns a Representational coercion tcLookupDataFamInst :: FamInstEnvs -> TyCon -> [TcType] -> (TyCon, [TcType], Coercion) tcLookupDataFamInst fam_inst_envs tc tc_args | Just (rep_tc, rep_args, co) <- tcLookupDataFamInst_maybe fam_inst_envs tc tc_args = (rep_tc, rep_args, co) | otherwise = (tc, tc_args, mkReflCo Representational (mkTyConApp tc tc_args)) tcLookupDataFamInst_maybe :: FamInstEnvs -> TyCon -> [TcType] -> Maybe (TyCon, [TcType], Coercion) -- ^ Converts a data family type (eg F [a]) to its representation type (eg FList a) -- and returns a coercion between the two: co :: F [a] ~R FList a tcLookupDataFamInst_maybe fam_inst_envs tc tc_args | isDataFamilyTyCon tc , match : _ <- lookupFamInstEnv fam_inst_envs tc tc_args , FamInstMatch { fim_instance = rep_fam , fim_tys = rep_args } <- match , let ax = famInstAxiom rep_fam rep_tc = dataFamInstRepTyCon rep_fam co = mkUnbranchedAxInstCo Representational ax rep_args = Just (rep_tc, rep_args, co) | otherwise = Nothing -- | 'tcTopNormaliseNewTypeTF_maybe' gets rid of top-level newtypes, -- potentially looking through newtype instances. -- -- It is only used by the type inference engine (specifically, when -- soliving 'Coercible' instances), and hence it is careful to unwrap -- only if the relevant data constructor is in scope. That's why -- it get a GlobalRdrEnv argument. -- -- It is careful not to unwrap data/newtype instances if it can't -- continue unwrapping. Such care is necessary for proper error -- messages. -- -- It does not look through type families. -- It does not normalise arguments to a tycon. -- -- Always produces a representational coercion. tcTopNormaliseNewTypeTF_maybe :: FamInstEnvs -> GlobalRdrEnv -> Type -> Maybe (TcCoercion, Type) tcTopNormaliseNewTypeTF_maybe faminsts rdr_env ty -- cf. FamInstEnv.topNormaliseType_maybe and Coercion.topNormaliseNewType_maybe = fmap (first TcCoercion) $ topNormaliseTypeX_maybe stepper ty where stepper = unwrap_newtype `composeSteppers` unwrap_newtype_instance -- For newtype instances we take a double step or nothing, so that -- we don't return the reprsentation type of the newtype instance, -- which would lead to terrible error messages unwrap_newtype_instance rec_nts tc tys | Just (tc', tys', co) <- tcLookupDataFamInst_maybe faminsts tc tys = modifyStepResultCo (co `mkTransCo`) $ unwrap_newtype rec_nts tc' tys' | otherwise = NS_Done unwrap_newtype rec_nts tc tys | data_cons_in_scope tc = unwrapNewTypeStepper rec_nts tc tys | otherwise = NS_Done data_cons_in_scope :: TyCon -> Bool data_cons_in_scope tc = isWiredInName (tyConName tc) || (not (isAbstractTyCon tc) && all in_scope data_con_names) where data_con_names = map dataConName (tyConDataCons tc) in_scope dc = not $ null $ lookupGRE_Name rdr_env dc {- ************************************************************************ * * Extending the family instance environment * * ************************************************************************ -} -- Add new locally-defined family instances tcExtendLocalFamInstEnv :: [FamInst] -> TcM a -> TcM a tcExtendLocalFamInstEnv fam_insts thing_inside = do { env <- getGblEnv ; (inst_env', fam_insts') <- foldlM addLocalFamInst (tcg_fam_inst_env env, tcg_fam_insts env) fam_insts ; let env' = env { tcg_fam_insts = fam_insts' , tcg_fam_inst_env = inst_env' } ; setGblEnv env' thing_inside } -- Check that the proposed new instance is OK, -- and then add it to the home inst env -- This must be lazy in the fam_inst arguments, see Note [Lazy axiom match] -- in FamInstEnv.hs addLocalFamInst :: (FamInstEnv,[FamInst]) -> FamInst -> TcM (FamInstEnv, [FamInst]) addLocalFamInst (home_fie, my_fis) fam_inst -- home_fie includes home package and this module -- my_fies is just the ones from this module = do { traceTc "addLocalFamInst" (ppr fam_inst) ; isGHCi <- getIsGHCi ; mod <- getModule ; traceTc "alfi" (ppr mod $$ ppr isGHCi) -- In GHCi, we *override* any identical instances -- that are also defined in the interactive context -- See Note [Override identical instances in GHCi] in HscTypes ; let home_fie' | isGHCi = deleteFromFamInstEnv home_fie fam_inst | otherwise = home_fie -- Load imported instances, so that we report -- overlaps correctly ; eps <- getEps ; let inst_envs = (eps_fam_inst_env eps, home_fie') home_fie'' = extendFamInstEnv home_fie fam_inst -- Check for conflicting instance decls ; no_conflict <- checkForConflicts inst_envs fam_inst ; if no_conflict then return (home_fie'', fam_inst : my_fis) else return (home_fie, my_fis) } {- ************************************************************************ * * Checking an instance against conflicts with an instance env * * ************************************************************************ Check whether a single family instance conflicts with those in two instance environments (one for the EPS and one for the HPT). -} checkForConflicts :: FamInstEnvs -> FamInst -> TcM Bool checkForConflicts inst_envs fam_inst = do { let conflicts = lookupFamInstEnvConflicts inst_envs fam_inst no_conflicts = null conflicts ; traceTc "checkForConflicts" $ vcat [ ppr (map fim_instance conflicts) , ppr fam_inst -- , ppr inst_envs ] ; unless no_conflicts $ conflictInstErr fam_inst conflicts ; return no_conflicts } conflictInstErr :: FamInst -> [FamInstMatch] -> TcRn () conflictInstErr fam_inst conflictingMatch | (FamInstMatch { fim_instance = confInst }) : _ <- conflictingMatch = addFamInstsErr (ptext (sLit "Conflicting family instance declarations:")) [fam_inst, confInst] | otherwise = panic "conflictInstErr" addFamInstsErr :: SDoc -> [FamInst] -> TcRn () addFamInstsErr herald insts = ASSERT( not (null insts) ) setSrcSpan srcSpan $ addErr $ hang herald 2 (vcat [ pprCoAxBranchHdr (famInstAxiom fi) 0 | fi <- sorted ]) where getSpan = getSrcLoc . famInstAxiom sorted = sortWith getSpan insts fi1 = head sorted srcSpan = coAxBranchSpan (coAxiomSingleBranch (famInstAxiom fi1)) -- The sortWith just arranges that instances are dislayed in order -- of source location, which reduced wobbling in error messages, -- and is better for users tcGetFamInstEnvs :: TcM FamInstEnvs -- Gets both the external-package inst-env -- and the home-pkg inst env (includes module being compiled) tcGetFamInstEnvs = do { eps <- getEps; env <- getGblEnv ; return (eps_fam_inst_env eps, tcg_fam_inst_env env) }
urbanslug/ghc
compiler/typecheck/FamInst.hs
Haskell
bsd-3-clause
16,229
module Main(main) where import System.Environment import System.IO import CCodeGen import Lexer import Parser import Program main :: IO () main = do (fileName:rest) <- getArgs fileHandle <- openFile fileName ReadMode programText <- hGetContents fileHandle putStrLn programText let compiledProg = compile programText outFileName = cFileName fileName writeFile outFileName compiledProg hClose fileHandle putStrLn compiledProg compile :: String -> String compile = show . toCProgram . parseProgram . strToToks parsedProg = parseProgram . strToToks cFileName :: String -> String cFileName name = (takeWhile (/='.') name) ++ ".c"
dillonhuff/IntLang
src/Main.hs
Haskell
bsd-3-clause
654
{-# LANGUAGE CPP #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilyDependencies #-} module Data.Diverse.WhichSpec (main, spec) where import Data.Diverse import Data.Int import Data.Tagged import Data.Typeable import Test.Hspec data Foo data Bar data Hi data Bye -- `main` is here so that this module can be run from GHCi on its own. It is -- not needed for automatic spec discovery. main :: IO () main = hspec spec -- | Utility to convert Either to Maybe hush :: Either a b -> Maybe b hush = either (const Nothing) Just spec :: Spec spec = do describe "Which" $ do it "is a Show" $ do let x = pickN @0 5 :: Which '[Int, Bool] show x `shouldBe` "pickN @0 5" it "is a Read and Show" $ do let s1 = "pickN @0 5" x1 = read s1 :: Which '[Int, Bool] show x1 `shouldBe` s1 let s2 = "pickN @1 True" x2 = read s2 :: Which '[Int, Bool] show x2 `shouldBe` s2 -- "zilch" `shouldBe` show zilch -- "zilch" `shouldBe` show (read "zilch" :: Which '[]) it "is an Eq" $ do let y = pick (5 :: Int) :: Which '[Int, Bool] let y' = pick (5 :: Int) :: Which '[Int, Bool] y `shouldBe` y' it "is an Ord" $ do let y5 = pick (5 :: Int) :: Which '[Int, Bool] let y6 = pick (6 :: Int) :: Which '[Int, Bool] compare y5 y5 `shouldBe` EQ compare y5 y6 `shouldBe` LT compare y6 y5 `shouldBe` GT it "can be constructed by type with 'pick' and destructed with 'trial'" $ do let y = pick (5 :: Int) :: Which '[Bool, Int, Char] x = hush $ trial @Int y x `shouldBe` (Just 5) it "can be constructed by label with 'pickL' and destructed with 'trialL'" $ do let y = pickL @Foo (Tagged (5 :: Int)) :: Which '[Bool, Tagged Foo Int, Tagged Bar Char] x = hush $ trialL @Foo y x `shouldBe` (Just (Tagged 5)) it "may contain possiblities of duplicate types" $ do let y = pick (5 :: Int) :: Which '[Bool, Int, Char, Bool, Char] x = hush $ trial @Int y x `shouldBe` (Just 5) it "can be constructed conveniently with 'pick'' and destructed with 'trial0'" $ do let y = pickOnly (5 :: Int) x = hush $ trial0 y x `shouldBe` (Just 5) it "can be constructed by index with 'pickN' and destructed with 'trialN" $ do let y = pickN @4 (5 :: Int) :: Which '[Bool, Int, Char, Bool, Int, Char] x = hush $ trialN @4 y x `shouldBe` (Just 5) it "can be 'trial'led until its final 'obvious' value" $ do let a = pick @_ @'[Char, Int, Bool, String] (5 :: Int) b = pick @_ @'[Char, Int, String] (5 :: Int) c = pick @_ @'[Int, String] (5 :: Int) d = pick @_ @'[Int] (5 :: Int) trial @Int a `shouldBe` Right 5 trial @Bool a `shouldBe` Left b trial @Int b `shouldBe` Right 5 trial @Char b `shouldBe` Left c trial @Int c `shouldBe` Right 5 trial @String c `shouldBe` Left d trial @Int d `shouldBe` Right 5 -- trial @Int d `shouldNotBe` Left zilch obvious d `shouldBe` 5 it "can be 'trialN'led until its final 'obvious' value" $ do let a = pickN @2 @_ @'[Char, Bool, Int, Bool, Char, String] (5 :: Int) b = pickN @2 @_ @'[Char, Bool, Int, Char, String] (5 :: Int) c = pickN @2 @_ @'[Char, Bool, Int, String] (5 :: Int) d = pickN @1 @_ @'[Bool, Int, String] (5 :: Int) e = pickN @1 @_ @'[Bool, Int] (5 :: Int) f = pickN @0 @_ @'[Int] (5 :: Int) trial @Int a `shouldBe` Right 5 trialN @2 a `shouldBe` Right 5 trialN @3 a `shouldBe` Left b trial @Int b `shouldBe` Right 5 trialN @2 b `shouldBe` Right 5 trialN @3 b `shouldBe` Left c trial @Int c `shouldBe` Right 5 trialN @2 c `shouldBe` Right 5 trial0 c `shouldBe` Left d trialN @0 c `shouldBe` Left d trial @Int d `shouldBe` Right 5 trialN @1 d `shouldBe` Right 5 trialN @2 d `shouldBe` Left e trial @Int e `shouldBe` Right 5 trialN @1 e `shouldBe` Right 5 trialN @0 e `shouldBe` Left f trial0 e `shouldBe` Left f trial @Int f `shouldBe` Right 5 -- trial @Int f `shouldNotBe` Left zilch trial0 f `shouldBe` Right 5 obvious f `shouldBe` 5 it "can be extended and rearranged by type with 'diversify'" $ do let y = pickOnly (5 :: Int) y' = diversify @_ @[Int, Bool] y y'' = diversify @_ @[Bool, Int] y' switch y'' (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Int" it "can be extended and rearranged by type with 'diversify'" $ do let y = pickOnly (5 :: Tagged Bar Int) y' = diversifyL @'[Bar] y :: Which '[Tagged Bar Int, Tagged Foo Bool] y'' = diversifyL @'[Bar, Foo] y' :: Which '[Tagged Foo Bool, Tagged Bar Int] switch y'' (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Tagged * Bar Int" it "can be extended and rearranged by index with 'diversifyN'" $ do let y = pickOnly (5 :: Int) y' = diversifyN @'[0] @_ @[Int, Bool] y y'' = diversifyN @[1,0] @_ @[Bool, Int] y' switch y'' (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Int" it "the 'diversify'ed type can contain multiple fields if they aren't in the original 'Many'" $ do let y = pick @_ @[Int, Char] (5 :: Int) x = diversify @_ @[String, String, Char, Bool, Int] y -- Compile error: Char is a duplicate -- z = diversify @[String, String, Char, Bool, Int, Char] y x `shouldBe` pick (5 :: Int) it "the 'diversify'ed type can't use indistinct fields from the original 'Many'" $ do let y = pickN @0 @_ @[Int, Char, Int] (5 :: Int) -- duplicate Int -- Compile error: Int is a duplicate -- x = diversify @[String, String, Char, Bool, Int] y y `shouldBe` y it "can be 'reinterpret'ed by type into a totally different Which" $ do let y = pick @_ @[Int, Char] (5 :: Int) a = reinterpret @[String, Bool] y a `shouldBe` Left y let b = reinterpret @[String, Char] y b `shouldBe` Left (pick (5 :: Int)) let c = reinterpret @[String, Int] y c `shouldBe` Right (pick (5 :: Int)) it "can be 'reinterpretL'ed by label into a totally different Which" $ do let y = pick @_ @[Tagged Bar Int, Tagged Foo Bool, Tagged Hi Char, Tagged Bye Bool] (5 :: Tagged Bar Int) y' = reinterpretL @[Foo, Bar] y x = pick @_ @[Tagged Foo Bool, Tagged Bar Int] (5 :: Tagged Bar Int) y' `shouldBe` Right x it "the 'reinterpret' type can contain indistinct fields if they aren't in the original 'Many'" $ do let y = pick @_ @[Int, Char] (5 :: Int) x = reinterpret @[String, String, Char, Bool] y -- Compile error: Char is a duplicate -- z = reinterpret @[String, Char, Char, Bool] y x `shouldBe` Left (pick (5 :: Int)) it "the 'reinterpret'ed from type can't indistinct fields'" $ do let y = pickN @0 @_ @[Int, Char, Int] (5 :: Int) -- duplicate Int -- Compile error: Int is a duplicate -- x = reinterpret @[String, String, Char, Bool] y y `shouldBe` y it "the 'reinterpret' type can't use indistinct fields from the original 'Many'" $ do let y = pickN @0 @_ @[Int, Char, Int] (5 :: Int) -- duplicate Int -- Compile error: Int is a duplicate -- x = reinterpret @[String, String, Char, Bool, Int] y y `shouldBe` y it "can be 'reinterpretN'ed by index into a subset Which" $ do let y = pick @_ @[Char, String, Int, Bool] (5 :: Int) a = reinterpretN' @[2, 0] @[Int, Char] y a' = reinterpretN' @[3, 0] @[Bool, Char] y a `shouldBe` Just (pick (5 :: Int)) a' `shouldBe` Nothing it "can be 'switch'ed with 'Many' handlers in any order" $ do let y = pickN @0 (5 :: Int) :: Which '[Int, Bool, Bool, Int] switch y ( cases $ show @Bool ./ show @Int ./ nil) `shouldBe` "5" it "can be 'switch'ed with 'Many' handlers with extraneous content" $ do let y = pick (5 :: Int) :: Which '[Int, Bool] switch y ( -- contrast with lowercase 'cases' which disallows extraneous content cases' $ show @Int ./ show @Bool ./ show @Char ./ show @(Maybe Char) ./ show @(Maybe Int) ./ nil ) `shouldBe` "5" it "can be 'switchN'ed with 'Many' handlers in index order" $ do let y = pickN @0 (5 :: Int) :: Which '[Int, Bool, Bool, Int] switchN y ( casesN $ show @Int ./ show @Bool ./ show @Bool ./ show @Int ./ nil) `shouldBe` "5" it "can be switched with a polymorphic 'CaseFunc' handler" $ do let y = pick (5 :: Int) :: Which '[Int, Bool] switch y (CaseFunc @Typeable (show . typeRep . (pure @Proxy))) `shouldBe` "Int" #if __GLASGOW_HASKELL__ >= 802 let expected = "Which (': * Int (': * Bool ('[] *)))" #else let expected = "Which (': * Int (': * Bool '[]))" #endif (show . typeRep . (pure @Proxy) $ y) `shouldBe` expected -- it "is a compile error to 'trial', 'diversify', 'reinterpret from non-zilch to 'zilch'" $ do -- let a = diversify @[Int, Bool] zilch -- let a = trial @Int zilch -- let a = trialN @0 zilch -- let a = reinterpret @[Int, Bool] zilch -- let a = reinterpretN @'[0] zilch -- zilch `shouldBe` zilch it "is ok to 'reinterpret' and 'diversity' from Which '[]" $ do let x = pick @_ @'[Int] (5 :: Int) case trial @Int x of Right y -> y `shouldBe` y Left z -> do -- Which '[] can be diversified into anything -- This is safe because Which '[] is uninhabited like Data.Void -- and so like Data.Void.absurd, "if given a falsehood, anything follows" diversify @'[] @'[Int, Bool] z `shouldBe` impossible z reinterpret' @'[] z `shouldBe` Just z reinterpret @'[] z `shouldBe` Right z diversify @'[] z `shouldBe` z compare z z `shouldBe` EQ reinterpret' @'[] x `shouldBe` Nothing reinterpret @'[] x `shouldBe` Left x it "'impossible' is just like 'absurd'. Once given an impossible Which '[], anything follows" $ do let x = pick @_ @'[Int] (5 :: Int) case trial @Int x of Right y -> y `shouldBe` y Left z -> impossible z it "every possibility can be mapped into a different type in a Functor-like fashion with using 'afmap'" $ do let x = pick (5 :: Int8) :: Which '[Int, Int8, Int16] y = pick (15 :: Int8) :: Which '[Int, Int8, Int16] z = pickN @1 ("5" :: String) :: Which '[String, String, String] mx = pick (Just 5 :: Maybe Int8) :: Which '[Maybe Int, Maybe Int8, Maybe Int16] my = pick (Just 15 :: Maybe Int8) :: Which '[Maybe Int, Maybe Int8, Maybe Int16] mz = pickN @1 (Just "5" :: Maybe String) :: Which '[Maybe String, Maybe String, Maybe String] mz' = pickN @1 (Just ("5", "5") :: Maybe (String, String)) :: Which '[Maybe (String, String), Maybe (String, String), Maybe (String, String)] afmap (CaseFunc' @Num (+10)) x `shouldBe` y afmap (CaseFunc @Show @String show) x `shouldBe` z afmap (CaseFunc1' @C0 @Functor @Num (fmap (+10))) mx `shouldBe` my afmap (CaseFunc1 @C0 @Functor @Show @String (fmap show)) mx `shouldBe` mz afmap (CaseFunc1_ @C0 @Functor @C0 @(String, String) (fmap (\i -> (i, i)))) mz `shouldBe` mz'
louispan/data-diverse
test/Data/Diverse/WhichSpec.hs
Haskell
bsd-3-clause
13,143
{-# LANGUAGE MultiParamTypeClasses , DefaultSignatures , FlexibleInstances , TypeSynonymInstances , OverlappingInstances #-} -- |Used as the context for diagrams-ghci module MyPrelude () where import Prelude import Data.List (intersperse) import Data.Ratio import Diagrams.Prelude import Diagrams.Backend.Cairo import Diagrams.TwoD.Path.Turtle import Diagrams.TwoD.Text import Graphics.UI.Toy.Gtk.Prelude class GhcdiShow a where -- First parameter is animation time ghcdiShow :: a -> Double -> CairoDiagram default ghcdiShow :: Show a => a -> Double -> CairoDiagram ghcdiShow x _ = preText $ show x -- You'd better be using cairo diagrams... :) instance GhcdiShow CairoDiagram where ghcdiShow d _ = d listLike' :: String -> String -> String -> [CairoDiagram] -> CairoDiagram listLike' s m e = listLike (preText s) (preText m) (preText e) listLike :: CairoDiagram -> CairoDiagram -> CairoDiagram -> [CairoDiagram] -> CairoDiagram listLike s m e xs = centerY (scale_it s) ||| inner ||| centerY (scale_it e) where inner = hcat . intersperse (m # translateY (max_height / (-2))) $ map centerY xs max_height = maximum $ map height xs ratio = max_height / height s scale_it = scaleX (1 - (1 - ratio) / 5) . scaleY (ratio * 1.2) instance GhcdiShow a => GhcdiShow [a] where ghcdiShow xs t = listLike' "[" ", " "]" $ map (`ghcdiShow` t) xs instance (GhcdiShow a, GhcdiShow b) => GhcdiShow (a, b) where ghcdiShow (x, y) t = listLike' "(" ", " ")" [ghcdiShow x t, ghcdiShow y t] instance (GhcdiShow a, GhcdiShow b, GhcdiShow c) => GhcdiShow (a, b, c) where ghcdiShow (x, y, u) t = listLike' "(" ", " ")" [ghcdiShow x t, ghcdiShow y t, ghcdiShow u t] instance (GhcdiShow a, GhcdiShow b, GhcdiShow c, GhcdiShow d) => GhcdiShow (a, b, c, d) where ghcdiShow (x, y, u, v) t = listLike' "(" ", " ")" [ghcdiShow x t, ghcdiShow y t, ghcdiShow u t, ghcdiShow v t] ctxt = centerY . preText cgs x = centerY . ghcdiShow x instance GhcdiShow a => GhcdiShow (Maybe a) where ghcdiShow Nothing _ = ctxt "Nothing" ghcdiShow (Just x) t = ctxt "Just " ||| cgs x t instance (GhcdiShow a, GhcdiShow b) => GhcdiShow (Either a b) where ghcdiShow (Left x) t = ctxt "Right " ||| cgs x t ghcdiShow (Right x) t = ctxt "Left " ||| cgs x t instance (GhcdiShow a, Integral a) => GhcdiShow (Ratio a) where ghcdiShow r t = centerX above === centerX (hrule bar_width) === centerX below where bar_width = max (width above) (width below) above = ghcdiShow (numerator r) t below = ghcdiShow (denominator r) t instance GhcdiShow Int where instance GhcdiShow Integer where instance GhcdiShow Rational where instance GhcdiShow Float where instance GhcdiShow Char where instance GhcdiShow Double where instance GhcdiShow Bool where instance GhcdiShow String where
mgsloan/diagrams-ghci
MyPrelude.hs
Haskell
bsd-3-clause
2,872
import System.Nemesis import System.Nemesis.Utils ((-)) import Prelude hiding ((-)) main = run - do -- desc is optional, it gives some description to the task -- task syntax: task "keyword: space seperated dependencies" io-action desc "Hunter attack macro" task "attack: pet-attack auto-attack" (putStrLn "attack macro done!") desc "Pet attack" task "pet-attack: mark" - do sh "echo 'pet attack'" desc "Hunter's mark" task "mark" - do sh "echo \"casting hunter's mark\"" desc "Auto attack" task "auto-attack" - do sh "echo 'auto shoot'"
nfjinjing/nemesis
test/N2.hs
Haskell
bsd-3-clause
574
----------------------------------------------------------------------------- -- | -- Module : Data.FMList -- Copyright : (c) Sjoerd Visscher 2009 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : sjoerd@w3future.com -- Stability : experimental -- Portability : portable -- -- FoldMap lists: lists represented by their 'foldMap' function. -- -- Examples: -- -- > -- A right-infinite list -- > c = 1 `cons` c -- -- > -- A left-infinite list -- > d = d `snoc` 2 -- -- > -- A middle-infinite list ?? -- > e = c `append` d -- -- > *> head e -- > 1 -- > *> last e -- > 2 ----------------------------------------------------------------------------- {-# LANGUAGE CPP #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveTraversable #-} module Data.FMList ( FMList(..) , transform -- * Construction , empty , singleton , cons , snoc , viewl , viewr , pair , append , fromList , fromFoldable -- * Basic functions , null , length , genericLength , head , tail , last , init , reverse -- * Folding , toList , flatten , foldMapA , filter , filterM , take , drop , takeWhile , dropWhile , zip , zipWith -- * Unfolding , iterate , repeat , cycle , unfold , unfoldr -- * Transforming , mapMaybe , wither ) where import Prelude ( (.), ($), ($!), flip, const, error, otherwise , Either(..), either , Bool(..), (&&) , Ord(..), Num(..), Int , Show(..), String, (++) ) import qualified Prelude as P import Data.Maybe (Maybe(..), maybe, fromMaybe, isNothing) import Data.Monoid (Monoid, mempty, mappend, Dual(..), First(..), Last(..), Sum(..)) #if MIN_VERSION_base(4,9,0) import Data.Semigroup (Semigroup) import qualified Data.Semigroup as S #endif import Data.Foldable (Foldable, foldMap, foldr, toList) import Data.Traversable (Traversable, traverse) import Control.Monad hiding (filterM) import Control.Monad.Fail as MF import Control.Applicative -- | 'FMList' is a 'foldMap' function wrapped up in a newtype. -- newtype FMList a = FM { unFM :: forall m . Monoid m => (a -> m) -> m } infixr 6 <> -- We define our own (<>) instead of using the one from Data.Semigroup -- or Data.Monoid. This has two advantages: -- -- 1. It avoids certain annoying compatibility issues in constraints. -- 2. In the situation (sadly common in this context) where things -- don't specialize and we actually pass a Monoid dictionary, it's -- faster to extract mempty from that dictionary than to first -- extract the Semigroup superclass dictionary and then extract its -- (<>) method. (<>) :: Monoid m => m -> m -> m (<>) = mappend {-# INLINE (<>) #-} -- | The function 'transform' transforms a list by changing -- the map function that is passed to 'foldMap'. -- -- It has the following property: -- -- @transform a . transform b = transform (b . a)@ -- -- For example: -- -- * @ m >>= g@ -- -- * @= flatten (fmap g m)@ -- -- * @= flatten . fmap g $ m@ -- -- * @= transform foldMap . transform (. g) $ m@ -- -- * @= transform ((. g) . foldMap) m@ -- -- * @= transform (\\f -> foldMap f . g) m@ -- transform :: (forall m. Monoid m => (a -> m) -> (b -> m)) -> FMList b -> FMList a transform t (FM l) = FM (l . t) -- shorthand constructors nil :: FMList a nil = FM mempty one :: a -> FMList a one x = FM ($ x) (><) :: FMList a -> FMList a -> FMList a FM l >< FM r = FM (l `mappend` r) -- exported constructors singleton :: a -> FMList a singleton = one cons :: a -> FMList a -> FMList a cons x l = one x >< l snoc :: FMList a -> a -> FMList a snoc l x = l >< one x pair :: a -> a -> FMList a pair l r = one l >< one r append :: FMList a -> FMList a -> FMList a append = (><) fromList :: [a] -> FMList a fromList = fromFoldable fromFoldable :: Foldable f => f a -> FMList a fromFoldable l = FM $ flip foldMap l mhead :: FMList a -> Maybe a mhead l = getFirst (unFM l (First . Just)) null :: FMList a -> Bool null = isNothing . mhead length :: FMList a -> Int length = genericLength genericLength :: Num b => FMList a -> b genericLength l = getSum $ unFM l (const $ Sum 1) infixl 5 :< data ViewL a = EmptyL | a :< FMList a deriving (Show, Functor, Foldable, Traversable) unviewl :: ViewL a -> FMList a unviewl EmptyL = nil unviewl (x :< xs) = cons x xs #if MIN_VERSION_base(4,9,0) instance Semigroup (ViewL a) where EmptyL <> v = v (x :< xs) <> v = x :< (xs >< unviewl v) #endif instance Monoid (ViewL a) where mempty = EmptyL #if MIN_VERSION_base(4,9,0) mappend = (S.<>) #else EmptyL `mappend` v = v (x :< xs) `mappend` v = x :< (xs >< unviewl v) #endif infixr 5 :> data ViewR a = EmptyR | FMList a :> a deriving (Show, Functor, Foldable, Traversable) unviewr :: ViewR a -> FMList a unviewr EmptyR = nil unviewr (xs :> x) = xs `snoc` x #if MIN_VERSION_base(4,9,0) instance Semigroup (ViewR a) where v <> EmptyR = v v <> (xs :> x) = (unviewr v >< xs) :> x #endif instance Monoid (ViewR a) where mempty = EmptyR #if MIN_VERSION_base(4,9,0) mappend = (S.<>) #else v `mappend` EmptyR = v v `mappend` (xs :> x) =(unviewr v >< xs) :> x #endif viewl :: FMList a -> ViewL a viewl = foldMap (:< nil) viewr :: FMList a -> ViewR a viewr = foldMap (nil :>) head :: FMList a -> a head l = mhead l `fromMaybeOrError` "Data.FMList.head: empty list" tail :: FMList a -> FMList a tail l = case viewl l of EmptyL -> error "Data.FMList.tail: empty list" _ :< l' -> l' last :: FMList a -> a last l = getLast (unFM l (Last . Just)) `fromMaybeOrError` "Data.FMList.last: empty list" init :: FMList a -> FMList a init l = case viewr l of EmptyR -> error "Data.FMList.init: empty list" l' :> _ -> l' reverse :: FMList a -> FMList a reverse l = FM $ getDual . unFM l . (Dual .) flatten :: Foldable t => FMList (t a) -> FMList a flatten = transform foldMap filter :: (a -> Bool) -> FMList a -> FMList a filter p = transform (\f x -> if p x then f x else mempty) mapMaybe :: (a -> Maybe b) -> FMList a -> FMList b mapMaybe p = transform (\f x -> maybe mempty f (p x)) filterM :: Applicative m => (a -> m Bool) -> FMList a -> m (FMList a) filterM p l = unWrapApp $ unFM l $ \a -> let go pr | pr = one a | otherwise = nil in WrapApp $ fmap go (p a) wither :: Applicative m => (a -> m (Maybe b)) -> FMList a -> m (FMList b) wither p l = unWrapApp $ unFM l $ \a -> WrapApp $ fmap (maybe nil one) (p a) -- transform the foldMap to foldr with state. transformCS :: (forall m. Monoid m => (b -> m) -> a -> (m -> s -> m) -> s -> m) -> s -> FMList a -> FMList b transformCS t s0 l = FM $ \f -> foldr (\e r -> t f e (\a -> mappend a . r)) mempty l s0 take :: (Ord n, Num n) => n -> FMList a -> FMList a take = transformCS (\f e c i -> if i > 0 then c (f e) (i-1) else mempty) takeWhile :: (a -> Bool) -> FMList a -> FMList a takeWhile p = transformCS (\f e c _ -> if p e then c (f e) True else mempty) True drop :: (Ord n, Num n) => n -> FMList a -> FMList a drop = transformCS (\f e c i -> if i > 0 then c mempty (i-1) else c (f e) 0) dropWhile :: (a -> Bool) -> FMList a -> FMList a dropWhile p = transformCS (\f e c ok -> if ok && p e then c mempty True else c (f e) False) True zipWith :: (a -> b -> c) -> FMList a -> FMList b -> FMList c zipWith t xs ys = fromList $ P.zipWith t (toList xs) (toList ys) zip :: FMList a -> FMList b -> FMList (a,b) zip = zipWith (,) iterate :: (a -> a) -> a -> FMList a iterate f x = x `cons` iterate f (f x) -- | 'repeat' buids an infinite list of a single value. -- While infinite, the result is still accessible from both the start and end. repeat :: a -> FMList a repeat = cycle . one -- | 'cycle' repeats a list to create an infinite list. -- It is also accessible from the end, where @last (cycle l)@ equals @last l@. -- -- Caution: @cycle 'empty'@ is an infinite loop. cycle :: FMList a -> FMList a cycle l = l >< cycle l >< l -- | 'unfoldr' builds an 'FMList' from a seed value from left to right. -- The function takes the element and returns 'Nothing' -- if it is done producing the list or returns 'Just' @(a,b)@, in which -- case, @a@ is a appended to the result and @b@ is used as the next -- seed value in a recursive call. -- -- A simple use of 'unfoldr': -- -- > *> unfoldr (\b -> if b == 0 then Nothing else Just (b, b-1)) 10 -- > fromList [10,9,8,7,6,5,4,3,2,1] -- unfoldr :: (b -> Maybe (a, b)) -> b -> FMList a unfoldr g = go where go b = maybe nil (\(a, b') -> cons a (go b')) (g b) -- | 'unfold' builds a list from a seed value. -- The function takes the seed and returns an 'FMList' of values. -- If the value is 'Right' @a@, then @a@ is appended to the result, and if the -- value is 'Left' @b@, then @b@ is used as seed value in a recursive call. -- -- A simple use of 'unfold' (simulating unfoldl): -- -- > *> unfold (\b -> if b == 0 then empty else Left (b-1) `pair` Right b) 10 -- > fromList [1,2,3,4,5,6,7,8,9,10] -- unfold :: (b -> FMList (Either b a)) -> b -> FMList a unfold g = transform (\f -> either (foldMap f . unfold g) f) . g -- | This is essentially the same as 'Data.Monoid.Ap'. We include it here -- partly for compatibility with older base versions. But as discussed at the -- local definition of '<>', it can be slightly better for performance to have -- 'mappend' for this type defined in terms of 'mappend' for the underlying -- 'Monoid' rather than 'S.<>' for the underlying 'Semigroup'. newtype WrapApp f m = WrapApp { unWrapApp :: f m } #if MIN_VERSION_base(4,9,0) instance (Applicative f, Monoid m) => Semigroup (WrapApp f m) where WrapApp a <> WrapApp b = WrapApp $ liftA2 (<>) a b instance (Applicative f, Monoid m) => Monoid (WrapApp f m) where mempty = WrapApp $ pure mempty mappend = (S.<>) #else instance (Applicative f, Monoid m) => Monoid (WrapApp f m) where mempty = WrapApp $ pure mempty mappend (WrapApp a) (WrapApp b) = WrapApp $ liftA2 mappend a b #endif -- | Map each element of a structure to an action, evaluate these actions from left to right, -- and concat the monoid results. foldMapA :: ( Foldable t, Applicative f, Monoid m) => (a -> f m) -> t a -> f m foldMapA f = unWrapApp . foldMap (WrapApp . f) instance Functor FMList where fmap g = transform (\f -> f . g) a <$ l = transform (\f -> const (f a)) l instance Foldable FMList where foldMap m f = unFM f m instance Traversable FMList where traverse f = foldMapA (fmap one . f) instance Monad FMList where return = pure m >>= g = transform (\f -> foldMap f . g) m (>>) = (*>) instance MF.MonadFail FMList where fail _ = nil instance Applicative FMList where pure = one gs <*> xs = transform (\f g -> unFM xs (f . g)) gs as <* bs = transform (\f a -> unFM bs (const (f a))) as as *> bs = transform (\f -> const (unFM bs f)) as #if MIN_VERSION_base (4,10,0) liftA2 g xs ys = transform (\f x -> unFM ys (\y -> f (g x y))) xs #endif #if MIN_VERSION_base(4,9,0) instance Semigroup (FMList a) where (<>) = (><) #endif instance Monoid (FMList a) where mempty = nil #if MIN_VERSION_base(4,9,0) mappend = (S.<>) #else mappend = (><) #endif instance MonadPlus FMList where mzero = nil mplus = (><) instance Alternative FMList where empty = nil (<|>) = (><) instance Show a => Show (FMList a) where show l = "fromList " ++ (show $! toList l) fromMaybeOrError :: Maybe a -> String -> a fromMaybeOrError ma e = fromMaybe (error e) ma
sjoerdvisscher/fmlist
Data/FMList.hs
Haskell
bsd-3-clause
11,902
{-# OPTIONS_GHC -fno-warn-orphans #-} module Test.Pos.Cbor.Arbitrary.UserSecret ( ) where import Universum import Test.QuickCheck (Arbitrary (..)) import Test.QuickCheck.Arbitrary.Generic (genericArbitrary, genericShrink) import Pos.Util.UserSecret (UserSecret, WalletUserSecret) import System.FileLock (FileLock) instance Arbitrary WalletUserSecret where arbitrary = genericArbitrary shrink = genericShrink instance Arbitrary (Maybe FileLock) => Arbitrary UserSecret where arbitrary = genericArbitrary shrink = genericShrink
input-output-hk/cardano-sl
lib/test/Test/Pos/Cbor/Arbitrary/UserSecret.hs
Haskell
apache-2.0
633
{-# OPTIONS -#include "comPrim.h" #-} -- Automatically generated by HaskellDirect (ihc.exe), version 0.20 -- Created: 20:11 Pacific Standard Time, Tuesday 16 December, 2003 -- Command line: -fno-qualified-names -fno-imports -fno-export-lists -fout-pointers-are-not-refs -c ComPrim.idl -o ComPrim.hs module ComPrim where import Pointer ( makeFO, finalNoFree ) import HDirect import Foreign.ForeignPtr import Foreign.Ptr {- BEGIN_GHC_ONLY import Dynamic import GHC.IOBase --import ForeignObj END_GHC_ONLY -} import Int import Word ( Word32 ) import IOExts ( unsafePerformIO ) import WideString ( WideString, marshallWideString, freeWideString, readWideString, writeWideString ) import IO ( hPutStrLn, stderr ) data IUnknown_ a = Unknown (ForeignPtr ()) type IUnknown a = IUnknown_ a type HRESULT = Int32 failed :: HRESULT -> Bool failed hr = hr < 0 ifaceToAddr :: IUnknown a -> Ptr b ifaceToAddr (Unknown x) = castPtr (foreignPtrToPtr x) addrToIPointer :: Bool -> Ptr b -> IO (IUnknown a) addrToIPointer finaliseMe x = do i <- makeFO x (castPtrToFunPtr $ if finaliseMe then addrOfReleaseIUnknown else finalNoFree) return (Unknown i) marshallIUnknown :: IUnknown a -> IO (ForeignPtr b) marshallIUnknown (Unknown x) = return (castForeignPtr x) checkHR :: HRESULT -> IO () checkHR hr | failed hr = coFailHR hr | otherwise = return () coFailHR :: HRESULT -> IO a coFailHR hr = do str <- stringFromHR hr coFailWithHR hr str {- BEGIN_GHC_ONLY -- ghc-specific newtype ComError = ComError Int32 comErrorTc = mkTyCon "ComError" instance Typeable ComError where typeOf _ = mkAppTy comErrorTc [] coFailWithHR :: HRESULT -> String -> IO a coFailWithHR hr msg = ioException (IOError Nothing (DynIOError (toDyn (ComError hr))) "" msg Nothing) END_GHC_ONLY -} {- BEGIN_NOT_FOR_GHC -} coPrefix = "Com error: " coFailWithHR :: HRESULT -> String -> IO a coFailWithHR hr msg = ioError (userError (coPrefix ++ msg ++ showParen True (shows hr) "")) {- END_NOT_FOR_GHC -} stringFromHR :: HRESULT -> IO String stringFromHR hr = do pstr <- hresultString hr -- static memory unmarshallString (castPtr pstr) comInitialize :: IO () comInitialize = do o_comInitialize <- prim_ComPrim_comInitialize checkHR o_comInitialize foreign import stdcall "comInitialize" prim_ComPrim_comInitialize :: IO Int32 comUnInitialize :: IO () comUnInitialize = prim_ComPrim_comUnInitialize foreign import stdcall "comUnInitialize" prim_ComPrim_comUnInitialize :: IO () messageBox :: Ptr Char -> Ptr Char -> Word32 -> IO () messageBox str title flg = prim_ComPrim_messageBox str title flg foreign import ccall "messageBox" prim_ComPrim_messageBox :: Ptr Char -> Ptr Char -> Word32 -> IO () type PIID = Ptr () type PCLSID = Ptr () type PGUID = Ptr () primCLSIDFromProgID :: Ptr Char -> PCLSID -> IO () primCLSIDFromProgID str rptr = do o_primCLSIDFromProgID <- prim_ComPrim_primCLSIDFromProgID str rptr checkHR o_primCLSIDFromProgID foreign import stdcall "primCLSIDFromProgID" prim_ComPrim_primCLSIDFromProgID :: Ptr Char -> Ptr () -> IO Int32 primProgIDFromCLSID :: ForeignPtr () -> IO (Ptr ()) primProgIDFromCLSID pclsid = do pwide <- allocBytes (fromIntegral sizeofPtr) o_primProgIDFromCLSID <- withForeignPtr pclsid (\ pclsid -> prim_ComPrim_primProgIDFromCLSID pclsid pwide) checkHR o_primProgIDFromCLSID doThenFree free readPtr pwide foreign import ccall "primProgIDFromCLSID" prim_ComPrim_primProgIDFromCLSID :: Ptr () -> Ptr (Ptr ()) -> IO Int32 primStringToGUID :: Ptr Wchar_t -> Ptr () -> IO () primStringToGUID str pguid = do o_primStringToGUID <- prim_ComPrim_primStringToGUID str pguid checkHR o_primStringToGUID foreign import ccall "primStringToGUID" prim_ComPrim_primStringToGUID :: Ptr Word16 -> Ptr () -> IO Int32 primGUIDToString :: ForeignPtr () -> IO (Ptr ()) primGUIDToString guid = do str <- allocBytes (fromIntegral sizeofPtr) o_primGUIDToString <- withForeignPtr guid (\ guid -> prim_ComPrim_primGUIDToString guid str) checkHR o_primGUIDToString doThenFree free readPtr str foreign import ccall "primGUIDToString" prim_ComPrim_primGUIDToString :: Ptr () -> Ptr (Ptr ()) -> IO Int32 primCopyGUID :: ForeignPtr () -> PGUID -> IO () primCopyGUID pguid1 pguid2 = do o_primCopyGUID <- withForeignPtr pguid1 (\ pguid1 -> prim_ComPrim_primCopyGUID pguid1 pguid2) checkHR o_primCopyGUID foreign import ccall "primCopyGUID" prim_ComPrim_primCopyGUID :: Ptr () -> Ptr () -> IO Int32 primNewGUID :: ForeignPtr () -> IO () primNewGUID pguid = do o_primNewGUID <- withForeignPtr pguid (\ pguid -> prim_ComPrim_primNewGUID pguid) checkHR o_primNewGUID foreign import ccall "primNewGUID" prim_ComPrim_primNewGUID :: Ptr () -> IO Int32 bindObject :: Ptr Wchar_t -> ForeignPtr () -> IO (Ptr (Ptr ())) bindObject name iid = do ppv <- allocBytes (fromIntegral sizeofPtr) o_bindObject <- withForeignPtr iid (\ iid -> prim_ComPrim_bindObject name iid ppv) checkHR o_bindObject return (ppv) foreign import ccall "bindObject" prim_ComPrim_bindObject :: Ptr Word16 -> Ptr () -> Ptr (Ptr ()) -> IO Int32 primComEqual :: IUnknown a0 -> IUnknown a1 -> IO Bool primComEqual unk1 unk2 = do unk1 <- marshallIUnknown unk1 unk2 <- marshallIUnknown unk2 o_primComEqual <- withForeignPtr unk1 (\ unk1 -> withForeignPtr unk2 (\ unk2 -> prim_ComPrim_primComEqual unk1 unk2)) unmarshallBool o_primComEqual foreign import ccall "primComEqual" prim_ComPrim_primComEqual :: Ptr (IUnknown a) -> Ptr (IUnknown a) -> IO Int32 isEqualGUID :: ForeignPtr () -> ForeignPtr () -> Bool isEqualGUID guid1 guid2 = unsafePerformIO (withForeignPtr guid1 (\ guid1 -> withForeignPtr guid2 (\ guid2 -> prim_ComPrim_isEqualGUID guid1 guid2)) >>= \ o_isEqualGUID -> unmarshallBool o_isEqualGUID) foreign import stdcall "IsEqualGUID" prim_ComPrim_isEqualGUID :: Ptr () -> Ptr () -> IO Int32 lOCALE_USER_DEFAULT :: Word32 lOCALE_USER_DEFAULT = unsafePerformIO (prim_ComPrim_lOCALE_USER_DEFAULT) foreign import ccall "lOCALE_USER_DEFAULT" prim_ComPrim_lOCALE_USER_DEFAULT :: IO Word32 primCreateTypeLib :: Int32 -> WideString -> IO (Ptr (Ptr ())) primCreateTypeLib skind lpkind = do ppv <- allocBytes (fromIntegral sizeofPtr) lpkind <- marshallWideString lpkind o_primCreateTypeLib <- prim_ComPrim_primCreateTypeLib skind lpkind ppv freeWideString lpkind checkHR o_primCreateTypeLib return (ppv) foreign import ccall "primCreateTypeLib" prim_ComPrim_primCreateTypeLib :: Int32 -> Ptr WideString -> Ptr (Ptr ()) -> IO Int32 getLastError :: IO Word32 getLastError = prim_ComPrim_getLastError foreign import stdcall "GetLastError" prim_ComPrim_getLastError :: IO Word32 hresultString :: Int32 -> IO (Ptr ()) hresultString i = prim_ComPrim_hresultString i foreign import ccall "hresultString" prim_ComPrim_hresultString :: Int32 -> IO (Ptr ()) coCreateInstance :: ForeignPtr () -> ForeignPtr () -> Int32 -> ForeignPtr () -> Ptr () -> IO () coCreateInstance clsid inner ctxt riid ppv = do o_coCreateInstance <- withForeignPtr clsid (\ clsid -> withForeignPtr inner (\ inner -> withForeignPtr riid (\ riid -> prim_ComPrim_coCreateInstance clsid inner ctxt riid ppv))) checkHR o_coCreateInstance foreign import stdcall "CoCreateInstance" prim_ComPrim_coCreateInstance :: Ptr () -> Ptr () -> Int32 -> Ptr () -> Ptr () -> IO Int32 type ULONG = Word32 type DWORD = Word32 data COAUTHIDENTITY = COAUTHIDENTITY {user :: String, domain :: String, password :: String, flags :: ULONG} writeCOAUTHIDENTITY :: Ptr COAUTHIDENTITY -> COAUTHIDENTITY -> IO () writeCOAUTHIDENTITY ptr (COAUTHIDENTITY user domain password flags) = let userLength = (fromIntegral (length user) :: Word32) in do user <- marshallString user let domainLength = (fromIntegral (length domain) :: Word32) domain <- marshallString domain let passwordLength = (fromIntegral (length password) :: Word32) password <- marshallString password let pf0 = ptr pf1 = addNCastPtr pf0 0 writePtr pf1 user let pf2 = addNCastPtr pf1 4 writeWord32 pf2 userLength let pf3 = addNCastPtr pf2 4 writePtr pf3 domain let pf4 = addNCastPtr pf3 4 writeWord32 pf4 domainLength let pf5 = addNCastPtr pf4 4 writePtr pf5 password let pf6 = addNCastPtr pf5 4 writeWord32 pf6 passwordLength let pf7 = addNCastPtr pf6 4 writeWord32 pf7 flags readCOAUTHIDENTITY :: Ptr COAUTHIDENTITY -> IO COAUTHIDENTITY readCOAUTHIDENTITY ptr = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do user <- readPtr pf1 let pf2 = addNCastPtr pf1 4 userLength <- readWord32 pf2 let pf3 = addNCastPtr pf2 4 domain <- readPtr pf3 let pf4 = addNCastPtr pf3 4 domainLength <- readWord32 pf4 let pf5 = addNCastPtr pf4 4 password <- readPtr pf5 let pf6 = addNCastPtr pf5 4 passwordLength <- readWord32 pf6 let pf7 = addNCastPtr pf6 4 flags <- readWord32 pf7 userLength <- unmarshallWord32 userLength domainLength <- unmarshallWord32 domainLength passwordLength <- unmarshallWord32 passwordLength user <- unmarshallString user domain <- unmarshallString domain password <- unmarshallString password return (COAUTHIDENTITY user domain password flags) sizeofCOAUTHIDENTITY :: Word32 sizeofCOAUTHIDENTITY = 28 data COAUTHINFO = COAUTHINFO {dwAuthnSvc :: DWORD, dwAuthzSvc :: DWORD, pwszServerPrincName :: WideString, dwAuthnLevel :: DWORD, dwImpersonationLevel :: DWORD, pAuthIdentityData :: (Maybe COAUTHIDENTITY), dwCapabilities :: DWORD} writeCOAUTHINFO :: Ptr COAUTHINFO -> COAUTHINFO -> IO () writeCOAUTHINFO ptr (COAUTHINFO dwAuthnSvc dwAuthzSvc pwszServerPrincName dwAuthnLevel dwImpersonationLevel pAuthIdentityData dwCapabilities) = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do writeWord32 pf1 dwAuthnSvc let pf2 = addNCastPtr pf1 4 writeWord32 pf2 dwAuthzSvc let pf3 = addNCastPtr pf2 4 writeWideString pf3 pwszServerPrincName let pf4 = addNCastPtr pf3 4 writeWord32 pf4 dwAuthnLevel let pf5 = addNCastPtr pf4 4 writeWord32 pf5 dwImpersonationLevel let pf6 = addNCastPtr pf5 4 writeunique (allocBytes (fromIntegral sizeofCOAUTHIDENTITY)) writeCOAUTHIDENTITY pf6 pAuthIdentityData let pf7 = addNCastPtr pf6 4 writeWord32 pf7 dwCapabilities readCOAUTHINFO :: Ptr COAUTHINFO -> IO COAUTHINFO readCOAUTHINFO ptr = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do dwAuthnSvc <- readWord32 pf1 let pf2 = addNCastPtr pf1 4 dwAuthzSvc <- readWord32 pf2 let pf3 = addNCastPtr pf2 4 pwszServerPrincName <- readWideString pf3 let pf4 = addNCastPtr pf3 4 dwAuthnLevel <- readWord32 pf4 let pf5 = addNCastPtr pf4 4 dwImpersonationLevel <- readWord32 pf5 let pf6 = addNCastPtr pf5 4 pAuthIdentityData <- readunique readCOAUTHIDENTITY pf6 let pf7 = addNCastPtr pf6 4 dwCapabilities <- readWord32 pf7 return (COAUTHINFO dwAuthnSvc dwAuthzSvc pwszServerPrincName dwAuthnLevel dwImpersonationLevel pAuthIdentityData dwCapabilities) sizeofCOAUTHINFO :: Word32 sizeofCOAUTHINFO = 28 data COSERVERINFO = COSERVERINFO {dwReserved1 :: DWORD, pwszName :: WideString, pAuthInfo :: (Maybe COAUTHINFO), dwReserved2 :: DWORD} writeCOSERVERINFO :: Ptr COSERVERINFO -> COSERVERINFO -> IO () writeCOSERVERINFO ptr (COSERVERINFO dwReserved1 pwszName pAuthInfo dwReserved2) = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do writeWord32 pf1 dwReserved1 let pf2 = addNCastPtr pf1 4 writeWideString pf2 pwszName let pf3 = addNCastPtr pf2 4 writeunique (allocBytes (fromIntegral sizeofCOAUTHINFO)) writeCOAUTHINFO pf3 pAuthInfo let pf4 = addNCastPtr pf3 4 writeWord32 pf4 dwReserved2 readCOSERVERINFO :: Ptr COSERVERINFO -> IO COSERVERINFO readCOSERVERINFO ptr = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do dwReserved1 <- readWord32 pf1 let pf2 = addNCastPtr pf1 4 pwszName <- readWideString pf2 let pf3 = addNCastPtr pf2 4 pAuthInfo <- readunique readCOAUTHINFO pf3 let pf4 = addNCastPtr pf3 4 dwReserved2 <- readWord32 pf4 return (COSERVERINFO dwReserved1 pwszName pAuthInfo dwReserved2) sizeofCOSERVERINFO :: Word32 sizeofCOSERVERINFO = 16 data MULTI_QI_PRIM = MULTI_QI {pIID :: PGUID, pItf :: (Ptr ()), hr :: HRESULT} writeMULTI_QI_PRIM :: Ptr MULTI_QI_PRIM -> MULTI_QI_PRIM -> IO () writeMULTI_QI_PRIM ptr (MULTI_QI pIID pItf hr) = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do writePtr pf1 pIID let pf2 = addNCastPtr pf1 4 writePtr pf2 pItf let pf3 = addNCastPtr pf2 4 writeInt32 pf3 hr readMULTI_QI_PRIM :: Ptr MULTI_QI_PRIM -> IO MULTI_QI_PRIM readMULTI_QI_PRIM ptr = let pf0 = ptr pf1 = addNCastPtr pf0 0 in do pIID <- readPtr pf1 let pf2 = addNCastPtr pf1 4 pItf <- readPtr pf2 let pf3 = addNCastPtr pf2 4 hr <- readInt32 pf3 return (MULTI_QI pIID pItf hr) sizeofMULTI_QI_PRIM :: Word32 sizeofMULTI_QI_PRIM = 12 coCreateInstanceEx :: ForeignPtr () -> ForeignPtr () -> DWORD -> Maybe COSERVERINFO -> [MULTI_QI_PRIM] -> IO [MULTI_QI_PRIM] coCreateInstanceEx clsid pUnkOuter dwClsCtx pServerInfo pResults = let cmq = (fromIntegral (length pResults) :: Word32) in do pResults <- marshalllist sizeofMULTI_QI_PRIM writeMULTI_QI_PRIM pResults pServerInfo <- marshallunique (allocBytes (fromIntegral sizeofCOSERVERINFO)) writeCOSERVERINFO pServerInfo o_coCreateInstanceEx <- withForeignPtr clsid (\ clsid -> withForeignPtr pUnkOuter (\ pUnkOuter -> prim_ComPrim_coCreateInstanceEx clsid pUnkOuter dwClsCtx pServerInfo cmq pResults)) free pServerInfo checkHR o_coCreateInstanceEx cmq <- unmarshallWord32 cmq unmarshalllist sizeofMULTI_QI_PRIM 0 cmq readMULTI_QI_PRIM pResults foreign import stdcall "CoCreateInstanceEx" prim_ComPrim_coCreateInstanceEx :: Ptr () -> Ptr () -> Word32 -> Ptr COSERVERINFO -> Word32 -> Ptr MULTI_QI_PRIM -> IO Int32 getActiveObject :: ForeignPtr () -> Ptr () -> Ptr () -> IO () getActiveObject clsid inner ppv = do o_getActiveObject <- withForeignPtr clsid (\ clsid -> prim_ComPrim_getActiveObject clsid inner ppv) checkHR o_getActiveObject foreign import stdcall "GetActiveObject" prim_ComPrim_getActiveObject :: Ptr () -> Ptr () -> Ptr () -> IO Int32 primQI :: Ptr () -> Ptr () -> ForeignPtr () -> Ptr (Ptr ()) -> IO () primQI methPtr iptr riid ppv = do o_primQI <- withForeignPtr riid (\ riid -> prim_ComPrim_primQI methPtr iptr riid ppv) checkHR o_primQI foreign import ccall "primQI" prim_ComPrim_primQI :: Ptr () -> Ptr () -> Ptr () -> Ptr (Ptr ()) -> IO Int32 primAddRef :: Ptr () -> Ptr () -> IO Word32 primAddRef methPtr iptr = prim_ComPrim_primAddRef methPtr iptr foreign import ccall "primAddRef" prim_ComPrim_primAddRef :: Ptr () -> Ptr () -> IO Word32 primRelease :: Ptr () -> Ptr () -> IO Word32 primRelease methPtr iptr = prim_ComPrim_primRelease methPtr iptr foreign import ccall "primRelease" prim_ComPrim_primRelease :: Ptr () -> Ptr () -> IO Word32 primEnumNext :: Ptr () -> Ptr () -> Word32 -> Ptr () -> Ptr () -> IO () primEnumNext methPtr iptr celt ptr po = do o_primEnumNext <- prim_ComPrim_primEnumNext methPtr iptr celt ptr po checkHR o_primEnumNext foreign import ccall "primEnumNext" prim_ComPrim_primEnumNext :: Ptr () -> Ptr () -> Word32 -> Ptr () -> Ptr () -> IO Int32 primEnumSkip :: Ptr () -> Ptr () -> Word32 -> IO () primEnumSkip methPtr iptr celt = do o_primEnumSkip <- prim_ComPrim_primEnumSkip methPtr iptr celt checkHR o_primEnumSkip foreign import ccall "primEnumSkip" prim_ComPrim_primEnumSkip :: Ptr () -> Ptr () -> Word32 -> IO Int32 primEnumReset :: Ptr () -> Ptr () -> IO () primEnumReset methPtr iptr = do o_primEnumReset <- prim_ComPrim_primEnumReset methPtr iptr checkHR o_primEnumReset foreign import ccall "primEnumReset" prim_ComPrim_primEnumReset :: Ptr () -> Ptr () -> IO Int32 primEnumClone :: Ptr () -> Ptr () -> Ptr () -> IO () primEnumClone methPtr iptr ppv = do o_primEnumClone <- prim_ComPrim_primEnumClone methPtr iptr ppv checkHR o_primEnumClone foreign import ccall "primEnumClone" prim_ComPrim_primEnumClone :: Ptr () -> Ptr () -> Ptr () -> IO Int32 primPersistLoad :: Ptr () -> Ptr () -> Ptr Wchar_t -> Word32 -> IO () primPersistLoad methPtr iptr pszFileName dwMode = do o_primPersistLoad <- prim_ComPrim_primPersistLoad methPtr iptr pszFileName dwMode checkHR o_primPersistLoad foreign import stdcall "primPersistLoad" prim_ComPrim_primPersistLoad :: Ptr () -> Ptr () -> Ptr Word16 -> Word32 -> IO Int32 primNullIID :: IO (Ptr ()) primNullIID = prim_ComPrim_primNullIID foreign import ccall "primNullIID" prim_ComPrim_primNullIID :: IO (Ptr ()) loadTypeLib :: Ptr Wchar_t -> Ptr () -> IO () loadTypeLib pfname ptr = do o_loadTypeLib <- prim_ComPrim_loadTypeLib pfname ptr checkHR o_loadTypeLib foreign import stdcall "LoadTypeLib" prim_ComPrim_loadTypeLib :: Ptr Word16 -> Ptr () -> IO Int32 loadTypeLibEx :: Ptr Wchar_t -> Int32 -> Ptr () -> IO () loadTypeLibEx pfname rkind ptr = do o_loadTypeLibEx <- prim_ComPrim_loadTypeLibEx pfname rkind ptr checkHR o_loadTypeLibEx foreign import stdcall "LoadTypeLibEx" prim_ComPrim_loadTypeLibEx :: Ptr Word16 -> Int32 -> Ptr () -> IO Int32 loadRegTypeLib :: ForeignPtr () -> Int32 -> Int32 -> Int32 -> Ptr () -> IO () loadRegTypeLib pguid maj min lcid ptr = do o_loadRegTypeLib <- withForeignPtr pguid (\ pguid -> prim_ComPrim_loadRegTypeLib pguid maj min lcid ptr) checkHR o_loadRegTypeLib foreign import stdcall "LoadRegTypeLib" prim_ComPrim_loadRegTypeLib :: Ptr () -> Int32 -> Int32 -> Int32 -> Ptr () -> IO Int32 primQueryPathOfRegTypeLib :: ForeignPtr () -> Word16 -> Word16 -> IO (Ptr Wchar_t) primQueryPathOfRegTypeLib pgd maj min = withForeignPtr pgd (\ pgd -> prim_ComPrim_primQueryPathOfRegTypeLib pgd maj min) foreign import ccall "primQueryPathOfRegTypeLib" prim_ComPrim_primQueryPathOfRegTypeLib :: Ptr () -> Word16 -> Word16 -> IO (Ptr Word16) addrOfReleaseIUnknown :: Ptr () addrOfReleaseIUnknown = unsafePerformIO (prim_ComPrim_addrOfReleaseIUnknown) foreign import stdcall "addrOfReleaseIUnknown" prim_ComPrim_addrOfReleaseIUnknown :: IO (Ptr ()) bstrToStringLen :: Ptr String -> Int32 -> Ptr Char -> IO () bstrToStringLen bstr len str = do o_bstrToStringLen <- prim_ComPrim_bstrToStringLen bstr len str checkHR o_bstrToStringLen foreign import ccall "bstrToStringLen" prim_ComPrim_bstrToStringLen :: Ptr String -> Int32 -> Ptr Char -> IO Int32 bstrLen :: Ptr String -> Int32 bstrLen bstr = unsafePerformIO (prim_ComPrim_bstrLen bstr) foreign import ccall "bstrLen" prim_ComPrim_bstrLen :: Ptr String -> IO Int32 stringToBSTR :: Ptr String -> IO (Ptr String) stringToBSTR bstr = do res <- allocBytes (fromIntegral sizeofPtr) o_stringToBSTR <- prim_ComPrim_stringToBSTR bstr res checkHR o_stringToBSTR return (res) foreign import ccall "stringToBSTR" prim_ComPrim_stringToBSTR :: Ptr String -> Ptr String -> IO Int32 getModuleFileName :: Ptr () -> IO String getModuleFileName hModule = do o_getModuleFileName <- prim_ComPrim_getModuleFileName hModule doThenFree freeString unmarshallString o_getModuleFileName foreign import ccall "getModuleFileName" prim_ComPrim_getModuleFileName :: Ptr () -> IO (Ptr String) messagePump :: IO () messagePump = prim_ComPrim_messagePump foreign import ccall "messagePump" prim_ComPrim_messagePump :: IO () postQuitMsg :: IO () postQuitMsg = prim_ComPrim_postQuitMsg foreign import ccall "postQuitMsg" prim_ComPrim_postQuitMsg :: IO () primOutputDebugString :: String -> IO () primOutputDebugString msg = do msg <- marshallString msg prim_ComPrim_primOutputDebugString msg freeString msg foreign import stdcall "OutputDebugString" prim_ComPrim_primOutputDebugString :: Ptr String -> IO () primGetVersionInfo :: IO (Word32, Word32, Word32) primGetVersionInfo = do maj <- allocBytes (fromIntegral sizeofWord32) min <- allocBytes (fromIntegral sizeofWord32) pid <- allocBytes (fromIntegral sizeofWord32) prim_ComPrim_primGetVersionInfo maj min pid maj <- doThenFree free readWord32 maj min <- doThenFree free readWord32 min pid <- doThenFree free readWord32 pid return (maj, min, pid) foreign import stdcall "primGetVersionInfo" prim_ComPrim_primGetVersionInfo :: Ptr Word32 -> Ptr Word32 -> Ptr Word32 -> IO () coRegisterClassObject :: ForeignPtr () -> ForeignPtr () -> Int32 -> Int32 -> IO Word32 coRegisterClassObject rclsid pUnk dwClsContext flags0 = do lpwRegister <- allocBytes (fromIntegral sizeofWord32) o_coRegisterClassObject <- withForeignPtr rclsid (\ rclsid -> withForeignPtr pUnk (\ pUnk -> prim_ComPrim_coRegisterClassObject rclsid pUnk dwClsContext flags0 lpwRegister)) checkHR o_coRegisterClassObject doThenFree free readWord32 lpwRegister foreign import stdcall "CoRegisterClassObject" prim_ComPrim_coRegisterClassObject :: Ptr () -> Ptr () -> Int32 -> Int32 -> Ptr Word32 -> IO Int32
sof/hdirect
comlib/ComPrim.hs
Haskell
bsd-3-clause
23,964
{-# LANGUAGE OverloadedStrings #-} -- | Home/landing page. module HL.View.Home where import HL.View import HL.View.Code import HL.View.Home.Features import HL.View.Template -- | Home view. homeV :: [(Text, Text, Text)] -> FromLucid App homeV vids = skeleton "Haskell Language" (\_ _ -> linkcss "https://fonts.googleapis.com/css?family=Ubuntu:700") (\cur url -> do navigation True [] Nothing url header url try url community url vids features sponsors transition events div_ [class_ "mobile"] $ (navigation False [] cur url)) (\_ url -> scripts url [js_jquery_console_js ,js_tryhaskell_js ,js_tryhaskell_pages_js]) -- | Top header section with the logo and code sample. header :: (Route App -> Text) -> Html () header 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 sample))))) 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." sample = div_ [class_ "code-sample",title_ "This example is contrived in order to demonstrate what Haskell looks like, including: (1) where syntax, (2) enumeration syntax, (3) pattern matching, (4) consing as an operator, (5) list comprehensions, (6) infix functions. Don't take it seriously as an efficient prime number generator."] (haskellPre codeSample) -- | Code sample. -- TODO: should be rotatable and link to some article. codeSample :: Text codeSample = "primes = filterPrime [2..] \n\ \ where filterPrime (p:xs) = \n\ \ p : filterPrime [x | x <- xs, x `mod` p /= 0]" -- | Try Haskell section. try :: (Route App -> Text) -> Html () 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) -> [(Text, Text, Text)] -> Html () community url vids = 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")))) container_ [id_ "video-description"] (row_ (span8_ [class_ "col-md-8"] (do h1_ (a_ [id_ "video-anchor"] "<title here>") p_ (a_ [id_ "video-view"] "View the video now \8594"))))) div_ [class_ "videos"] (container_ (row_ (span12_ [class_ "col-md-12"] (ul_ (forM_ vids vid)))))) where vid :: (Text,Text,Text) -> Html () vid (n,u,thumb) = li_ (a_ [class_ "vid-thumbnail",href_ u,title_ n] (img_ [src_ thumb])) -- | Information for people to help transition from the old site to the new locations. transition :: Html () transition = div_ [class_ "transition"] (container_ (row_ (span6_ [class_ "col-md-6"] (do h1_ "Psst! Looking for the wiki?" p_ (do "This is the new Haskell home page! The wiki has moved to " a_ [href_ "https://wiki.haskell.org"] "wiki.haskell.org."))))) -- | Events section. -- TODO: Take events section from Haskell News? events :: Html () events = return () -- | List of sponsors. sponsors :: Html () 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.datadoghq.com"] "DataDog") " provides powerful, customizable 24/7 metrics and monitoring \ \integration for all of Haskell.org, and complains loudly for \ \us when things go wrong.")) span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "https://www.fastly.com"] "Fastly") "'s Next Generation CDN provides low latency access for all of \ \Haskell.org's downloads and highest traffic services, including \ \the primary Hackage server, Haskell Platform downloads, and more." ))) row_ (do span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "https://www.rackspace.com"] "Rackspace") " provides compute, storage, and networking resources, powering \ \almost all of Haskell.org in several regions around the world.")) span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "https://www.status.io"] "Status.io") " powers " a_ [href_ "https://status.haskell.org"] "https://status.haskell.org" ", and lets us easily tell you \ \when we broke something." ))) row_ (do span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "http://www.galois.com"] "Galois") " provides infrastructure, funds, administrative resources and \ \has historically hosted critical Haskell.org infrastructure, \ \as well as helping the Haskell community at large with their work." )) span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "https://www.dreamhost.com"] "DreamHost") " has teamed up to provide Haskell.org with redundant, scalable object-storage \ \through their Dream Objects service." ))) row_ (do span6_ [class_ "col-md-6"] (p_ (do strong_ (a_ [href_ "https://webmon.com"] "Webmon") " provides monitoring and escalation for core haskell.org infrastructure." )))
josefs/hl
src/HL/View/Home.hs
Haskell
bsd-3-clause
7,563
-- | -- Module : Data.ASN1.Types -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE BangPatterns #-} module Data.ASN1.Types ( -- * Raw types ASN1Class(..) , ASN1Tag , ASN1Length(..) , ASN1Header(..) -- * Errors types , ASN1Error(..) -- * Events types , ASN1Event(..) ) where import Control.Exception (Exception) import Data.Typeable import Data.ByteString (ByteString) -- | Element class data ASN1Class = Universal | Application | Context | Private deriving (Show,Eq,Ord,Enum) -- | ASN1 Tag type ASN1Tag = Int -- | ASN1 Length with all different formats data ASN1Length = LenShort Int -- ^ Short form with only one byte. length has to be < 127. | LenLong Int Int -- ^ Long form of N bytes | LenIndefinite -- ^ Length is indefinite expect an EOC in the stream to finish the type deriving (Show,Eq) -- | ASN1 Header with the class, tag, constructed flag and length. data ASN1Header = ASN1Header !ASN1Class !ASN1Tag !Bool !ASN1Length deriving (Show,Eq) -- | represent one event from an asn1 data stream data ASN1Event = Header ASN1Header -- ^ ASN1 Header | Primitive !ByteString -- ^ Primitive | ConstructionBegin -- ^ Constructed value start | ConstructionEnd -- ^ Constructed value end deriving (Show,Eq) -- | Possible errors during parsing operations data ASN1Error = StreamUnexpectedEOC -- ^ Unexpected EOC in the stream. | StreamInfinitePrimitive -- ^ Invalid primitive with infinite length in a stream. | StreamConstructionWrongSize -- ^ A construction goes over the size specified in the header. | StreamUnexpectedSituation String -- ^ An unexpected situation has come up parsing an ASN1 event stream. | ParsingHeaderFail String -- ^ Parsing an invalid header. | ParsingPartial -- ^ Parsing is not finished, there is construction unended. | TypeNotImplemented String -- ^ Decoding of a type that is not implemented. Contribution welcome. | TypeDecodingFailed String -- ^ Decoding of a knowed type failed. | PolicyFailed String String -- ^ Policy failed including the name of the policy and the reason. deriving (Typeable, Show, Eq) instance Exception ASN1Error
mboes/hs-asn1
data/Data/ASN1/Types.hs
Haskell
bsd-3-clause
2,624
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP #-} module VarSet ( -- * Var, Id and TyVar set types VarSet, IdSet, TyVarSet, CoVarSet, TyCoVarSet, -- ** Manipulating these sets emptyVarSet, unitVarSet, mkVarSet, extendVarSet, extendVarSetList, extendVarSet_C, elemVarSet, varSetElems, subVarSet, unionVarSet, unionVarSets, mapUnionVarSet, intersectVarSet, intersectsVarSet, disjointVarSet, isEmptyVarSet, delVarSet, delVarSetList, delVarSetByKey, minusVarSet, foldVarSet, filterVarSet, transCloVarSet, fixVarSet, lookupVarSet, lookupVarSetByName, mapVarSet, sizeVarSet, seqVarSet, elemVarSetByKey, partitionVarSet, -- * Deterministic Var set types DVarSet, DIdSet, DTyVarSet, DTyCoVarSet, -- ** Manipulating these sets emptyDVarSet, unitDVarSet, mkDVarSet, extendDVarSet, extendDVarSetList, elemDVarSet, dVarSetElems, subDVarSet, unionDVarSet, unionDVarSets, mapUnionDVarSet, intersectDVarSet, intersectsDVarSet, disjointDVarSet, isEmptyDVarSet, delDVarSet, delDVarSetList, minusDVarSet, foldDVarSet, filterDVarSet, transCloDVarSet, sizeDVarSet, seqDVarSet, partitionDVarSet, ) where #include "HsVersions.h" import Var ( Var, TyVar, CoVar, TyCoVar, Id ) import Unique import Name ( Name ) import UniqSet import UniqDSet import UniqFM( disjointUFM ) import UniqDFM( disjointUDFM ) -- | A non-deterministic set of variables. -- See Note [Deterministic UniqFM] in UniqDFM for explanation why it's not -- deterministic and why it matters. Use DVarSet if the set eventually -- gets converted into a list or folded over in a way where the order -- changes the generated code, for example when abstracting variables. type VarSet = UniqSet Var type IdSet = UniqSet Id type TyVarSet = UniqSet TyVar type CoVarSet = UniqSet CoVar type TyCoVarSet = UniqSet TyCoVar emptyVarSet :: VarSet intersectVarSet :: VarSet -> VarSet -> VarSet unionVarSet :: VarSet -> VarSet -> VarSet unionVarSets :: [VarSet] -> VarSet mapUnionVarSet :: (a -> VarSet) -> [a] -> VarSet -- ^ map the function over the list, and union the results varSetElems :: VarSet -> [Var] unitVarSet :: Var -> VarSet extendVarSet :: VarSet -> Var -> VarSet extendVarSetList:: VarSet -> [Var] -> VarSet elemVarSet :: Var -> VarSet -> Bool delVarSet :: VarSet -> Var -> VarSet delVarSetList :: VarSet -> [Var] -> VarSet minusVarSet :: VarSet -> VarSet -> VarSet isEmptyVarSet :: VarSet -> Bool mkVarSet :: [Var] -> VarSet foldVarSet :: (Var -> a -> a) -> a -> VarSet -> a lookupVarSet :: VarSet -> Var -> Maybe Var -- Returns the set element, which may be -- (==) to the argument, but not the same as lookupVarSetByName :: VarSet -> Name -> Maybe Var mapVarSet :: (Var -> Var) -> VarSet -> VarSet sizeVarSet :: VarSet -> Int filterVarSet :: (Var -> Bool) -> VarSet -> VarSet extendVarSet_C :: (Var->Var->Var) -> VarSet -> Var -> VarSet delVarSetByKey :: VarSet -> Unique -> VarSet elemVarSetByKey :: Unique -> VarSet -> Bool partitionVarSet :: (Var -> Bool) -> VarSet -> (VarSet, VarSet) emptyVarSet = emptyUniqSet unitVarSet = unitUniqSet extendVarSet = addOneToUniqSet extendVarSetList= addListToUniqSet intersectVarSet = intersectUniqSets intersectsVarSet:: VarSet -> VarSet -> Bool -- True if non-empty intersection disjointVarSet :: VarSet -> VarSet -> Bool -- True if empty intersection subVarSet :: VarSet -> VarSet -> Bool -- True if first arg is subset of second -- (s1 `intersectsVarSet` s2) doesn't compute s2 if s1 is empty; -- ditto disjointVarSet, subVarSet unionVarSet = unionUniqSets unionVarSets = unionManyUniqSets varSetElems = uniqSetToList elemVarSet = elementOfUniqSet minusVarSet = minusUniqSet delVarSet = delOneFromUniqSet delVarSetList = delListFromUniqSet isEmptyVarSet = isEmptyUniqSet mkVarSet = mkUniqSet foldVarSet = foldUniqSet lookupVarSet = lookupUniqSet lookupVarSetByName = lookupUniqSet mapVarSet = mapUniqSet sizeVarSet = sizeUniqSet filterVarSet = filterUniqSet extendVarSet_C = addOneToUniqSet_C delVarSetByKey = delOneFromUniqSet_Directly elemVarSetByKey = elemUniqSet_Directly partitionVarSet = partitionUniqSet mapUnionVarSet get_set xs = foldr (unionVarSet . get_set) emptyVarSet xs -- See comments with type signatures intersectsVarSet s1 s2 = not (s1 `disjointVarSet` s2) disjointVarSet s1 s2 = disjointUFM s1 s2 subVarSet s1 s2 = isEmptyVarSet (s1 `minusVarSet` s2) fixVarSet :: (VarSet -> VarSet) -- Map the current set to a new set -> VarSet -> VarSet -- (fixVarSet f s) repeatedly applies f to the set s, -- until it reaches a fixed point. fixVarSet fn vars | new_vars `subVarSet` vars = vars | otherwise = fixVarSet fn new_vars where new_vars = fn vars transCloVarSet :: (VarSet -> VarSet) -- Map some variables in the set to -- extra variables that should be in it -> VarSet -> VarSet -- (transCloVarSet f s) repeatedly applies f to new candidates, adding any -- new variables to s that it finds thereby, until it reaches a fixed point. -- -- The function fn could be (Var -> VarSet), but we use (VarSet -> VarSet) -- for efficiency, so that the test can be batched up. -- It's essential that fn will work fine if given new candidates -- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2 -- Use fixVarSet if the function needs to see the whole set all at once transCloVarSet fn seeds = go seeds seeds where go :: VarSet -- Accumulating result -> VarSet -- Work-list; un-processed subset of accumulating result -> VarSet -- Specification: go acc vs = acc `union` transClo fn vs go acc candidates | isEmptyVarSet new_vs = acc | otherwise = go (acc `unionVarSet` new_vs) new_vs where new_vs = fn candidates `minusVarSet` acc seqVarSet :: VarSet -> () seqVarSet s = sizeVarSet s `seq` () -- Deterministic VarSet -- See Note [Deterministic UniqFM] in UniqDFM for explanation why we need -- DVarSet. type DVarSet = UniqDSet Var type DIdSet = UniqDSet Id type DTyVarSet = UniqDSet TyVar type DTyCoVarSet = UniqDSet TyCoVar emptyDVarSet :: DVarSet emptyDVarSet = emptyUniqDSet unitDVarSet :: Var -> DVarSet unitDVarSet = unitUniqDSet mkDVarSet :: [Var] -> DVarSet mkDVarSet = mkUniqDSet extendDVarSet :: DVarSet -> Var -> DVarSet extendDVarSet = addOneToUniqDSet elemDVarSet :: Var -> DVarSet -> Bool elemDVarSet = elementOfUniqDSet dVarSetElems :: DVarSet -> [Var] dVarSetElems = uniqDSetToList subDVarSet :: DVarSet -> DVarSet -> Bool subDVarSet s1 s2 = isEmptyDVarSet (s1 `minusDVarSet` s2) unionDVarSet :: DVarSet -> DVarSet -> DVarSet unionDVarSet = unionUniqDSets unionDVarSets :: [DVarSet] -> DVarSet unionDVarSets = unionManyUniqDSets -- | Map the function over the list, and union the results mapUnionDVarSet :: (a -> DVarSet) -> [a] -> DVarSet mapUnionDVarSet get_set xs = foldr (unionDVarSet . get_set) emptyDVarSet xs intersectDVarSet :: DVarSet -> DVarSet -> DVarSet intersectDVarSet = intersectUniqDSets -- | True if empty intersection disjointDVarSet :: DVarSet -> DVarSet -> Bool disjointDVarSet s1 s2 = disjointUDFM s1 s2 -- | True if non-empty intersection intersectsDVarSet :: DVarSet -> DVarSet -> Bool intersectsDVarSet s1 s2 = not (s1 `disjointDVarSet` s2) isEmptyDVarSet :: DVarSet -> Bool isEmptyDVarSet = isEmptyUniqDSet delDVarSet :: DVarSet -> Var -> DVarSet delDVarSet = delOneFromUniqDSet minusDVarSet :: DVarSet -> DVarSet -> DVarSet minusDVarSet = minusUniqDSet foldDVarSet :: (Var -> a -> a) -> a -> DVarSet -> a foldDVarSet = foldUniqDSet filterDVarSet :: (Var -> Bool) -> DVarSet -> DVarSet filterDVarSet = filterUniqDSet sizeDVarSet :: DVarSet -> Int sizeDVarSet = sizeUniqDSet -- | Partition DVarSet according to the predicate given partitionDVarSet :: (Var -> Bool) -> DVarSet -> (DVarSet, DVarSet) partitionDVarSet = partitionUniqDSet -- | Delete a list of variables from DVarSet delDVarSetList :: DVarSet -> [Var] -> DVarSet delDVarSetList = delListFromUniqDSet seqDVarSet :: DVarSet -> () seqDVarSet s = sizeDVarSet s `seq` () -- | Add a list of variables to DVarSet extendDVarSetList :: DVarSet -> [Var] -> DVarSet extendDVarSetList = addListToUniqDSet -- | transCloVarSet for DVarSet transCloDVarSet :: (DVarSet -> DVarSet) -- Map some variables in the set to -- extra variables that should be in it -> DVarSet -> DVarSet -- (transCloDVarSet f s) repeatedly applies f to new candidates, adding any -- new variables to s that it finds thereby, until it reaches a fixed point. -- -- The function fn could be (Var -> DVarSet), but we use (DVarSet -> DVarSet) -- for efficiency, so that the test can be batched up. -- It's essential that fn will work fine if given new candidates -- one at at time; ie fn {v1,v2} = fn v1 `union` fn v2 transCloDVarSet fn seeds = go seeds seeds where go :: DVarSet -- Accumulating result -> DVarSet -- Work-list; un-processed subset of accumulating result -> DVarSet -- Specification: go acc vs = acc `union` transClo fn vs go acc candidates | isEmptyDVarSet new_vs = acc | otherwise = go (acc `unionDVarSet` new_vs) new_vs where new_vs = fn candidates `minusDVarSet` acc
oldmanmike/ghc
compiler/basicTypes/VarSet.hs
Haskell
bsd-3-clause
9,744
module Turbinado.Database.ORM.Types where import qualified Data.Map as M import Database.HDBC type TypeName = String -- -- * Types for the Table descriptions -- type Tables = M.Map TableName (Columns, PrimaryKey) type TableName = String type Columns = M.Map ColumnName ColumnDesc type ColumnName = String type PrimaryKey = [ColumnName] type ColumnDesc = (SqlColDesc, ForeignKeyReferences, HasDefault) type HasDefault = Bool type ForeignKeyReferences = [(TableName, ColumnName)] -- all columns which are targets of foreign keys
alsonkemp/turbinado-website
Turbinado/Database/ORM/Types.hs
Haskell
bsd-3-clause
532
{-# OPTIONS -fglasgow-exts #-} module BinaryDerive where import Data.Generics import Data.List deriveM :: (Typeable a, Data a) => a -> IO () deriveM (a :: a) = mapM_ putStrLn . lines $ derive (undefined :: a) derive :: (Typeable a, Data a) => a -> String derive x = "instance " ++ context ++ "Binary " ++ inst ++ " where\n" ++ concat putDefs ++ getDefs where context | nTypeChildren > 0 = wrap (join ", " (map ("Binary "++) typeLetters)) ++ " => " | otherwise = "" inst = wrap $ tyConString typeName ++ concatMap (" "++) typeLetters wrap x = if nTypeChildren > 0 then "("++x++")" else x join sep lst = concat $ intersperse sep lst nTypeChildren = length typeChildren typeLetters = take nTypeChildren manyLetters manyLetters = map (:[]) ['a'..'z'] (typeName,typeChildren) = splitTyConApp (typeOf x) constrs :: [(Int, (String, Int))] constrs = zip [0..] $ map gen $ dataTypeConstrs (dataTypeOf x) gen con = ( showConstr con , length $ gmapQ undefined $ fromConstr con `asTypeOf` x ) putDefs = map ((++"\n") . putDef) constrs putDef (n, (name, ps)) = let wrap = if ps /= 0 then ("("++) . (++")") else id pattern = name ++ concatMap (' ':) (take ps manyLetters) in " put " ++ wrap pattern ++" = " ++ concat [ "putWord8 " ++ show n | length constrs > 1 ] ++ concat [ " >> " | length constrs > 1 && ps > 0 ] ++ concat [ "return ()" | length constrs == 1 && ps == 0 ] ++ join " >> " (map ("put "++) (take ps manyLetters)) getDefs = (if length constrs > 1 then " get = do\n tag_ <- getWord8\n case tag_ of\n" else " get =") ++ concatMap ((++"\n")) (map getDef constrs) ++ (if length constrs > 1 then " _ -> fail \"no parse\"" else "" ) getDef (n, (name, ps)) = let wrap = if ps /= 0 then ("("++) . (++")") else id in concat [ " " ++ show n ++ " ->" | length constrs > 1 ] ++ concatMap (\x -> " get >>= \\"++x++" ->") (take ps manyLetters) ++ " return " ++ wrap (name ++ concatMap (" "++) (take ps manyLetters))
beni55/binary
tools/derive/BinaryDerive.hs
Haskell
bsd-3-clause
2,264
<?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="it-IT"> <title>Alert Filters | 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>
kingthorin/zap-extensions
addOns/alertFilters/src/main/javahelp/org/zaproxy/zap/extension/alertFilters/resources/help_it_IT/helpset_it_IT.hs
Haskell
apache-2.0
974
{-# LANGUAGE CPP, GADTs #-} ----------------------------------------------------------------------------- -- -- Generating machine code (instruction selection) -- -- (c) The University of Glasgow 1996-2004 -- ----------------------------------------------------------------------------- -- This is a big module, but, if you pay attention to -- (a) the sectioning, (b) the type signatures, and -- (c) the #if blah_TARGET_ARCH} things, the -- structure should not be too overwhelming. module PPC.CodeGen ( cmmTopCodeGen, generateJumpTableForInstr, InstrBlock ) where #include "HsVersions.h" #include "nativeGen/NCG.h" #include "../includes/MachDeps.h" -- NCG stuff: import CodeGen.Platform import PPC.Instr import PPC.Cond import PPC.Regs import CPrim import NCGMonad import Instruction import PIC import Format import RegClass import Reg import TargetReg import Platform -- Our intermediate code: import BlockId import PprCmm ( pprExpr ) import Cmm import CmmUtils import CmmSwitch import CLabel import Hoopl -- The rest: import OrdList import Outputable import Unique import DynFlags import Control.Monad ( mapAndUnzipM, when ) import Data.Bits import Data.Word import BasicTypes import FastString import Util -- ----------------------------------------------------------------------------- -- Top-level of the instruction selector -- | 'InstrBlock's are the insn sequences generated by the insn selectors. -- They are really trees of insns to facilitate fast appending, where a -- left-to-right traversal (pre-order?) yields the insns in the correct -- order. cmmTopCodeGen :: RawCmmDecl -> NatM [NatCmmDecl CmmStatics Instr] cmmTopCodeGen (CmmProc info lab live graph) = do let blocks = toBlockListEntryFirst graph (nat_blocks,statics) <- mapAndUnzipM basicBlockCodeGen blocks dflags <- getDynFlags let proc = CmmProc info lab live (ListGraph $ concat nat_blocks) tops = proc : concat statics os = platformOS $ targetPlatform dflags arch = platformArch $ targetPlatform dflags case arch of ArchPPC -> do picBaseMb <- getPicBaseMaybeNat case picBaseMb of Just picBase -> initializePicBase_ppc arch os picBase tops Nothing -> return tops ArchPPC_64 ELF_V1 -> return tops -- generating function descriptor is handled in -- pretty printer ArchPPC_64 ELF_V2 -> return tops -- generating function prologue is handled in -- pretty printer _ -> panic "PPC.cmmTopCodeGen: unknown arch" cmmTopCodeGen (CmmData sec dat) = do return [CmmData sec dat] -- no translation, we just use CmmStatic basicBlockCodeGen :: Block CmmNode C C -> NatM ( [NatBasicBlock Instr] , [NatCmmDecl CmmStatics Instr]) basicBlockCodeGen block = do let (_, nodes, tail) = blockSplit block id = entryLabel block stmts = blockToList nodes mid_instrs <- stmtsToInstrs stmts tail_instrs <- stmtToInstrs tail let instrs = mid_instrs `appOL` tail_instrs -- code generation may introduce new basic block boundaries, which -- are indicated by the NEWBLOCK instruction. We must split up the -- instruction stream into basic blocks again. Also, we extract -- LDATAs here too. let (top,other_blocks,statics) = foldrOL mkBlocks ([],[],[]) instrs mkBlocks (NEWBLOCK id) (instrs,blocks,statics) = ([], BasicBlock id instrs : blocks, statics) mkBlocks (LDATA sec dat) (instrs,blocks,statics) = (instrs, blocks, CmmData sec dat:statics) mkBlocks instr (instrs,blocks,statics) = (instr:instrs, blocks, statics) return (BasicBlock id top : other_blocks, statics) stmtsToInstrs :: [CmmNode e x] -> NatM InstrBlock stmtsToInstrs stmts = do instrss <- mapM stmtToInstrs stmts return (concatOL instrss) stmtToInstrs :: CmmNode e x -> NatM InstrBlock stmtToInstrs stmt = do dflags <- getDynFlags case stmt of CmmComment s -> return (unitOL (COMMENT s)) CmmTick {} -> return nilOL CmmUnwind {} -> return nilOL CmmAssign reg src | isFloatType ty -> assignReg_FltCode format reg src | target32Bit (targetPlatform dflags) && isWord64 ty -> assignReg_I64Code reg src | otherwise -> assignReg_IntCode format reg src where ty = cmmRegType dflags reg format = cmmTypeFormat ty CmmStore addr src | isFloatType ty -> assignMem_FltCode format addr src | target32Bit (targetPlatform dflags) && isWord64 ty -> assignMem_I64Code addr src | otherwise -> assignMem_IntCode format addr src where ty = cmmExprType dflags src format = cmmTypeFormat ty CmmUnsafeForeignCall target result_regs args -> genCCall target result_regs args CmmBranch id -> genBranch id CmmCondBranch arg true false _ -> do b1 <- genCondJump true arg b2 <- genBranch false return (b1 `appOL` b2) CmmSwitch arg ids -> do dflags <- getDynFlags genSwitch dflags arg ids CmmCall { cml_target = arg } -> genJump arg _ -> panic "stmtToInstrs: statement should have been cps'd away" -------------------------------------------------------------------------------- -- | 'InstrBlock's are the insn sequences generated by the insn selectors. -- They are really trees of insns to facilitate fast appending, where a -- left-to-right traversal yields the insns in the correct order. -- type InstrBlock = OrdList Instr -- | Register's passed up the tree. If the stix code forces the register -- to live in a pre-decided machine register, it comes out as @Fixed@; -- otherwise, it comes out as @Any@, and the parent can decide which -- register to put it in. -- data Register = Fixed Format Reg InstrBlock | Any Format (Reg -> InstrBlock) swizzleRegisterRep :: Register -> Format -> Register swizzleRegisterRep (Fixed _ reg code) format = Fixed format reg code swizzleRegisterRep (Any _ codefn) format = Any format codefn -- | Grab the Reg for a CmmReg getRegisterReg :: Platform -> CmmReg -> Reg getRegisterReg _ (CmmLocal (LocalReg u pk)) = RegVirtual $ mkVirtualReg u (cmmTypeFormat pk) getRegisterReg platform (CmmGlobal mid) = case globalRegMaybe platform mid of Just reg -> RegReal reg Nothing -> pprPanic "getRegisterReg-memory" (ppr $ CmmGlobal mid) -- By this stage, the only MagicIds remaining should be the -- ones which map to a real machine register on this -- platform. Hence ... -- | Convert a BlockId to some CmmStatic data jumpTableEntry :: DynFlags -> Maybe BlockId -> CmmStatic jumpTableEntry dflags Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags)) jumpTableEntry _ (Just blockid) = CmmStaticLit (CmmLabel blockLabel) where blockLabel = mkAsmTempLabel (getUnique blockid) -- ----------------------------------------------------------------------------- -- General things for putting together code sequences -- Expand CmmRegOff. ToDo: should we do it this way around, or convert -- CmmExprs into CmmRegOff? mangleIndexTree :: DynFlags -> CmmExpr -> CmmExpr mangleIndexTree dflags (CmmRegOff reg off) = CmmMachOp (MO_Add width) [CmmReg reg, CmmLit (CmmInt (fromIntegral off) width)] where width = typeWidth (cmmRegType dflags reg) mangleIndexTree _ _ = panic "PPC.CodeGen.mangleIndexTree: no match" -- ----------------------------------------------------------------------------- -- Code gen for 64-bit arithmetic on 32-bit platforms {- Simple support for generating 64-bit code (ie, 64 bit values and 64 bit assignments) on 32-bit platforms. Unlike the main code generator we merely shoot for generating working code as simply as possible, and pay little attention to code quality. Specifically, there is no attempt to deal cleverly with the fixed-vs-floating register distinction; all values are generated into (pairs of) floating registers, even if this would mean some redundant reg-reg moves as a result. Only one of the VRegUniques is returned, since it will be of the VRegUniqueLo form, and the upper-half VReg can be determined by applying getHiVRegFromLo to it. -} data ChildCode64 -- a.k.a "Register64" = ChildCode64 InstrBlock -- code Reg -- the lower 32-bit temporary which contains the -- result; use getHiVRegFromLo to find the other -- VRegUnique. Rules of this simplified insn -- selection game are therefore that the returned -- Reg may be modified -- | Compute an expression into a register, but -- we don't mind which one it is. getSomeReg :: CmmExpr -> NatM (Reg, InstrBlock) getSomeReg expr = do r <- getRegister expr case r of Any rep code -> do tmp <- getNewRegNat rep return (tmp, code tmp) Fixed _ reg code -> return (reg, code) getI64Amodes :: CmmExpr -> NatM (AddrMode, AddrMode, InstrBlock) getI64Amodes addrTree = do Amode hi_addr addr_code <- getAmode D addrTree case addrOffset hi_addr 4 of Just lo_addr -> return (hi_addr, lo_addr, addr_code) Nothing -> do (hi_ptr, code) <- getSomeReg addrTree return (AddrRegImm hi_ptr (ImmInt 0), AddrRegImm hi_ptr (ImmInt 4), code) assignMem_I64Code :: CmmExpr -> CmmExpr -> NatM InstrBlock assignMem_I64Code addrTree valueTree = do (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree ChildCode64 vcode rlo <- iselExpr64 valueTree let rhi = getHiVRegFromLo rlo -- Big-endian store mov_hi = ST II32 rhi hi_addr mov_lo = ST II32 rlo lo_addr return (vcode `appOL` addr_code `snocOL` mov_lo `snocOL` mov_hi) assignReg_I64Code :: CmmReg -> CmmExpr -> NatM InstrBlock assignReg_I64Code (CmmLocal (LocalReg u_dst _)) valueTree = do ChildCode64 vcode r_src_lo <- iselExpr64 valueTree let r_dst_lo = RegVirtual $ mkVirtualReg u_dst II32 r_dst_hi = getHiVRegFromLo r_dst_lo r_src_hi = getHiVRegFromLo r_src_lo mov_lo = MR r_dst_lo r_src_lo mov_hi = MR r_dst_hi r_src_hi return ( vcode `snocOL` mov_lo `snocOL` mov_hi ) assignReg_I64Code _ _ = panic "assignReg_I64Code(powerpc): invalid lvalue" iselExpr64 :: CmmExpr -> NatM ChildCode64 iselExpr64 (CmmLoad addrTree ty) | isWord64 ty = do (hi_addr, lo_addr, addr_code) <- getI64Amodes addrTree (rlo, rhi) <- getNewRegPairNat II32 let mov_hi = LD II32 rhi hi_addr mov_lo = LD II32 rlo lo_addr return $ ChildCode64 (addr_code `snocOL` mov_lo `snocOL` mov_hi) rlo iselExpr64 (CmmReg (CmmLocal (LocalReg vu ty))) | isWord64 ty = return (ChildCode64 nilOL (RegVirtual $ mkVirtualReg vu II32)) iselExpr64 (CmmLit (CmmInt i _)) = do (rlo,rhi) <- getNewRegPairNat II32 let half0 = fromIntegral (fromIntegral i :: Word16) half1 = fromIntegral (fromIntegral (i `shiftR` 16) :: Word16) half2 = fromIntegral (fromIntegral (i `shiftR` 32) :: Word16) half3 = fromIntegral (fromIntegral (i `shiftR` 48) :: Word16) code = toOL [ LIS rlo (ImmInt half1), OR rlo rlo (RIImm $ ImmInt half0), LIS rhi (ImmInt half3), OR rhi rhi (RIImm $ ImmInt half2) ] return (ChildCode64 code rlo) iselExpr64 (CmmMachOp (MO_Add _) [e1,e2]) = do ChildCode64 code1 r1lo <- iselExpr64 e1 ChildCode64 code2 r2lo <- iselExpr64 e2 (rlo,rhi) <- getNewRegPairNat II32 let r1hi = getHiVRegFromLo r1lo r2hi = getHiVRegFromLo r2lo code = code1 `appOL` code2 `appOL` toOL [ ADDC rlo r1lo r2lo, ADDE rhi r1hi r2hi ] return (ChildCode64 code rlo) iselExpr64 (CmmMachOp (MO_Sub _) [e1,e2]) = do ChildCode64 code1 r1lo <- iselExpr64 e1 ChildCode64 code2 r2lo <- iselExpr64 e2 (rlo,rhi) <- getNewRegPairNat II32 let r1hi = getHiVRegFromLo r1lo r2hi = getHiVRegFromLo r2lo code = code1 `appOL` code2 `appOL` toOL [ SUBFC rlo r2lo r1lo, SUBFE rhi r2hi r1hi ] return (ChildCode64 code rlo) iselExpr64 (CmmMachOp (MO_UU_Conv W32 W64) [expr]) = do (expr_reg,expr_code) <- getSomeReg expr (rlo, rhi) <- getNewRegPairNat II32 let mov_hi = LI rhi (ImmInt 0) mov_lo = MR rlo expr_reg return $ ChildCode64 (expr_code `snocOL` mov_lo `snocOL` mov_hi) rlo iselExpr64 expr = pprPanic "iselExpr64(powerpc)" (pprExpr expr) getRegister :: CmmExpr -> NatM Register getRegister e = do dflags <- getDynFlags getRegister' dflags e getRegister' :: DynFlags -> CmmExpr -> NatM Register getRegister' dflags (CmmReg (CmmGlobal PicBaseReg)) | target32Bit (targetPlatform dflags) = do reg <- getPicBaseNat $ archWordFormat (target32Bit (targetPlatform dflags)) return (Fixed (archWordFormat (target32Bit (targetPlatform dflags))) reg nilOL) | otherwise = return (Fixed II64 toc nilOL) getRegister' dflags (CmmReg reg) = return (Fixed (cmmTypeFormat (cmmRegType dflags reg)) (getRegisterReg (targetPlatform dflags) reg) nilOL) getRegister' dflags tree@(CmmRegOff _ _) = getRegister' dflags (mangleIndexTree dflags tree) -- for 32-bit architectuers, support some 64 -> 32 bit conversions: -- TO_W_(x), TO_W_(x >> 32) getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 (getHiVRegFromLo rlo) code getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [CmmMachOp (MO_U_Shr W64) [x,CmmLit (CmmInt 32 _)]]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 (getHiVRegFromLo rlo) code getRegister' dflags (CmmMachOp (MO_UU_Conv W64 W32) [x]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 rlo code getRegister' dflags (CmmMachOp (MO_SS_Conv W64 W32) [x]) | target32Bit (targetPlatform dflags) = do ChildCode64 code rlo <- iselExpr64 x return $ Fixed II32 rlo code getRegister' dflags (CmmLoad mem pk) | not (isWord64 pk) = do let platform = targetPlatform dflags Amode addr addr_code <- getAmode D mem let code dst = ASSERT((targetClassOfReg platform dst == RcDouble) == isFloatType pk) addr_code `snocOL` LD format dst addr return (Any format code) | not (target32Bit (targetPlatform dflags)) = do Amode addr addr_code <- getAmode DS mem let code dst = addr_code `snocOL` LD II64 dst addr return (Any II64 code) where format = cmmTypeFormat pk -- catch simple cases of zero- or sign-extended load getRegister' _ (CmmMachOp (MO_UU_Conv W8 W32) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II32 (\dst -> addr_code `snocOL` LD II8 dst addr)) getRegister' _ (CmmMachOp (MO_UU_Conv W8 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LD II8 dst addr)) -- Note: there is no Load Byte Arithmetic instruction, so no signed case here getRegister' _ (CmmMachOp (MO_UU_Conv W16 W32) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II32 (\dst -> addr_code `snocOL` LD II16 dst addr)) getRegister' _ (CmmMachOp (MO_SS_Conv W16 W32) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II32 (\dst -> addr_code `snocOL` LA II16 dst addr)) getRegister' _ (CmmMachOp (MO_UU_Conv W16 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LD II16 dst addr)) getRegister' _ (CmmMachOp (MO_SS_Conv W16 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LA II16 dst addr)) getRegister' _ (CmmMachOp (MO_UU_Conv W32 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LD II32 dst addr)) getRegister' _ (CmmMachOp (MO_SS_Conv W32 W64) [CmmLoad mem _]) = do Amode addr addr_code <- getAmode D mem return (Any II64 (\dst -> addr_code `snocOL` LA II32 dst addr)) getRegister' dflags (CmmMachOp mop [x]) -- unary MachOps = case mop of MO_Not rep -> triv_ucode_int rep NOT MO_F_Neg w -> triv_ucode_float w FNEG MO_S_Neg w -> triv_ucode_int w NEG MO_FF_Conv W64 W32 -> trivialUCode FF32 FRSP x MO_FF_Conv W32 W64 -> conversionNop FF64 x MO_FS_Conv from to -> coerceFP2Int from to x MO_SF_Conv from to -> coerceInt2FP from to x MO_SS_Conv from to | from == to -> conversionNop (intFormat to) x -- narrowing is a nop: we treat the high bits as undefined MO_SS_Conv W64 to | arch32 -> panic "PPC.CodeGen.getRegister no 64 bit int register" | otherwise -> conversionNop (intFormat to) x MO_SS_Conv W32 to | arch32 -> conversionNop (intFormat to) x | otherwise -> case to of W64 -> triv_ucode_int to (EXTS II32) W16 -> conversionNop II16 x W8 -> conversionNop II8 x _ -> panic "PPC.CodeGen.getRegister: no match" MO_SS_Conv W16 W8 -> conversionNop II8 x MO_SS_Conv W8 to -> triv_ucode_int to (EXTS II8) MO_SS_Conv W16 to -> triv_ucode_int to (EXTS II16) MO_UU_Conv from to | from == to -> conversionNop (intFormat to) x -- narrowing is a nop: we treat the high bits as undefined MO_UU_Conv W64 to | arch32 -> panic "PPC.CodeGen.getRegister no 64 bit target" | otherwise -> conversionNop (intFormat to) x MO_UU_Conv W32 to | arch32 -> conversionNop (intFormat to) x | otherwise -> case to of W64 -> trivialCode to False AND x (CmmLit (CmmInt 4294967295 W64)) W16 -> conversionNop II16 x W8 -> conversionNop II8 x _ -> panic "PPC.CodeGen.getRegister: no match" MO_UU_Conv W16 W8 -> conversionNop II8 x MO_UU_Conv W8 to -> trivialCode to False AND x (CmmLit (CmmInt 255 W32)) MO_UU_Conv W16 to -> trivialCode to False AND x (CmmLit (CmmInt 65535 W32)) _ -> panic "PPC.CodeGen.getRegister: no match" where triv_ucode_int width instr = trivialUCode (intFormat width) instr x triv_ucode_float width instr = trivialUCode (floatFormat width) instr x conversionNop new_format expr = do e_code <- getRegister' dflags expr return (swizzleRegisterRep e_code new_format) arch32 = target32Bit $ targetPlatform dflags getRegister' dflags (CmmMachOp mop [x, y]) -- dyadic PrimOps = case mop of MO_F_Eq _ -> condFltReg EQQ x y MO_F_Ne _ -> condFltReg NE x y MO_F_Gt _ -> condFltReg GTT x y MO_F_Ge _ -> condFltReg GE x y MO_F_Lt _ -> condFltReg LTT x y MO_F_Le _ -> condFltReg LE x y MO_Eq rep -> condIntReg EQQ (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_Ne rep -> condIntReg NE (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_S_Gt rep -> condIntReg GTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Ge rep -> condIntReg GE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Lt rep -> condIntReg LTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Le rep -> condIntReg LE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Gt rep -> condIntReg GU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_U_Ge rep -> condIntReg GEU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_U_Lt rep -> condIntReg LU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_U_Le rep -> condIntReg LEU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_F_Add w -> triv_float w FADD MO_F_Sub w -> triv_float w FSUB MO_F_Mul w -> triv_float w FMUL MO_F_Quot w -> triv_float w FDIV -- optimize addition with 32-bit immediate -- (needed for PIC) MO_Add W32 -> case y of CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate W32 True (-imm) -> trivialCode W32 True ADD x (CmmLit $ CmmInt imm immrep) CmmLit lit -> do (src, srcCode) <- getSomeReg x let imm = litToImm lit code dst = srcCode `appOL` toOL [ ADDIS dst src (HA imm), ADD dst dst (RIImm (LO imm)) ] return (Any II32 code) _ -> trivialCode W32 True ADD x y MO_Add rep -> trivialCode rep True ADD x y MO_Sub rep -> case y of -- subfi ('substract from' with immediate) doesn't exist CmmLit (CmmInt imm immrep) | Just _ <- makeImmediate rep True (-imm) -> trivialCode rep True ADD x (CmmLit $ CmmInt (-imm) immrep) _ -> trivialCodeNoImm' (intFormat rep) SUBF y x MO_Mul rep | arch32 -> trivialCode rep True MULLW x y | otherwise -> trivialCode rep True MULLD x y MO_S_MulMayOflo W32 -> trivialCodeNoImm' II32 MULLW_MayOflo x y MO_S_MulMayOflo W64 -> trivialCodeNoImm' II64 MULLD_MayOflo x y MO_S_MulMayOflo _ -> panic "S_MulMayOflo: (II8/16) not implemented" MO_U_MulMayOflo _ -> panic "U_MulMayOflo: not implemented" MO_S_Quot rep | arch32 -> trivialCodeNoImm' (intFormat rep) DIVW (extendSExpr dflags rep x) (extendSExpr dflags rep y) | otherwise -> trivialCodeNoImm' (intFormat rep) DIVD (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Quot rep | arch32 -> trivialCodeNoImm' (intFormat rep) DIVWU (extendUExpr dflags rep x) (extendUExpr dflags rep y) | otherwise -> trivialCodeNoImm' (intFormat rep) DIVDU (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_S_Rem rep | arch32 -> remainderCode rep DIVW (extendSExpr dflags rep x) (extendSExpr dflags rep y) | otherwise -> remainderCode rep DIVD (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Rem rep | arch32 -> remainderCode rep DIVWU (extendSExpr dflags rep x) (extendSExpr dflags rep y) | otherwise -> remainderCode rep DIVDU (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_And rep -> trivialCode rep False AND x y MO_Or rep -> trivialCode rep False OR x y MO_Xor rep -> trivialCode rep False XOR x y MO_Shl rep -> shiftCode rep SL x y MO_S_Shr rep -> shiftCode rep SRA (extendSExpr dflags rep x) y MO_U_Shr rep -> shiftCode rep SR (extendUExpr dflags rep x) y _ -> panic "PPC.CodeGen.getRegister: no match" where triv_float :: Width -> (Format -> Reg -> Reg -> Reg -> Instr) -> NatM Register triv_float width instr = trivialCodeNoImm (floatFormat width) instr x y arch32 = target32Bit $ targetPlatform dflags getRegister' _ (CmmLit (CmmInt i rep)) | Just imm <- makeImmediate rep True i = let code dst = unitOL (LI dst imm) in return (Any (intFormat rep) code) getRegister' _ (CmmLit (CmmFloat f frep)) = do lbl <- getNewLabelNat dflags <- getDynFlags dynRef <- cmmMakeDynamicReference dflags DataReference lbl Amode addr addr_code <- getAmode D dynRef let format = floatFormat frep code dst = LDATA (Section ReadOnlyData lbl) (Statics lbl [CmmStaticLit (CmmFloat f frep)]) `consOL` (addr_code `snocOL` LD format dst addr) return (Any format code) getRegister' dflags (CmmLit lit) | target32Bit (targetPlatform dflags) = let rep = cmmLitType dflags lit imm = litToImm lit code dst = toOL [ LIS dst (HA imm), ADD dst dst (RIImm (LO imm)) ] in return (Any (cmmTypeFormat rep) code) | otherwise = do lbl <- getNewLabelNat dflags <- getDynFlags dynRef <- cmmMakeDynamicReference dflags DataReference lbl Amode addr addr_code <- getAmode D dynRef let rep = cmmLitType dflags lit format = cmmTypeFormat rep code dst = LDATA (Section ReadOnlyData lbl) (Statics lbl [CmmStaticLit lit]) `consOL` (addr_code `snocOL` LD format dst addr) return (Any format code) getRegister' _ other = pprPanic "getRegister(ppc)" (pprExpr other) -- extend?Rep: wrap integer expression of type rep -- in a conversion to II32 or II64 resp. extendSExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr extendSExpr dflags W32 x | target32Bit (targetPlatform dflags) = x extendSExpr dflags W64 x | not (target32Bit (targetPlatform dflags)) = x extendSExpr dflags rep x = let size = if target32Bit $ targetPlatform dflags then W32 else W64 in CmmMachOp (MO_SS_Conv rep size) [x] extendUExpr :: DynFlags -> Width -> CmmExpr -> CmmExpr extendUExpr dflags W32 x | target32Bit (targetPlatform dflags) = x extendUExpr dflags W64 x | not (target32Bit (targetPlatform dflags)) = x extendUExpr dflags rep x = let size = if target32Bit $ targetPlatform dflags then W32 else W64 in CmmMachOp (MO_UU_Conv rep size) [x] -- ----------------------------------------------------------------------------- -- The 'Amode' type: Memory addressing modes passed up the tree. data Amode = Amode AddrMode InstrBlock {- Now, given a tree (the argument to an CmmLoad) that references memory, produce a suitable addressing mode. A Rule of the Game (tm) for Amodes: use of the addr bit must immediately follow use of the code part, since the code part puts values in registers which the addr then refers to. So you can't put anything in between, lest it overwrite some of those registers. If you need to do some other computation between the code part and use of the addr bit, first store the effective address from the amode in a temporary, then do the other computation, and then use the temporary: code LEA amode, tmp ... other computation ... ... (tmp) ... -} data InstrForm = D | DS getAmode :: InstrForm -> CmmExpr -> NatM Amode getAmode inf tree@(CmmRegOff _ _) = do dflags <- getDynFlags getAmode inf (mangleIndexTree dflags tree) getAmode _ (CmmMachOp (MO_Sub W32) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W32 True (-i) = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W32 True i = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode D (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True (-i) = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode D (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True i = do (reg, code) <- getSomeReg x return (Amode (AddrRegImm reg off) code) getAmode DS (CmmMachOp (MO_Sub W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True (-i) = do (reg, code) <- getSomeReg x (reg', off', code') <- if i `mod` 4 == 0 then do return (reg, off, code) else do tmp <- getNewRegNat II64 return (tmp, ImmInt 0, code `snocOL` ADD tmp reg (RIImm off)) return (Amode (AddrRegImm reg' off') code') getAmode DS (CmmMachOp (MO_Add W64) [x, CmmLit (CmmInt i _)]) | Just off <- makeImmediate W64 True i = do (reg, code) <- getSomeReg x (reg', off', code') <- if i `mod` 4 == 0 then do return (reg, off, code) else do tmp <- getNewRegNat II64 return (tmp, ImmInt 0, code `snocOL` ADD tmp reg (RIImm off)) return (Amode (AddrRegImm reg' off') code') -- optimize addition with 32-bit immediate -- (needed for PIC) getAmode _ (CmmMachOp (MO_Add W32) [x, CmmLit lit]) = do tmp <- getNewRegNat II32 (src, srcCode) <- getSomeReg x let imm = litToImm lit code = srcCode `snocOL` ADDIS tmp src (HA imm) return (Amode (AddrRegImm tmp (LO imm)) code) getAmode _ (CmmLit lit) = do dflags <- getDynFlags case platformArch $ targetPlatform dflags of ArchPPC -> do tmp <- getNewRegNat II32 let imm = litToImm lit code = unitOL (LIS tmp (HA imm)) return (Amode (AddrRegImm tmp (LO imm)) code) _ -> do -- TODO: Load from TOC, -- see getRegister' _ (CmmLit lit) tmp <- getNewRegNat II64 let imm = litToImm lit code = toOL [ LIS tmp (HIGHESTA imm), OR tmp tmp (RIImm (HIGHERA imm)), SL II64 tmp tmp (RIImm (ImmInt 32)), ORIS tmp tmp (HA imm) ] return (Amode (AddrRegImm tmp (LO imm)) code) getAmode _ (CmmMachOp (MO_Add W32) [x, y]) = do (regX, codeX) <- getSomeReg x (regY, codeY) <- getSomeReg y return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY)) getAmode _ (CmmMachOp (MO_Add W64) [x, y]) = do (regX, codeX) <- getSomeReg x (regY, codeY) <- getSomeReg y return (Amode (AddrRegReg regX regY) (codeX `appOL` codeY)) getAmode _ other = do (reg, code) <- getSomeReg other let off = ImmInt 0 return (Amode (AddrRegImm reg off) code) -- The 'CondCode' type: Condition codes passed up the tree. data CondCode = CondCode Bool Cond InstrBlock -- Set up a condition code for a conditional branch. getCondCode :: CmmExpr -> NatM CondCode -- almost the same as everywhere else - but we need to -- extend small integers to 32 bit or 64 bit first getCondCode (CmmMachOp mop [x, y]) = do dflags <- getDynFlags case mop of MO_F_Eq W32 -> condFltCode EQQ x y MO_F_Ne W32 -> condFltCode NE x y MO_F_Gt W32 -> condFltCode GTT x y MO_F_Ge W32 -> condFltCode GE x y MO_F_Lt W32 -> condFltCode LTT x y MO_F_Le W32 -> condFltCode LE x y MO_F_Eq W64 -> condFltCode EQQ x y MO_F_Ne W64 -> condFltCode NE x y MO_F_Gt W64 -> condFltCode GTT x y MO_F_Ge W64 -> condFltCode GE x y MO_F_Lt W64 -> condFltCode LTT x y MO_F_Le W64 -> condFltCode LE x y MO_Eq rep -> condIntCode EQQ (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_Ne rep -> condIntCode NE (extendUExpr dflags rep x) (extendUExpr dflags rep y) MO_S_Gt rep -> condIntCode GTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Ge rep -> condIntCode GE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Lt rep -> condIntCode LTT (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_S_Le rep -> condIntCode LE (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Gt rep -> condIntCode GU (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Ge rep -> condIntCode GEU (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Lt rep -> condIntCode LU (extendSExpr dflags rep x) (extendSExpr dflags rep y) MO_U_Le rep -> condIntCode LEU (extendSExpr dflags rep x) (extendSExpr dflags rep y) _ -> pprPanic "getCondCode(powerpc)" (pprMachOp mop) getCondCode _ = panic "getCondCode(2)(powerpc)" -- @cond(Int|Flt)Code@: Turn a boolean expression into a condition, to be -- passed back up the tree. condIntCode, condFltCode :: Cond -> CmmExpr -> CmmExpr -> NatM CondCode -- ###FIXME: I16 and I8! -- TODO: Is this still an issue? All arguments are extend?Expr'd. condIntCode cond x (CmmLit (CmmInt y rep)) | Just src2 <- makeImmediate rep (not $ condUnsigned cond) y = do (src1, code) <- getSomeReg x dflags <- getDynFlags let format = archWordFormat $ target32Bit $ targetPlatform dflags code' = code `snocOL` (if condUnsigned cond then CMPL else CMP) format src1 (RIImm src2) return (CondCode False cond code') condIntCode cond x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y dflags <- getDynFlags let format = archWordFormat $ target32Bit $ targetPlatform dflags code' = code1 `appOL` code2 `snocOL` (if condUnsigned cond then CMPL else CMP) format src1 (RIReg src2) return (CondCode False cond code') condFltCode cond x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code' = code1 `appOL` code2 `snocOL` FCMP src1 src2 code'' = case cond of -- twiddle CR to handle unordered case GE -> code' `snocOL` CRNOR ltbit eqbit gtbit LE -> code' `snocOL` CRNOR gtbit eqbit ltbit _ -> code' where ltbit = 0 ; eqbit = 2 ; gtbit = 1 return (CondCode True cond code'') -- ----------------------------------------------------------------------------- -- Generating assignments -- Assignments are really at the heart of the whole code generation -- business. Almost all top-level nodes of any real importance are -- assignments, which correspond to loads, stores, or register -- transfers. If we're really lucky, some of the register transfers -- will go away, because we can use the destination register to -- complete the code generation for the right hand side. This only -- fails when the right hand side is forced into a fixed register -- (e.g. the result of a call). assignMem_IntCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock assignReg_IntCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock assignMem_FltCode :: Format -> CmmExpr -> CmmExpr -> NatM InstrBlock assignReg_FltCode :: Format -> CmmReg -> CmmExpr -> NatM InstrBlock assignMem_IntCode pk addr src = do (srcReg, code) <- getSomeReg src Amode dstAddr addr_code <- case pk of II64 -> getAmode DS addr _ -> getAmode D addr return $ code `appOL` addr_code `snocOL` ST pk srcReg dstAddr -- dst is a reg, but src could be anything assignReg_IntCode _ reg src = do dflags <- getDynFlags let dst = getRegisterReg (targetPlatform dflags) reg r <- getRegister src return $ case r of Any _ code -> code dst Fixed _ freg fcode -> fcode `snocOL` MR dst freg -- Easy, isn't it? assignMem_FltCode = assignMem_IntCode assignReg_FltCode = assignReg_IntCode genJump :: CmmExpr{-the branch target-} -> NatM InstrBlock genJump (CmmLit (CmmLabel lbl)) = return (unitOL $ JMP lbl) genJump tree = do dflags <- getDynFlags let platform = targetPlatform dflags case platformOS platform of OSLinux -> case platformArch platform of ArchPPC -> genJump' tree GCPLinux ArchPPC_64 ELF_V1 -> genJump' tree (GCPLinux64ELF 1) ArchPPC_64 ELF_V2 -> genJump' tree (GCPLinux64ELF 2) _ -> panic "PPC.CodeGen.genJump: Unknown Linux" OSDarwin -> genJump' tree GCPDarwin _ -> panic "PPC.CodeGen.genJump: not defined for this os" genJump' :: CmmExpr -> GenCCallPlatform -> NatM InstrBlock genJump' tree (GCPLinux64ELF 1) = do (target,code) <- getSomeReg tree return (code `snocOL` LD II64 r11 (AddrRegImm target (ImmInt 0)) `snocOL` LD II64 toc (AddrRegImm target (ImmInt 8)) `snocOL` MTCTR r11 `snocOL` LD II64 r11 (AddrRegImm target (ImmInt 16)) `snocOL` BCTR [] Nothing) genJump' tree (GCPLinux64ELF 2) = do (target,code) <- getSomeReg tree return (code `snocOL` MR r12 target `snocOL` MTCTR r12 `snocOL` BCTR [] Nothing) genJump' tree _ = do (target,code) <- getSomeReg tree return (code `snocOL` MTCTR target `snocOL` BCTR [] Nothing) -- ----------------------------------------------------------------------------- -- Unconditional branches genBranch :: BlockId -> NatM InstrBlock genBranch = return . toOL . mkJumpInstr -- ----------------------------------------------------------------------------- -- Conditional jumps {- Conditional jumps are always to local labels, so we can use branch instructions. We peek at the arguments to decide what kind of comparison to do. -} genCondJump :: BlockId -- the branch target -> CmmExpr -- the condition on which to branch -> NatM InstrBlock genCondJump id bool = do CondCode _ cond code <- getCondCode bool return (code `snocOL` BCC cond id) -- ----------------------------------------------------------------------------- -- Generating C calls -- Now the biggest nightmare---calls. Most of the nastiness is buried in -- @get_arg@, which moves the arguments to the correct registers/stack -- locations. Apart from that, the code is easy. -- -- (If applicable) Do not fill the delay slots here; you will confuse the -- register allocator. genCCall :: ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock genCCall target dest_regs argsAndHints = do dflags <- getDynFlags let platform = targetPlatform dflags case platformOS platform of OSLinux -> case platformArch platform of ArchPPC -> genCCall' dflags GCPLinux target dest_regs argsAndHints ArchPPC_64 ELF_V1 -> genCCall' dflags (GCPLinux64ELF 1) target dest_regs argsAndHints ArchPPC_64 ELF_V2 -> genCCall' dflags (GCPLinux64ELF 2) target dest_regs argsAndHints _ -> panic "PPC.CodeGen.genCCall: Unknown Linux" OSDarwin -> genCCall' dflags GCPDarwin target dest_regs argsAndHints _ -> panic "PPC.CodeGen.genCCall: not defined for this os" data GenCCallPlatform = GCPLinux | GCPDarwin | GCPLinux64ELF Int genCCall' :: DynFlags -> GenCCallPlatform -> ForeignTarget -- function to call -> [CmmFormal] -- where to put the result -> [CmmActual] -- arguments (of mixed type) -> NatM InstrBlock {- The PowerPC calling convention for Darwin/Mac OS X is described in Apple's document "Inside Mac OS X - Mach-O Runtime Architecture". PowerPC Linux uses the System V Release 4 Calling Convention for PowerPC. It is described in the "System V Application Binary Interface PowerPC Processor Supplement". Both conventions are similar: Parameters may be passed in general-purpose registers starting at r3, in floating point registers starting at f1, or on the stack. But there are substantial differences: * The number of registers used for parameter passing and the exact set of nonvolatile registers differs (see MachRegs.hs). * On Darwin, stack space is always reserved for parameters, even if they are passed in registers. The called routine may choose to save parameters from registers to the corresponding space on the stack. * On Darwin, a corresponding amount of GPRs is skipped when a floating point parameter is passed in an FPR. * SysV insists on either passing I64 arguments on the stack, or in two GPRs, starting with an odd-numbered GPR. It may skip a GPR to achieve this. Darwin just treats an I64 like two separate II32s (high word first). * I64 and FF64 arguments are 8-byte aligned on the stack for SysV, but only 4-byte aligned like everything else on Darwin. * The SysV spec claims that FF32 is represented as FF64 on the stack. GCC on PowerPC Linux does not agree, so neither do we. PowerPC 64 Linux uses the System V Release 4 Calling Convention for 64-bit PowerPC. It is specified in "64-bit PowerPC ELF Application Binary Interface Supplement 1.9". According to all conventions, the parameter area should be part of the caller's stack frame, allocated in the caller's prologue code (large enough to hold the parameter lists for all called routines). The NCG already uses the stack for register spilling, leaving 64 bytes free at the top. If we need a larger parameter area than that, we just allocate a new stack frame just before ccalling. -} genCCall' _ _ (PrimTarget MO_WriteBarrier) _ _ = return $ unitOL LWSYNC genCCall' _ _ (PrimTarget MO_Touch) _ _ = return $ nilOL genCCall' _ _ (PrimTarget (MO_Prefetch_Data _)) _ _ = return $ nilOL genCCall' dflags gcp target dest_regs args = ASSERT(not $ any (`elem` [II16]) $ map cmmTypeFormat argReps) -- we rely on argument promotion in the codeGen do (finalStack,passArgumentsCode,usedRegs) <- passArguments (zip args argReps) allArgRegs (allFPArgRegs platform) initialStackOffset (toOL []) [] (labelOrExpr, reduceToFF32) <- case target of ForeignTarget (CmmLit (CmmLabel lbl)) _ -> do uses_pic_base_implicitly return (Left lbl, False) ForeignTarget expr _ -> do uses_pic_base_implicitly return (Right expr, False) PrimTarget mop -> outOfLineMachOp mop let codeBefore = move_sp_down finalStack `appOL` passArgumentsCode `appOL` toc_before codeAfter = toc_after labelOrExpr `appOL` move_sp_up finalStack `appOL` moveResult reduceToFF32 case labelOrExpr of Left lbl -> do -- the linker does all the work for us return ( codeBefore `snocOL` BL lbl usedRegs `appOL` codeAfter) Right dyn -> do -- implement call through function pointer (dynReg, dynCode) <- getSomeReg dyn case gcp of GCPLinux64ELF 1 -> return ( dynCode `appOL` codeBefore `snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 0)) `snocOL` LD II64 toc (AddrRegImm dynReg (ImmInt 8)) `snocOL` MTCTR r11 `snocOL` LD II64 r11 (AddrRegImm dynReg (ImmInt 16)) `snocOL` BCTRL usedRegs `appOL` codeAfter) GCPLinux64ELF 2 -> return ( dynCode `appOL` codeBefore `snocOL` MR r12 dynReg `snocOL` MTCTR r12 `snocOL` BCTRL usedRegs `appOL` codeAfter) _ -> return ( dynCode `snocOL` MTCTR dynReg `appOL` codeBefore `snocOL` BCTRL usedRegs `appOL` codeAfter) where platform = targetPlatform dflags uses_pic_base_implicitly = do -- See Note [implicit register in PPC PIC code] -- on why we claim to use PIC register here when (gopt Opt_PIC dflags && target32Bit platform) $ do _ <- getPicBaseNat $ archWordFormat True return () initialStackOffset = case gcp of GCPDarwin -> 24 GCPLinux -> 8 GCPLinux64ELF 1 -> 48 GCPLinux64ELF 2 -> 32 _ -> panic "genCall': unknown calling convention" -- size of linkage area + size of arguments, in bytes stackDelta finalStack = case gcp of GCPDarwin -> roundTo 16 $ (24 +) $ max 32 $ sum $ map (widthInBytes . typeWidth) argReps GCPLinux -> roundTo 16 finalStack GCPLinux64ELF 1 -> roundTo 16 $ (48 +) $ max 64 $ sum $ map (widthInBytes . typeWidth) argReps GCPLinux64ELF 2 -> roundTo 16 $ (32 +) $ max 64 $ sum $ map (widthInBytes . typeWidth) argReps _ -> panic "genCall': unknown calling conv." argReps = map (cmmExprType dflags) args roundTo a x | x `mod` a == 0 = x | otherwise = x + a - (x `mod` a) spFormat = if target32Bit platform then II32 else II64 move_sp_down finalStack | delta > 64 = toOL [STU spFormat sp (AddrRegImm sp (ImmInt (-delta))), DELTA (-delta)] | otherwise = nilOL where delta = stackDelta finalStack toc_before = case gcp of GCPLinux64ELF 1 -> unitOL $ ST spFormat toc (AddrRegImm sp (ImmInt 40)) GCPLinux64ELF 2 -> unitOL $ ST spFormat toc (AddrRegImm sp (ImmInt 24)) _ -> nilOL toc_after labelOrExpr = case gcp of GCPLinux64ELF 1 -> case labelOrExpr of Left _ -> toOL [ NOP ] Right _ -> toOL [ LD spFormat toc (AddrRegImm sp (ImmInt 40)) ] GCPLinux64ELF 2 -> case labelOrExpr of Left _ -> toOL [ NOP ] Right _ -> toOL [ LD spFormat toc (AddrRegImm sp (ImmInt 24)) ] _ -> nilOL move_sp_up finalStack | delta > 64 = -- TODO: fix-up stack back-chain toOL [ADD sp sp (RIImm (ImmInt delta)), DELTA 0] | otherwise = nilOL where delta = stackDelta finalStack passArguments [] _ _ stackOffset accumCode accumUsed = return (stackOffset, accumCode, accumUsed) passArguments ((arg,arg_ty):args) gprs fprs stackOffset accumCode accumUsed | isWord64 arg_ty && target32Bit (targetPlatform dflags) = do ChildCode64 code vr_lo <- iselExpr64 arg let vr_hi = getHiVRegFromLo vr_lo case gcp of GCPDarwin -> do let storeWord vr (gpr:_) _ = MR gpr vr storeWord vr [] offset = ST II32 vr (AddrRegImm sp (ImmInt offset)) passArguments args (drop 2 gprs) fprs (stackOffset+8) (accumCode `appOL` code `snocOL` storeWord vr_hi gprs stackOffset `snocOL` storeWord vr_lo (drop 1 gprs) (stackOffset+4)) ((take 2 gprs) ++ accumUsed) GCPLinux -> do let stackOffset' = roundTo 8 stackOffset stackCode = accumCode `appOL` code `snocOL` ST II32 vr_hi (AddrRegImm sp (ImmInt stackOffset')) `snocOL` ST II32 vr_lo (AddrRegImm sp (ImmInt (stackOffset'+4))) regCode hireg loreg = accumCode `appOL` code `snocOL` MR hireg vr_hi `snocOL` MR loreg vr_lo case gprs of hireg : loreg : regs | even (length gprs) -> passArguments args regs fprs stackOffset (regCode hireg loreg) (hireg : loreg : accumUsed) _skipped : hireg : loreg : regs -> passArguments args regs fprs stackOffset (regCode hireg loreg) (hireg : loreg : accumUsed) _ -> -- only one or no regs left passArguments args [] fprs (stackOffset'+8) stackCode accumUsed GCPLinux64ELF _ -> panic "passArguments: 32 bit code" passArguments ((arg,rep):args) gprs fprs stackOffset accumCode accumUsed | reg : _ <- regs = do register <- getRegister arg let code = case register of Fixed _ freg fcode -> fcode `snocOL` MR reg freg Any _ acode -> acode reg stackOffsetRes = case gcp of -- The Darwin ABI requires that we reserve -- stack slots for register parameters GCPDarwin -> stackOffset + stackBytes -- ... the SysV ABI 32-bit doesn't. GCPLinux -> stackOffset -- ... but SysV ABI 64-bit does. GCPLinux64ELF _ -> stackOffset + stackBytes passArguments args (drop nGprs gprs) (drop nFprs fprs) stackOffsetRes (accumCode `appOL` code) (reg : accumUsed) | otherwise = do (vr, code) <- getSomeReg arg passArguments args (drop nGprs gprs) (drop nFprs fprs) (stackOffset' + stackBytes) (accumCode `appOL` code `snocOL` ST (cmmTypeFormat rep) vr stackSlot) accumUsed where stackOffset' = case gcp of GCPDarwin -> -- stackOffset is at least 4-byte aligned -- The Darwin ABI is happy with that. stackOffset GCPLinux -- ... the SysV ABI requires 8-byte -- alignment for doubles. | isFloatType rep && typeWidth rep == W64 -> roundTo 8 stackOffset | otherwise -> stackOffset GCPLinux64ELF _ -> -- everything on the stack is 8-byte -- aligned on a 64 bit system -- (except vector status, not used now) stackOffset stackSlot = AddrRegImm sp (ImmInt stackOffset') (nGprs, nFprs, stackBytes, regs) = case gcp of GCPDarwin -> case cmmTypeFormat rep of II8 -> (1, 0, 4, gprs) II16 -> (1, 0, 4, gprs) II32 -> (1, 0, 4, gprs) -- The Darwin ABI requires that we skip a -- corresponding number of GPRs when we use -- the FPRs. FF32 -> (1, 1, 4, fprs) FF64 -> (2, 1, 8, fprs) II64 -> panic "genCCall' passArguments II64" FF80 -> panic "genCCall' passArguments FF80" GCPLinux -> case cmmTypeFormat rep of II8 -> (1, 0, 4, gprs) II16 -> (1, 0, 4, gprs) II32 -> (1, 0, 4, gprs) -- ... the SysV ABI doesn't. FF32 -> (0, 1, 4, fprs) FF64 -> (0, 1, 8, fprs) II64 -> panic "genCCall' passArguments II64" FF80 -> panic "genCCall' passArguments FF80" GCPLinux64ELF _ -> case cmmTypeFormat rep of II8 -> (1, 0, 8, gprs) II16 -> (1, 0, 8, gprs) II32 -> (1, 0, 8, gprs) II64 -> (1, 0, 8, gprs) -- The ELFv1 ABI requires that we skip a -- corresponding number of GPRs when we use -- the FPRs. FF32 -> (1, 1, 8, fprs) FF64 -> (1, 1, 8, fprs) FF80 -> panic "genCCall' passArguments FF80" moveResult reduceToFF32 = case dest_regs of [] -> nilOL [dest] | reduceToFF32 && isFloat32 rep -> unitOL (FRSP r_dest f1) | isFloat32 rep || isFloat64 rep -> unitOL (MR r_dest f1) | isWord64 rep && target32Bit (targetPlatform dflags) -> toOL [MR (getHiVRegFromLo r_dest) r3, MR r_dest r4] | otherwise -> unitOL (MR r_dest r3) where rep = cmmRegType dflags (CmmLocal dest) r_dest = getRegisterReg platform (CmmLocal dest) _ -> panic "genCCall' moveResult: Bad dest_regs" outOfLineMachOp mop = do dflags <- getDynFlags mopExpr <- cmmMakeDynamicReference dflags CallReference $ mkForeignLabel functionName Nothing ForeignLabelInThisPackage IsFunction let mopLabelOrExpr = case mopExpr of CmmLit (CmmLabel lbl) -> Left lbl _ -> Right mopExpr return (mopLabelOrExpr, reduce) where (functionName, reduce) = case mop of MO_F32_Exp -> (fsLit "exp", True) MO_F32_Log -> (fsLit "log", True) MO_F32_Sqrt -> (fsLit "sqrt", True) MO_F32_Sin -> (fsLit "sin", True) MO_F32_Cos -> (fsLit "cos", True) MO_F32_Tan -> (fsLit "tan", True) MO_F32_Asin -> (fsLit "asin", True) MO_F32_Acos -> (fsLit "acos", True) MO_F32_Atan -> (fsLit "atan", True) MO_F32_Sinh -> (fsLit "sinh", True) MO_F32_Cosh -> (fsLit "cosh", True) MO_F32_Tanh -> (fsLit "tanh", True) MO_F32_Pwr -> (fsLit "pow", True) MO_F64_Exp -> (fsLit "exp", False) MO_F64_Log -> (fsLit "log", False) MO_F64_Sqrt -> (fsLit "sqrt", False) MO_F64_Sin -> (fsLit "sin", False) MO_F64_Cos -> (fsLit "cos", False) MO_F64_Tan -> (fsLit "tan", False) MO_F64_Asin -> (fsLit "asin", False) MO_F64_Acos -> (fsLit "acos", False) MO_F64_Atan -> (fsLit "atan", False) MO_F64_Sinh -> (fsLit "sinh", False) MO_F64_Cosh -> (fsLit "cosh", False) MO_F64_Tanh -> (fsLit "tanh", False) MO_F64_Pwr -> (fsLit "pow", False) MO_UF_Conv w -> (fsLit $ word2FloatLabel w, False) MO_Memcpy _ -> (fsLit "memcpy", False) MO_Memset _ -> (fsLit "memset", False) MO_Memmove _ -> (fsLit "memmove", False) MO_BSwap w -> (fsLit $ bSwapLabel w, False) MO_PopCnt w -> (fsLit $ popCntLabel w, False) MO_Clz w -> (fsLit $ clzLabel w, False) MO_Ctz w -> (fsLit $ ctzLabel w, False) MO_AtomicRMW w amop -> (fsLit $ atomicRMWLabel w amop, False) MO_Cmpxchg w -> (fsLit $ cmpxchgLabel w, False) MO_AtomicRead w -> (fsLit $ atomicReadLabel w, False) MO_AtomicWrite w -> (fsLit $ atomicWriteLabel w, False) MO_S_QuotRem {} -> unsupported MO_U_QuotRem {} -> unsupported MO_U_QuotRem2 {} -> unsupported MO_Add2 {} -> unsupported MO_SubWordC {} -> unsupported MO_AddIntC {} -> unsupported MO_SubIntC {} -> unsupported MO_U_Mul2 {} -> unsupported MO_WriteBarrier -> unsupported MO_Touch -> unsupported (MO_Prefetch_Data _ ) -> unsupported unsupported = panic ("outOfLineCmmOp: " ++ show mop ++ " not supported") -- ----------------------------------------------------------------------------- -- Generating a table-branch genSwitch :: DynFlags -> CmmExpr -> SwitchTargets -> NatM InstrBlock genSwitch dflags expr targets | (gopt Opt_PIC dflags) || (not $ target32Bit $ targetPlatform dflags) = do (reg,e_code) <- getSomeReg (cmmOffset dflags expr offset) let fmt = archWordFormat $ target32Bit $ targetPlatform dflags sha = if target32Bit $ targetPlatform dflags then 2 else 3 tmp <- getNewRegNat fmt lbl <- getNewLabelNat dynRef <- cmmMakeDynamicReference dflags DataReference lbl (tableReg,t_code) <- getSomeReg $ dynRef let code = e_code `appOL` t_code `appOL` toOL [ SL fmt tmp reg (RIImm (ImmInt sha)), LD fmt tmp (AddrRegReg tableReg tmp), ADD tmp tmp (RIReg tableReg), MTCTR tmp, BCTR ids (Just lbl) ] return code | otherwise = do (reg,e_code) <- getSomeReg (cmmOffset dflags expr offset) let fmt = archWordFormat $ target32Bit $ targetPlatform dflags sha = if target32Bit $ targetPlatform dflags then 2 else 3 tmp <- getNewRegNat fmt lbl <- getNewLabelNat let code = e_code `appOL` toOL [ SL fmt tmp reg (RIImm (ImmInt sha)), ADDIS tmp tmp (HA (ImmCLbl lbl)), LD fmt tmp (AddrRegImm tmp (LO (ImmCLbl lbl))), MTCTR tmp, BCTR ids (Just lbl) ] return code where (offset, ids) = switchTargetsToTable targets generateJumpTableForInstr :: DynFlags -> Instr -> Maybe (NatCmmDecl CmmStatics Instr) generateJumpTableForInstr dflags (BCTR ids (Just lbl)) = let jumpTable | (gopt Opt_PIC dflags) || (not $ target32Bit $ targetPlatform dflags) = map jumpTableEntryRel ids | otherwise = map (jumpTableEntry dflags) ids where jumpTableEntryRel Nothing = CmmStaticLit (CmmInt 0 (wordWidth dflags)) jumpTableEntryRel (Just blockid) = CmmStaticLit (CmmLabelDiffOff blockLabel lbl 0) where blockLabel = mkAsmTempLabel (getUnique blockid) in Just (CmmData (Section ReadOnlyData lbl) (Statics lbl jumpTable)) generateJumpTableForInstr _ _ = Nothing -- ----------------------------------------------------------------------------- -- 'condIntReg' and 'condFltReg': condition codes into registers -- Turn those condition codes into integers now (when they appear on -- the right hand side of an assignment). condIntReg, condFltReg :: Cond -> CmmExpr -> CmmExpr -> NatM Register condReg :: NatM CondCode -> NatM Register condReg getCond = do CondCode _ cond cond_code <- getCond dflags <- getDynFlags let code dst = cond_code `appOL` negate_code `appOL` toOL [ MFCR dst, RLWINM dst dst (bit + 1) 31 31 ] negate_code | do_negate = unitOL (CRNOR bit bit bit) | otherwise = nilOL (bit, do_negate) = case cond of LTT -> (0, False) LE -> (1, True) EQQ -> (2, False) GE -> (0, True) GTT -> (1, False) NE -> (2, True) LU -> (0, False) LEU -> (1, True) GEU -> (0, True) GU -> (1, False) _ -> panic "PPC.CodeGen.codeReg: no match" format = archWordFormat $ target32Bit $ targetPlatform dflags return (Any format code) condIntReg cond x y = condReg (condIntCode cond x y) condFltReg cond x y = condReg (condFltCode cond x y) -- ----------------------------------------------------------------------------- -- 'trivial*Code': deal with trivial instructions -- Trivial (dyadic: 'trivialCode', floating-point: 'trivialFCode', -- unary: 'trivialUCode', unary fl-pt:'trivialUFCode') instructions. -- Only look for constants on the right hand side, because that's -- where the generic optimizer will have put them. -- Similarly, for unary instructions, we don't have to worry about -- matching an StInt as the argument, because genericOpt will already -- have handled the constant-folding. {- Wolfgang's PowerPC version of The Rules: A slightly modified version of The Rules to take advantage of the fact that PowerPC instructions work on all registers and don't implicitly clobber any fixed registers. * The only expression for which getRegister returns Fixed is (CmmReg reg). * If getRegister returns Any, then the code it generates may modify only: (a) fresh temporaries (b) the destination register It may *not* modify global registers, unless the global register happens to be the destination register. It may not clobber any other registers. In fact, only ccalls clobber any fixed registers. Also, it may not modify the counter register (used by genCCall). Corollary: If a getRegister for a subexpression returns Fixed, you need not move it to a fresh temporary before evaluating the next subexpression. The Fixed register won't be modified. Therefore, we don't need a counterpart for the x86's getStableReg on PPC. * SDM's First Rule is valid for PowerPC, too: subexpressions can depend on the value of the destination register. -} trivialCode :: Width -> Bool -> (Reg -> Reg -> RI -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCode rep signed instr x (CmmLit (CmmInt y _)) | Just imm <- makeImmediate rep signed y = do (src1, code1) <- getSomeReg x let code dst = code1 `snocOL` instr dst src1 (RIImm imm) return (Any (intFormat rep) code) trivialCode rep _ instr x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code dst = code1 `appOL` code2 `snocOL` instr dst src1 (RIReg src2) return (Any (intFormat rep) code) shiftCode :: Width -> (Format-> Reg -> Reg -> RI -> Instr) -> CmmExpr -> CmmExpr -> NatM Register shiftCode width instr x (CmmLit (CmmInt y _)) | Just imm <- makeImmediate width False y = do (src1, code1) <- getSomeReg x let format = intFormat width let code dst = code1 `snocOL` instr format dst src1 (RIImm imm) return (Any format code) shiftCode width instr x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let format = intFormat width let code dst = code1 `appOL` code2 `snocOL` instr format dst src1 (RIReg src2) return (Any format code) trivialCodeNoImm' :: Format -> (Reg -> Reg -> Reg -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCodeNoImm' format instr x y = do (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code dst = code1 `appOL` code2 `snocOL` instr dst src1 src2 return (Any format code) trivialCodeNoImm :: Format -> (Format -> Reg -> Reg -> Reg -> Instr) -> CmmExpr -> CmmExpr -> NatM Register trivialCodeNoImm format instr x y = trivialCodeNoImm' format (instr format) x y trivialUCode :: Format -> (Reg -> Reg -> Instr) -> CmmExpr -> NatM Register trivialUCode rep instr x = do (src, code) <- getSomeReg x let code' dst = code `snocOL` instr dst src return (Any rep code') -- There is no "remainder" instruction on the PPC, so we have to do -- it the hard way. -- The "div" parameter is the division instruction to use (DIVW or DIVWU) remainderCode :: Width -> (Reg -> Reg -> Reg -> Instr) -> CmmExpr -> CmmExpr -> NatM Register remainderCode rep div x y = do dflags <- getDynFlags let mull_instr = if target32Bit $ targetPlatform dflags then MULLW else MULLD (src1, code1) <- getSomeReg x (src2, code2) <- getSomeReg y let code dst = code1 `appOL` code2 `appOL` toOL [ div dst src1 src2, mull_instr dst dst (RIReg src2), SUBF dst dst src1 ] return (Any (intFormat rep) code) coerceInt2FP :: Width -> Width -> CmmExpr -> NatM Register coerceInt2FP fromRep toRep x = do dflags <- getDynFlags let arch = platformArch $ targetPlatform dflags coerceInt2FP' arch fromRep toRep x coerceInt2FP' :: Arch -> Width -> Width -> CmmExpr -> NatM Register coerceInt2FP' ArchPPC fromRep toRep x = do (src, code) <- getSomeReg x lbl <- getNewLabelNat itmp <- getNewRegNat II32 ftmp <- getNewRegNat FF64 dflags <- getDynFlags dynRef <- cmmMakeDynamicReference dflags DataReference lbl Amode addr addr_code <- getAmode D dynRef let code' dst = code `appOL` maybe_exts `appOL` toOL [ LDATA (Section ReadOnlyData lbl) $ Statics lbl [CmmStaticLit (CmmInt 0x43300000 W32), CmmStaticLit (CmmInt 0x80000000 W32)], XORIS itmp src (ImmInt 0x8000), ST II32 itmp (spRel dflags 3), LIS itmp (ImmInt 0x4330), ST II32 itmp (spRel dflags 2), LD FF64 ftmp (spRel dflags 2) ] `appOL` addr_code `appOL` toOL [ LD FF64 dst addr, FSUB FF64 dst ftmp dst ] `appOL` maybe_frsp dst maybe_exts = case fromRep of W8 -> unitOL $ EXTS II8 src src W16 -> unitOL $ EXTS II16 src src W32 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" maybe_frsp dst = case toRep of W32 -> unitOL $ FRSP dst dst W64 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" return (Any (floatFormat toRep) code') -- On an ELF v1 Linux we use the compiler doubleword in the stack frame -- this is the TOC pointer doubleword on ELF v2 Linux. The latter is only -- set right before a call and restored right after return from the call. -- So it is fine. coerceInt2FP' (ArchPPC_64 _) fromRep toRep x = do (src, code) <- getSomeReg x dflags <- getDynFlags let code' dst = code `appOL` maybe_exts `appOL` toOL [ ST II64 src (spRel dflags 3), LD FF64 dst (spRel dflags 3), FCFID dst dst ] `appOL` maybe_frsp dst maybe_exts = case fromRep of W8 -> unitOL $ EXTS II8 src src W16 -> unitOL $ EXTS II16 src src W32 -> unitOL $ EXTS II32 src src W64 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" maybe_frsp dst = case toRep of W32 -> unitOL $ FRSP dst dst W64 -> nilOL _ -> panic "PPC.CodeGen.coerceInt2FP: no match" return (Any (floatFormat toRep) code') coerceInt2FP' _ _ _ _ = panic "PPC.CodeGen.coerceInt2FP: unknown arch" coerceFP2Int :: Width -> Width -> CmmExpr -> NatM Register coerceFP2Int fromRep toRep x = do dflags <- getDynFlags let arch = platformArch $ targetPlatform dflags coerceFP2Int' arch fromRep toRep x coerceFP2Int' :: Arch -> Width -> Width -> CmmExpr -> NatM Register coerceFP2Int' ArchPPC _ toRep x = do dflags <- getDynFlags -- the reps don't really matter: F*->FF64 and II32->I* are no-ops (src, code) <- getSomeReg x tmp <- getNewRegNat FF64 let code' dst = code `appOL` toOL [ -- convert to int in FP reg FCTIWZ tmp src, -- store value (64bit) from FP to stack ST FF64 tmp (spRel dflags 2), -- read low word of value (high word is undefined) LD II32 dst (spRel dflags 3)] return (Any (intFormat toRep) code') coerceFP2Int' (ArchPPC_64 _) _ toRep x = do dflags <- getDynFlags -- the reps don't really matter: F*->FF64 and II64->I* are no-ops (src, code) <- getSomeReg x tmp <- getNewRegNat FF64 let code' dst = code `appOL` toOL [ -- convert to int in FP reg FCTIDZ tmp src, -- store value (64bit) from FP to compiler word on stack ST FF64 tmp (spRel dflags 3), LD II64 dst (spRel dflags 3)] return (Any (intFormat toRep) code') coerceFP2Int' _ _ _ _ = panic "PPC.CodeGen.coerceFP2Int: unknown arch" -- Note [.LCTOC1 in PPC PIC code] -- The .LCTOC1 label is defined to point 32768 bytes into the GOT table -- to make the most of the PPC's 16-bit displacements. -- As 16-bit signed offset is used (usually via addi/lwz instructions) -- first element will have '-32768' offset against .LCTOC1. -- Note [implicit register in PPC PIC code] -- PPC generates calls by labels in assembly -- in form of: -- bl puts+32768@plt -- in this form it's not seen directly (by GHC NCG) -- that r30 (PicBaseReg) is used, -- but r30 is a required part of PLT code setup: -- puts+32768@plt: -- lwz r11,-30484(r30) ; offset in .LCTOC1 -- mtctr r11 -- bctr
oldmanmike/ghc
compiler/nativeGen/PPC/CodeGen.hs
Haskell
bsd-3-clause
73,920
module Compose where {-@ cmp :: forall < p :: b -> c -> Prop , q :: a -> b -> Prop , r :: a -> c -> Prop >. {x::a, w::b<q x> |- c<p w> <: c<r x>} f:(y:b -> c<p y>) -> g:(z:a -> b<q z>) -> x:a -> c<r x> @-} cmp :: (b -> c) -> (a -> b) -> a -> c cmp f g x = f (g x) {-@ incr :: x:Nat -> {v:Nat | v == x + 1} @-} incr :: Int -> Int incr x = x + 1 {-@ incr2 :: x:Nat -> {v:Nat | v = x + 2} @-} incr2 :: Int -> Int incr2 = incr `cmp` incr {-@ incr2' :: x:Nat -> {v:Nat | v = x + 2} @-} incr2' :: Int -> Int incr2' = incr `cmp` incr {-@ plusminus :: n:Nat -> m:Nat -> x:{Nat | x <= m} -> {v:Nat | v < (m - x) + n} @-} plusminus :: Int -> Int -> Int -> Int plusminus n m = (n+) `cmp` (m-) {-@ plus :: n:a -> x:a -> {v:a | v = (x + n)} @-} plus :: Num a => a -> a -> a plus = undefined minus :: Num a => a -> a -> a {-@ minus :: n:a -> x:a -> {v:a | v = x - n} @-} minus _ _ = undefined {-@ plus1 :: x:Nat -> {v:Nat | v == x + 20} @-} plus1 :: Int -> Int plus1 x = x + 20 {-@ plus2 :: x:{v:Nat | v > 10} -> {v:Nat | v == x + 2} @-} plus2 :: Int -> Int plus2 x = x + 2 {-@ plus42 :: x:Nat -> {v:Nat | v == x + 42} @-} plus42 :: Int -> Int plus42 = cmp plus2 plus1 {-@ qualif PLUSMINUS(v:int, x:int, y:int, z:int): (v = (x - y) + z) @-} {-@ qualif PLUS (v:int, x:int, y:int) : (v = x + y) @-} {-@ qualif MINUS (v:int, x:int, y:int) : (v = x - y) @-}
mightymoose/liquidhaskell
benchmarks/icfp15/neg/Composition.hs
Haskell
bsd-3-clause
1,474
{-# LANGUAGE TypeFamilies, PatternGuards, CPP #-} module Yesod.Core.Internal.LiteApp where #if __GLASGOW_HASKELL__ < 710 import Data.Monoid #endif import Yesod.Routes.Class import Yesod.Core.Class.Yesod import Yesod.Core.Class.Dispatch import Yesod.Core.Types import Yesod.Core.Content import Data.Text (Text) import Web.PathPieces import Network.Wai import Yesod.Core.Handler import Yesod.Core.Internal.Run import Network.HTTP.Types (Method) import Data.Maybe (fromMaybe) import Control.Applicative ((<|>)) import Control.Monad.Trans.Writer newtype LiteApp = LiteApp { unLiteApp :: Method -> [Text] -> Maybe (LiteHandler TypedContent) } instance Yesod LiteApp instance YesodDispatch LiteApp where yesodDispatch yre req = yesodRunner (fromMaybe notFound $ f (requestMethod req) (pathInfo req)) yre (Just $ LiteAppRoute $ pathInfo req) req where LiteApp f = yreSite yre instance RenderRoute LiteApp where data Route LiteApp = LiteAppRoute [Text] deriving (Show, Eq, Read, Ord) renderRoute (LiteAppRoute x) = (x, []) instance ParseRoute LiteApp where parseRoute (x, _) = Just $ LiteAppRoute x instance Monoid LiteApp where mempty = LiteApp $ \_ _ -> Nothing mappend (LiteApp x) (LiteApp y) = LiteApp $ \m ps -> x m ps <|> y m ps type LiteHandler = HandlerT LiteApp IO type LiteWidget = WidgetT LiteApp IO liteApp :: Writer LiteApp () -> LiteApp liteApp = execWriter dispatchTo :: ToTypedContent a => LiteHandler a -> Writer LiteApp () dispatchTo handler = tell $ LiteApp $ \_ ps -> if null ps then Just $ fmap toTypedContent handler else Nothing onMethod :: Method -> Writer LiteApp () -> Writer LiteApp () onMethod method f = tell $ LiteApp $ \m ps -> if method == m then unLiteApp (liteApp f) m ps else Nothing onStatic :: Text -> Writer LiteApp () -> Writer LiteApp () onStatic p0 f = tell $ LiteApp $ \m ps0 -> case ps0 of p:ps | p == p0 -> unLiteApp (liteApp f) m ps _ -> Nothing withDynamic :: PathPiece p => (p -> Writer LiteApp ()) -> Writer LiteApp () withDynamic f = tell $ LiteApp $ \m ps0 -> case ps0 of p:ps | Just v <- fromPathPiece p -> unLiteApp (liteApp $ f v) m ps _ -> Nothing withDynamicMulti :: PathMultiPiece ps => (ps -> Writer LiteApp ()) -> Writer LiteApp () withDynamicMulti f = tell $ LiteApp $ \m ps -> case fromPathMultiPiece ps of Nothing -> Nothing Just v -> unLiteApp (liteApp $ f v) m []
MaxGabriel/yesod
yesod-core/Yesod/Core/Internal/LiteApp.hs
Haskell
mit
2,542
{-| Ganeti logging functions expressed using MonadBase This allows to use logging functions without having instances for all possible transformers. -} {- Copyright (C) 2014 Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} module Ganeti.Logging.Lifted ( MonadLog() , Priority(..) , L.withErrorLogAt , L.isDebugMode , logAt , logDebug , logInfo , logNotice , logWarning , logError , logCritical , logAlert , logEmergency ) where import Control.Monad.Base import Ganeti.Logging (MonadLog, Priority(..)) import qualified Ganeti.Logging as L -- * Logging function aliases for MonadBase -- | A monad that allows logging. logAt :: (MonadLog b, MonadBase b m) => Priority -> String -> m () logAt p = liftBase . L.logAt p -- | Log at debug level. logDebug :: (MonadLog b, MonadBase b m) => String -> m () logDebug = logAt DEBUG -- | Log at info level. logInfo :: (MonadLog b, MonadBase b m) => String -> m () logInfo = logAt INFO -- | Log at notice level. logNotice :: (MonadLog b, MonadBase b m) => String -> m () logNotice = logAt NOTICE -- | Log at warning level. logWarning :: (MonadLog b, MonadBase b m) => String -> m () logWarning = logAt WARNING -- | Log at error level. logError :: (MonadLog b, MonadBase b m) => String -> m () logError = logAt ERROR -- | Log at critical level. logCritical :: (MonadLog b, MonadBase b m) => String -> m () logCritical = logAt CRITICAL -- | Log at alert level. logAlert :: (MonadLog b, MonadBase b m) => String -> m () logAlert = logAt ALERT -- | Log at emergency level. logEmergency :: (MonadLog b, MonadBase b m) => String -> m () logEmergency = logAt EMERGENCY
apyrgio/ganeti
src/Ganeti/Logging/Lifted.hs
Haskell
bsd-2-clause
2,867
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP, NoImplicitPrelude #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Bool -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : portable -- -- The 'Bool' type and related functions. -- ----------------------------------------------------------------------------- module Data.Bool ( -- * Booleans Bool(..), -- ** Operations (&&), -- :: Bool -> Bool -> Bool (||), -- :: Bool -> Bool -> Bool not, -- :: Bool -> Bool otherwise, -- :: Bool ) where #ifdef __GLASGOW_HASKELL__ import GHC.Base #endif #ifdef __NHC__ import Prelude import Prelude ( Bool(..) , (&&) , (||) , not , otherwise ) #endif
beni55/haste-compiler
libraries/ghc-7.8/base/Data/Bool.hs
Haskell
bsd-3-clause
919
module D where data T = A Int | B Float deriving Eq f x = x + 1
urbanslug/ghc
testsuite/tests/ghci/prog001/D2.hs
Haskell
bsd-3-clause
66
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.EXTBlendMinMax (pattern MIN_EXT, pattern MAX_EXT, EXTBlendMinMax(..), gTypeEXTBlendMinMax) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums pattern MIN_EXT = 32775 pattern MAX_EXT = 32776
ghcjs/jsaddle-dom
src/JSDOM/Generated/EXTBlendMinMax.hs
Haskell
mit
1,104
-- 1. It’s not a typo, we’re just being cute with the name. data TisAnInteger = TisAn Integer instance Eq TisAnInteger where (==) (TisAn a) (TisAn b) = a == b --2. data TwoIntegers = Two Integer Integer instance Eq TwoIntegers where (==) (Two a b) (Two a' b') = a == a' && b == b' -- 3. data StringOrInt = TisAnInt Int | TisAString String instance Eq StringOrInt where (==) (TisAnInt _) (TisAString _) = False (==) (TisAnInt a) (TisAnInt a') = a == a' (==) (TisAString a) (TisAString a') = a == a' -- 4. data Pair a = Pair a a instance (Eq a) => Eq (Pair a) where (==) (Pair a b) (Pair a' b') = a == a' && b == b' -- 5. data Tuple a b = Tuple a b instance (Eq a, Eq b) => Eq (Tuple a b) where (==) (Tuple a b) (Tuple a' b') = a == a' && b == b' -- 6. data Which a = ThisOne a | ThatOne a instance Eq a => Eq (Which a) where (==) (ThisOne a) (ThatOne a') = a == a' (==) (ThisOne a) (ThisOne a') = a == a' (==) (ThatOne a) (ThatOne a') = a == a' -- 7. data EitherOr a b = Hello a | Goodbye b instance (Eq a, Eq b) => Eq (EitherOr a b) where (==) (Hello _) (Goodbye _) = False (==) (Hello a) (Hello a') = a == a' (==) (Goodbye a) (Goodbye a') = a == a'
diminishedprime/.org
reading-list/haskell_programming_from_first_principles/06_12.hs
Haskell
mit
1,184
main = putStrLn . show. sum $ [ x | x <- [1..999], (x `mod` 3) == 0 || (x `mod` 5) == 0]
clementlee/projecteuler-haskell
p1.hs
Haskell
mit
89
module Graphics.Layouts ( fixedLayout, borderLayout, AnchorConstraint(..), anchorLayout, adaptativeLayout, ) where import Data.Maybe import Data.Tree import Data.Tree.Zipper import Graphics.Rendering.OpenGL import Graphics.View ---------------------------------------------------------------------------------------------------- setBounds position size tree = layoutSetSize (viewLayout (rootLabel tree')) size tree' where tree' = setPosition position tree fixedLayout (Size w h) = Layout (const (Just w, Just h)) setSize {- ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ top ┃ ┠─────┬──────────────┬─────┨ ┃ │ │ ┃ ┃ │ │ ┃ ┃ │ │ ┃ ┃left │ center │right┃ ┃ │ │ ┃ ┃ │ │ ┃ ┃ │ │ ┃ ┠─────┴──────────────┴─────┨ ┃ bottom ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -} data BordelLayouPosition = Center | Top | Left | Bottom | Right borderLayout :: [BordelLayouPosition] -> Layout a borderLayout positions = undefined -- TODO {- ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ▲ ┃ ┃ ┆ top ┃ ┃ ▼ ┃ ┃ ┌───────┐ ┃ ┃ left │ │ right┃ ┃◀---------▶│ │◀----▶┃ ┃ │ │ ┃ ┃ └───────┘ ┃ ┃ ▲ ┃ ┃ ┆ bottom ┃ ┃ ▼ ┃ ┗━━━━━━━━━━━━━━━━━━━━━━━━━━┛ -} data AnchorConstraint = AnchorConstraint { topDistance :: Maybe GLsizei , rightDistance :: Maybe GLsizei , bottomDistance :: Maybe GLsizei , leftDistance :: Maybe GLsizei } deriving Show anchorLayout :: [AnchorConstraint] -> Layout a anchorLayout constraints = Layout getter setter where getter t = (Nothing, Nothing) setter s t = setSize s t{ subForest = zipWith updateChild constraints (subForest t) } where (Size w h) = s updateChild constraint child = setBounds (Position xChild yChild) (Size wChild hChild) child where (mWidth, mHeigh) = layoutGetNaturalSize (viewLayout (rootLabel child)) child (xChild, wChild) = case (leftDistance constraint, mWidth, rightDistance constraint) of (Nothing, _, Nothing) -> let iw = fromMaybe w mWidth in ((w - iw) `div` 2, iw) -- centrage (Just l, _, Nothing) -> (l, w') where w' = fromMaybe (w - l) mWidth (Nothing, _, Just r) -> (w - w' - r, w') where w' = fromMaybe (w - r) mWidth (Just l, _, Just r) -> (l, w - l - r) -- La taille naturelle du composant est ignorée. (yChild, hChild) = case (topDistance constraint, mHeigh, bottomDistance constraint) of (Nothing, _, Nothing) -> let ih = fromMaybe h mHeigh in ((h - ih) `div` 2, ih) -- centrage (Just t, _, Nothing) -> (t, h') where h' = fromMaybe (h - t) mHeigh (Nothing, _, Just b) -> (h - h' - b, h') where h' = fromMaybe (h - b) mHeigh (Just t, _, Just b) -> (t, h - t - b) -- La taille naturelle du composant est ignorée. {- ┏━━━━━━━━━━━━━━━━━━━━━━━━━━┓ ┃ ┃ ┃ 9x27 ┃ ┃ (master) ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┃ ┠────────┬────────┬────────┨ ┃ 3x9 │ 3x9 │ 3x9 ┃ ┃(slave) │(slave) │(slave) ┃ ┗━━━━━━━━┷━━━━━━━━┷━━━━━━━━┛ -} adaptativeLayout :: Layout a adaptativeLayout = Layout getter setter where getter t = case subForest t of [] -> (Nothing, Nothing) (master : slaves) -> let n = fromIntegral (length slaves) (mw, mh) = layoutGetNaturalSize (viewLayout (rootLabel master)) master in if n > 0 then (mw, (\h -> h + h `div` n) <$> mh) else (mw, mh) setter s t = setSize s t' where t' = case subForest t of [] -> t (master : slaves) -> let n = fromIntegral (length slaves) in if n > 0 then let (Size w h) = s wMaster = w hMaster = (n * h) `div` (n + 1) wSlave = w `div` n hSlave = h - hMaster master' = setBounds (Position 0 0) (Size wMaster hMaster) master updateSlave index = setBounds (Position (wSlave * index) hMaster) (Size wSlave hSlave) in t{ subForest = master' : zipWith updateSlave [0..] slaves } else t{ subForest = [setBounds (Position 0 0) s master] }
Chatanga/kage
src/Graphics/Layouts.hs
Haskell
mit
5,724
{-# LANGUAGE DeriveGeneric #-} module Handler.Account where import Import import Yesod.Auth.Simple (setPasswordR) import Util.Slug (mkSlug) import Util.User (newToken) import Util.Handler (title) import Util.Alert (successHtml) import qualified Model.Snippet.Api as SnippetApi import qualified Model.Run.Api as RunApi data ProfileData = ProfileData { name :: Text, username :: Text } deriving (Show, Generic) instance FromJSON ProfileData getAccountProfileR :: Handler Html getAccountProfileR = do userId <- requireAuthId Entity _ profile <- runDB $ getBy404 $ UniqueProfile userId defaultLayout $ do setTitle $ title "Profile" $(widgetFile "account/profile") putAccountProfileR :: Handler Value putAccountProfileR = do userId <- requireAuthId profileData <- requireJsonBody :: Handler ProfileData Entity profileId _ <- runDB $ getBy404 $ UniqueProfile userId now <- liftIO getCurrentTime runDB $ update profileId [ ProfileName =. name profileData, ProfileUsername =. (mkSlug $ username profileData), ProfileModified =. now] setMessage $ successHtml "Profile updated" return $ object [] getAccountTokenR :: Handler Html getAccountTokenR = do userId <- requireAuthId Entity _ apiUser <- runDB $ getBy404 $ UniqueApiUser userId defaultLayout $ do setTitle $ title "Api token" $(widgetFile "account/token") putAccountTokenR :: Handler Value putAccountTokenR = do userId <- requireAuthId Entity apiUserId apiUser <- runDB $ getBy404 $ UniqueApiUser userId token <- liftIO newToken liftIO $ SnippetApi.setUserToken (apiUserSnippetsId apiUser) token liftIO $ RunApi.setUserToken (apiUserRunId apiUser) token now <- liftIO getCurrentTime runDB $ update apiUserId [ApiUserToken =. token, ApiUserModified =. now] setMessage $ successHtml "New token generated" return $ object []
vinnymac/glot-www
Handler/Account.hs
Haskell
mit
1,929
module Main where {- A Tic-Tac-Toe Board 012 345 678 -} import TTT.GameLogic as GL main :: IO () main = print $ GL.hasWon 012
tripattern/haskell
ticTacToe/src/Main.hs
Haskell
mit
138
{-| Module : Database.Orville.PostgreSQL.Internal.Select Copyright : Flipstone Technology Partners 2016-2018 License : MIT -} module Database.Orville.PostgreSQL.Internal.Select where import Control.Monad.Reader import qualified Data.List as List import Database.HDBC import Database.Orville.PostgreSQL.Internal.Expr import Database.Orville.PostgreSQL.Internal.FieldDefinition (fieldToNameForm) import Database.Orville.PostgreSQL.Internal.FromClause import Database.Orville.PostgreSQL.Internal.SelectOptions import Database.Orville.PostgreSQL.Internal.Types data Select row = Select { selectBuilder :: FromSql row , selectSql :: String , selectValues :: [SqlValue] } selectQueryColumns :: [SelectExpr] -> FromSql row -> FromClause -> SelectOptions -> Select row selectQueryColumns selectExprs builder fromClause opts = selectQueryRaw builder querySql (selectOptValues opts) where columns = List.intercalate ", " $ map (rawExprToSql . generateSql) selectExprs querySql = List.concat [ selectClause opts , columns , " " , fromClauseToSql fromClause , " " , selectOptClause opts ] selectQuery :: FromSql row -> FromClause -> SelectOptions -> Select row selectQuery builder = selectQueryColumns (expr <$> fromSqlSelects builder) builder selectQueryTable :: TableDefinition readEntity writeEntity key -> SelectOptions -> Select readEntity selectQueryTable tbl = selectQuery (tableFromSql tbl) (fromClauseTable tbl) selectQueryRows :: [SelectExpr] -> FromClause -> SelectOptions -> Select [(String, SqlValue)] selectQueryRows exprs = selectQueryColumns exprs rowFromSql selectQueryRaw :: FromSql row -> String -> [SqlValue] -> Select row selectQueryRaw = Select selectQueryRawRows :: String -> [SqlValue] -> Select [(String, SqlValue)] selectQueryRawRows = selectQueryRaw rowFromSql -- N.B. This FromSql does *not* contain an accurate list of the columns -- it decodes, because it does not decode any columns at all. It is not -- suitable for uses where the FromSql is used to generate the columns in -- a select clause. It is not exposed publically for this reason. -- rowFromSql :: FromSql [(String, SqlValue)] rowFromSql = FromSql { fromSqlSelects = error "Database.Orville.PostgreSQL.Select.rowFromSql: fromSqlColumnNames was accessed. This is a bug." , runFromSql = Right <$> ask } selectField :: FieldDefinition nulability a -> SelectForm selectField field = selectColumn (fieldToNameForm field)
flipstone/orville
orville-postgresql/src/Database/Orville/PostgreSQL/Internal/Select.hs
Haskell
mit
2,552
module Solar.Caster.Client where
Cordite-Studios/solar
solar-wind/Solar/Caster/Client.hs
Haskell
mit
33
module Exercise where money :: Int -> [[Int]] money 0 = [[]] money n = [(k:rest) | k <- [1,2,5,10,20,50], k <= n, rest <- (money (n - k)), k <= minimum (n:rest), -- ordering does not matter n == sum (k:rest) ]
tcoenraad/functioneel-programmeren
2014/opg1b.hs
Haskell
mit
321
------------------------------------------------------------------------------ -- | -- Module : Hajong.Server.Config -- Copyright : (C) 2016 Samuli Thomasson -- License : %% (see the file LICENSE) -- Maintainer : Samuli Thomasson <samuli.thomasson@paivola.fi> -- Stability : experimental -- Portability : non-portable -- -- Game server configuration. ------------------------------------------------------------------------------ module Hajong.Server.Config where import Import import Data.Aeson (FromJSON(..), withObject, (.:), (.:?), (.!=)) import Data.Yaml (decodeFileEither, parseEither) import System.Exit (exitFailure) data ServerConfig = ServerConfig { _websocketHost :: String -- ^ Host to use for incoming websocket clients. Default to 0.0.0.0 , _websocketPort :: Int -- ^ Port to use for incoming websocket clients. , _databaseSocket :: FilePath -- ^ Provide access to the ACIDic database at this socket. , _logDirectory :: FilePath -- ^ Directory to store logs into , _websocketCtrlSecret :: Text -- ^ A secret key a client must know to gain access into the internal -- control channel via WS. } deriving (Show, Read, Eq, Typeable) instance FromJSON ServerConfig where parseJSON = withObject "ServerConfig" $ \o -> do _websocketHost <- o .:? "websocket-addr" .!= "0.0.0.0" _websocketPort <- o .: "websocket-port" _websocketCtrlSecret <- o .: "ctrl-secret-ws" _databaseSocket <- o .: "db-socket-file" _logDirectory <- o .: "logs-directory" return ServerConfig{..} -- * Reading configuration -- | Exits when the configuration could not be read. readConfigFile :: FilePath -> Maybe Text -- ^ Optional subsection to use as the root. -> IO ServerConfig readConfigFile file mobj = do val <- decodeFileEither file >>= either (\err -> print err >> exitFailure) return either (\err -> print err >> exitFailure) return $ parseEither (maybe parseJSON (\k -> withObject "ServerConfig" (.: k)) mobj) val -- * Lenses makeLenses ''ServerConfig
SimSaladin/hajong
hajong-server/src/Hajong/Server/Config.hs
Haskell
mit
2,149
{-# LANGUAGE AllowAmbiguousTypes #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} {- hsCRDT.hs Copyright 2015 Sebastien Soudan Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} -- @Author: Sebastien Soudan -- @Date: 2015-04-22 11:16:32 -- @Last Modified by: Sebastien Soudan -- @Last Modified time: 2015-04-24 14:23:22 module CRDT where import Data.Monoid ---------------------------- -- Join semi-Lattice related definitions ---------------------------- class Compare p where is :: p -> p -> Bool -- (is p p') is True if p <= p' class (Compare p) => JoinSemiLattice p where lub :: p -> p -> p -- least-upper-bound ---------------------------- -- CRDT related definitions - state-based specification ---------------------------- class Payload p where initial :: p class (Eq a, Payload p) => Query p q a where query :: p -> q -> Maybe a ---------------------------- -- CvRDT definition ---------------------------- class (Payload p, Compare p, JoinSemiLattice p) => CvRDT p u where update :: p -> u -> Maybe p instance (CvRDT p u) => Monoid p where mempty = initial mappend = lub -- merge is an alias for 'lub' merge :: (JoinSemiLattice p) => p -> p -> p merge = lub
ssoudan/hsCRDT
src/CRDT.hs
Haskell
apache-2.0
1,946
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE TypeFamilies #-} -- | Data types for K3 dataflow provenance module Language.K3.Analysis.Provenance.Core where import Control.DeepSeq import GHC.Generics (Generic) import Data.Binary import Data.Serialize import Data.List import Data.Tree import Data.Typeable import Language.K3.Core.Annotation import Language.K3.Core.Common import Language.K3.Utils.Pretty import Data.Text ( Text ) import qualified Data.Text as T import qualified Language.K3.Utils.PrettyText as PT type PPtr = Int data PMatVar = PMatVar {pmvn :: !Identifier, pmvloc :: !UID, pmvptr :: !PPtr} deriving (Eq, Ord, Read, Show, Typeable, Generic) data Provenance = -- Atoms PFVar !Identifier !(Maybe UID) | PBVar !PMatVar | PTemporary -- A local leading to no lineage of interest -- Terms | PGlobal !Identifier | PSet -- Non-deterministic (if-then-else or case) | PChoice -- One of the cases must be chosen ie. they're exclusive | PDerived -- A value derived from named children e.g. x + y ==> [x;y] | PData !(Maybe [Identifier]) -- A value derived from a data constructor (optionally with named components) | PRecord !Identifier | PTuple !Int | PIndirection | POption | PLambda !Identifier ![PMatVar] -- Lambda argument identifier, and new bound variables introduced for closure-captures. | PApply !(Maybe PMatVar) -- The lambda, argument, and return value provenances of the application. -- The apply also tracks any provenance variable binding needed for the lambda. | PMaterialize ![PMatVar] -- A materialized return value scope, denoting provenance varibles bound in the child. | PProject !Identifier -- The source of the projection, and the provenance of the projected value if available. | PAssign !Identifier -- The provenance of the expression used for assignment. | PSend -- The provenance of the value being sent. deriving (Eq, Ord, Read, Show, Typeable, Generic) data instance Annotation Provenance = PDeclared !(K3 Provenance) deriving (Eq, Ord, Read, Show, Generic) {- Provenance instances -} instance NFData PMatVar instance NFData Provenance instance NFData (Annotation Provenance) instance Binary PMatVar instance Binary Provenance instance Binary (Annotation Provenance) instance Serialize PMatVar instance Serialize Provenance instance Serialize (Annotation Provenance) {- Annotation extractors -} isPDeclared :: Annotation Provenance -> Bool isPDeclared (PDeclared _) = True instance Pretty (K3 Provenance) where prettyLines (Node (tg :@: as) ch) = let (aStr, chAStr) = drawPAnnotations as in [show tg ++ aStr] ++ (let (p,l) = if null ch then ("`- ", " ") else ("+- ", "| ") in shift p l chAStr) ++ drawSubTrees ch drawPAnnotations :: [Annotation Provenance] -> (String, [String]) drawPAnnotations as = let (pdeclAnns, anns) = partition isPDeclared as prettyPrAnns = concatMap drawPDeclAnnotation pdeclAnns in (drawAnnotations anns, prettyPrAnns) where drawPDeclAnnotation (PDeclared p) = ["PDeclared "] %+ prettyLines p instance PT.Pretty (K3 Provenance) where prettyLines (Node (tg :@: as) ch) = let (aTxt, chATxt) = drawPAnnotationsT as in [T.append (T.pack $ show tg) aTxt] ++ (let (p,l) = if null ch then (T.pack "`- ", T.pack " ") else (T.pack "+- ", T.pack "| ") in PT.shift p l chATxt) ++ PT.drawSubTrees ch drawPAnnotationsT :: [Annotation Provenance] -> (Text, [Text]) drawPAnnotationsT as = let (pdeclAnns, anns) = partition isPDeclared as prettyPrAnns = concatMap drawPDeclAnnotation pdeclAnns in (PT.drawAnnotations anns, prettyPrAnns) where drawPDeclAnnotation (PDeclared p) = [T.pack "PDeclared "] PT.%+ PT.prettyLines p
DaMSL/K3
src/Language/K3/Analysis/Provenance/Core.hs
Haskell
apache-2.0
4,165
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QTextLayout.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:15 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QTextLayout ( QqTextLayout(..) ,QqTextLayout_nf(..) ,additionalFormats ,beginLayout ,cacheEnabled ,clearAdditionalFormats ,createLine ,QdrawCursor(..), QqdrawCursor(..) ,endLayout ,isValidCursorPosition ,lineAt ,lineCount ,lineForTextPosition ,QnextCursorPosition(..) ,preeditAreaPosition ,preeditAreaText ,QpreviousCursorPosition(..) ,setCacheEnabled ,setPreeditArea ,setTextOption ,textOption ,qTextLayout_delete ) where import Qth.ClassTypes.Core import Qtc.Enums.Base import Qtc.Enums.Gui.QTextLayout import Qtc.Classes.Base import Qtc.Classes.Qccs import Qtc.Classes.Core import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui import Qtc.ClassTypes.Gui class QqTextLayout x1 where qTextLayout :: x1 -> IO (QTextLayout ()) instance QqTextLayout (()) where qTextLayout () = withQTextLayoutResult $ qtc_QTextLayout foreign import ccall "qtc_QTextLayout" qtc_QTextLayout :: IO (Ptr (TQTextLayout ())) instance QqTextLayout ((String)) where qTextLayout (x1) = withQTextLayoutResult $ withCWString x1 $ \cstr_x1 -> qtc_QTextLayout1 cstr_x1 foreign import ccall "qtc_QTextLayout1" qtc_QTextLayout1 :: CWString -> IO (Ptr (TQTextLayout ())) instance QqTextLayout ((QTextBlock t1)) where qTextLayout (x1) = withQTextLayoutResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QTextLayout2 cobj_x1 foreign import ccall "qtc_QTextLayout2" qtc_QTextLayout2 :: Ptr (TQTextBlock t1) -> IO (Ptr (TQTextLayout ())) instance QqTextLayout ((String, QFont t2)) where qTextLayout (x1, x2) = withQTextLayoutResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextLayout3 cstr_x1 cobj_x2 foreign import ccall "qtc_QTextLayout3" qtc_QTextLayout3 :: CWString -> Ptr (TQFont t2) -> IO (Ptr (TQTextLayout ())) instance QqTextLayout ((String, QFont t2, QPaintDevice t3)) where qTextLayout (x1, x2, x3) = withQTextLayoutResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QTextLayout4 cstr_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QTextLayout4" qtc_QTextLayout4 :: CWString -> Ptr (TQFont t2) -> Ptr (TQPaintDevice t3) -> IO (Ptr (TQTextLayout ())) instance QqTextLayout ((String, QFont t2, QWidget t3)) where qTextLayout (x1, x2, x3) = withQTextLayoutResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QTextLayout4_widget cstr_x1 cobj_x2 cobj_x3 foreign import ccall "qtc_QTextLayout4_widget" qtc_QTextLayout4_widget :: CWString -> Ptr (TQFont t2) -> Ptr (TQWidget t3) -> IO (Ptr (TQTextLayout ())) class QqTextLayout_nf x1 where qTextLayout_nf :: x1 -> IO (QTextLayout ()) instance QqTextLayout_nf (()) where qTextLayout_nf () = withObjectRefResult $ qtc_QTextLayout instance QqTextLayout_nf ((String)) where qTextLayout_nf (x1) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> qtc_QTextLayout1 cstr_x1 instance QqTextLayout_nf ((QTextBlock t1)) where qTextLayout_nf (x1) = withObjectRefResult $ withObjectPtr x1 $ \cobj_x1 -> qtc_QTextLayout2 cobj_x1 instance QqTextLayout_nf ((String, QFont t2)) where qTextLayout_nf (x1, x2) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextLayout3 cstr_x1 cobj_x2 instance QqTextLayout_nf ((String, QFont t2, QPaintDevice t3)) where qTextLayout_nf (x1, x2, x3) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QTextLayout4 cstr_x1 cobj_x2 cobj_x3 instance QqTextLayout_nf ((String, QFont t2, QWidget t3)) where qTextLayout_nf (x1, x2, x3) = withObjectRefResult $ withCWString x1 $ \cstr_x1 -> withObjectPtr x2 $ \cobj_x2 -> withObjectPtr x3 $ \cobj_x3 -> qtc_QTextLayout4_widget cstr_x1 cobj_x2 cobj_x3 additionalFormats :: QTextLayout a -> (()) -> IO ([QTextLayout__FormatRange ()]) additionalFormats x0 () = withQListObjectRefResult $ \arr -> withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_additionalFormats cobj_x0 arr foreign import ccall "qtc_QTextLayout_additionalFormats" qtc_QTextLayout_additionalFormats :: Ptr (TQTextLayout a) -> Ptr (Ptr (TQTextLayout__FormatRange ())) -> IO CInt beginLayout :: QTextLayout a -> (()) -> IO () beginLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_beginLayout cobj_x0 foreign import ccall "qtc_QTextLayout_beginLayout" qtc_QTextLayout_beginLayout :: Ptr (TQTextLayout a) -> IO () instance QqqboundingRect (QTextLayout a) (()) (IO (QRectF ())) where qqboundingRect x0 () = withQRectFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_boundingRect cobj_x0 foreign import ccall "qtc_QTextLayout_boundingRect" qtc_QTextLayout_boundingRect :: Ptr (TQTextLayout a) -> IO (Ptr (TQRectF ())) instance QqboundingRect (QTextLayout a) (()) (IO (RectF)) where qboundingRect x0 () = withRectFResult $ \crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_boundingRect_qth cobj_x0 crectf_ret_x crectf_ret_y crectf_ret_w crectf_ret_h foreign import ccall "qtc_QTextLayout_boundingRect_qth" qtc_QTextLayout_boundingRect_qth :: Ptr (TQTextLayout a) -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> Ptr CDouble -> IO () cacheEnabled :: QTextLayout a -> (()) -> IO (Bool) cacheEnabled x0 () = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_cacheEnabled cobj_x0 foreign import ccall "qtc_QTextLayout_cacheEnabled" qtc_QTextLayout_cacheEnabled :: Ptr (TQTextLayout a) -> IO CBool clearAdditionalFormats :: QTextLayout a -> (()) -> IO () clearAdditionalFormats x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_clearAdditionalFormats cobj_x0 foreign import ccall "qtc_QTextLayout_clearAdditionalFormats" qtc_QTextLayout_clearAdditionalFormats :: Ptr (TQTextLayout a) -> IO () createLine :: QTextLayout a -> (()) -> IO (QTextLine ()) createLine x0 () = withQTextLineResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_createLine cobj_x0 foreign import ccall "qtc_QTextLayout_createLine" qtc_QTextLayout_createLine :: Ptr (TQTextLayout a) -> IO (Ptr (TQTextLine ())) instance Qdraw (QTextLayout a) ((QPainter t1, PointF)) where draw x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCPointF x2 $ \cpointf_x2_x cpointf_x2_y -> qtc_QTextLayout_draw_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y foreign import ccall "qtc_QTextLayout_draw_qth" qtc_QTextLayout_draw_qth :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> IO () instance Qqdraw (QTextLayout a) ((QPainter t1, QPointF t2)) where qdraw x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextLayout_draw cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QTextLayout_draw" qtc_QTextLayout_draw :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> Ptr (TQPointF t2) -> IO () class QdrawCursor x1 where drawCursor :: QTextLayout a -> x1 -> IO () class QqdrawCursor x1 where qdrawCursor :: QTextLayout a -> x1 -> IO () instance QdrawCursor ((QPainter t1, PointF, Int)) where drawCursor x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCPointF x2 $ \cpointf_x2_x cpointf_x2_y -> qtc_QTextLayout_drawCursor_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y (toCInt x3) foreign import ccall "qtc_QTextLayout_drawCursor_qth" qtc_QTextLayout_drawCursor_qth :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> CInt -> IO () instance QdrawCursor ((QPainter t1, PointF, Int, Int)) where drawCursor x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withCPointF x2 $ \cpointf_x2_x cpointf_x2_y -> qtc_QTextLayout_drawCursor1_qth cobj_x0 cobj_x1 cpointf_x2_x cpointf_x2_y (toCInt x3) (toCInt x4) foreign import ccall "qtc_QTextLayout_drawCursor1_qth" qtc_QTextLayout_drawCursor1_qth :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> CDouble -> CDouble -> CInt -> CInt -> IO () instance QqdrawCursor ((QPainter t1, QPointF t2, Int)) where qdrawCursor x0 (x1, x2, x3) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextLayout_drawCursor cobj_x0 cobj_x1 cobj_x2 (toCInt x3) foreign import ccall "qtc_QTextLayout_drawCursor" qtc_QTextLayout_drawCursor :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> Ptr (TQPointF t2) -> CInt -> IO () instance QqdrawCursor ((QPainter t1, QPointF t2, Int, Int)) where qdrawCursor x0 (x1, x2, x3, x4) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QTextLayout_drawCursor1 cobj_x0 cobj_x1 cobj_x2 (toCInt x3) (toCInt x4) foreign import ccall "qtc_QTextLayout_drawCursor1" qtc_QTextLayout_drawCursor1 :: Ptr (TQTextLayout a) -> Ptr (TQPainter t1) -> Ptr (TQPointF t2) -> CInt -> CInt -> IO () endLayout :: QTextLayout a -> (()) -> IO () endLayout x0 () = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_endLayout cobj_x0 foreign import ccall "qtc_QTextLayout_endLayout" qtc_QTextLayout_endLayout :: Ptr (TQTextLayout a) -> IO () instance Qfont (QTextLayout a) (()) where font x0 () = withQFontResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_font cobj_x0 foreign import ccall "qtc_QTextLayout_font" qtc_QTextLayout_font :: Ptr (TQTextLayout a) -> IO (Ptr (TQFont ())) isValidCursorPosition :: QTextLayout a -> ((Int)) -> IO (Bool) isValidCursorPosition x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_isValidCursorPosition cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextLayout_isValidCursorPosition" qtc_QTextLayout_isValidCursorPosition :: Ptr (TQTextLayout a) -> CInt -> IO CBool lineAt :: QTextLayout a -> ((Int)) -> IO (QTextLine ()) lineAt x0 (x1) = withQTextLineResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_lineAt cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextLayout_lineAt" qtc_QTextLayout_lineAt :: Ptr (TQTextLayout a) -> CInt -> IO (Ptr (TQTextLine ())) lineCount :: QTextLayout a -> (()) -> IO (Int) lineCount x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_lineCount cobj_x0 foreign import ccall "qtc_QTextLayout_lineCount" qtc_QTextLayout_lineCount :: Ptr (TQTextLayout a) -> IO CInt lineForTextPosition :: QTextLayout a -> ((Int)) -> IO (QTextLine ()) lineForTextPosition x0 (x1) = withQTextLineResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_lineForTextPosition cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextLayout_lineForTextPosition" qtc_QTextLayout_lineForTextPosition :: Ptr (TQTextLayout a) -> CInt -> IO (Ptr (TQTextLine ())) instance QmaximumWidth (QTextLayout a) (()) (IO (Double)) where maximumWidth x0 () = withDoubleResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_maximumWidth cobj_x0 foreign import ccall "qtc_QTextLayout_maximumWidth" qtc_QTextLayout_maximumWidth :: Ptr (TQTextLayout a) -> IO CDouble instance QminimumWidth (QTextLayout a) (()) (IO (Double)) where minimumWidth x0 () = withDoubleResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_minimumWidth cobj_x0 foreign import ccall "qtc_QTextLayout_minimumWidth" qtc_QTextLayout_minimumWidth :: Ptr (TQTextLayout a) -> IO CDouble class QnextCursorPosition x1 where nextCursorPosition :: QTextLayout a -> x1 -> IO (Int) instance QnextCursorPosition ((Int)) where nextCursorPosition x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_nextCursorPosition cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextLayout_nextCursorPosition" qtc_QTextLayout_nextCursorPosition :: Ptr (TQTextLayout a) -> CInt -> IO CInt instance QnextCursorPosition ((Int, CursorMode)) where nextCursorPosition x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_nextCursorPosition1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QTextLayout_nextCursorPosition1" qtc_QTextLayout_nextCursorPosition1 :: Ptr (TQTextLayout a) -> CInt -> CLong -> IO CInt instance Qposition (QTextLayout a) (()) (IO (PointF)) where position x0 () = withPointFResult $ \cpointf_ret_x cpointf_ret_y -> withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_position_qth cobj_x0 cpointf_ret_x cpointf_ret_y foreign import ccall "qtc_QTextLayout_position_qth" qtc_QTextLayout_position_qth :: Ptr (TQTextLayout a) -> Ptr CDouble -> Ptr CDouble -> IO () instance Qqposition (QTextLayout a) (()) where qposition x0 () = withQPointFResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_position cobj_x0 foreign import ccall "qtc_QTextLayout_position" qtc_QTextLayout_position :: Ptr (TQTextLayout a) -> IO (Ptr (TQPointF ())) preeditAreaPosition :: QTextLayout a -> (()) -> IO (Int) preeditAreaPosition x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_preeditAreaPosition cobj_x0 foreign import ccall "qtc_QTextLayout_preeditAreaPosition" qtc_QTextLayout_preeditAreaPosition :: Ptr (TQTextLayout a) -> IO CInt preeditAreaText :: QTextLayout a -> (()) -> IO (String) preeditAreaText x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_preeditAreaText cobj_x0 foreign import ccall "qtc_QTextLayout_preeditAreaText" qtc_QTextLayout_preeditAreaText :: Ptr (TQTextLayout a) -> IO (Ptr (TQString ())) class QpreviousCursorPosition x1 where previousCursorPosition :: QTextLayout a -> x1 -> IO (Int) instance QpreviousCursorPosition ((Int)) where previousCursorPosition x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_previousCursorPosition cobj_x0 (toCInt x1) foreign import ccall "qtc_QTextLayout_previousCursorPosition" qtc_QTextLayout_previousCursorPosition :: Ptr (TQTextLayout a) -> CInt -> IO CInt instance QpreviousCursorPosition ((Int, CursorMode)) where previousCursorPosition x0 (x1, x2) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_previousCursorPosition1 cobj_x0 (toCInt x1) (toCLong $ qEnum_toInt x2) foreign import ccall "qtc_QTextLayout_previousCursorPosition1" qtc_QTextLayout_previousCursorPosition1 :: Ptr (TQTextLayout a) -> CInt -> CLong -> IO CInt setCacheEnabled :: QTextLayout a -> ((Bool)) -> IO () setCacheEnabled x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_setCacheEnabled cobj_x0 (toCBool x1) foreign import ccall "qtc_QTextLayout_setCacheEnabled" qtc_QTextLayout_setCacheEnabled :: Ptr (TQTextLayout a) -> CBool -> IO () instance QsetFont (QTextLayout a) ((QFont t1)) where setFont x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextLayout_setFont cobj_x0 cobj_x1 foreign import ccall "qtc_QTextLayout_setFont" qtc_QTextLayout_setFont :: Ptr (TQTextLayout a) -> Ptr (TQFont t1) -> IO () instance QsetPosition (QTextLayout a) ((PointF)) where setPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCPointF x1 $ \cpointf_x1_x cpointf_x1_y -> qtc_QTextLayout_setPosition_qth cobj_x0 cpointf_x1_x cpointf_x1_y foreign import ccall "qtc_QTextLayout_setPosition_qth" qtc_QTextLayout_setPosition_qth :: Ptr (TQTextLayout a) -> CDouble -> CDouble -> IO () instance QqsetPosition (QTextLayout a) ((QPointF t1)) where qsetPosition x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextLayout_setPosition cobj_x0 cobj_x1 foreign import ccall "qtc_QTextLayout_setPosition" qtc_QTextLayout_setPosition :: Ptr (TQTextLayout a) -> Ptr (TQPointF t1) -> IO () setPreeditArea :: QTextLayout a -> ((Int, String)) -> IO () setPreeditArea x0 (x1, x2) = withObjectPtr x0 $ \cobj_x0 -> withCWString x2 $ \cstr_x2 -> qtc_QTextLayout_setPreeditArea cobj_x0 (toCInt x1) cstr_x2 foreign import ccall "qtc_QTextLayout_setPreeditArea" qtc_QTextLayout_setPreeditArea :: Ptr (TQTextLayout a) -> CInt -> CWString -> IO () instance QsetText (QTextLayout a) ((String)) where setText x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withCWString x1 $ \cstr_x1 -> qtc_QTextLayout_setText cobj_x0 cstr_x1 foreign import ccall "qtc_QTextLayout_setText" qtc_QTextLayout_setText :: Ptr (TQTextLayout a) -> CWString -> IO () setTextOption :: QTextLayout a -> ((QTextOption t1)) -> IO () setTextOption x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QTextLayout_setTextOption cobj_x0 cobj_x1 foreign import ccall "qtc_QTextLayout_setTextOption" qtc_QTextLayout_setTextOption :: Ptr (TQTextLayout a) -> Ptr (TQTextOption t1) -> IO () instance Qtext (QTextLayout a) (()) (IO (String)) where text x0 () = withStringResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_text cobj_x0 foreign import ccall "qtc_QTextLayout_text" qtc_QTextLayout_text :: Ptr (TQTextLayout a) -> IO (Ptr (TQString ())) textOption :: QTextLayout a -> (()) -> IO (QTextOption ()) textOption x0 () = withQTextOptionResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_textOption cobj_x0 foreign import ccall "qtc_QTextLayout_textOption" qtc_QTextLayout_textOption :: Ptr (TQTextLayout a) -> IO (Ptr (TQTextOption ())) qTextLayout_delete :: QTextLayout a -> IO () qTextLayout_delete x0 = withObjectPtr x0 $ \cobj_x0 -> qtc_QTextLayout_delete cobj_x0 foreign import ccall "qtc_QTextLayout_delete" qtc_QTextLayout_delete :: Ptr (TQTextLayout a) -> IO ()
uduki/hsQt
Qtc/Gui/QTextLayout.hs
Haskell
bsd-2-clause
18,021
{-# OPTIONS_GHC -Wall -Werror #-} module IRTS.CLaSH.Show where import Core.CaseTree import Core.TT showSC :: SC -> String showSC (STerm t) = showTerm t showSC (Case n alts) = "Case " ++ show n ++ " of " ++ unlines (map showAlt alts) showSC sc = "showSC: " ++ show sc showAlt :: CaseAlt -> String showAlt (ConCase n i ns sc) = show (n,i,ns) ++ " -> " ++ showSC sc showAlt (ConstCase c sc) = showConstant c ++ " -> " ++ showSC sc showAlt (DefaultCase sc) = "_ ->" ++ showSC sc showAlt alt = "showAlt: " ++ show alt showTerm :: Term -> String showTerm (App e1 e2) = "App (" ++ showTerm e1 ++ ") (" ++ showTerm e2 ++ ")" showTerm (Constant c) = "Constant (" ++ showConstant c ++ ")" showTerm Impossible = "Impossible" showTerm Erased = "Erased" showTerm (P nt n tm) = "P {" ++ show nt ++ "} " ++ show n ++ " (" ++ showTerm tm ++ ")" showTerm (V v) = "V " ++ show v showTerm (Bind n bndr tm) = "Bind " ++ show n ++ " (" ++ showBinder bndr ++ ") (" ++ showTerm tm ++ ")" showTerm (Proj tm i) = "Proj " ++ show i ++ " (" ++ show tm ++ ")" showTerm (TType uexp) = "TType " ++ show uexp showBinder :: Binder Term -> String showBinder (Pi tm) = "Pi (" ++ showTerm tm ++ ")" showBinder b = "showBinder: " ++ show b showConstant :: Const -> String showConstant (I _) = "(I i)" showConstant (BI _) = "(BI i)" showConstant (Fl _) = "(Fl f)" showConstant (Ch _) = "(Ch c)" showConstant (Str _) = "(Str s)" showConstant (AType a) = "AType (" ++ showAType a ++ ")" showConstant StrType = "StrType" showConstant PtrType = "PtrType " showConstant VoidType = "VoidType" showConstant Forgot = "Forgot" showConstant (B8 _) = "(B8 w)" showConstant (B16 _) = "(B16 w)" showConstant (B32 _) = "(B32 w)" showConstant (B64 _) = "(B64 w)" showConstant c = "showConstant: " ++ show c showAType :: ArithTy -> String showAType (ATInt ITNative) = "(ATInt ITNative)" showAType (ATInt ITBig) = "(ATInt ITBig)" showAType (ATInt ITChar) = "(ATInt ITChar)" showAType (ATInt (ITFixed _)) = "(ATInt (ITFixed n))" showAType (ATInt (ITVec _ _)) = "(ATInt (ITVec e c))" showAType ATFloat = "ATFloat"
christiaanb/Idris-dev
src/IRTS/CLaSH/Show.hs
Haskell
bsd-3-clause
2,225
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Passman.Engine.Conversions where import Control.Error.Safe (assertErr) import Data.Bits (shift) import Data.Foldable (all) import Data.Semigroup ((<>)) import Data.Vector.Unboxed (Vector, (!)) import qualified Data.Vector.Unboxed as V import qualified Passman.Engine.ByteString as B import Passman.Engine.Errors import Passman.Engine.Strength (Strength(..)) data CharSpace = CharSpace { charSpaceName :: String , charSpaceSymbols :: Vector Char } charSpaceSize :: CharSpace -> Int charSpaceSize CharSpace{..} = V.length charSpaceSymbols makeCharSpace :: String -> String -> CharSpace makeCharSpace name symbols = CharSpace name $ V.fromList symbols type Converter = B.ByteString -> String data ConverterSpec = ConverterSpec CharSpace Strength makeConverter :: Maybe Int -> ConverterSpec -> Either EngineError Converter makeConverter inLength spec = do validateBase spec validateInputRequirements inLength spec return $ convert spec validateBase :: ConverterSpec -> Either EngineError () validateBase (ConverterSpec charSpace _) = assertErr invalidBase checkBase where checkBase = 2 <= base && base <= 256 invalidBase = InvalidOutputBase base base = charSpaceSize charSpace validateInputRequirements :: Maybe Int -> ConverterSpec -> Either EngineError () validateInputRequirements provided spec = assertErr insufficientInput checkInputLength where checkInputLength = all (inLength <=) provided insufficientInput = ExcessiveDerivedBits outLength inLength (inLength, outLength) = inputOutputLength spec inputOutputLength :: ConverterSpec -> (Int, Int) inputOutputLength (ConverterSpec CharSpace{..} Strength{..}) = (inLength, outLength) where base = V.length charSpaceSymbols rawOutputLength = ceiling $ fromIntegral strengthBits / logBase (2 :: Double) (fromIntegral base) outLength = rawOutputLength + (rawOutputLength `mod` 2) inLength = ceiling $ fromIntegral outLength * logBase (256 :: Double) (fromIntegral base) inputLength :: ConverterSpec -> Int inputLength = fst . inputOutputLength integerOfBytes :: Int -> B.ByteString -> Integer integerOfBytes inLength bytes = B.foldr (\a b -> fromIntegral a + shift b 8) 0 $ B.take inLength (bytes <> zeroes) where zeroes = B.replicate inLength 0 materialize :: Int -> Vector Char -> Integer -> String materialize outputLength chars src = take outputLength $ materialize' src where base = V.length chars materialize' n = let (q, r) = n `quotRem` fromIntegral base in chars ! fromIntegral r : materialize' q convert :: ConverterSpec -> B.ByteString -> String convert spec@(ConverterSpec charSpace _) bytes = materialize outLength (charSpaceSymbols charSpace) $ integerOfBytes inLength bytes where (inLength, outLength) = inputOutputLength spec
chwthewke/passman-hs
src/Passman/Engine/Conversions.hs
Haskell
bsd-3-clause
3,136
{-# LANGUAGE Rank2Types, TemplateHaskell, BangPatterns, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.AD.Mode.Reverse -- Copyright : (c) Edward Kmett 2010 -- License : BSD3 -- Maintainer : ekmett@gmail.com -- Stability : experimental -- Portability : GHC only -- -- Mixed-Mode Automatic Differentiation. -- -- For reverse mode AD we use 'System.Mem.StableName.StableName' to recover sharing information from -- the tape to avoid combinatorial explosion, and thus run asymptotically faster -- than it could without such sharing information, but the use of side-effects -- contained herein is benign. -- ----------------------------------------------------------------------------- module Numeric.AD.Mode.Reverse ( -- * Gradient grad , grad' , gradWith , gradWith' -- * Jacobian , jacobian , jacobian' , jacobianWith , jacobianWith' -- * Hessian , hessian , hessianF -- * Derivatives , diff , diff' , diffF , diffF' -- * Unsafe Variadic Gradient , vgrad, vgrad' , Grad ) where import Control.Applicative ((<$>)) import Data.Traversable (Traversable) import Numeric.AD.Types import Numeric.AD.Internal.Classes import Numeric.AD.Internal.Composition import Numeric.AD.Internal.Reverse import Numeric.AD.Internal.Var -- | The 'grad' function calculates the gradient of a non-scalar-to-scalar function with 'Reverse' AD in a single pass. -- -- >>> grad (\[x,y,z] -> x*y+z) [1,2,3] -- [2,1,1] grad :: (Traversable f, Num a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> f a grad f as = unbind vs (partialArray bds $ f vs) where (vs,bds) = bind as {-# INLINE grad #-} -- | The 'grad'' function calculates the result and gradient of a non-scalar-to-scalar function with 'Reverse' AD in a single pass. -- -- >>> grad' (\[x,y,z] -> 4*x*exp y+cos z) [1,2,3] -- (28.566231899122155,[29.5562243957226,29.5562243957226,-0.1411200080598672]) grad' :: (Traversable f, Num a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> (a, f a) grad' f as = (primal r, unbind vs $ partialArray bds r) where (vs, bds) = bind as r = f vs {-# INLINE grad' #-} -- | @'grad' g f@ function calculates the gradient of a non-scalar-to-scalar function @f@ with reverse-mode AD in a single pass. -- The gradient is combined element-wise with the argument using the function @g@. -- -- @ -- 'grad' = 'gradWith' (\_ dx -> dx) -- 'id' = 'gradWith' const -- @ -- -- gradWith :: (Traversable f, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> f b gradWith g f as = unbindWith g vs (partialArray bds $ f vs) where (vs,bds) = bind as {-# INLINE gradWith #-} -- | @'grad'' g f@ calculates the result and gradient of a non-scalar-to-scalar function @f@ with 'Reverse' AD in a single pass -- the gradient is combined element-wise with the argument using the function @g@. -- -- @'grad'' == 'gradWith'' (\_ dx -> dx)@ gradWith' :: (Traversable f, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> (a, f b) gradWith' g f as = (primal r, unbindWith g vs $ partialArray bds r) where (vs, bds) = bind as r = f vs {-# INLINE gradWith' #-} -- | The 'jacobian' function calculates the jacobian of a non-scalar-to-non-scalar function with reverse AD lazily in @m@ passes for @m@ outputs. -- -- >>> jacobian (\[x,y] -> [y,x,x*y]) [2,1] -- [[0,1],[1,0],[1,2]] -- -- >>> jacobian (\[x,y] -> [exp y,cos x,x+y]) [1,2] -- [[0.0,7.38905609893065],[-0.8414709848078965,0.0],[1.0,1.0]] jacobian :: (Traversable f, Functor g, Num a) => (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (f a) jacobian f as = unbind vs . partialArray bds <$> f vs where (vs, bds) = bind as {-# INLINE jacobian #-} -- | The 'jacobian'' function calculates both the result and the Jacobian of a nonscalar-to-nonscalar function, using @m@ invocations of reverse AD, -- where @m@ is the output dimensionality. Applying @fmap snd@ to the result will recover the result of 'jacobian' -- | An alias for 'gradF'' -- -- ghci> jacobian' (\[x,y] -> [y,x,x*y]) [2,1] -- [(1,[0,1]),(2,[1,0]),(2,[1,2])] jacobian' :: (Traversable f, Functor g, Num a) => (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (a, f a) jacobian' f as = row <$> f vs where (vs, bds) = bind as row a = (primal a, unbind vs (partialArray bds a)) {-# INLINE jacobian' #-} -- | 'jacobianWith g f' calculates the Jacobian of a non-scalar-to-non-scalar function @f@ with reverse AD lazily in @m@ passes for @m@ outputs. -- -- Instead of returning the Jacobian matrix, the elements of the matrix are combined with the input using the @g@. -- -- @ -- 'jacobian' = 'jacobianWith' (\_ dx -> dx) -- 'jacobianWith' 'const' = (\f x -> 'const' x '<$>' f x) -- @ jacobianWith :: (Traversable f, Functor g, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (f b) jacobianWith g f as = unbindWith g vs . partialArray bds <$> f vs where (vs, bds) = bind as {-# INLINE jacobianWith #-} -- | 'jacobianWith' g f' calculates both the result and the Jacobian of a nonscalar-to-nonscalar function @f@, using @m@ invocations of reverse AD, -- where @m@ is the output dimensionality. Applying @fmap snd@ to the result will recover the result of 'jacobianWith' -- -- Instead of returning the Jacobian matrix, the elements of the matrix are combined with the input using the @g@. -- -- @'jacobian'' == 'jacobianWith'' (\_ dx -> dx)@ jacobianWith' :: (Traversable f, Functor g, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (a, f b) jacobianWith' g f as = row <$> f vs where (vs, bds) = bind as row a = (primal a, unbindWith g vs (partialArray bds a)) {-# INLINE jacobianWith' #-} -- | Compute the derivative of a function. -- -- >>> diff sin 0 -- 1.0 -- -- >>> cos 0 -- 1.0 diff :: Num a => (forall s. Mode s => AD s a -> AD s a) -> a -> a diff f a = derivative $ f (var a 0) {-# INLINE diff #-} -- | The 'diff'' function calculates the value and derivative, as a -- pair, of a scalar-to-scalar function. -- -- -- >>> diff' sin 0 -- (0.0,1.0) diff' :: Num a => (forall s. Mode s => AD s a -> AD s a) -> a -> (a, a) diff' f a = derivative' $ f (var a 0) {-# INLINE diff' #-} -- | Compute the derivatives of a function that returns a vector with regards to its single input. -- -- >>> diffF (\a -> [sin a, cos a]) 0 -- [1.0,0.0] diffF :: (Functor f, Num a) => (forall s. Mode s => AD s a -> f (AD s a)) -> a -> f a diffF f a = derivative <$> f (var a 0) {-# INLINE diffF #-} -- | Compute the derivatives of a function that returns a vector with regards to its single input -- as well as the primal answer. -- -- >>> diffF' (\a -> [sin a, cos a]) 0 -- [(0.0,1.0),(1.0,0.0)] diffF' :: (Functor f, Num a) => (forall s. Mode s => AD s a -> f (AD s a)) -> a -> f (a, a) diffF' f a = derivative' <$> f (var a 0) {-# INLINE diffF' #-} -- | Compute the 'hessian' via the 'jacobian' of the gradient. gradient is computed in reverse mode and then the 'jacobian' is computed in reverse mode. -- -- However, since the @'grad' f :: f a -> f a@ is square this is not as fast as using the forward-mode 'jacobian' of a reverse mode gradient provided by 'Numeric.AD.hessian'. -- -- >>> hessian (\[x,y] -> x*y) [1,2] -- [[0,1],[1,0]] hessian :: (Traversable f, Num a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> f (f a) hessian f = jacobian (grad (decomposeMode . f . fmap composeMode)) -- | Compute the order 3 Hessian tensor on a non-scalar-to-non-scalar function via the reverse-mode Jacobian of the reverse-mode Jacobian of the function. -- -- Less efficient than 'Numeric.AD.Mode.Mixed.hessianF'. -- -- >>> hessianF (\[x,y] -> [x*y,x+y,exp x*cos y]) [1,2] -- [[[0.0,1.0],[1.0,0.0]],[[0.0,0.0],[0.0,0.0]],[[-1.1312043837568135,-2.4717266720048188],[-2.4717266720048188,1.1312043837568135]]] hessianF :: (Traversable f, Functor g, Num a) => (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (f (f a)) hessianF f = decomposeFunctor . jacobian (ComposeFunctor . jacobian (fmap decomposeMode . f . fmap composeMode))
yairchu/ad
src/Numeric/AD/Mode/Reverse.hs
Haskell
bsd-3-clause
8,302
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} -- | Abstract Haskell syntax for expressions. module HsExpr where #include "HsVersions.h" -- friends: import HsDecls import HsPat import HsLit import PlaceHolder ( PostTc,PostRn,DataId ) import HsTypes import HsBinds -- others: import TcEvidence import CoreSyn import Var import Name import BasicTypes import ConLike import SrcLoc import Util import StaticFlags( opt_PprStyle_Debug ) import Outputable import FastString import Type -- libraries: import Data.Data hiding (Fixity) import Data.Maybe (isNothing) {- ************************************************************************ * * \subsection{Expressions proper} * * ************************************************************************ -} -- * Expressions proper type LHsExpr id = Located (HsExpr id) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation ------------------------- -- | PostTcExpr is an evidence expression attached to the syntax tree by the -- type checker (c.f. postTcType). type PostTcExpr = HsExpr Id -- | We use a PostTcTable where there are a bunch of pieces of evidence, more -- than is convenient to keep individually. type PostTcTable = [(Name, PostTcExpr)] noPostTcExpr :: PostTcExpr noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr")) noPostTcTable :: PostTcTable noPostTcTable = [] ------------------------- -- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier, -- by the renamer. It's used for rebindable syntax. -- -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for -- @(>>=)@, and then instantiated by the type checker with its type args -- etc type SyntaxExpr id = HsExpr id noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after, -- (if the syntax slot makes no sense) noSyntaxExpr = HsLit (HsString "" (fsLit "noSyntaxExpr")) type CmdSyntaxTable id = [(Name, SyntaxExpr id)] -- See Note [CmdSyntaxTable] {- Note [CmdSyntaxtable] ~~~~~~~~~~~~~~~~~~~~~ Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps track of the methods needed for a Cmd. * Before the renamer, this list is an empty list * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@ For example, for the 'arr' method * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr) * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22) where @arr_22@ is whatever 'arr' is in scope * After the type checker, it takes the form [(std_name, <expression>)] where <expression> is the evidence for the method. This evidence is instantiated with the class, but is still polymorphic in everything else. For example, in the case of 'arr', the evidence has type forall b c. (b->c) -> a b c where 'a' is the ambient type of the arrow. This polymorphism is important because the desugarer uses the same evidence at multiple different types. This is Less Cool than what we normally do for rebindable syntax, which is to make fully-instantiated piece of evidence at every use site. The Cmd way is Less Cool because * The renamer has to predict which methods are needed. See the tedious RnExpr.methodNamesCmd. * The desugarer has to know the polymorphic type of the instantiated method. This is checked by Inst.tcSyntaxName, but is less flexible than the rest of rebindable syntax, where the type is less pre-ordained. (And this flexibility is useful; for example we can typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.) -} -- | A Haskell expression. data HsExpr id = HsVar (Located id) -- ^ Variable -- See Note [Located RdrNames] | HsUnboundVar OccName -- ^ Unbound variable; also used for "holes" _, or _x. -- Turned from HsVar to HsUnboundVar by the renamer, when -- it finds an out-of-scope variable -- Turned into HsVar by type checker, to support deferred -- type errors. (The HsUnboundVar only has an OccName.) | HsRecFld (AmbiguousFieldOcc id) -- ^ Variable pointing to record selector | HsOverLabel FastString -- ^ Overloaded label (See Note [Overloaded labels] -- in GHC.OverloadedLabels) | HsIPVar HsIPName -- ^ Implicit parameter | HsOverLit (HsOverLit id) -- ^ Overloaded literals | HsLit HsLit -- ^ Simple (non-overloaded) literals | HsLam (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsLamCase (PostTc id Type) (MatchGroup id (LHsExpr id)) -- ^ Lambda-case -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsApp (LHsExpr id) (LHsExpr id) -- ^ Application -- | Operator applications: -- NB Bracketed ops such as (+) come out as Vars. -- NB We need an expr for the operator in an OpApp/Section since -- the typechecker may need to apply the operator to a few types. | OpApp (LHsExpr id) -- left operand (LHsExpr id) -- operator (PostRn id Fixity) -- Renamer adds fixity; bottom until then (LHsExpr id) -- right operand -- | Negation operator. Contains the negated expression and the name -- of 'negate' -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus' -- For details on above see note [Api annotations] in ApiAnnotation | NegApp (LHsExpr id) (SyntaxExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsPar (LHsExpr id) -- ^ Parenthesised expr; see Note [Parens in HsSyn] | SectionL (LHsExpr id) -- operand; see Note [Sections in HsSyn] (LHsExpr id) -- operator | SectionR (LHsExpr id) -- operator; see Note [Sections in HsSyn] (LHsExpr id) -- operand -- | Used for explicit tuples and sections thereof -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitTuple [LHsTupArg id] Boxity -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCase (LHsExpr id) (MatchGroup id (LHsExpr id)) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsIf (Maybe (SyntaxExpr id)) -- cond function -- Nothing => use the built-in 'if' -- See Note [Rebindable if] (LHsExpr id) -- predicate (LHsExpr id) -- then part (LHsExpr id) -- else part -- | Multi-way if -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf' -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation | HsMultiIf (PostTc id Type) [LGRHS id (LHsExpr id)] -- | let(rec) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsLet (Located (HsLocalBinds id)) (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsDo (HsStmtContext Name) -- The parameterisation is unimportant -- because in this context we never use -- the PatGuard or ParStmt variant (Located [ExprLStmt id]) -- "do":one or more stmts (PostTc id Type) -- Type of the whole expression -- | Syntactic list: [a,b,c,...] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitList (PostTc id Type) -- Gives type of components of list (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness [LHsExpr id] -- | Syntactic parallel array: [:e1, ..., en:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnVbar' -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitPArr (PostTc id Type) -- type of elements of the parallel array [LHsExpr id] -- | Record construction -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordCon { rcon_con_name :: Located id -- The constructor name; -- not used after type checking , rcon_con_like :: PostTc id ConLike -- The data constructor or pattern synonym , rcon_con_expr :: PostTcExpr -- Instantiated constructor function , rcon_flds :: HsRecordBinds id } -- The fields -- | Record update -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordUpd { rupd_expr :: LHsExpr id , rupd_flds :: [LHsRecUpdField id] , rupd_cons :: PostTc id [ConLike] -- Filled in by the type checker to the -- _non-empty_ list of DataCons that have -- all the upd'd fields , rupd_in_tys :: PostTc id [Type] -- Argument types of *input* record type , rupd_out_tys :: PostTc id [Type] -- and *output* record type -- The original type can be reconstructed -- with conLikeResTy , rupd_wrap :: PostTc id HsWrapper -- See note [Record Update HsWrapper] } -- For a type family, the arg types are of the *instance* tycon, -- not the family tycon -- | Expression with an explicit type signature. @e :: type@ -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | ExprWithTySig (LHsExpr id) (LHsSigWcType id) | ExprWithTySigOut -- Post typechecking (LHsExpr id) (LHsSigWcType Name) -- Retain the signature, -- as HsSigType Name, for -- round-tripping purposes -- | Arithmetic sequence -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ArithSeq PostTcExpr (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromList witness (ArithSeqInfo id) -- | Arithmetic sequence for parallel array -- -- > [:e1..e2:] or [:e1, e2..e3:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | PArrSeq PostTcExpr (ArithSeqInfo id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@, -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsSCC SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- "set cost centre" SCC pragma (LHsExpr id) -- expr whose cost is to be measured -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@, -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- hdaume: core annotation (LHsExpr id) ----------------------------------------------------------- -- MetaHaskell Extensions -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsBracket (HsBracket id) -- See Note [Pending Splices] | HsRnBracketOut (HsBracket Name) -- Output of the renamer is the *original* renamed -- expression, plus [PendingRnSplice] -- _renamed_ splices to be type checked | HsTcBracketOut (HsBracket Name) -- Output of the type checker is the *original* -- renamed expression, plus [PendingTcSplice] -- _typechecked_ splices to be -- pasted back in by the desugarer -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsSpliceE (HsSplice id) ----------------------------------------------------------- -- Arrow notation extension -- | @proc@ notation for Arrows -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc', -- 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | HsProc (LPat id) -- arrow abstraction, proc (LHsCmdTop id) -- body of the abstraction -- always has an empty stack --------------------------------------- -- static pointers extension -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic', -- For details on above see note [Api annotations] in ApiAnnotation | HsStatic (LHsExpr id) --------------------------------------- -- The following are commands, not expressions proper -- They are only used in the parsing stage and are removed -- immediately in parser.RdrHsSyn.checkCommand -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation | HsArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg (PostTc id Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands --------------------------------------- -- Haskell program coverage (Hpc) Support | HsTick (Tickish id) (LHsExpr id) -- sub-expression | HsBinTick Int -- module-local tick number for True Int -- module-local tick number for False (LHsExpr id) -- sub-expression -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnMinus', -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon', -- 'ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTickPragma -- A pragma introduced tick SourceText -- Note [Pragma source text] in BasicTypes (StringLiteral,(Int,Int),(Int,Int)) -- external span for this tick ((SourceText,SourceText),(SourceText,SourceText)) -- Source text for the four integers used in the span. -- See note [Pragma source text] in BasicTypes (LHsExpr id) --------------------------------------- -- These constructors only appear temporarily in the parser. -- The renamer translates them into the Right Thing. | EWildPat -- wildcard -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | EAsPat (Located id) -- as pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | EViewPat (LHsExpr id) -- view pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | ELazyPat (LHsExpr id) -- ~ pattern -- | Use for type application in expressions. -- 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | HsType (LHsWcType id) -- Explicit type argument; e.g f @Int x y -- NB: Has wildcards, but no implicit quant. | HsTypeOut (LHsWcType Name) -- just for pretty-printing --------------------------------------- -- Finally, HsWrap appears only in typechecker output | HsWrap HsWrapper -- TRANSLATION (HsExpr id) deriving (Typeable) deriving instance (DataId id) => Data (HsExpr id) -- | HsTupArg is used for tuple sections -- (,a,) is represented by ExplicitTuple [Missing ty1, Present a, Missing ty3] -- Which in turn stands for (\x:ty1 \y:ty2. (x,a,y)) type LHsTupArg id = Located (HsTupArg id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation data HsTupArg id = Present (LHsExpr id) -- ^ The argument | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type deriving (Typeable) deriving instance (DataId id) => Data (HsTupArg id) tupArgPresent :: LHsTupArg id -> Bool tupArgPresent (L _ (Present {})) = True tupArgPresent (L _ (Missing {})) = False {- Note [Parens in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~ HsPar (and ParPat in patterns, HsParTy in types) is used as follows * Generally HsPar is optional; the pretty printer adds parens where necessary. Eg (HsApp f (HsApp g x)) is fine, and prints 'f (g x)' * HsPars are pretty printed as '( .. )' regardless of whether or not they are strictly necssary * HsPars are respected when rearranging operator fixities. So a * (b + c) means what it says (where the parens are an HsPar) Note [Sections in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~~~ Sections should always appear wrapped in an HsPar, thus HsPar (SectionR ...) The parser parses sections in a wider variety of situations (See Note [Parsing sections]), but the renamer checks for those parens. This invariant makes pretty-printing easier; we don't need a special case for adding the parens round sections. Note [Rebindable if] ~~~~~~~~~~~~~~~~~~~~ The rebindable syntax for 'if' is a bit special, because when rebindable syntax is *off* we do not want to treat (if c then t else e) as if it was an application (ifThenElse c t e). Why not? Because we allow an 'if' to return *unboxed* results, thus if blah then 3# else 4# whereas that would not be possible using a all to a polymorphic function (because you can't call a polymorphic function at an unboxed type). So we use Nothing to mean "use the old built-in typing rule". Note [Record Update HsWrapper] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is a wrapper in RecordUpd which is used for the *required* constraints for pattern synonyms. This wrapper is created in the typechecking and is then directly used in the desugaring without modification. For example, if we have the record pattern synonym P, pattern P :: (Show a) => a -> Maybe a pattern P{x} = Just x foo = (Just True) { x = False } then `foo` desugars to something like foo = case Just True of P x -> P False hence we need to provide the correct dictionaries to P's matcher on the RHS so that we can build the expression. Note [Located RdrNames] ~~~~~~~~~~~~~~~~~~~~~~~ A number of syntax elements have seemingly redundant locations attached to them. This is deliberate, to allow transformations making use of the API Annotations to easily correlate a Located Name in the RenamedSource with a Located RdrName in the ParsedSource. There are unfortunately enough differences between the ParsedSource and the RenamedSource that the API Annotations cannot be used directly with RenamedSource, so this allows a simple mapping to be used based on the location. -} instance OutputableBndr id => Outputable (HsExpr id) where ppr expr = pprExpr expr ----------------------- -- pprExpr, pprLExpr, pprBinds call pprDeeper; -- the underscore versions do not pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc pprLExpr (L _ e) = pprExpr e pprExpr :: OutputableBndr id => HsExpr id -> SDoc pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e | otherwise = pprDeeper (ppr_expr e) isQuietHsExpr :: HsExpr id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsExpr (HsPar _) = True -- applications don't display anything themselves isQuietHsExpr (HsApp _ _) = True isQuietHsExpr (OpApp _ _ _ _) = True isQuietHsExpr _ = False pprBinds :: (OutputableBndr idL, OutputableBndr idR) => HsLocalBindsLR idL idR -> SDoc pprBinds b = pprDeeper (ppr b) ----------------------- ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc ppr_lexpr e = ppr_expr (unLoc e) ppr_expr :: forall id. OutputableBndr id => HsExpr id -> SDoc ppr_expr (HsVar (L _ v)) = pprPrefixOcc v ppr_expr (HsUnboundVar v) = pprPrefixOcc v ppr_expr (HsIPVar v) = ppr v ppr_expr (HsOverLabel l) = char '#' <> ppr l ppr_expr (HsLit lit) = ppr lit ppr_expr (HsOverLit lit) = ppr lit ppr_expr (HsPar e) = parens (ppr_lexpr e) ppr_expr (HsCoreAnn _ (StringLiteral _ s) e) = vcat [text "HsCoreAnn" <+> ftext s, ppr_lexpr e] ppr_expr (HsApp e1 e2) = let (fun, args) = collect_args e1 [e2] in hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args)) where collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args) collect_args fun args = (fun, args) ppr_expr (OpApp e1 op _ e2) = case unLoc op of HsVar (L _ v) -> pp_infixly v HsRecFld f -> pp_infixly f _ -> pp_prefixly where pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens pp_e2 = pprDebugParendExpr e2 -- to make precedence clear pp_prefixly = hang (ppr op) 2 (sep [pp_e1, pp_e2]) pp_infixly v = sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]] ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e ppr_expr (SectionL expr op) = case unLoc op of HsVar (L _ v) -> pp_infixly v _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op]) 4 (hsep [pp_expr, text "x_ )"]) pp_infixly v = (sep [pp_expr, pprInfixOcc v]) ppr_expr (SectionR op expr) = case unLoc op of HsVar (L _ v) -> pp_infixly v _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"]) 4 (pp_expr <> rparen) pp_infixly v = sep [pprInfixOcc v, pp_expr] ppr_expr (ExplicitTuple exprs boxity) = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs)) where ppr_tup_args [] = [] ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es punc (Present {} : _) = comma <> space punc (Missing {} : _) = comma punc [] = empty ppr_expr (HsLam matches) = pprMatches (LambdaExpr :: HsMatchContext id) matches ppr_expr (HsLamCase _ matches) = sep [ sep [text "\\case {"], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_expr (HsCase expr matches) = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_expr (HsIf _ e1 e2 e3) = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")], nest 4 (ppr e2), text "else", nest 4 (ppr e3)] ppr_expr (HsMultiIf _ alts) = sep $ text "if" : map ppr_alt alts where ppr_alt (L _ (GRHS guards expr)) = sep [ vbar <+> interpp'SP guards , text "->" <+> pprDeeper (ppr expr) ] -- special case: let ... in let ... ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _))) = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lexpr expr] ppr_expr (HsLet (L _ binds) expr) = sep [hang (text "let") 2 (pprBinds binds), hang (text "in") 2 (ppr expr)] ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts ppr_expr (ExplicitList _ _ exprs) = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (ExplicitPArr _ exprs) = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds }) = hang (ppr con_id) 2 (ppr rbinds) ppr_expr (RecordUpd { rupd_expr = aexp, rupd_flds = rbinds }) = hang (pprLExpr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds)))) ppr_expr (ExprWithTySig expr sig) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ExprWithTySigOut expr sig) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ArithSeq _ _ info) = brackets (ppr info) ppr_expr (PArrSeq _ info) = paBrackets (ppr info) ppr_expr EWildPat = char '_' ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e ppr_expr (HsSCC _ (StringLiteral _ lbl) expr) = sep [ text "{-# SCC" <+> doubleQuotes (ftext lbl) <+> ptext (sLit "#-}"), pprParendExpr expr ] ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn ppr_expr (HsType (HsWC { hswc_body = ty })) = char '@' <> pprParendHsType (unLoc ty) ppr_expr (HsTypeOut (HsWC { hswc_body = ty })) = char '@' <> pprParendHsType (unLoc ty) ppr_expr (HsSpliceE s) = pprSplice s ppr_expr (HsBracket b) = pprHsBracket b ppr_expr (HsRnBracketOut e []) = ppr e ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps ppr_expr (HsTcBracketOut e []) = ppr e ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _))) = hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd] ppr_expr (HsStatic e) = hsep [text "static", pprParendExpr e] ppr_expr (HsTick tickish exp) = pprTicks (ppr exp) $ ppr tickish <+> ppr_lexpr exp ppr_expr (HsBinTick tickIdTrue tickIdFalse exp) = pprTicks (ppr exp) $ hcat [text "bintick<", ppr tickIdTrue, text ",", ppr tickIdFalse, text ">(", ppr exp, text ")"] ppr_expr (HsTickPragma _ externalSrcLoc _ exp) = pprTicks (ppr exp) $ hcat [text "tickpragma<", pprExternalSrcLoc externalSrcLoc, text ">(", ppr exp, text ")"] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]] ppr_expr (HsArrForm op _ args) = hang (text "(|" <+> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)") ppr_expr (HsRecFld f) = ppr f pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4)) = ppr (src,(n1,n2),(n3,n4)) {- HsSyn records exactly where the user put parens, with HsPar. So generally speaking we print without adding any parens. However, some code is internally generated, and in some places parens are absolutely required; so for these places we use pprParendExpr (but don't print double parens of course). For operator applications we don't add parens, because the operator fixities should do the job, except in debug mode (-dppr-debug) so we can see the structure of the parse tree. -} pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc pprDebugParendExpr expr = getPprStyle (\sty -> if debugStyle sty then pprParendExpr expr else pprLExpr expr) pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc pprParendExpr expr | hsExprNeedsParens (unLoc expr) = parens (pprLExpr expr) | otherwise = pprLExpr expr -- Using pprLExpr makes sure that we go 'deeper' -- I think that is usually (always?) right hsExprNeedsParens :: HsExpr id -> Bool -- True of expressions for which '(e)' and 'e' -- mean the same thing hsExprNeedsParens (ArithSeq {}) = False hsExprNeedsParens (PArrSeq {}) = False hsExprNeedsParens (HsLit {}) = False hsExprNeedsParens (HsOverLit {}) = False hsExprNeedsParens (HsVar {}) = False hsExprNeedsParens (HsUnboundVar {}) = False hsExprNeedsParens (HsIPVar {}) = False hsExprNeedsParens (HsOverLabel {}) = False hsExprNeedsParens (ExplicitTuple {}) = False hsExprNeedsParens (ExplicitList {}) = False hsExprNeedsParens (ExplicitPArr {}) = False hsExprNeedsParens (RecordCon {}) = False hsExprNeedsParens (RecordUpd {}) = False hsExprNeedsParens (HsPar {}) = False hsExprNeedsParens (HsBracket {}) = False hsExprNeedsParens (HsRnBracketOut {}) = False hsExprNeedsParens (HsTcBracketOut {}) = False hsExprNeedsParens (HsDo sc _ _) | isListCompExpr sc = False hsExprNeedsParens (HsRecFld{}) = False hsExprNeedsParens (HsType {}) = False hsExprNeedsParens (HsTypeOut {}) = False hsExprNeedsParens _ = True isAtomicHsExpr :: HsExpr id -> Bool -- True of a single token isAtomicHsExpr (HsVar {}) = True isAtomicHsExpr (HsLit {}) = True isAtomicHsExpr (HsOverLit {}) = True isAtomicHsExpr (HsIPVar {}) = True isAtomicHsExpr (HsOverLabel {}) = True isAtomicHsExpr (HsUnboundVar {}) = True isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e) isAtomicHsExpr (HsRecFld{}) = True isAtomicHsExpr _ = False {- ************************************************************************ * * \subsection{Commands (in arrow abstractions)} * * ************************************************************************ We re-use HsExpr to represent these. -} type LHsCmd id = Located (HsCmd id) data HsCmd id -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg (PostTc id Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands | HsCmdApp (LHsCmd id) (LHsExpr id) | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdPar (LHsCmd id) -- parenthesised command -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdCase (LHsExpr id) (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function (LHsExpr id) -- predicate (LHsCmd id) -- then part (LHsCmd id) -- else part -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdLet (Located (HsLocalBinds id)) -- let(rec) (LHsCmd id) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdDo (Located [CmdLStmt id]) (PostTc id Type) -- Type of the whole expression -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdWrap HsWrapper (HsCmd id) -- If cmd :: arg1 --> res -- wrap :: arg1 "->" arg2 -- Then (HsCmdWrap wrap cmd) :: arg2 --> res deriving (Typeable) deriving instance (DataId id) => Data (HsCmd id) data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp deriving (Data, Typeable) {- | Top-level command, introducing a new arrow. This may occur inside a proc (where the stack is empty) or as an argument of a command-forming operator. -} type LHsCmdTop id = Located (HsCmdTop id) data HsCmdTop id = HsCmdTop (LHsCmd id) (PostTc id Type) -- Nested tuple of inputs on the command's stack (PostTc id Type) -- return type of the command (CmdSyntaxTable id) -- See Note [CmdSyntaxTable] deriving (Typeable) deriving instance (DataId id) => Data (HsCmdTop id) instance OutputableBndr id => Outputable (HsCmd id) where ppr cmd = pprCmd cmd ----------------------- -- pprCmd and pprLCmd call pprDeeper; -- the underscore versions do not pprLCmd :: OutputableBndr id => LHsCmd id -> SDoc pprLCmd (L _ c) = pprCmd c pprCmd :: OutputableBndr id => HsCmd id -> SDoc pprCmd c | isQuietHsCmd c = ppr_cmd c | otherwise = pprDeeper (ppr_cmd c) isQuietHsCmd :: HsCmd id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsCmd (HsCmdPar _) = True -- applications don't display anything themselves isQuietHsCmd (HsCmdApp _ _) = True isQuietHsCmd _ = False ----------------------- ppr_lcmd :: OutputableBndr id => LHsCmd id -> SDoc ppr_lcmd c = ppr_cmd (unLoc c) ppr_cmd :: forall id. OutputableBndr id => HsCmd id -> SDoc ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c) ppr_cmd (HsCmdApp c e) = let (fun, args) = collect_args c [e] in hang (ppr_lcmd fun) 2 (sep (map pprParendExpr args)) where collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args) collect_args fun args = (fun, args) ppr_cmd (HsCmdLam matches) = pprMatches (LambdaExpr :: HsMatchContext id) matches ppr_cmd (HsCmdCase expr matches) = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_cmd (HsCmdIf _ e ct ce) = sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")], nest 4 (ppr ct), text "else", nest 4 (ppr ce)] -- special case: let ... in let ... ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _))) = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lcmd cmd] ppr_cmd (HsCmdLet (L _ binds) cmd) = sep [hang (text "let") 2 (pprBinds binds), hang (text "in") 2 (ppr cmd)] ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts ppr_cmd (HsCmdWrap w cmd) = pprHsWrapper (ppr_cmd cmd) w ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]] ppr_cmd (HsCmdArrForm op _ args) = hang (text "(|" <> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <> text "|)") pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc pprCmdArg (HsCmdTop cmd@(L _ (HsCmdArrForm _ Nothing [])) _ _ _) = ppr_lcmd cmd pprCmdArg (HsCmdTop cmd _ _ _) = parens (ppr_lcmd cmd) instance OutputableBndr id => Outputable (HsCmdTop id) where ppr = pprCmdArg {- ************************************************************************ * * \subsection{Record binds} * * ************************************************************************ -} type HsRecordBinds id = HsRecFields id (LHsExpr id) {- ************************************************************************ * * \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes} * * ************************************************************************ @Match@es are sets of pattern bindings and right hand sides for functions, patterns or case branches. For example, if a function @g@ is defined as: \begin{verbatim} g (x,y) = y g ((x:ys),y) = y+1, \end{verbatim} then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@. It is always the case that each element of an @[Match]@ list has the same number of @pats@s inside it. This corresponds to saying that a function defined by pattern matching must have the same number of patterns in each equation. -} data MatchGroup id body = MG { mg_alts :: Located [LMatch id body] -- The alternatives , mg_arg_tys :: [PostTc id Type] -- Types of the arguments, t1..tn , mg_res_ty :: PostTc id Type -- Type of the result, tr , mg_origin :: Origin } -- The type is the type of the entire group -- t1 -> ... -> tn -> tr -- where there are n patterns deriving (Typeable) deriving instance (Data body,DataId id) => Data (MatchGroup id body) type LMatch id body = Located (Match id body) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a -- list -- For details on above see note [Api annotations] in ApiAnnotation data Match id body = Match { m_fixity :: MatchFixity id, -- See note [m_fixity in Match] m_pats :: [LPat id], -- The patterns m_type :: (Maybe (LHsType id)), -- A type signature for the result of the match -- Nothing after typechecking -- NB: No longer supported m_grhss :: (GRHSs id body) } deriving (Typeable) deriving instance (Data body,DataId id) => Data (Match id body) {- Note [m_fixity in Match] ~~~~~~~~~~~~~~~~~~~~~~ The parser initially creates a FunBind with a single Match in it for every function definition it sees. These are then grouped together by getMonoBind into a single FunBind, where all the Matches are combined. In the process, all the original FunBind fun_id's bar one are discarded, including the locations. This causes a problem for source to source conversions via API Annotations, so the original fun_ids and infix flags are preserved in the Match, when it originates from a FunBind. Example infix function definition requiring individual API Annotations (&&& ) [] [] = [] xs &&& [] = xs ( &&& ) [] ys = ys -} -- |When a Match is part of a FunBind, it captures one complete equation for the -- function. As such it has the function name, and its fixity. data MatchFixity id = NonFunBindMatch | FunBindMatch (Located id) -- of the Id Bool -- is infix deriving (Typeable) deriving instance (DataId id) => Data (MatchFixity id) isInfixMatch :: Match id body -> Bool isInfixMatch match = case m_fixity match of FunBindMatch _ True -> True _ -> False isEmptyMatchGroup :: MatchGroup id body -> Bool isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms -- | Is there only one RHS in this group? isSingletonMatchGroup :: MatchGroup id body -> Bool isSingletonMatchGroup (MG { mg_alts = L _ [match] }) | L _ (Match { m_grhss = GRHSs { grhssGRHSs = [_] } }) <- match = True isSingletonMatchGroup _ = False matchGroupArity :: MatchGroup id body -> Arity -- Precondition: MatchGroup is non-empty -- This is called before type checking, when mg_arg_tys is not set matchGroupArity (MG { mg_alts = alts }) | L _ (alt1:_) <- alts = length (hsLMatchPats alt1) | otherwise = panic "matchGroupArity" hsLMatchPats :: LMatch id body -> [LPat id] hsLMatchPats (L _ (Match _ pats _ _)) = pats -- | GRHSs are used both for pattern bindings and for Matches -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose' -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi' -- For details on above see note [Api annotations] in ApiAnnotation data GRHSs id body = GRHSs { grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs grhssLocalBinds :: Located (HsLocalBinds id) -- ^ The where clause } deriving (Typeable) deriving instance (Data body,DataId id) => Data (GRHSs id body) type LGRHS id body = Located (GRHS id body) -- | Guarded Right Hand Side. data GRHS id body = GRHS [GuardLStmt id] -- Guards body -- Right hand side deriving (Typeable) deriving instance (Data body,DataId id) => Data (GRHS id body) -- We know the list must have at least one @Match@ in it. pprMatches :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> MatchGroup idR body -> SDoc pprMatches ctxt (MG { mg_alts = matches }) = vcat (map (pprMatch ctxt) (map unLoc (unLoc matches))) -- Don't print the type; it's only a place-holder before typechecking -- Exported to HsBinds, which can't see the defn of HsMatchContext pprFunBind :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => idL -> MatchGroup idR body -> SDoc pprFunBind fun matches = pprMatches (FunRhs fun) matches -- Exported to HsBinds, which can't see the defn of HsMatchContext pprPatBind :: forall bndr id body. (OutputableBndr bndr, OutputableBndr id, Outputable body) => LPat bndr -> GRHSs id body -> SDoc pprPatBind pat (grhss) = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)] pprMatch :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> Match idR body -> SDoc pprMatch ctxt match = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats) , nest 2 ppr_maybe_ty , nest 2 (pprGRHSs ctxt (m_grhss match)) ] where is_infix = isInfixMatch match (herald, other_pats) = case ctxt of FunRhs fun | not is_infix -> (pprPrefixOcc fun, m_pats match) -- f x y z = e -- Not pprBndr; the AbsBinds will -- have printed the signature | null pats2 -> (pp_infix, []) -- x &&& y = e | otherwise -> (parens pp_infix, pats2) -- (x &&& y) z = e where pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2 LambdaExpr -> (char '\\', m_pats match) _ -> ASSERT( null pats1 ) (ppr pat1, []) -- No parens around the single pat (pat1:pats1) = m_pats match (pat2:pats2) = pats1 ppr_maybe_ty = case m_type match of Just ty -> dcolon <+> ppr ty Nothing -> empty pprGRHSs :: (OutputableBndr idR, Outputable body) => HsMatchContext idL -> GRHSs idR body -> SDoc pprGRHSs ctxt (GRHSs grhss (L _ binds)) = vcat (map (pprGRHS ctxt . unLoc) grhss) $$ ppUnless (isEmptyLocalBinds binds) (text "where" $$ nest 4 (pprBinds binds)) pprGRHS :: (OutputableBndr idR, Outputable body) => HsMatchContext idL -> GRHS idR body -> SDoc pprGRHS ctxt (GRHS [] body) = pp_rhs ctxt body pprGRHS ctxt (GRHS guards body) = sep [vbar <+> interpp'SP guards, pp_rhs ctxt body] pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs) {- ************************************************************************ * * \subsection{Do stmts and list comprehensions} * * ************************************************************************ -} type LStmt id body = Located (StmtLR id id body) type LStmtLR idL idR body = Located (StmtLR idL idR body) type Stmt id body = StmtLR id id body type CmdLStmt id = LStmt id (LHsCmd id) type CmdStmt id = Stmt id (LHsCmd id) type ExprLStmt id = LStmt id (LHsExpr id) type ExprStmt id = Stmt id (LHsExpr id) type GuardLStmt id = LStmt id (LHsExpr id) type GuardStmt id = Stmt id (LHsExpr id) type GhciLStmt id = LStmt id (LHsExpr id) type GhciStmt id = Stmt id (LHsExpr id) -- The SyntaxExprs in here are used *only* for do-notation and monad -- comprehensions, which have rebindable syntax. Otherwise they are unused. -- | API Annotations when in qualifier lists or guards -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen', -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy', -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing' -- For details on above see note [Api annotations] in ApiAnnotation data StmtLR idL idR body -- body should always be (LHs**** idR) = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp, -- and (after the renamer) DoExpr, MDoExpr -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff body Bool -- True <=> return was stripped by ApplicativeDo (SyntaxExpr idR) -- The return operator, used only for -- MonadComp For ListComp, PArrComp, we -- use the baked-in 'return' For DoExpr, -- MDoExpr, we don't apply a 'return' at -- all See Note [Monad Comprehensions] | -- - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnLarrow' -- For details on above see note [Api annotations] in ApiAnnotation | BindStmt (LPat idL) body (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts] (SyntaxExpr idR) -- The fail operator -- The fail operator is noSyntaxExpr -- if the pattern match can't fail -- | 'ApplicativeStmt' represents an applicative expression built with -- <$> and <*>. It is generated by the renamer, and is desugared into the -- appropriate applicative expression by the desugarer, but it is intended -- to be invisible in error messages. -- -- For full details, see Note [ApplicativeDo] in RnExpr -- | ApplicativeStmt [ ( SyntaxExpr idR , ApplicativeArg idL idR) ] -- [(<$>, e1), (<*>, e2), ..., (<*>, en)] (Maybe (SyntaxExpr idR)) -- 'join', if necessary (PostTc idR Type) -- Type of the body | BodyStmt body -- See Note [BodyStmt] (SyntaxExpr idR) -- The (>>) operator (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp -- See notes [Monad Comprehensions] (PostTc idR Type) -- Element type of the RHS (used for arrows) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet' -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@, -- For details on above see note [Api annotations] in ApiAnnotation | LetStmt (Located (HsLocalBindsLR idL idR)) -- ParStmts only occur in a list/monad comprehension | ParStmt [ParStmtBlock idL idR] (SyntaxExpr idR) -- Polymorphic `mzip` for monad comprehensions (SyntaxExpr idR) -- The `>>=` operator -- See notes [Monad Comprehensions] -- After renaming, the ids are the binders -- bound by the stmts and used after themp | TransStmt { trS_form :: TransForm, trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group' -- which generates the tuples to be grouped trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map] trS_using :: LHsExpr idR, trS_by :: Maybe (LHsExpr idR), -- "by e" (optional) -- Invariant: if trS_form = GroupBy, then grp_by = Just e trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for -- the inner monad comprehensions trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator trS_fmap :: SyntaxExpr idR -- The polymorphic 'fmap' function for desugaring -- Only for 'group' forms } -- See Note [Monad Comprehensions] -- Recursive statement (see Note [How RecStmt works] below) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec' -- For details on above see note [Api annotations] in ApiAnnotation | RecStmt { recS_stmts :: [LStmtLR idL idR body] -- The next two fields are only valid after renaming , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the -- stmts that are used in stmts that follow the RecStmt , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones, -- that are used before they are bound in the stmts of -- the RecStmt. -- An Id can be in both groups -- Both sets of Ids are (now) treated monomorphically -- See Note [How RecStmt works] for why they are separate -- Rebindable syntax , recS_bind_fn :: SyntaxExpr idR -- The bind function , recS_ret_fn :: SyntaxExpr idR -- The return function , recS_mfix_fn :: SyntaxExpr idR -- The mfix function -- These fields are only valid after typechecking , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version) , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1 -- with recS_later_ids and recS_rec_ids, -- and are the expressions that should be -- returned by the recursion. -- They may not quite be the Ids themselves, -- because the Id may be *polymorphic*, but -- the returned thing has to be *monomorphic*, -- so they may be type applications , recS_ret_ty :: PostTc idR Type -- The type of -- do { stmts; return (a,b,c) } -- With rebindable syntax the type might not -- be quite as simple as (m (tya, tyb, tyc)). } deriving (Typeable) deriving instance (Data body, DataId idL, DataId idR) => Data (StmtLR idL idR body) data TransForm -- The 'f' below is the 'using' function, 'e' is the by function = ThenForm -- then f or then f by e (depending on trS_by) | GroupForm -- then group using f or then group by e using f (depending on trS_by) deriving (Data, Typeable) data ParStmtBlock idL idR = ParStmtBlock [ExprLStmt idL] [idR] -- The variables to be returned (SyntaxExpr idR) -- The return operator deriving( Typeable ) deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR) data ApplicativeArg idL idR = ApplicativeArgOne -- pat <- expr (pat must be irrefutable) (LPat idL) (LHsExpr idL) | ApplicativeArgMany -- do { stmts; return vars } [ExprLStmt idL] -- stmts (SyntaxExpr idL) -- return (v1,..,vn), or just (v1,..,vn) (LPat idL) -- (v1,...,vn) deriving( Typeable ) deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR) {- Note [The type of bind in Stmts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some Stmts, notably BindStmt, keep the (>>=) bind operator. We do NOT assume that it has type (>>=) :: m a -> (a -> m b) -> m b In some cases (see Trac #303, #1537) it might have a more exotic type, such as (>>=) :: m i j a -> (a -> m j k b) -> m i k b So we must be careful not to make assumptions about the type. In particular, the monad may not be uniform throughout. Note [TransStmt binder map] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The [(idR,idR)] in a TransStmt behaves as follows: * Before renaming: [] * After renaming: [ (x27,x27), ..., (z35,z35) ] These are the variables bound by the stmts to the left of the 'group' and used either in the 'by' clause, or in the stmts following the 'group' Each item is a pair of identical variables. * After typechecking: [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ] Each pair has the same unique, but different *types*. Note [BodyStmt] ~~~~~~~~~~~~~~~ BodyStmts are a bit tricky, because what they mean depends on the context. Consider the following contexts: A do expression of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E any_ty: do { ....; E; ... } E :: m any_ty Translation: E >> ... A list comprehensions of type [elt_ty] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] [ .. | ..., E, ... ] [ .. | .... | ..., E | ... ] E :: Bool Translation: if E then fail else ... A guard list, guarding a RHS of type rhs_ty ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs... E :: Bool Translation: if E then fail else ... A monad comprehension of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] E :: Bool Translation: guard E >> ... Array comprehensions are handled like list comprehensions. Note [How RecStmt works] ~~~~~~~~~~~~~~~~~~~~~~~~ Example: HsDo [ BindStmt x ex , RecStmt { recS_rec_ids = [a, c] , recS_stmts = [ BindStmt b (return (a,c)) , LetStmt a = ...b... , BindStmt c ec ] , recS_later_ids = [a, b] , return (a b) ] Here, the RecStmt binds a,b,c; but - Only a,b are used in the stmts *following* the RecStmt, - Only a,c are used in the stmts *inside* the RecStmt *before* their bindings Why do we need *both* rec_ids and later_ids? For monads they could be combined into a single set of variables, but not for arrows. That follows from the types of the respective feedback operators: mfix :: MonadFix m => (a -> m a) -> m a loop :: ArrowLoop a => a (b,d) (c,d) -> a b c * For mfix, the 'a' covers the union of the later_ids and the rec_ids * For 'loop', 'c' is the later_ids and 'd' is the rec_ids Note [Typing a RecStmt] ~~~~~~~~~~~~~~~~~~~~~~~ A (RecStmt stmts) types as if you had written (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) -> do { stmts ; return (v1,..vn, r1, ..., rm) }) where v1..vn are the later_ids r1..rm are the rec_ids Note [Monad Comprehensions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monad comprehensions require separate functions like 'return' and '>>=' for desugaring. These functions are stored in the statements used in monad comprehensions. For example, the 'return' of the 'LastStmt' expression is used to lift the body of the monad comprehension: [ body | stmts ] => stmts >>= \bndrs -> return body In transform and grouping statements ('then ..' and 'then group ..') the 'return' function is required for nested monad comprehensions, for example: [ body | stmts, then f, rest ] => f [ env | stmts ] >>= \bndrs -> [ body | rest ] BodyStmts require the 'Control.Monad.guard' function for boolean expressions: [ body | exp, stmts ] => guard exp >> [ body | stmts ] Parallel statements require the 'Control.Monad.Zip.mzip' function: [ body | stmts1 | stmts2 | .. ] => mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body In any other context than 'MonadComp', the fields for most of these 'SyntaxExpr's stay bottom. -} instance (OutputableBndr idL) => Outputable (ParStmtBlock idL idR) where ppr (ParStmtBlock stmts _ _) = interpp'SP stmts instance (OutputableBndr idL, OutputableBndr idR, Outputable body) => Outputable (StmtLR idL idR body) where ppr stmt = pprStmt stmt pprStmt :: forall idL idR body . (OutputableBndr idL, OutputableBndr idR, Outputable body) => (StmtLR idL idR body) -> SDoc pprStmt (LastStmt expr ret_stripped _) = ifPprDebug (text "[last]") <+> (if ret_stripped then text "return" else empty) <+> ppr expr pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, larrow, ppr expr] pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds] pprStmt (BodyStmt expr _ _ _) = ppr expr pprStmt (ParStmt stmtss _ _) = sep (punctuate (text " | ") (map ppr stmtss)) pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form }) = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form]) pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids , recS_later_ids = later_ids }) = text "rec" <+> vcat [ ppr_do_stmts segment , ifPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids , text "later_ids=" <> ppr later_ids])] pprStmt (ApplicativeStmt args mb_join _) = getPprStyle $ \style -> if userStyle style then pp_for_user else pp_debug where -- make all the Applicative stuff invisible in error messages by -- flattening the whole ApplicativeStmt nest back to a sequence -- of statements. pp_for_user = vcat $ punctuate semi $ concatMap flattenArg args -- ppr directly rather than transforming here, because we need to -- inject a "return" which is hard when we're polymorphic in the id -- type. flattenStmt :: ExprLStmt idL -> [SDoc] flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args flattenStmt stmt = [ppr stmt] flattenArg (_, ApplicativeArgOne pat expr) = [ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr :: ExprStmt idL)] flattenArg (_, ApplicativeArgMany stmts _ _) = concatMap flattenStmt stmts pp_debug = let ap_expr = sep (punctuate (text " |") (map pp_arg args)) in if isNothing mb_join then ap_expr else text "join" <+> parens ap_expr pp_arg (_, ApplicativeArgOne pat expr) = ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr :: ExprStmt idL) pp_arg (_, ApplicativeArgMany stmts return pat) = ppr pat <+> text "<-" <+> ppr (HsDo DoExpr (noLoc (stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)])) (error "pprStmt")) pprTransformStmt :: OutputableBndr id => [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc pprTransformStmt bndrs using by = sep [ text "then" <+> ifPprDebug (braces (ppr bndrs)) , nest 2 (ppr using) , nest 2 (pprBy by)] pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc pprTransStmt by using ThenForm = sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)] pprTransStmt by using GroupForm = sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)] pprBy :: Outputable body => Maybe body -> SDoc pprBy Nothing = empty pprBy (Just e) = text "by" <+> ppr e pprDo :: (OutputableBndr id, Outputable body) => HsStmtContext any -> [LStmt id body] -> SDoc pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts pprDo ListComp stmts = brackets $ pprComp stmts pprDo PArrComp stmts = paBrackets $ pprComp stmts pprDo MonadComp stmts = brackets $ pprComp stmts pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt ppr_do_stmts :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => [LStmtLR idL idR body] -> SDoc -- Print a bunch of do stmts, with explicit braces and semicolons, -- so that we are not vulnerable to layout bugs ppr_do_stmts stmts = lbrace <+> pprDeeperList vcat (punctuate semi (map ppr stmts)) <+> rbrace pprComp :: (OutputableBndr id, Outputable body) => [LStmt id body] -> SDoc pprComp quals -- Prints: body | qual1, ..., qualn | not (null quals) , L _ (LastStmt body _ _) <- last quals = hang (ppr body <+> vbar) 2 (pprQuals (dropTail 1 quals)) | otherwise = pprPanic "pprComp" (pprQuals quals) pprQuals :: (OutputableBndr id, Outputable body) => [LStmt id body] -> SDoc -- Show list comprehension qualifiers separated by commas pprQuals quals = interpp'SP quals {- ************************************************************************ * * Template Haskell quotation brackets * * ************************************************************************ -} data HsSplice id = HsTypedSplice -- $$z or $$(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsUntypedSplice -- $z or $(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice id -- Splice point id -- Quoter SrcSpan -- The span of the enclosed string FastString -- The enclosed string deriving (Typeable ) deriving instance (DataId id) => Data (HsSplice id) isTypedSplice :: HsSplice id -> Bool isTypedSplice (HsTypedSplice {}) = True isTypedSplice _ = False -- Quasi-quotes are untyped splices -- See Note [Pending Splices] type SplicePointName = Name data PendingRnSplice = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr Name) deriving (Data, Typeable) data UntypedSpliceFlavour = UntypedExpSplice | UntypedPatSplice | UntypedTypeSplice | UntypedDeclSplice deriving( Data, Typeable ) data PendingTcSplice = PendingTcSplice SplicePointName (LHsExpr Id) deriving( Data, Typeable ) {- Note [Pending Splices] ~~~~~~~~~~~~~~~~~~~~~~ When we rename an untyped bracket, we name and lift out all the nested splices, so that when the typechecker hits the bracket, it can typecheck those nested splices without having to walk over the untyped bracket code. So for example [| f $(g x) |] looks like HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x))) which the renamer rewrites to HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x))) [PendingRnSplice UntypedExpSplice sn (g x)] * The 'sn' is the Name of the splice point, the SplicePointName * The PendingRnExpSplice gives the splice that splice-point name maps to; and the typechecker can now conveniently find these sub-expressions * The other copy of the splice, in the second argument of HsSpliceE in the renamed first arg of HsRnBracketOut is used only for pretty printing There are four varieties of pending splices generated by the renamer, distinguished by their UntypedSpliceFlavour * Pending expression splices (UntypedExpSplice), e.g., [|$(f x) + 2|] UntypedExpSplice is also used for * quasi-quotes, where the pending expression expands to $(quoter "...blah...") (see RnSplice.makePending, HsQuasiQuote case) * cross-stage lifting, where the pending expression expands to $(lift x) (see RnSplice.checkCrossStageLifting) * Pending pattern splices (UntypedPatSplice), e.g., [| \$(f x) -> x |] * Pending type splices (UntypedTypeSplice), e.g., [| f :: $(g x) |] * Pending declaration (UntypedDeclSplice), e.g., [| let $(f x) in ... |] There is a fifth variety of pending splice, which is generated by the type checker: * Pending *typed* expression splices, (PendingTcSplice), e.g., [||1 + $$(f 2)||] It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the output of the renamer. However, when pretty printing the output of the renamer, e.g., in a type error message, we *do not* want to print out the pending splices. In contrast, when pretty printing the output of the type checker, we *do* want to print the pending splices. So splitting them up seems to make sense, although I hate to add another constructor to HsExpr. -} instance OutputableBndr id => Outputable (HsSplice id) where ppr s = pprSplice s pprPendingSplice :: OutputableBndr id => SplicePointName -> LHsExpr id -> SDoc pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e) pprSplice :: OutputableBndr id => HsSplice id -> SDoc pprSplice (HsTypedSplice n e) = ppr_splice (text "$$") n e pprSplice (HsUntypedSplice n e) = ppr_splice (text "$") n e pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s ppr_quasi :: OutputableBndr id => id -> id -> FastString -> SDoc ppr_quasi n quoter quote = ifPprDebug (brackets (ppr n)) <> char '[' <> ppr quoter <> vbar <> ppr quote <> text "|]" ppr_splice :: OutputableBndr id => SDoc -> id -> LHsExpr id -> SDoc ppr_splice herald n e = herald <> ifPprDebug (brackets (ppr n)) <> eDoc where -- We use pprLExpr to match pprParendExpr: -- Using pprLExpr makes sure that we go 'deeper' -- I think that is usually (always?) right pp_as_was = pprLExpr e eDoc = case unLoc e of HsPar _ -> pp_as_was HsVar _ -> pp_as_was _ -> parens pp_as_was data HsBracket id = ExpBr (LHsExpr id) -- [| expr |] | PatBr (LPat id) -- [p| pat |] | DecBrL [LHsDecl id] -- [d| decls |]; result of parser | DecBrG (HsGroup id) -- [d| decls |]; result of renamer | TypBr (LHsType id) -- [t| type |] | VarBr Bool id -- True: 'x, False: ''T -- (The Bool flag is used only in pprHsBracket) | TExpBr (LHsExpr id) -- [|| expr ||] deriving (Typeable) deriving instance (DataId id) => Data (HsBracket id) isTypedBracket :: HsBracket id -> Bool isTypedBracket (TExpBr {}) = True isTypedBracket _ = False instance OutputableBndr id => Outputable (HsBracket id) where ppr = pprHsBracket pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc pprHsBracket (ExpBr e) = thBrackets empty (ppr e) pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p) pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp) pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds)) pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t) pprHsBracket (VarBr True n) = char '\'' <> ppr n pprHsBracket (VarBr False n) = text "''" <> ppr n pprHsBracket (TExpBr e) = thTyBrackets (ppr e) thBrackets :: SDoc -> SDoc -> SDoc thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+> pp_body <+> text "|]" thTyBrackets :: SDoc -> SDoc thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]") instance Outputable PendingRnSplice where ppr (PendingRnSplice _ n e) = pprPendingSplice n e instance Outputable PendingTcSplice where ppr (PendingTcSplice n e) = pprPendingSplice n e {- ************************************************************************ * * \subsection{Enumerations and list comprehensions} * * ************************************************************************ -} data ArithSeqInfo id = From (LHsExpr id) | FromThen (LHsExpr id) (LHsExpr id) | FromTo (LHsExpr id) (LHsExpr id) | FromThenTo (LHsExpr id) (LHsExpr id) (LHsExpr id) deriving (Typeable) deriving instance (DataId id) => Data (ArithSeqInfo id) instance OutputableBndr id => Outputable (ArithSeqInfo id) where ppr (From e1) = hcat [ppr e1, pp_dotdot] ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot] ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3] ppr (FromThenTo e1 e2 e3) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3] pp_dotdot :: SDoc pp_dotdot = text " .. " {- ************************************************************************ * * \subsection{HsMatchCtxt} * * ************************************************************************ -} data HsMatchContext id -- Context of a Match = FunRhs id -- Function binding for f | LambdaExpr -- Patterns of a lambda | CaseAlt -- Patterns and guards on a case alternative | IfAlt -- Guards of a multi-way if alternative | ProcExpr -- Patterns of a proc | PatBindRhs -- A pattern binding eg [y] <- e = e | RecUpd -- Record update [used only in DsExpr to -- tell matchWrapper what sort of -- runtime error message to generate] | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt, list comprehension, -- pattern guard, etc | ThPatSplice -- A Template Haskell pattern splice | ThPatQuote -- A Template Haskell pattern quotation [p| (a,b) |] | PatSyn -- A pattern synonym declaration deriving (Data, Typeable) data HsStmtContext id = ListComp | MonadComp | PArrComp -- Parallel array comprehension | DoExpr -- do { ... } | MDoExpr -- mdo { ... } ie recursive do-expression | ArrowExpr -- do-notation in an arrow-command context | GhciStmtCtxt -- A command-line Stmt in GHCi pat <- rhs | PatGuard (HsMatchContext id) -- Pattern guard for specified thing | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt | TransStmtCtxt (HsStmtContext id) -- A branch of a transform stmt deriving (Data, Typeable) isListCompExpr :: HsStmtContext id -> Bool -- Uses syntax [ e | quals ] isListCompExpr ListComp = True isListCompExpr PArrComp = True isListCompExpr MonadComp = True isListCompExpr (ParStmtCtxt c) = isListCompExpr c isListCompExpr (TransStmtCtxt c) = isListCompExpr c isListCompExpr _ = False isMonadCompExpr :: HsStmtContext id -> Bool isMonadCompExpr MonadComp = True isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr _ = False matchSeparator :: HsMatchContext id -> SDoc matchSeparator (FunRhs {}) = text "=" matchSeparator CaseAlt = text "->" matchSeparator IfAlt = text "->" matchSeparator LambdaExpr = text "->" matchSeparator ProcExpr = text "->" matchSeparator PatBindRhs = text "=" matchSeparator (StmtCtxt _) = text "<-" matchSeparator RecUpd = panic "unused" matchSeparator ThPatSplice = panic "unused" matchSeparator ThPatQuote = panic "unused" matchSeparator PatSyn = panic "unused" pprMatchContext :: Outputable id => HsMatchContext id -> SDoc pprMatchContext ctxt | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt | otherwise = text "a" <+> pprMatchContextNoun ctxt where want_an (FunRhs {}) = True -- Use "an" in front want_an ProcExpr = True want_an _ = False pprMatchContextNoun :: Outputable id => HsMatchContext id -> SDoc pprMatchContextNoun (FunRhs fun) = text "equation for" <+> quotes (ppr fun) pprMatchContextNoun CaseAlt = text "case alternative" pprMatchContextNoun IfAlt = text "multi-way if alternative" pprMatchContextNoun RecUpd = text "record-update construct" pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice" pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation" pprMatchContextNoun PatBindRhs = text "pattern binding" pprMatchContextNoun LambdaExpr = text "lambda abstraction" pprMatchContextNoun ProcExpr = text "arrow abstraction" pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in" $$ pprStmtContext ctxt pprMatchContextNoun PatSyn = text "pattern synonym declaration" ----------------- pprAStmtContext, pprStmtContext :: Outputable id => HsStmtContext id -> SDoc pprAStmtContext ctxt = article <+> pprStmtContext ctxt where pp_an = text "an" pp_a = text "a" article = case ctxt of MDoExpr -> pp_an PArrComp -> pp_an GhciStmtCtxt -> pp_an _ -> pp_a ----------------- pprStmtContext GhciStmtCtxt = text "interactive GHCi command" pprStmtContext DoExpr = text "'do' block" pprStmtContext MDoExpr = text "'mdo' block" pprStmtContext ArrowExpr = text "'do' block in an arrow command" pprStmtContext ListComp = text "list comprehension" pprStmtContext MonadComp = text "monad comprehension" pprStmtContext PArrComp = text "array comprehension" pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt -- Drop the inner contexts when reporting errors, else we get -- Unexpected transform statement -- in a transformed branch of -- transformed branch of -- transformed branch of monad comprehension pprStmtContext (ParStmtCtxt c) | opt_PprStyle_Debug = sep [text "parallel branch of", pprAStmtContext c] | otherwise = pprStmtContext c pprStmtContext (TransStmtCtxt c) | opt_PprStyle_Debug = sep [text "transformed branch of", pprAStmtContext c] | otherwise = pprStmtContext c -- Used to generate the string for a *runtime* error message matchContextErrString :: Outputable id => HsMatchContext id -> SDoc matchContextErrString (FunRhs fun) = text "function" <+> ppr fun matchContextErrString CaseAlt = text "case" matchContextErrString IfAlt = text "multi-way if" matchContextErrString PatBindRhs = text "pattern binding" matchContextErrString RecUpd = text "record update" matchContextErrString LambdaExpr = text "lambda" matchContextErrString ProcExpr = text "proc" matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard" matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command" matchContextErrString (StmtCtxt DoExpr) = text "'do' block" matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block" matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block" matchContextErrString (StmtCtxt ListComp) = text "list comprehension" matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension" matchContextErrString (StmtCtxt PArrComp) = text "array comprehension" pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> Match idR body -> SDoc pprMatchInCtxt ctxt match = hang (text "In" <+> pprMatchContext ctxt <> colon) 4 (pprMatch ctxt match) pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsStmtContext idL -> StmtLR idL idR body -> SDoc pprStmtInCtxt ctxt (LastStmt e _ _) | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts" = hang (text "In the expression:") 2 (ppr e) pprStmtInCtxt ctxt stmt = hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon) 2 (ppr_stmt stmt) where -- For Group and Transform Stmts, don't print the nested stmts! ppr_stmt (TransStmt { trS_by = by, trS_using = using , trS_form = form }) = pprTransStmt by using form ppr_stmt stmt = pprStmt stmt
gridaphobe/ghc
compiler/hsSyn/HsExpr.hs
Haskell
bsd-3-clause
84,578
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Data.Default.Aux (Default(..)) where import Data.Default import Foreign.Ptr (Ptr, FunPtr, IntPtr, WordPtr, nullPtr, nullFunPtr, ptrToIntPtr, ptrToWordPtr) import Data.Bits (Bits, zeroBits) instance Default (Ptr a) where def = nullPtr instance Default (FunPtr a) where def = nullFunPtr instance Default IntPtr where def = ptrToIntPtr nullPtr instance Default WordPtr where def = ptrToWordPtr nullPtr instance {-# OVERLAPPABLE #-} Bits a => Default a where def = zeroBits
michaeljklein/CPlug
src/Data/Default/Aux.hs
Haskell
bsd-3-clause
588
module ParserTest where import Test.Hspec import qualified Parser as Parser testParser = hspec $ do describe "Parser" $ do it "1. consumes head of lexemes when head of lexemes is identical to lookahead" $ do Parser.match "sTag" ["sTag", "eTag"] `shouldBe` ["eTag"] it "2. consumes head of lexemes when head of lexemes is identical to lookahead" $ do Parser.match "sTag" ["sTag", "the", "red", "dog", "eTag"] `shouldBe` ["the", "red", "dog", "eTag"]
chris-bacon/HTML-LaTeX-Compiler
tests/ParserTest.hs
Haskell
bsd-3-clause
496
{- Copyright (c) 2014-2015, Johan Nordlander, Jonas Duregård, Michał Pałka, Patrik Jansson and Josef Svenningsson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Chalmers University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} {-# LANGUAGE FlexibleInstances #-} module AR where import qualified Data.Map as Map import Data.Map (Map, keys, elems) import Data.List import Data.Maybe dom :: Map a b -> [a] rng :: Map a b -> [b] dom = keys rng = elems a `subsetof` b = all (`elem` b) a a `equal` b = a `subsetof` b && b `subsetof` a unique xs = xs == nub xs data Component = Atomic (Map PortName Port) (Map VarName Type) [Runnable] | Composition (Map PortName Port) (Map CompName Component) [Connector] ports (Atomic iface _ _) = iface ports (Composition iface _ _) = iface data PortKind = SenderReceiver (Map VarName Type) | ClientServer (Map OpName Operation) -- a sum (choice) of operations instance Eq PortKind where SenderReceiver ts == SenderReceiver ts' = ts == ts' ClientServer ops == ClientServer ops' = ops == ops' _ == _ = False data Port = Provided PortKind | Required PortKind deriving Eq inverse (Provided p) = Required p inverse (Required p) = Provided p data Operation = Op (Map VarName ArgType) [Int] -- ^ a product (tuple) of arguments, set of error codes instance Eq Operation where Op args errs == Op args' errs' = args == args' && errs == errs' data ArgType = In Type | InOut Type | Out Type deriving Eq type Connector = (PortRef, PortRef) data PortRef = Qual CompName PortName | Ext PortName deriving Eq type PortName = String type CompName = String type FieldName = String type TagName = String type OpName = String type VarName = String type Statevars = Map VarName Value type Arguments = Map VarName Value type Response = Either Int (Map VarName Value) -- | Four different kinds of |Runnable|s data Runnable = Init Behavior -- ^ should set up initial state etc. | DataReceived PortName (Statevars -> Arguments -> Behavior) -- ^ async. method | OperationInvoked PortName OpName (Statevars -> Arguments -> Behavior) -- ^ sync. operation | Timing Double (Statevars -> Behavior) -- ^ repeated execution {- There are different classes of runnables. This type is not covering all of them. For example, in the full AUTOSAR standard, a runnable could have a set of waitPoints, but this simplified description assumes this set is empty. -} -- | Observable effect of a |Runnable| data Behavior = Sending PortName Arguments Behavior -- ^ | Invoking PortName OpName Arguments (Response -> Behavior) -- ^ Invoke operation (must check "port matching") | Responding Response Behavior -- ^ Act. on a call (might be better to merge with Idling) | Idling Statevars | Crashed | Comp (Map CompName Behavior) data Observation = Send PortRef Arguments | Invoke PortRef OpName Arguments | Respond Response | Tau update :: k -> v -> Map k v -> Map k v update = undefined connections :: env -> CompName -> PortName -> [PortRef] connections = undefined runnables :: env -> CompName -> [Runnable] runnables = undefined data Msg = Msg CompName PortName Arguments deriving Eq type ComponentLinks = [(CompName, CompName)] -- | perhaps a queue or at least timestamped messages type MsgPool = [Msg] type State = (Map CompName Behavior, MsgPool, ComponentLinks) reduce :: env -> State -> [(State, Observation)] reduce env (bhvs, msgs, links) = [ ((update c next bhvs, Msg c' p' args : msgs, links), Tau) | (c,Sending p args next) <- Map.assocs bhvs , Qual c' p' <- connections env c p ] ++ [ ((update c (run svars args) bhvs, delete (Msg c p args) msgs, links), Tau) | (c,Idling svars) <- Map.assocs bhvs , DataReceived p run <- runnables env c , Msg c1 p1 args <- msgs , c == c1, p == p1 ] ++ [ ((update c' (run svars args) bhvs, msgs, (c,c'):links), Tau) | (c,Invoking p op args cont) <- Map.assocs bhvs , (c',Idling svars) <- Map.assocs bhvs , OperationInvoked p' op' run <- runnables env c' , Qual c' p' `elem` connections env c p ] ++ [ ((update c (cont resp) (update c' next bhvs), msgs, delete (c,c') links), Tau) | (c,Invoking p op args cont) <- Map.assocs bhvs , (c',Responding resp next) <- Map.assocs bhvs , (c,c') `elem` links ] ++ [ ((update c next bhvs, msgs, links), Send (Ext p') args) | (c,Sending p args next) <- Map.assocs bhvs , Ext p' <- connections env c p ] ++ [ ((update c (Invoking p op args cont) bhvs, msgs, links), Invoke (Ext p') op args) | (c,Invoking p op args cont) <- Map.assocs bhvs , Ext p' <- connections env c p ] ++ [ ] -------------------------------------------------------------- validComp partial (Atomic iface sig runns) = unique (dom iface) && unique int_rcvs && unique int_ops && int_rcvs `subsetof` ext_rcvs && int_ops `subsetof` ext_ops && (partial || total) where ext_rcvs = [ p | (p, Provided (SenderReceiver _)) <- Map.assocs iface ] ext_ops = [ (p,o) | (p, Provided (ClientServer ops)) <- Map.assocs iface, o <- dom ops ] int_rcvs = [ p | DataReceived p _ <- runns ] int_ops = [ (p,o) | OperationInvoked p o _ <- runns ] total = ext_rcvs `subsetof` int_rcvs && ext_ops `subsetof` int_ops validComp partial (Composition iface comps conns) = unique (dom iface) && unique (dom comps) && all (validComp partial) (rng comps) && all (validConn all_ports) conns && all (== 1) (map fan_out req_clisrv) && all (>= 1) (map fan_out req_sndrcv) where all_ports = [ (Qual c p, port) | (c,comp) <- Map.assocs comps, (p,port) <- Map.assocs $ ports comp ] ++ [ (Ext p, inverse port) | (p,port) <- Map.assocs iface ] req_sndrcv = [ r | (r,Required (SenderReceiver _)) <- all_ports ] req_clisrv = [ r | (r,Required (ClientServer _)) <- all_ports ] fan_out r = length [ q | (p,q) <- conns, p == r ] validConn ports (r,r') = case (lookup r ports, lookup r' ports) of (Just (Required p), Just (Provided p')) -> p == p' _ -> False ------------------------------------------------------------------ data Type = TInt | TBool | TChar | TArray Type | TStruct (Map FieldName Type) | TUnion (Map TagName Type) instance Eq Type where TInt == TInt = True TBool == TBool = True TChar == TChar = True TArray t == TArray t' = t == t' TStruct ts == TStruct ts' = ts == ts' TUnion ts == TUnion ts' = ts == ts' _ == _ = False data Value = VInt Int | VBool Bool | VChar Char | VArray [Value] | VStruct (Map FieldName Value) | VUnion TagName Value deriving Eq hasType TInt (VInt _) = True hasType TBool (VBool _) = True hasType TChar (VChar _) = True hasType (TArray t) (VArray vs) = all (hasType t) vs hasType (TStruct ts) (VStruct fs) = unique (dom fs) && dom ts `equal` dom fs && and [ hasTypeIn ts f v | (f,v) <- Map.assocs fs ] hasType (TUnion ts) (VUnion tag v) = hasTypeIn ts tag v hasTypeIn ts k v = case Map.lookup k ts of Just t -> hasType t v; _ -> False
josefs/autosar
oldARSim/AR.hs
Haskell
bsd-3-clause
10,018
module Signal.Wavelet.List2Test where import Test.HUnit (Assertion) import Signal.Wavelet.List2 import Signal.Wavelet.List.Common (inv) import Test.ArbitraryInstances (DwtInputList(..)) import Test.Data.Wavelet as DW import Test.Utils ((=~), (@=~?)) testDwt :: ([Double], [Double], [Double]) -> Assertion testDwt (ls, sig, expected) = expected @=~? dwt ls sig dataDwt :: [([Double], [Double], [Double])] dataDwt = DW.dataDwt testIdwt :: ([Double], [Double], [Double]) -> Assertion testIdwt (ls, sig, expected) = expected @=~? idwt ls sig dataIdwt :: [([Double], [Double], [Double])] dataIdwt = DW.dataIdwt propDWTInvertible :: DwtInputList -> Bool propDWTInvertible (DwtInputList (ls, sig)) = idwt (inv ls) (dwt ls sig) =~ sig
jstolarek/lattice-structure-hs
tests/Signal/Wavelet/List2Test.hs
Haskell
bsd-3-clause
779
-- | NLP.WordNet.Prims provides primitive operations over the word net database. -- The general scheme of things is to call 'initializeWordNet' to get a 'WordNetEnv'. -- Once you have this, you can start querying. A query usually looks like (suppose -- we want "Dog" as a Noun: -- -- 'getIndexString' on "Dog". This will give us back a cannonicalized string, in this -- case, still "dog". We then use 'indexLookup' to get back an index for this string. -- Then, we call 'indexToSenseKey' to with the index and the sense number (the Index -- contains the number of senses) to get back a SenseKey. We finally call -- 'getSynsetForSense' on the sense key to get back a Synset. -- -- We can continue to query like this or we can use the offsets provided in the -- various fields of the Synset to query directly on an offset. Given an offset -- and a part of speech, we can use 'readSynset' directly to get a synset (instead -- of going through all this business with indices and sensekeys. module NLP.WordNet.Prims ( initializeWordNet, initializeWordNetWithOptions, closeWordNet, getIndexString, getSynsetForSense, readSynset, indexToSenseKey, indexLookup ) where import System.IO -- hiding (try, catch) import System.Environment import Numeric (readHex, readDec) import Data.Char (toLower, isSpace) import Data.Array import Data.Foldable (forM_) import Control.Exception import Control.Monad (when, liftM, mplus, unless) import Data.List (findIndex, find, elemIndex) import Data.Maybe (isNothing, fromJust, isJust, fromMaybe) import NLP.WordNet.PrimTypes import NLP.WordNet.Util import NLP.WordNet.Consts -- | initializeWordNet looks for the word net data files in the -- default directories, starting with environment variables WNSEARCHDIR -- and WNHOME, and then falling back to 'defaultPath' as defined in -- NLP.WordNet.Consts. initializeWordNet :: IO WordNetEnv initializeWordNet = initializeWordNetWithOptions Nothing Nothing -- | initializeWordNetWithOptions looks for the word net data files in the -- specified directory. Use this if wordnet is installed in a non-standard -- place on your machine and you don't have the appropriate env vars set up. initializeWordNetWithOptions :: Maybe FilePath -> -- word net data directory Maybe (String -> SomeException -> IO ()) -> -- "warning" function (by default, warnings go to stderr) IO WordNetEnv initializeWordNetWithOptions mSearchdir mWarn = do searchdir <- case mSearchdir of { Nothing -> getDefaultSearchDir ; Just d -> return d } let warn = fromMaybe (\s e -> hPutStrLn stderr (s ++ "\n" ++ show e)) mWarn version <- tryMaybe $ getEnv "WNDBVERSION" dHands <- mapM (\pos' -> do idxH <- openFileEx (makePath [searchdir, "index." ++ partName pos']) (BinaryMode ReadMode) dataH <- openFileEx (makePath [searchdir, "data." ++ partName pos']) (BinaryMode ReadMode) return (idxH, dataH) ) allPOS -- the following are unnecessary sense <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file index.sense") $ openFileEx (makePath [searchdir, "index.sense"]) (BinaryMode ReadMode) cntlst <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file cntlist.rev") $ openFileEx (makePath [searchdir, "cntlist.rev"]) (BinaryMode ReadMode) keyidx <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file index.key") $ openFileEx (makePath [searchdir, "index.key" ]) (BinaryMode ReadMode) rkeyidx <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file index.key.rev") $ openFileEx (makePath [searchdir, "index.key.rev"]) (BinaryMode ReadMode) vsent <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open sentence files (sentidx.vrb and sents.vrb)") $ do idx <- openFileEx (makePath [searchdir, "sentidx.vrb"]) (BinaryMode ReadMode) snt <- openFileEx (makePath [searchdir, "sents.vrb" ]) (BinaryMode ReadMode) return (idx, snt) mHands <- mapM (\pos' -> openFileEx (makePath [searchdir, partName pos' ++ ".exc"]) (BinaryMode ReadMode)) allPOS return WordNetEnv { dataHandles = listArray (Noun, Adv) dHands, excHandles = listArray (Noun, Adv) mHands, senseHandle = sense, countListHandle = cntlst, keyIndexHandle = keyidx, revKeyIndexHandle = rkeyidx, vSentHandle = vsent, wnReleaseVersion = version, dataDirectory = searchdir, warnAbout = warn } where getDefaultSearchDir = do Just searchdir <- tryMaybe (getEnv "WNSEARCHDIR") >>= \m1 -> tryMaybe (getEnv "WNHOME") >>= \m2 -> return (m1 `mplus` liftM (++dictDir) m2 `mplus` Just defaultPath) return searchdir -- | closeWordNet is not strictly necessary. However, a 'WordNetEnv' tends to -- hog a few Handles, so if you run out of Handles and won't be using -- your WordNetEnv for a while, you can close it and always create a new -- one later. closeWordNet :: WordNetEnv -> IO () closeWordNet wne = do mapM_ (\ (h1,h2) -> hClose h1 >> hClose h2) (elems (dataHandles wne)) mapM_ hClose (elems (excHandles wne)) mapM_ (`forM_` hClose) [senseHandle wne, countListHandle wne, keyIndexHandle wne, revKeyIndexHandle wne, liftM fst (vSentHandle wne), liftM snd (vSentHandle wne)] -- | getIndexString takes a string and a part of speech and tries to find -- that string (or something like it) in the database. It is essentially -- a cannonicalization routine and should be used before querying the -- database, to ensure that your string is in the right form. getIndexString :: WordNetEnv -> String -> POS -> IO (Maybe String) getIndexString wne str partOfSpeech = getIndexString' . cannonWNString $ str where getIndexString' [] = return Nothing getIndexString' (s:ss) = do i <- binarySearch (fst (dataHandles wne ! partOfSpeech)) s if isJust i then return (Just s) else getIndexString' ss -- | getSynsetForSense takes a sensekey and finds the appropriate Synset. SenseKeys can -- be built using indexToSenseKey. getSynsetForSense :: WordNetEnv -> SenseKey -> IO (Maybe Synset) getSynsetForSense wne _ | isNothing (senseHandle wne) = ioError $ userError "no sense dictionary" getSynsetForSense wne key' = do l <- binarySearch (fromJust $ senseHandle wne) (senseKeyString key') -- ++ " " ++ charForPOS (senseKeyPOS key)) case l of Nothing -> return Nothing Just l' -> do offset <- maybeRead $ takeWhile (not . isSpace) $ drop 1 $ dropWhile (not . isSpace) l' ss <- readSynset wne (senseKeyPOS key') offset (senseKeyWord key') return (Just ss) -- | readSynset takes a part of speech, and an offset (the offset can be found -- in another Synset) and (perhaps) a word we're looking for (this is optional) -- and will return its Synset. readSynset :: WordNetEnv -> POS -> Offset -> String -> IO Synset readSynset wne searchPos offset w = do let h = snd (dataHandles wne ! searchPos) hSeek h AbsoluteSeek offset toks <- liftM words $ hGetLine h --print toks (ptrTokS:fnumS:posS:numWordsS:rest1) <- matchN 4 toks hiam <- maybeRead ptrTokS fn <- maybeRead fnumS let ss1 = synset0 { hereIAm = hiam, pos = readEPOS posS, fnum = fn, ssType = if readEPOS posS == Satellite then IndirectAnt else UnknownEPos } let numWords = case readHex numWordsS of (n,_):_ -> n _ -> 0 --read numWordsS let (wrds,ptrCountS:rest2) = splitAt (numWords*2) rest1 -- words and lexids let ptrCount = case readDec ptrCountS of (n,_):_ -> n _ -> 0 -- print (toks, ptrCountS, ptrCount) wrds' <- readWords ss1 wrds let ss2 = ss1 { ssWords = wrds', whichWord = elemIndex w wrds } let (ptrs,rest3) = splitAt (ptrCount*4) rest2 let (fp,ss3) = readPtrs (False,ss2) ptrs let ss4 = if fp && searchPos == Adj && ssType ss3 == UnknownEPos then ss3 { ssType = Pertainym } else ss3 let (ss5,rest4) = if searchPos /= Verb then (ss4, rest3) else let (fcountS:_) = rest3 (_ , rest5) = splitAt (read fcountS * 3) rest4 in (ss4, rest5) let ss6 = ss5 { defn = unwords $ drop 1 rest4 } return ss6 where readWords ss (w':lid:xs) = do let s = map toLower $ replaceChar ' ' '_' w' idx <- indexLookup wne s (fromEPOS $ pos ss) -- print (w,st,idx) let posn = case idx of Nothing -> Nothing Just ix -> elemIndex (hereIAm ss) (indexOffsets ix) rest <- readWords ss xs return ((w', fst $ head $ readHex lid, maybe AllSenses SenseNumber posn) : rest) readWords _ _ = return [] readPtrs (fp,ss) (typ:off:ppos:lexp:xs) = let (fp',ss') = readPtrs (fp,ss) xs this = (getPointerType typ, read off, readEPOS ppos, fst $ head $ readHex (take 2 lexp), fst $ head $ readHex (drop 2 lexp)) in if searchPos == Adj && ssType ss' == UnknownEPos then if getPointerType typ == Antonym then (fp' , ss' { forms = this : forms ss', ssType = DirectAnt }) else (True, ss' { forms = this : forms ss' }) else (fp', ss' { forms = this : forms ss' }) readPtrs (fp,ss) _ = (fp,ss) -- | indexToSenseKey takes an Index (as returned by, ex., indexLookup) and a sense -- number and returns a SenseKey for that sense. indexToSenseKey :: WordNetEnv -> Index -> Int -> IO (Maybe SenseKey) indexToSenseKey wne idx sense = do let cpos = fromEPOS $ indexPOS idx ss1 <- readSynset wne cpos (indexOffsets idx !! (sense-1)) "" ss2 <- followSatellites ss1 --print ss2 case findIndex ((==indexWord idx) . map toLower) (map (\ (w,_,_) -> w) $ ssWords ss2) of Nothing -> return Nothing Just j -> do let skey = ((indexWord idx ++ "%") ++) (if ssType ss2 == Satellite then show (fromEnum Satellite) ++ ":" ++ padTo 2 (show $ fnum ss2) ++ ":" ++ headWord ss2 ++ ":" ++ padTo 2 (show $ headSense ss2) else show (fromEnum $ pos ss2) ++ ":" ++ padTo 2 (show $ fnum ss2) ++ ":" ++ padTo 2 (show $ lexId ss2 j) ++ "::") return (Just $ SenseKey cpos skey (indexWord idx)) where followSatellites ss | ssType ss == Satellite = case find (\ (f,_,_,_,_) -> f == Similar) (forms ss) of Nothing -> return ss Just (_,offset,p,_,_) -> do adjss <- readSynset wne (fromEPOS p) offset "" case ssWords adjss of (hw,_,hs):_ -> return (ss { headWord = map toLower hw, headSense = hs }) _ -> return ss | otherwise = return ss -- indexLookup takes a word and part of speech and gives back its index. indexLookup :: WordNetEnv -> String -> POS -> IO (Maybe Index) indexLookup wne w pos' = do ml <- binarySearch (fst (dataHandles wne ! pos')) w case ml of Nothing -> return Nothing Just l -> do (wdS:posS:ccntS:pcntS:rest1) <- matchN 4 (words l) isc <- maybeRead ccntS pc <- maybeRead pcntS let idx1 = index0 { indexWord = wdS, indexPOS = readEPOS posS, indexSenseCount = isc } let (ptrs,rest2) = splitAt pc rest1 let idx2 = idx1 { indexForms = map getPointerType ptrs } (ocntS:tcntS:rest3) <- matchN 2 rest2 itc <- maybeRead tcntS otc <- maybeRead ocntS let idx3 = idx2 { indexTaggedCount = itc } let (offsets,_) = splitAt otc rest3 io <- mapM maybeRead offsets return (Just $ idx3 { indexOffsets = io }) -- do binary search on an index file binarySearch :: Handle -> String -> IO (Maybe String) binarySearch h s = do hSeek h SeekFromEnd 0 bot <- hTell h binarySearch' 0 bot (bot `div` 2) where binarySearch' :: Integer -> Integer -> Integer -> IO (Maybe String) binarySearch' top bot mid = do hSeek h AbsoluteSeek (mid-1) when (mid /= 1) readUntilNL eof <- hIsEOF h if eof then if top >= bot-1 then return Nothing else binarySearch' top (bot-1) ((top+bot-1) `div` 2) else do l <- hGetLine h let key' = takeWhile (/=' ') l if key' == s then return (Just l) else case (bot - top) `div` 2 of 0 -> return Nothing d -> case key' `compare` s of LT -> binarySearch' mid bot (mid + d) GT -> binarySearch' top mid (top + d) EQ -> undefined readUntilNL = do eof <- hIsEOF h unless eof $ do hGetLine h return ()
pikajude/WordNet-ghc74
NLP/WordNet/Prims.hs
Haskell
bsd-3-clause
13,742
module Main where import SDL hiding (Event) import SDL.Video.Renderer (Rectangle(..), drawRect, fillRect) import SDL.Vect (Point(..)) import qualified SDL.Event as SDLEvent import Linear (V4(..), V2(..)) import qualified Data.Set as Set import qualified Data.Map.Strict as Map import Data.Maybe (mapMaybe, fromMaybe) import Control.Lens import Control.Monad (unless) import qualified Control.Wire as Wire $(makeLensesFor [ ("keyboardEventKeysym", "keysym"), ("keyboardEventKeyMotion", "keyMotion") ] ''KeyboardEventData) $(makeLensesFor [ ("keysymKeycode", "keycode") ] ''Keysym) data Direction = MoveLeft | MoveRight | MoveUp | MoveDown deriving (Eq, Ord) data SceneEvent = Move Direction deriving (Eq, Ord) data Event = SceneEvent SceneEvent | Quit deriving (Eq, Ord) $(makePrisms ''Event) type Events = Set.Set Event data Scene = Scene { _position :: (Int, Int) } $(makeLenses ''Scene) type Draw = Renderer -> IO () height = 100 width = 100 main :: IO () main = do initializeAll window <- createWindow "Lonely Rectangle" defaultWindow renderer <- createRenderer window (-1) defaultRenderer appLoop renderer $ appWire $ Scene (50, 50) createRect :: (Integral i, Num r) => (i, i) -> (i, i) -> Rectangle r createRect (x, y) (w, h) = let leftCorner = P (V2 (fromIntegral x) (fromIntegral y)) in let dimensions = V2 (fromIntegral w) (fromIntegral h) in Rectangle leftCorner dimensions renderScene :: Scene -> Renderer -> IO () renderScene (Scene position) renderer = do rendererDrawColor renderer $= V4 0 255 0 255 fillRect renderer $ Just $ createRect position (height, width) parseEvents :: [SDLEvent.Event] -> Events parseEvents = foldl parseEvent Set.empty where parseEvent s (SDLEvent.Event _ (KeyboardEvent keyboardEvent)) = parseKeyboardEvent keyboardEvent s parseEvent s (SDLEvent.Event _ (WindowClosedEvent _)) = Set.insert Quit s parseEvent s _ = s eventsMap = Map.fromList [ (KeycodeQ, Quit), (KeycodeLeft, SceneEvent $ Move MoveLeft), (KeycodeRight, SceneEvent $ Move MoveRight), (KeycodeUp, SceneEvent $ Move MoveUp), (KeycodeDown, SceneEvent $ Move MoveDown), (KeycodeA, SceneEvent $ Move MoveLeft), (KeycodeD, SceneEvent $ Move MoveRight), (KeycodeW, SceneEvent $ Move MoveUp), (KeycodeS, SceneEvent $ Move MoveDown) ] parseKeyboardEvent :: KeyboardEventData -> Events -> Events parseKeyboardEvent keyboardEvent s = if keyboardEvent ^. keyMotion == Pressed then fromMaybe s $ flip Set.insert s <$> Map.lookup (keyboardEvent ^. keysym ^. keycode) eventsMap else s updateScene :: Scene -> Events -> Scene updateScene scene = foldr applyEvent scene . onlySceneEvents where onlySceneEvents = mapMaybe (^? _SceneEvent) . Set.toList applyEvent (Move MoveLeft) = (position . _1) `over` subtract 10 applyEvent (Move MoveRight) = (position . _1) `over` (+10) applyEvent (Move MoveUp) = (position . _2) `over` subtract 10 applyEvent (Move MoveDown) = (position . _2) `over` (+10) appWire :: Scene -> Wire.Wire Int e IO Events Draw appWire init = proc events -> do rec scene <- Wire.delay init -< scene' let scene' = flip updateScene events scene Wire.returnA -< renderScene scene appLoop :: Renderer -> Wire.Wire Int e IO Events Draw -> IO () appLoop renderer w = do events <- parseEvents <$> pollEvents (Right draw, w') <- Wire.stepWire w 0 (Right events) rendererDrawColor renderer $= V4 0 0 255 255 clear renderer draw renderer present renderer unless (Set.member Quit events) $ appLoop renderer w'
SPY/netwire-sandbox
app/Main.hs
Haskell
bsd-3-clause
3,669
{-# LANGUAGE OverloadedStrings, TupleSections, Arrows, RankNTypes, ScopedTypeVariables #-} module FRP.Yampa.Canvas.Virtual (reactimateVirtualSFinContext) where import FRP.Yampa import Data.Time.Clock import Data.IORef import Control.Concurrent.STM import Graphics.Blank hiding (Event) import qualified Graphics.Blank as Blank ------------------------------------------------------------------- -- | Redraw the entire canvas. renderCanvas :: DeviceContext -> Canvas () -> IO () renderCanvas context drawAction = send context canvas where canvas :: Canvas () canvas = do clearCanvas beginPath () saveRestore drawAction ------------------------------------------------------------------- -- | A specialisation of 'FRP.Yampa.reactimate' to Blank Canvas. -- The arguments are: the Canvas action to get input, the Canvas action to emit output, the signal function to be run, and the device context to use. reactimateVirtualSFinContext :: forall a . Double -- time interval -> Int -- How often to update the screen -> (Blank.Event -> Event a) -> SF (Event a) (Canvas ()) -- only update on *events* -> DeviceContext -> IO () reactimateVirtualSFinContext gap count interpEvent sf context = do c <- newIORef (cycle [1..count]) let getInput :: Bool -> IO (DTime,Maybe (Event a)) getInput canBlock = do let opt_block m = if canBlock then m else m `orElse` return Nothing opt_e <- atomically $ opt_block $ fmap Just $ readTChan (eventQueue context) ev <- case opt_e of Nothing -> return NoEvent Just e -> return (interpEvent e) return (gap, Just ev) putOutput :: Bool -> Canvas () -> IO Bool putOutput changed b = do (i:is) <- readIORef c writeIORef c is if changed && i == 1 then renderCanvas context b >> return False else return False reactimate (return NoEvent) getInput putOutput sf -------------------------------------------------------------------
ku-fpg/protocols
FRP/Yampa/Canvas/Virtual.hs
Haskell
bsd-3-clause
2,283
module Network.Orchid.Format.Xml (fXml) where import Text.XML.Light.Output import Data.FileStore (FileStore) import Network.Orchid.Core.Format import Text.Document.Document fXml :: WikiFormat fXml = WikiFormat "xml" "text/xml" xml xml :: FileStore -> FilePath -> FilePath -> String -> IO Output xml _ _ _ src = return $ TextOutput $ either show (ppContent . toXML) $ fromWiki src
sebastiaanvisser/orchid
src/Network/Orchid/Format/Xml.hs
Haskell
bsd-3-clause
391
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} module Haskell.Ide.Engine.BasePlugin where import Control.Monad import Data.Aeson import Data.Foldable import Data.List import qualified Data.Map as Map import Data.Monoid import qualified Data.Text as T import Development.GitRev (gitCommitCount) import Distribution.System (buildArch) import Distribution.Text (display) import Haskell.Ide.Engine.PluginDescriptor import Haskell.Ide.Engine.PluginUtils import Options.Applicative.Simple (simpleVersion) import qualified Paths_haskell_ide_engine as Meta import Prelude hiding (log) -- --------------------------------------------------------------------- baseDescriptor :: TaggedPluginDescriptor _ baseDescriptor = PluginDescriptor { pdUIShortName = "HIE Base" , pdUIOverview = "Commands for HIE itself, " , pdCommands = buildCommand versionCmd (Proxy :: Proxy "version") "return HIE version" [] (SCtxNone :& RNil) RNil :& buildCommand pluginsCmd (Proxy :: Proxy "plugins") "list available plugins" [] (SCtxNone :& RNil) RNil :& buildCommand commandsCmd (Proxy :: Proxy "commands") "list available commands for a given plugin" [] (SCtxNone :& RNil) ( SParamDesc (Proxy :: Proxy "plugin") (Proxy :: Proxy "the plugin name") SPtText SRequired :& RNil) :& buildCommand commandDetailCmd (Proxy :: Proxy "commandDetail") "list parameters required for a given command" [] (SCtxNone :& RNil) ( SParamDesc (Proxy :: Proxy "plugin") (Proxy :: Proxy "the plugin name") SPtText SRequired :& SParamDesc (Proxy :: Proxy "command") (Proxy :: Proxy "the command name") SPtText SRequired :& RNil) :& RNil , pdExposedServices = [] , pdUsedServices = [] } -- --------------------------------------------------------------------- versionCmd :: CommandFunc T.Text versionCmd = CmdSync $ \_ _ -> return $ IdeResponseOk (T.pack version) pluginsCmd :: CommandFunc IdePlugins pluginsCmd = CmdSync $ \_ _ -> IdeResponseOk . IdePlugins . Map.map (map cmdDesc . pdCommands) <$> getPlugins commandsCmd :: CommandFunc [CommandName] commandsCmd = CmdSync $ \_ req -> do plugins <- getPlugins -- TODO: Use Maybe Monad. What abut error reporting? case Map.lookup "plugin" (ideParams req) of Nothing -> return (missingParameter "plugin") Just (ParamTextP p) -> case Map.lookup p plugins of Nothing -> return $ IdeResponseFail $ IdeError { ideCode = UnknownPlugin , ideMessage = "Can't find plugin:" <> p , ideInfo = toJSON p } Just pl -> return $ IdeResponseOk $ map (cmdName . cmdDesc) (pdCommands pl) Just x -> return $ incorrectParameter "plugin" ("ParamText"::String) x commandDetailCmd :: CommandFunc ExtendedCommandDescriptor commandDetailCmd = CmdSync $ \_ req -> do plugins <- getPlugins case getParams (IdText "plugin" :& IdText "command" :& RNil) req of Left err -> return err Right (ParamText p :& ParamText command :& RNil) -> do case Map.lookup p plugins of Nothing -> return $ IdeResponseError $ IdeError { ideCode = UnknownPlugin , ideMessage = "Can't find plugin:" <> p , ideInfo = toJSON p } Just pl -> case find (\cmd -> command == (cmdName $ cmdDesc cmd) ) (pdCommands pl) of Nothing -> return $ IdeResponseError $ IdeError { ideCode = UnknownCommand , ideMessage = "Can't find command:" <> command , ideInfo = toJSON command } Just detail -> return $ IdeResponseOk (ExtendedCommandDescriptor (cmdDesc detail) p) Right _ -> return $ IdeResponseError $ IdeError { ideCode = InternalError , ideMessage = "commandDetailCmd: ghc’s exhaustiveness checker is broken" , ideInfo = Null } -- --------------------------------------------------------------------- version :: String version = let commitCount = $gitCommitCount in concat $ concat [ [$(simpleVersion Meta.version)] -- Leave out number of commits for --depth=1 clone -- See https://github.com/commercialhaskell/stack/issues/792 , [" (" ++ commitCount ++ " commits)" | commitCount /= ("1"::String) && commitCount /= ("UNKNOWN" :: String)] , [" ", display buildArch] ] -- --------------------------------------------------------------------- replPluginInfo :: Plugins -> Map.Map T.Text (T.Text,UntaggedCommand) replPluginInfo plugins = Map.fromList commands where commands = concatMap extractCommands $ Map.toList plugins extractCommands (pluginName,descriptor) = cmds where cmds = map (\cmd -> (pluginName <> ":" <> (cmdName $ cmdDesc cmd),(pluginName,cmd))) $ pdCommands descriptor -- ---------------------------------------------------------------------
JPMoresmau/haskell-ide-engine
src/Haskell/Ide/Engine/BasePlugin.hs
Haskell
bsd-3-clause
5,320
{-# LANGUAGE OverloadedStrings #-} module Main where import Route import Nix import Conf import Control.Monad.Error () import Control.Monad.IO.Class (liftIO) import Data.ByteString.Lazy.Char8 (pack) import Data.Default (def) import Data.List (isPrefixOf) import Network.HTTP.Types import Network.Wai import Network.Wai.Middleware.RequestLogger import qualified Network.Wai.Handler.Warp as W import System.FilePath import System.Log.Logger import qualified System.Directory as Dir main :: IO () main = do opts <- parseOpts routes <- either fail return (mapM parseRoute (nixrbdRoutes opts)) let addrSource = if nixrbdBehindProxy opts then FromHeader else FromSocket reqLogger <- mkRequestLogger $ def { outputFormat = Apache addrSource } updateGlobalLogger "nixrbd" (setLevel DEBUG) let warpSettings = W.setPort (nixrbdPort opts ) W.defaultSettings infoM "nixrbd" ("Listening on port "++show (nixrbdPort opts)) W.runSettings warpSettings $ reqLogger $ app routes opts app :: [Route] -> Nixrbd -> Application app routes opts req respond = case lookupTarget req routes of (NixHandler p nixpaths, ps') -> do buildRes <- liftIO $ nixBuild opts req p nixpaths ps' either respondFailed serveFile buildRes (StaticPath p, ps') -> do let fp = combine p (joinPath ps') exists <- liftIO $ Dir.doesFileExist fp if not exists then respondNotFound fp else do p' <- liftIO $ Dir.canonicalizePath p fp' <- liftIO $ Dir.canonicalizePath fp if p' `isPrefixOf` fp' then serveFile fp' else respondNotFound fp' (StaticResp s, _) -> stringResp s "" where stringResp s = respond . responseLBS s [("Content-Type","text/plain")] . pack respondFailed err = do liftIO $ errorM "nixrbd" ("Failure: "++show err) stringResp internalServerError500 "Failed building response" respondNotFound fp = do liftIO $ infoM "nixrbd" ("Not found: "++fp) stringResp notFound404 "Not found" serveFile filePath = do filePath' <- liftIO $ Dir.canonicalizePath filePath liftIO $ infoM "nixrbd" ("Serve file: "++filePath') respond $ responseFile status200 [] filePath' Nothing
rickynils/nixrbd
Main.hs
Haskell
bsd-3-clause
2,169
{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving, DeriveDataTypeable #-} {-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans -cpp #-} {- | Module : $Header$ Description : Working with Shrimp M4 abstract syntax. Copyright : (c) Galois, Inc. Working with Shrimp M4 abstract syntax. -} module SCD.M4.Util where import SCD.SELinux.Syntax as SE import SCD.M4.Syntax as M4 import Data.List ( intercalate ) elementId :: InterfaceElement -> M4Id elementId (InterfaceElement _ _ i _) = i implementationId :: Implementation -> ModuleId implementationId (Implementation m _ _) = m layerModule2Identifier :: IsIdentifier i => LayerModule -> i layerModule2Identifier (l,m) = mkId ((idString l) ++ '_' : idString m) -- | unravel left-to-right. splitId :: String -> [String] splitId xs = case break (=='_') xs of (as,[]) -> [as] (as,_:bs) -> as : splitId bs unsplitId :: [String] -> String unsplitId = intercalate "_" -- | split up again, but with reversed result; -- most specific kind/name first. revSplitId :: String -> [String] revSplitId = go [] where go acc "" = acc go acc xs = case break (=='_') xs of (as,[]) -> as:acc (as,_:bs) -> go (as : acc) bs -- | @dropIdSuffix "t" "foo_bar_t"@ returns @"foo_bar"@, -- snipping out the @t@ suffix. If no such suffix, it -- returns the dropIdSuffix :: String -> String -> String dropIdSuffix t s = case revSplitId s of (x:xs) | t == x -> unsplitId (reverse xs) _ -> s isInstantiatedId :: [String] -> Bool isInstantiatedId forMe = bigBucks `any` forMe where bigBucks ('$':_) = True bigBucks _ = False
GaloisInc/sk-dev-platform
libs/SCD/src/SCD/M4/Util.hs
Haskell
bsd-3-clause
1,608
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.CS (classifiers) where import Prelude import Duckling.Ranking.Types import qualified Data.HashMap.Strict as HashMap import Data.String classifiers :: Classifiers classifiers = HashMap.fromList []
rfranek/duckling
Duckling/Ranking/Classifiers/CS.hs
Haskell
bsd-3-clause
825
{-# LANGUAGE DeriveGeneric #-} module Day11 (part1, part2, test1, testStartState, part1Solution,part2Solution) where import Control.Arrow (second) import Data.Foldable import Data.Graph.AStar import Data.Hashable import qualified Data.HashSet as H import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import GHC.Generics (Generic) data Gen = Gen String deriving (Eq,Ord,Show,Generic) instance Hashable Gen data Chip = Chip String deriving (Eq,Ord,Show,Generic) instance Hashable Chip type ElevatorFloor = Int data ProbState = ProbState ElevatorFloor (Map Int (Set Gen)) (Map Int (Set Chip)) deriving (Eq,Ord,Show) data HProbState = HProbState ElevatorFloor [(Int,[Gen])] [(Int,[Chip])] deriving (Eq,Ord,Show,Generic) instance Hashable HProbState fromHState :: HProbState -> ProbState fromHState (HProbState e gs cs) = ProbState e (Map.fromList $ map (second Set.fromList) gs) (Map.fromList $ map (second Set.fromList) cs) toHState :: ProbState -> HProbState toHState (ProbState e gs cs) = HProbState e (map (second Set.toList) $ Map.toList gs) (map (second Set.toList) $ Map.toList cs) validFloor :: Set Gen -> Set Chip -> Bool validFloor gs cs | Set.null gs = True | otherwise = all (`Set.member` gs) $ Set.map (\(Chip c) -> Gen c) cs validState :: ProbState -> Bool validState (ProbState _ gs' cs') = and $ zipWith validFloor (Map.elems gs') (Map.elems cs') nextStates :: ProbState -> [ProbState] nextStates (ProbState e gs cs) = filter validState $ concat . concat $ [mixedStates,singleGStates,doubleGStates,singleCStates,doubleCStates] where singleGStates = map (\nE -> map (f nE . (:[])) singleGs) nextElevators doubleGStates = map (\nE -> map (f nE) doubleGs) notDownNextElevators singleCStates = map (\nE -> map (h nE . (:[])) singleCs) nextElevators doubleCStates = map (\nE -> map (h nE) doubleCs) notDownNextElevators mixedStates = map (\nE -> map (\(g,c) -> ProbState nE (Map.adjust (Set.insert g) nE (Map.adjust (Set.delete g) e gs)) (Map.adjust (Set.insert c) nE (Map.adjust (Set.delete c) e cs))) mixed) notDownNextElevators f nE gs' = ProbState nE (foldl' (\m g -> Map.adjust (Set.insert g) nE m) (foldl' (\m g -> Map.adjust (Set.delete g) e m) gs gs') gs') cs h nE cs' = ProbState nE gs (foldl' (\m c -> Map.adjust (Set.insert c) nE m) (foldl' (\m c -> Map.adjust (Set.delete c) e m) cs cs') cs') nextElevators = [nE | nE <- [e-1,e+1], nE >= 0 && nE < 4] notDownNextElevators = [nE | nE <- [e+1], nE >= 0 && nE < 4] singleGs = Set.toList (Map.findWithDefault Set.empty e gs) doubleGs = [[g1,g2] | g1 <- singleGs, g2 <- singleGs, g1 /= g2] singleCs = Set.toList (Map.findWithDefault Set.empty e cs) doubleCs = [[c1,c2] | c1 <- singleCs,c2 <- singleCs, c1 /= c2] mixed = [(g,c) | g@(Gen gStr) <-singleGs, c@(Chip cStr) <- singleCs, gStr == cStr] heuristic :: HProbState -> Int heuristic (HProbState _ gs cs) = movesToTop cs + movesToTop gs where movesToTop = sum . map (\(f,c) -> (3-f) * length c) part1 s e = length <$> aStar (H.fromList . map toHState . nextStates . fromHState) (const . const 1) heuristic (toHState s ==) (toHState e) part2 = part1 part1Solution = part1 inputStartState input part2Solution = part2 input2StartState input2 probStateViz :: ProbState -> IO () probStateViz (ProbState e gs cs) = mapM_ putStrLn floors where floors = map showFloor $ reverse $ sortOn (\(f,_,_) -> f) $ Map.elems $ Map.mapWithKey (\f g -> (f,g,Map.findWithDefault Set.empty f cs)) gs showFloor (f,gfs,cfs) = show f ++ " " ++ (if f == e then "E" else " ") ++ " " ++ foldMap shortG gfs ++ foldMap shortC cfs shortG (Gen g) = g++"G " shortC (Chip c) = c++"M " input2 = ProbState 0 (Map.fromList [(0,Set.fromList [Gen "T", Gen "Pl",Gen "S",Gen "E",Gen "D"]), (1,Set.empty),(2,Set.fromList [Gen"Pr", Gen"R"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "T",Chip "E",Chip "D"]),(1,Set.fromList [Chip "Pl",Chip "S"]),(2,Set.fromList [Chip "Pr",Chip "R"]),(3,Set.empty)]) input2StartState = ProbState 3 (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Gen"T",Gen"Pl",Gen"S",Gen"Pr",Gen"R",Gen"E",Gen"D"])]) (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Chip"T",Chip"Pl",Chip"S",Chip"Pr",Chip"R",Chip"E",Chip"D"])]) inputStartState = ProbState 3 (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Gen"T",Gen"Pl",Gen"S",Gen"Pr",Gen"R"])]) (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Chip"T",Chip"Pl",Chip"S",Chip"Pr",Chip"R"])]) input = ProbState 0 (Map.fromList [(0,Set.fromList [Gen "T", Gen "Pl",Gen "S"]), (1,Set.empty),(2,Set.fromList [Gen"Pr", Gen"R"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "T"]),(1,Set.fromList [Chip "Pl",Chip "S"]),(2,Set.fromList [Chip "Pr",Chip "R"]),(3,Set.empty)]) testStartState = ProbState 3 (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Gen"H",Gen"L"])]) (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Chip "H",Chip "L"])]) test2 = ProbState 0 (Map.fromList [(0,Set.fromList [Gen "T", Gen "Pl",Gen "S"]), (1,Set.empty),(2,Set.fromList [Gen"Pr", Gen"R"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "T",Chip "Pl"]),(1,Set.fromList [Chip "S"]),(2,Set.fromList [Chip "Pr",Chip "R"]),(3,Set.empty)]) test1 = ProbState 0 (Map.fromList [(0,Set.empty), (1,Set.fromList [Gen "H"]),(2,Set.fromList [Gen"L"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "H",Chip "L"]),(1,Set.empty),(2,Set.empty),(3,Set.empty)])
z0isch/aoc2016
src/Day11.hs
Haskell
bsd-3-clause
5,992
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PartialTypeSignatures #-} module Omniscient.Server.Core where import Control.Monad.Reader import Control.Monad.Logger import Control.Monad.Except import Database.Persist.Sql import Servant type OmniscientT m = LoggingT (ReaderT ConnectionPool (ExceptT ServantErr m)) class ( MonadIO m , MonadError ServantErr m , MonadReader ConnectionPool m , MonadLogger m ) => Omni m where instance MonadIO m => Omni (OmniscientT m) db :: Omni app => _ -> app a db = (ask >>=) . liftSqlPersistMPool
bheklilr/omniscient
src/Omniscient/Server/Core.hs
Haskell
bsd-3-clause
634
{- | Module : Main Description : Test the PuffyTools journal functions Copyright : 2014, Peter Harpending License : BSD3 Maintainer : Peter Harpending <pharpend2@gmail.com> Stability : experimental Portability : Linux -} module Main where import Data.Char import Data.List import PuffyTools.Journal import TestPuffyToolsJournal import Test.Framework import Test.Framework.Providers.QuickCheck2 main :: IO () main = defaultMain tests tests :: [Test] tests = [testGroup "PuffyTools.Journal" [testGroup "Aeson properties" [ testProperty "(encode . decode . encode) = (encode)" prop_encDecEnc , testProperty "(decode . encode . decode . encode) = (decode . encode)" prop_decEncDecEnc , testProperty "(decode . encode . decode . encode)^n = (decode . encode)" prop_dEn ]]]
pharpend/puffytools
test/Test.hs
Haskell
bsd-3-clause
939
module Test.QuickCheck.Arbitrary ( -- * Arbitrary and CoArbitrary classes Arbitrary(..) , CoArbitrary(..) -- ** Helper functions for implementing arbitrary , arbitrarySizedIntegral -- :: Num a => Gen a , arbitraryBoundedIntegral -- :: (Bounded a, Integral a) => Gen a , arbitrarySizedBoundedIntegral -- :: (Bounded a, Integral a) => Gen a , arbitrarySizedFractional -- :: Fractional a => Gen a , arbitraryBoundedRandom -- :: (Bounded a, Random a) => Gen a , arbitraryBoundedEnum -- :: (Bounded a, Enum a) => Gen a -- ** Helper functions for implementing shrink , shrinkNothing -- :: a -> [a] , shrinkList -- :: (a -> [a]) -> [a] -> [[a]] , shrinkIntegral -- :: Integral a => a -> [a] , shrinkRealFrac -- :: RealFrac a => a -> [a] -- ** Helper functions for implementing coarbitrary , (><) , coarbitraryIntegral -- :: Integral a => a -> Gen b -> Gen b , coarbitraryReal -- :: Real a => a -> Gen b -> Gen b , coarbitraryShow -- :: Show a => a -> Gen b -> Gen b , coarbitraryEnum -- :: Enum a => a -> Gen b -> Gen b -- ** Generators which use arbitrary , vector -- :: Arbitrary a => Int -> Gen [a] , orderedList -- :: (Ord a, Arbitrary a) => Gen [a] ) where -------------------------------------------------------------------------- -- imports import Test.QuickCheck.Gen {- import Data.Generics ( (:*:)(..) , (:+:)(..) , Unit(..) ) -} import Data.Char ( chr , ord , isLower , isUpper , toLower , isDigit , isSpace ) import Data.Fixed ( Fixed , HasResolution ) import Data.Ratio ( Ratio , (%) , numerator , denominator ) import Data.Complex ( Complex((:+)) ) import System.Random ( Random ) import Data.List ( sort , nub ) import Control.Monad ( liftM , liftM2 , liftM3 , liftM4 , liftM5 ) import Data.Int(Int8, Int16, Int32, Int64) import Data.Word(Word, Word8, Word16, Word32, Word64) -------------------------------------------------------------------------- -- ** class Arbitrary -- | Random generation and shrinking of values. class Arbitrary a where -- | A generator for values of the given type. arbitrary :: Gen a arbitrary = error "no default generator" -- | Produces a (possibly) empty list of all the possible -- immediate shrinks of the given value. shrink :: a -> [a] shrink _ = [] -- instances instance (CoArbitrary a, Arbitrary b) => Arbitrary (a -> b) where arbitrary = promote (`coarbitrary` arbitrary) instance Arbitrary () where arbitrary = return () instance Arbitrary Bool where arbitrary = choose (False,True) shrink True = [False] shrink False = [] instance Arbitrary Ordering where arbitrary = arbitraryBoundedEnum shrink GT = [EQ, LT] shrink LT = [EQ] shrink EQ = [] instance Arbitrary a => Arbitrary (Maybe a) where arbitrary = frequency [(1, return Nothing), (3, liftM Just arbitrary)] shrink (Just x) = Nothing : [ Just x' | x' <- shrink x ] shrink _ = [] instance (Arbitrary a, Arbitrary b) => Arbitrary (Either a b) where arbitrary = oneof [liftM Left arbitrary, liftM Right arbitrary] shrink (Left x) = [ Left x' | x' <- shrink x ] shrink (Right y) = [ Right y' | y' <- shrink y ] instance Arbitrary a => Arbitrary [a] where arbitrary = sized $ \n -> do k <- choose (0,n) sequence [ arbitrary | _ <- [1..k] ] shrink xs = shrinkList shrink xs shrinkList :: (a -> [a]) -> [a] -> [[a]] shrinkList shr xs = concat [ removes k n xs | k <- takeWhile (>0) (iterate (`div`2) n) ] ++ shrinkOne xs where n = length xs shrinkOne [] = [] shrinkOne (x:xs) = [ x':xs | x' <- shr x ] ++ [ x:xs' | xs' <- shrinkOne xs ] removes k n xs | k > n = [] | null xs2 = [[]] | otherwise = xs2 : map (xs1 ++) (removes k (n-k) xs2) where xs1 = take k xs xs2 = drop k xs {- -- "standard" definition for lists: shrink [] = [] shrink (x:xs) = [ xs ] ++ [ x:xs' | xs' <- shrink xs ] ++ [ x':xs | x' <- shrink x ] -} instance (Integral a, Arbitrary a) => Arbitrary (Ratio a) where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac instance (RealFloat a, Arbitrary a) => Arbitrary (Complex a) where arbitrary = liftM2 (:+) arbitrary arbitrary shrink (x :+ y) = [ x' :+ y | x' <- shrink x ] ++ [ x :+ y' | y' <- shrink y ] instance HasResolution a => Arbitrary (Fixed a) where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac instance (Arbitrary a, Arbitrary b) => Arbitrary (a,b) where arbitrary = liftM2 (,) arbitrary arbitrary shrink (x,y) = [ (x',y) | x' <- shrink x ] ++ [ (x,y') | y' <- shrink y ] instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (a,b,c) where arbitrary = liftM3 (,,) arbitrary arbitrary arbitrary shrink (x,y,z) = [ (x',y,z) | x' <- shrink x ] ++ [ (x,y',z) | y' <- shrink y ] ++ [ (x,y,z') | z' <- shrink z ] instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary (a,b,c,d) where arbitrary = liftM4 (,,,) arbitrary arbitrary arbitrary arbitrary shrink (w,x,y,z) = [ (w',x,y,z) | w' <- shrink w ] ++ [ (w,x',y,z) | x' <- shrink x ] ++ [ (w,x,y',z) | y' <- shrink y ] ++ [ (w,x,y,z') | z' <- shrink z ] instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e) => Arbitrary (a,b,c,d,e) where arbitrary = liftM5 (,,,,) arbitrary arbitrary arbitrary arbitrary arbitrary shrink (v,w,x,y,z) = [ (v',w,x,y,z) | v' <- shrink v ] ++ [ (v,w',x,y,z) | w' <- shrink w ] ++ [ (v,w,x',y,z) | x' <- shrink x ] ++ [ (v,w,x,y',z) | y' <- shrink y ] ++ [ (v,w,x,y,z') | z' <- shrink z ] -- typical instance for primitive (numerical) types instance Arbitrary Integer where arbitrary = arbitrarySizedIntegral shrink = shrinkIntegral instance Arbitrary Int where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int8 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int16 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int32 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int64 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word8 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word16 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word32 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word64 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Char where arbitrary = chr `fmap` oneof [choose (0,127), choose (0,255)] shrink c = filter (<. c) $ nub $ ['a','b','c'] ++ [ toLower c | isUpper c ] ++ ['A','B','C'] ++ ['1','2','3'] ++ [' ','\n'] where a <. b = stamp a < stamp b stamp a = ( (not (isLower a) , not (isUpper a) , not (isDigit a)) , (not (a==' ') , not (isSpace a) , a) ) instance Arbitrary Float where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac instance Arbitrary Double where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac -- ** Helper functions for implementing arbitrary -- | Generates an integral number. The number can be positive or negative -- and its maximum absolute value depends on the size parameter. arbitrarySizedIntegral :: Num a => Gen a arbitrarySizedIntegral = sized $ \n -> let n' = toInteger n in fmap fromInteger (choose (-n', n')) -- | Generates a fractional number. The number can be positive or negative -- and its maximum absolute value depends on the size parameter. arbitrarySizedFractional :: Fractional a => Gen a arbitrarySizedFractional = sized $ \n -> let n' = toInteger n in do a <- choose ((-n') * precision, n' * precision) b <- choose (1, precision) return (fromRational (a % b)) where precision = 9999999999999 :: Integer -- | Generates an integral number. The number is chosen uniformly from -- the entire range of the type. You may want to use -- 'arbitrarySizedBoundedIntegral' instead. arbitraryBoundedIntegral :: (Bounded a, Integral a) => Gen a arbitraryBoundedIntegral = do let mn = minBound mx = maxBound `asTypeOf` mn n <- choose (toInteger mn, toInteger mx) return (fromInteger n `asTypeOf` mn) -- | Generates an element of a bounded type. The element is -- chosen from the entire range of the type. arbitraryBoundedRandom :: (Bounded a, Random a) => Gen a arbitraryBoundedRandom = choose (minBound,maxBound) -- | Generates an element of a bounded enumeration. arbitraryBoundedEnum :: (Bounded a, Enum a) => Gen a arbitraryBoundedEnum = do let mn = minBound mx = maxBound `asTypeOf` mn n <- choose (fromEnum mn, fromEnum mx) return (toEnum n `asTypeOf` mn) -- | Generates an integral number from a bounded domain. The number is -- chosen from the entire range of the type, but small numbers are -- generated more often than big numbers. Inspired by demands from -- Phil Wadler. arbitrarySizedBoundedIntegral :: (Bounded a, Integral a) => Gen a arbitrarySizedBoundedIntegral = sized $ \s -> do let mn = minBound mx = maxBound `asTypeOf` mn bits n | n `quot` 2 == 0 = 0 | otherwise = 1 + bits (n `quot` 2) k = 2^(s*(bits mn `max` bits mx `max` 40) `div` 100) n <- choose (toInteger mn `max` (-k), toInteger mx `min` k) return (fromInteger n `asTypeOf` mn) -- ** Helper functions for implementing shrink -- | Returns no shrinking alternatives. shrinkNothing :: a -> [a] shrinkNothing _ = [] -- | Shrink an integral number. shrinkIntegral :: Integral a => a -> [a] shrinkIntegral x = nub $ [ -x | x < 0, -x > x ] ++ [ x' | x' <- takeWhile (<< x) (0:[ x - i | i <- tail (iterate (`quot` 2) x) ]) ] where -- a << b is "morally" abs a < abs b, but taking care of overflow. a << b = case (a >= 0, b >= 0) of (True, True) -> a < b (False, False) -> a > b (True, False) -> a + b < 0 (False, True) -> a + b > 0 -- | Shrink a fraction. shrinkRealFrac :: RealFrac a => a -> [a] shrinkRealFrac x = nub $ [ -x | x < 0 ] ++ [ x' | x' <- [fromInteger (truncate x)] , x' << x ] where a << b = abs a < abs b -------------------------------------------------------------------------- -- ** CoArbitrary -- | Used for random generation of functions. class CoArbitrary a where -- | Used to generate a function of type @a -> c@. The implementation -- should use the first argument to perturb the random generator -- given as the second argument. the returned generator -- is then used to generate the function result. -- You can often use 'variant' and '><' to implement -- 'coarbitrary'. coarbitrary :: a -> Gen c -> Gen c {- -- GHC definition: coarbitrary{| Unit |} Unit = id coarbitrary{| a :*: b |} (x :*: y) = coarbitrary x >< coarbitrary y coarbitrary{| a :+: b |} (Inl x) = variant 0 . coarbitrary x coarbitrary{| a :+: b |} (Inr y) = variant (-1) . coarbitrary y -} -- | Combine two generator perturbing functions, for example the -- results of calls to 'variant' or 'coarbitrary'. (><) :: (Gen a -> Gen a) -> (Gen a -> Gen a) -> (Gen a -> Gen a) (><) f g gen = do n <- arbitrary (g . variant (n :: Int) . f) gen -- for the sake of non-GHC compilers, I have added definitions -- for coarbitrary here. instance (Arbitrary a, CoArbitrary b) => CoArbitrary (a -> b) where coarbitrary f gen = do xs <- arbitrary coarbitrary (map f xs) gen instance CoArbitrary () where coarbitrary _ = id instance CoArbitrary Bool where coarbitrary False = variant 0 coarbitrary True = variant (-1) instance CoArbitrary Ordering where coarbitrary GT = variant 1 coarbitrary EQ = variant 0 coarbitrary LT = variant (-1) instance CoArbitrary a => CoArbitrary (Maybe a) where coarbitrary Nothing = variant 0 coarbitrary (Just x) = variant (-1) . coarbitrary x instance (CoArbitrary a, CoArbitrary b) => CoArbitrary (Either a b) where coarbitrary (Left x) = variant 0 . coarbitrary x coarbitrary (Right y) = variant (-1) . coarbitrary y instance CoArbitrary a => CoArbitrary [a] where coarbitrary [] = variant 0 coarbitrary (x:xs) = variant (-1) . coarbitrary (x,xs) instance (Integral a, CoArbitrary a) => CoArbitrary (Ratio a) where coarbitrary r = coarbitrary (numerator r,denominator r) instance HasResolution a => CoArbitrary (Fixed a) where coarbitrary = coarbitraryReal instance (RealFloat a, CoArbitrary a) => CoArbitrary (Complex a) where coarbitrary (x :+ y) = coarbitrary x >< coarbitrary y instance (CoArbitrary a, CoArbitrary b) => CoArbitrary (a,b) where coarbitrary (x,y) = coarbitrary x >< coarbitrary y instance (CoArbitrary a, CoArbitrary b, CoArbitrary c) => CoArbitrary (a,b,c) where coarbitrary (x,y,z) = coarbitrary x >< coarbitrary y >< coarbitrary z instance (CoArbitrary a, CoArbitrary b, CoArbitrary c, CoArbitrary d) => CoArbitrary (a,b,c,d) where coarbitrary (x,y,z,v) = coarbitrary x >< coarbitrary y >< coarbitrary z >< coarbitrary v instance (CoArbitrary a, CoArbitrary b, CoArbitrary c, CoArbitrary d, CoArbitrary e) => CoArbitrary (a,b,c,d,e) where coarbitrary (x,y,z,v,w) = coarbitrary x >< coarbitrary y >< coarbitrary z >< coarbitrary v >< coarbitrary w -- typical instance for primitive (numerical) types instance CoArbitrary Integer where coarbitrary = coarbitraryIntegral instance CoArbitrary Int where coarbitrary = coarbitraryIntegral instance CoArbitrary Int8 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int16 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int32 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int64 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word where coarbitrary = coarbitraryIntegral instance CoArbitrary Word8 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word16 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word32 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word64 where coarbitrary = coarbitraryIntegral instance CoArbitrary Char where coarbitrary = coarbitrary . ord instance CoArbitrary Float where coarbitrary = coarbitraryReal instance CoArbitrary Double where coarbitrary = coarbitraryReal -- ** Helpers for implementing coarbitrary -- | A 'coarbitrary' implementation for integral numbers. coarbitraryIntegral :: Integral a => a -> Gen b -> Gen b coarbitraryIntegral = variant -- | A 'coarbitrary' implementation for real numbers. coarbitraryReal :: Real a => a -> Gen b -> Gen b coarbitraryReal x = coarbitrary (toRational x) -- | 'coarbitrary' helper for lazy people :-). coarbitraryShow :: Show a => a -> Gen b -> Gen b coarbitraryShow x = coarbitrary (show x) -- | A 'coarbitrary' implementation for enums. coarbitraryEnum :: Enum a => a -> Gen b -> Gen b coarbitraryEnum = variant . fromEnum -------------------------------------------------------------------------- -- ** arbitrary generators -- these are here and not in Gen because of the Arbitrary class constraint -- | Generates a list of a given length. vector :: Arbitrary a => Int -> Gen [a] vector k = vectorOf k arbitrary -- | Generates an ordered list of a given length. orderedList :: (Ord a, Arbitrary a) => Gen [a] orderedList = sort `fmap` arbitrary -------------------------------------------------------------------------- -- the end.
AlexBaranosky/QuickCheck
Test/QuickCheck/Arbitrary.hs
Haskell
bsd-3-clause
16,724
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS -fno-warn-unused-imports #-} {-# OPTIONS -fno-warn-unused-binds #-} {-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.Array.Accelerate.Debug -- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller -- [2009..2014] Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Embedded array processing language: debugging support (internal). This module -- provides functionality that is useful for developers of the library. It is -- not meant for library users. -- module Data.Array.Accelerate.Debug ( -- * Dynamic debugging flags dump_sharing, dump_simpl_stats, dump_simpl_iterations, verbose, queryFlag, setFlag, -- * Tracing traceMessage, traceEvent, tracePure, -- * Statistics inline, ruleFired, knownBranch, betaReduce, substitution, simplifierDone, fusionDone, resetSimplCount, simplCount, ) where -- standard libraries import Data.Function ( on ) import Data.IORef import Data.Label import Data.List ( groupBy, sortBy, isPrefixOf ) import Data.Ord ( comparing ) import Numeric import Text.PrettyPrint import System.CPUTime import System.Environment import System.IO.Unsafe ( unsafePerformIO ) import qualified Data.Map as Map import Debug.Trace ( traceIO, traceEventIO ) -- ----------------------------------------------------------------------------- -- Flag option parsing data FlagSpec flag = Option String -- external form flag -- internal form data Flags = Flags { -- debugging _dump_sharing :: !Bool -- sharing recovery phase , _dump_simpl_stats :: !Bool -- statistics form fusion/simplification , _dump_simpl_iterations :: !Bool -- output from each simplifier iteration , _verbose :: !Bool -- additional, uncategorised status messages -- functionality / phase control , _acc_sharing :: !(Maybe Bool) -- recover sharing of array computations , _exp_sharing :: !(Maybe Bool) -- recover sharing of scalar expressions , _fusion :: !(Maybe Bool) -- fuse array expressions , _simplify :: !(Maybe Bool) -- simplify scalar expressions } $(mkLabels [''Flags]) allFlags :: [FlagSpec (Flags -> Flags)] allFlags = map (enable 'd') dflags ++ map (enable 'f') fflags ++ map (disable 'f') fflags where enable p (Option f go) = Option ('-':p:f) (go True) disable p (Option f go) = Option ('-':p:"no-"++f) (go False) -- These @-d\<blah\>@ flags can be reversed with @-dno-\<blah\>@ -- dflags :: [FlagSpec (Bool -> Flags -> Flags)] dflags = [ Option "dump-sharing" (set dump_sharing) -- print sharing recovery trace , Option "dump-simpl-stats" (set dump_simpl_stats) -- dump simplifier stats , Option "dump-simpl-iterations" (set dump_simpl_iterations) -- dump output from each simplifier iteration , Option "verbose" (set verbose) -- print additional information ] -- These @-f\<blah\>@ flags can be reversed with @-fno-\<blah\>@ -- fflags :: [FlagSpec (Bool -> Flags -> Flags)] fflags = [ Option "acc-sharing" (set' acc_sharing) -- sharing of array computations , Option "exp-sharing" (set' exp_sharing) -- sharing of scalar expressions , Option "fusion" (set' fusion) -- fusion of array computations , Option "simplify" (set' simplify) -- scalar expression simplification -- , Option "unfolding-use-threshold" -- the magic cut-off figure for inlining ] where set' f v = set f (Just v) initialise :: IO Flags initialise = parse `fmap` getArgs where defaults = Flags False False False False Nothing Nothing Nothing Nothing parse = foldl parse1 defaults parse1 opts this = case filter (\(Option flag _) -> this `isPrefixOf` flag) allFlags of [Option _ go] -> go opts _ -> opts -- not specified, or ambiguous -- Indicates which tracing messages are to be emitted, and which phases are to -- be run. -- {-# NOINLINE options #-} options :: IORef Flags options = unsafePerformIO $ newIORef =<< initialise -- Query the status of a flag -- queryFlag :: (Flags :-> a) -> IO a queryFlag f = get f `fmap` readIORef options -- Set the status of a debug flag -- setFlag :: (Flags :-> a) -> a -> IO () setFlag f v = modifyIORef' options (set f v) -- Execute an action only if the corresponding flag is set -- when :: (Flags :-> Bool) -> IO () -> IO () #ifdef ACCELERATE_DEBUG when f action = do enabled <- queryFlag f if enabled then action else return () #else when _ _ = return () #endif -- ----------------------------------------------------------------------------- -- Trace messages -- Emit a trace message if the corresponding debug flag is set. -- traceMessage :: (Flags :-> Bool) -> String -> IO () #ifdef ACCELERATE_DEBUG traceMessage f str = when f $ do psec <- getCPUTime let sec = fromIntegral psec * 1E-12 :: Double traceIO $ showFFloat (Just 2) sec (':':str) #else traceMessage _ _ = return () #endif -- Emit a message to the event log if the corresponding debug flag is set -- traceEvent :: (Flags :-> Bool) -> String -> IO () #ifdef ACCELERATE_DEBUG traceEvent f str = when f (traceEventIO str) #else traceEvent _ _ = return () #endif -- Emit a trace message from a pure computation -- tracePure :: (Flags :-> Bool) -> String -> a -> a #ifdef ACCELERATE_DEBUG tracePure f msg next = unsafePerformIO (traceMessage f msg) `seq` next #else tracePure _ _ next = next #endif -- ----------------------------------------------------------------------------- -- Recording statistics ruleFired, inline, knownBranch, betaReduce, substitution :: String -> a -> a inline = annotate Inline ruleFired = annotate RuleFired knownBranch = annotate KnownBranch betaReduce = annotate BetaReduce substitution = annotate Substitution simplifierDone, fusionDone :: a -> a simplifierDone = tick SimplifierDone fusionDone = tick FusionDone -- Add an entry to the statistics counters -- tick :: Tick -> a -> a #ifdef ACCELERATE_DEBUG tick t next = unsafePerformIO (modifyIORef' statistics (simplTick t)) `seq` next #else tick _ next = next #endif -- Add an entry to the statistics counters with an annotation -- annotate :: (Id -> Tick) -> String -> a -> a annotate name ctx = tick (name (Id ctx)) -- Simplifier counts -- ----------------- data SimplStats = Simple {-# UNPACK #-} !Int -- when we don't want detailed stats | Detail { ticks :: {-# UNPACK #-} !Int, -- total ticks details :: !TickCount -- how many of each type } instance Show SimplStats where show = render . pprSimplCount -- Stores the current statistics counters -- {-# NOINLINE statistics #-} statistics :: IORef SimplStats statistics = unsafePerformIO $ newIORef =<< initSimplCount -- Initialise the statistics counters. If we are dumping the stats -- (-ddump-simpl-stats) record extra information, else just a total tick count. -- initSimplCount :: IO SimplStats #ifdef ACCELERATE_DEBUG initSimplCount = do d <- queryFlag dump_simpl_stats return $! if d then Detail { ticks = 0, details = Map.empty } else Simple 0 #else initSimplCount = return $! Simple 0 #endif -- Reset the statistics counters. Do this at the beginning at each HOAS -> de -- Bruijn conversion + optimisation pass. -- resetSimplCount :: IO () #ifdef ACCELERATE_DEBUG resetSimplCount = writeIORef statistics =<< initSimplCount #else resetSimplCount = return () #endif -- Tick a counter -- simplTick :: Tick -> SimplStats -> SimplStats simplTick _ (Simple n) = Simple (n+1) simplTick t (Detail n dts) = Detail (n+1) (dts `addTick` t) -- Pretty print the tick counts. Remarkably reminiscent of GHC style... -- pprSimplCount :: SimplStats -> Doc pprSimplCount (Simple n) = text "Total ticks:" <+> int n pprSimplCount (Detail n dts) = vcat [ text "Total ticks:" <+> int n , text "" , pprTickCount dts ] simplCount :: IO Doc simplCount = pprSimplCount `fmap` readIORef statistics -- Ticks -- ----- type TickCount = Map.Map Tick Int data Id = Id String deriving (Eq, Ord) data Tick = Inline Id | RuleFired Id | KnownBranch Id | BetaReduce Id | Substitution Id -- tick at each iteration | SimplifierDone | FusionDone deriving (Eq, Ord) addTick :: TickCount -> Tick -> TickCount addTick tc t = let x = 1 + Map.findWithDefault 0 t tc in x `seq` Map.insert t x tc pprTickCount :: TickCount -> Doc pprTickCount counts = vcat (map pprTickGroup groups) where groups = groupBy sameTag (Map.toList counts) sameTag = (==) `on` tickToTag . fst pprTickGroup :: [(Tick,Int)] -> Doc pprTickGroup [] = error "pprTickGroup" pprTickGroup group = hang (int groupTotal <+> text groupName) 2 (vcat [ int n <+> pprTickCtx t | (t,n) <- sortBy (flip (comparing snd)) group ]) where groupName = tickToStr (fst (head group)) groupTotal = sum [n | (_,n) <- group] tickToTag :: Tick -> Int tickToTag Inline{} = 0 tickToTag RuleFired{} = 1 tickToTag KnownBranch{} = 2 tickToTag BetaReduce{} = 3 tickToTag Substitution{} = 4 tickToTag SimplifierDone = 99 tickToTag FusionDone = 100 tickToStr :: Tick -> String tickToStr Inline{} = "Inline" tickToStr RuleFired{} = "RuleFired" tickToStr KnownBranch{} = "KnownBranch" tickToStr BetaReduce{} = "BetaReduce" tickToStr Substitution{} = "Substitution" tickToStr SimplifierDone = "SimplifierDone" tickToStr FusionDone = "FusionDone" pprTickCtx :: Tick -> Doc pprTickCtx (Inline v) = pprId v pprTickCtx (RuleFired v) = pprId v pprTickCtx (KnownBranch v) = pprId v pprTickCtx (BetaReduce v) = pprId v pprTickCtx (Substitution v) = pprId v pprTickCtx SimplifierDone = empty pprTickCtx FusionDone = empty pprId :: Id -> Doc pprId (Id s) = text s
kumasento/accelerate
Data/Array/Accelerate/Debug.hs
Haskell
bsd-3-clause
10,874
{-# LANGUAGE GADTs, RecordWildCards, ScopedTypeVariables, FlexibleContexts, FlexibleInstances, DeriveDataTypeable, MultiParamTypeClasses, UndecidableInstances #-} -- | Declaration of exceptions types module YaLedger.Exceptions (throwP, InternalError (..), NoSuchRate (..), InsufficientFunds (..), ReconciliationError (..), DuplicatedRecord (..), NoSuchHold (..), InvalidAccountType (..), NoCorrespondingAccountFound (..), NoSuchTemplate (..), InvalidCmdLine (..), InvalidPath (..), NotAnAccount (..) ) where import Control.Monad.Exception import Control.Monad.State import Data.List (intercalate) import Data.Decimal import YaLedger.Types (Path) import YaLedger.Types.Ledger import YaLedger.Types.Common import YaLedger.Types.Monad showPos :: SourcePos -> String -> String showPos pos msg = msg ++ "\n at " ++ show pos throwP e = do pos <- gets lsPosition throw (e pos) data InternalError = InternalError String SourcePos deriving (Typeable) instance Show InternalError where show (InternalError msg pos) = showPos pos $ "Internal error: " ++ msg instance Exception InternalError instance UncaughtException InternalError data NoSuchRate = NoSuchRate Currency Currency SourcePos deriving (Typeable) instance Show NoSuchRate where show (NoSuchRate c1 c2 pos) = showPos pos $ "No conversion rate defined to convert " ++ show c1 ++ " -> " ++ show c2 instance Exception NoSuchRate data InsufficientFunds = InsufficientFunds String Decimal Currency SourcePos deriving (Typeable) instance Show InsufficientFunds where show (InsufficientFunds account x c pos) = showPos pos $ "Insufficient funds on account " ++ account ++ ": balance would be " ++ show (x :# c) instance Exception InsufficientFunds data ReconciliationError = ReconciliationError String SourcePos deriving (Typeable) instance Show ReconciliationError where show (ReconciliationError msg pos) = showPos pos $ "Reconciliation error: " ++ msg instance Exception ReconciliationError data NoSuchHold = NoSuchHold PostingType Decimal Path SourcePos deriving (Typeable) instance Show NoSuchHold where show (NoSuchHold ptype amt path pos) = showPos pos $ "There is no " ++ show ptype ++ " hold of amount " ++ show amt ++ " on account " ++ intercalate "/" path instance Exception NoSuchHold data DuplicatedRecord = DuplicatedRecord String SourcePos deriving (Typeable) instance Show DuplicatedRecord where show (DuplicatedRecord s pos) = showPos pos $ "Duplicated records:\n" ++ s instance Exception DuplicatedRecord data InvalidAccountType = InvalidAccountType String Decimal AccountGroupType AccountGroupType SourcePos deriving (Typeable) instance Show InvalidAccountType where show (InvalidAccountType name amt t1 t2 pos) = showPos pos $ "Internal error:\n Invalid account type: " ++ name ++ ": " ++ show t1 ++ " instead of " ++ show t2 ++ " (amount: " ++ show amt ++ ")" instance Exception InvalidAccountType data NoCorrespondingAccountFound = NoCorrespondingAccountFound (Delta Amount) CQuery SourcePos deriving (Typeable) instance Show NoCorrespondingAccountFound where show (NoCorrespondingAccountFound delta qry pos) = showPos pos $ "No corresponding account found by query: " ++ show qry ++ "\nwhile need to change some balance: " ++ show delta instance Exception NoCorrespondingAccountFound data NoSuchTemplate = NoSuchTemplate String SourcePos deriving (Typeable) instance Show NoSuchTemplate where show (NoSuchTemplate name pos) = showPos pos $ "No such template was defined: " ++ name instance Exception NoSuchTemplate data InvalidCmdLine = InvalidCmdLine String deriving (Typeable) instance Show InvalidCmdLine where show (InvalidCmdLine e) = "Invalid command line parameter: " ++ e instance Exception InvalidCmdLine data InvalidPath = InvalidPath Path [ChartOfAccounts] SourcePos deriving (Typeable) instance Show InvalidPath where show (InvalidPath path [] pos) = showPos pos $ "No such account: " ++ intercalate "/" path show (InvalidPath path list pos) = showPos pos $ "Ambigous account/group specification: " ++ intercalate "/" path ++ ". Matching are:\n" ++ unlines (map show list) instance Exception InvalidPath data NotAnAccount = NotAnAccount Path SourcePos deriving (Typeable) instance Show NotAnAccount where show (NotAnAccount p pos) = showPos pos $ "This is accounts group, not an account: " ++ intercalate "/" p instance Exception NotAnAccount
portnov/yaledger
YaLedger/Exceptions.hs
Haskell
bsd-3-clause
4,623
module Data.TrieMap.WordMap.Tests where import Data.TrieMap.WordMap () import Data.Word import qualified Data.TrieMap.TrieKey.Tests as TrieKeyTests import Test.QuickCheck tests :: Property tests = TrieKeyTests.tests "Data.TrieMap.WordMap" (0 :: Word)
lowasser/TrieMap
Data/TrieMap/WordMap/Tests.hs
Haskell
bsd-3-clause
254
{-# LANGUAGE CPP, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Py.Token -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Maintainer : bjpop@csse.unimelb.edu.au -- Stability : experimental -- Portability : ghc -- -- Lexical tokens for the Python lexer. Contains the superset of tokens from -- version 2 and version 3 of Python (they are mostly the same). ----------------------------------------------------------------------------- module Language.Py.Token -- * The tokens ( Token (..) -- * String conversion , debugTokenString , tokenString -- * Classification , hasLiteral , TokenClass (..) , classifyToken ) where import Language.Py.Pretty import Language.Py.SrcLocation (SrcSpan (..), SrcLocation (..), Span(getSpan)) import Data.Data -- | Lexical tokens. data Token -- Whitespace = IndentToken { tokenSpan :: !SrcSpan } -- ^ Indentation: increase. | DedentToken { tokenSpan :: !SrcSpan } -- ^ Indentation: decrease. | NewlineToken { tokenSpan :: !SrcSpan } -- ^ Newline. | LineJoinToken { tokenSpan :: !SrcSpan } -- ^ Line join (backslash at end of line). -- Comment | CommentToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Single line comment. -- Identifiers | IdentifierToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Identifier. -- Literals | StringToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Literal: string. | ByteStringToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Literal: byte string. | UnicodeStringToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Literal: unicode string, version 2 only. | IntegerToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenInteger :: !Integer } -- ^ Literal: integer. | LongIntegerToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenInteger :: !Integer } -- ^ Literal: long integer. /Version 2 only/. | FloatToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenDouble :: !Double } -- ^ Literal: floating point. | ImaginaryToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenDouble :: !Double } -- ^ Literal: imaginary number. -- Keywords | DefToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'def\'. | WhileToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'while\'. | IfToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'if\'. | TrueToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'True\'. | FalseToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'False\'. | ReturnToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'Return\'. | TryToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'try\'. | ExceptToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'except\'. | RaiseToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'raise\'. | InToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'in\'. | IsToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'is\'. | LambdaToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'lambda\'. | ClassToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'class\'. | FinallyToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'finally\'. | NoneToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'None\'. | ForToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'for\'. | FromToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'from\'. | GlobalToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'global\'. | WithToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'with\'. | AsToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'as\'. | ElifToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'elif\'. | YieldToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'yield\'. | AssertToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'assert\'. | ImportToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'import\'. | PassToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'pass\'. | BreakToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'break\'. | ContinueToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'continue\'. | DeleteToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'del\'. | ElseToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'else\'. | NotToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'not\'. | AndToken { tokenSpan :: !SrcSpan } -- ^ Keyword: boolean conjunction \'and\'. | OrToken { tokenSpan :: !SrcSpan } -- ^ Keyword: boolean disjunction \'or\'. -- Version 3.x only: | NonLocalToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'nonlocal\' (Python 3.x only) -- Version 2.x only: | PrintToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'print\'. (Python 2.x only) | ExecToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'exec\'. (Python 2.x only) -- Delimiters | AtToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: at sign \'\@\'. | LeftRoundBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: left round bracket \'(\'. | RightRoundBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right round bracket \')\'. | LeftSquareBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: left square bracket \'[\'. | RightSquareBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right square bracket \']\'. | LeftBraceToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: left curly bracket \'{\'. | RightBraceToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right curly bracket \'}\'. | DotToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: dot (full stop) \'.\'. | CommaToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: comma \',\'. | SemiColonToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: semicolon \';\'. | ColonToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: colon \':\'. | EllipsisToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: ellipses (three dots) \'...\'. | RightArrowToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right facing arrow \'->\'. | AssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: assignment \'=\'. | PlusAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: plus assignment \'+=\'. | MinusAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: minus assignment \'-=\'. | MultAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: multiply assignment \'*=\' | DivAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: divide assignment \'/=\'. | ModAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: modulus assignment \'%=\'. | PowAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: power assignment \'**=\'. | BinAndAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-and assignment \'&=\'. | BinOrAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-or assignment \'|=\'. | BinXorAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-xor assignment \'^=\'. | LeftShiftAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-left-shift assignment \'<<=\'. | RightShiftAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-right-shift assignment \'>>=\'. | FloorDivAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: floor-divide assignment \'//=\'. | BackQuoteToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: back quote character \'`\'. -- Operators | PlusToken { tokenSpan :: !SrcSpan } -- ^ Operator: plus \'+\'. | MinusToken { tokenSpan :: !SrcSpan } -- ^ Operator: minus: \'-\'. | MultToken { tokenSpan :: !SrcSpan } -- ^ Operator: multiply \'*\'. | DivToken { tokenSpan :: !SrcSpan } -- ^ Operator: divide \'/\'. | GreaterThanToken { tokenSpan :: !SrcSpan } -- ^ Operator: greater-than \'>\'. | LessThanToken { tokenSpan :: !SrcSpan } -- ^ Operator: less-than \'<\'. | EqualityToken { tokenSpan :: !SrcSpan } -- ^ Operator: equals \'==\'. | GreaterThanEqualsToken { tokenSpan :: !SrcSpan } -- ^ Operator: greater-than-or-equals \'>=\'. | LessThanEqualsToken { tokenSpan :: !SrcSpan } -- ^ Operator: less-than-or-equals \'<=\'. | ExponentToken { tokenSpan :: !SrcSpan } -- ^ Operator: exponential \'**\'. | BinaryOrToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-or \'|\'. | XorToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-xor \'^\'. | BinaryAndToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-and \'&\'. | ShiftLeftToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-shift-left \'<<\'. | ShiftRightToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-shift-right \'>>\'. | ModuloToken { tokenSpan :: !SrcSpan } -- ^ Operator: modulus \'%\'. | FloorDivToken { tokenSpan :: !SrcSpan } -- ^ Operator: floor-divide \'//\'. | TildeToken { tokenSpan :: !SrcSpan } -- ^ Operator: tilde \'~\'. | NotEqualsToken { tokenSpan :: !SrcSpan } -- ^ Operator: not-equals \'!=\'. | NotEqualsV2Token { tokenSpan :: !SrcSpan } -- ^ Operator: not-equals \'<>\'. Version 2 only. -- Special cases | EOFToken { tokenSpan :: !SrcSpan } -- ^ End of file deriving (Eq, Ord, Show, Typeable, Data) instance Span Token where getSpan = tokenSpan -- | Produce a string from a token containing detailed information. Mainly intended for debugging. debugTokenString :: Token -> String debugTokenString token = render (text (show $ toConstr token) <+> pretty (tokenSpan token) <+> if hasLiteral token then text (tokenLiteral token) else empty) -- | Test if a token contains its literal source text. hasLiteral :: Token -> Bool hasLiteral token = case token of CommentToken {} -> True IdentifierToken {} -> True StringToken {} -> True ByteStringToken {} -> True IntegerToken {} -> True LongIntegerToken {} -> True FloatToken {} -> True ImaginaryToken {} -> True other -> False -- | Classification of tokens data TokenClass = Comment | Number | Identifier | Punctuation | Bracket | Layout | Keyword | String | Operator | Assignment deriving (Show, Eq, Ord) classifyToken :: Token -> TokenClass classifyToken token = case token of IndentToken {} -> Layout DedentToken {} -> Layout NewlineToken {} -> Layout CommentToken {} -> Comment IdentifierToken {} -> Identifier StringToken {} -> String ByteStringToken {} -> String IntegerToken {} -> Number LongIntegerToken {} -> Number FloatToken {} -> Number ImaginaryToken {} -> Number DefToken {} -> Keyword WhileToken {} -> Keyword IfToken {} -> Keyword TrueToken {} -> Keyword FalseToken {} -> Keyword ReturnToken {} -> Keyword TryToken {} -> Keyword ExceptToken {} -> Keyword RaiseToken {} -> Keyword InToken {} -> Keyword IsToken {} -> Keyword LambdaToken {} -> Keyword ClassToken {} -> Keyword FinallyToken {} -> Keyword NoneToken {} -> Keyword ForToken {} -> Keyword FromToken {} -> Keyword GlobalToken {} -> Keyword WithToken {} -> Keyword AsToken {} -> Keyword ElifToken {} -> Keyword YieldToken {} -> Keyword AssertToken {} -> Keyword ImportToken {} -> Keyword PassToken {} -> Keyword BreakToken {} -> Keyword ContinueToken {} -> Keyword DeleteToken {} -> Keyword ElseToken {} -> Keyword NotToken {} -> Keyword AndToken {} -> Keyword OrToken {} -> Keyword NonLocalToken {} -> Keyword PrintToken {} -> Keyword ExecToken {} -> Keyword AtToken {} -> Keyword LeftRoundBracketToken {} -> Bracket RightRoundBracketToken {} -> Bracket LeftSquareBracketToken {} -> Bracket RightSquareBracketToken {} -> Bracket LeftBraceToken {} -> Bracket RightBraceToken {} -> Bracket DotToken {} -> Operator CommaToken {} -> Punctuation SemiColonToken {} -> Punctuation ColonToken {} -> Punctuation EllipsisToken {} -> Keyword -- What kind of thing is an ellipsis? RightArrowToken {} -> Punctuation AssignToken {} -> Assignment PlusAssignToken {} -> Assignment MinusAssignToken {} -> Assignment MultAssignToken {} -> Assignment DivAssignToken {} -> Assignment ModAssignToken {} -> Assignment PowAssignToken {} -> Assignment BinAndAssignToken {} -> Assignment BinOrAssignToken {} -> Assignment BinXorAssignToken {} -> Assignment LeftShiftAssignToken {} -> Assignment RightShiftAssignToken {} -> Assignment FloorDivAssignToken {} -> Assignment BackQuoteToken {} -> Punctuation PlusToken {} -> Operator MinusToken {} -> Operator MultToken {} -> Operator DivToken {} -> Operator GreaterThanToken {} -> Operator LessThanToken {} -> Operator EqualityToken {} -> Operator GreaterThanEqualsToken {} -> Operator LessThanEqualsToken {} -> Operator ExponentToken {} -> Operator BinaryOrToken {} -> Operator XorToken {} -> Operator BinaryAndToken {} -> Operator ShiftLeftToken {} -> Operator ShiftRightToken {} -> Operator ModuloToken {} -> Operator FloorDivToken {} -> Operator TildeToken {} -> Operator NotEqualsToken {} -> Operator NotEqualsV2Token {} -> Operator LineJoinToken {} -> Layout EOFToken {} -> Layout -- maybe a spurious classification. -- | Produce a string from a token which is suitable for printing as Python concrete syntax. -- /Invisible/ tokens yield an empty string. tokenString :: Token -> String tokenString token = case token of IndentToken {} -> "" DedentToken {} -> "" NewlineToken {} -> "" CommentToken {} -> tokenLiteral token IdentifierToken {} -> tokenLiteral token StringToken {} -> tokenLiteral token ByteStringToken {} -> tokenLiteral token IntegerToken {} -> tokenLiteral token LongIntegerToken {} -> tokenLiteral token FloatToken {} -> tokenLiteral token ImaginaryToken {} -> tokenLiteral token DefToken {} -> "def" WhileToken {} -> "while" IfToken {} -> "if" TrueToken {} -> "True" FalseToken {} -> "False" ReturnToken {} -> "return" TryToken {} -> "try" ExceptToken {} -> "except" RaiseToken {} -> "raise" InToken {} -> "in" IsToken {} -> "is" LambdaToken {} -> "lambda" ClassToken {} -> "class" FinallyToken {} -> "finally" NoneToken {} -> "None" ForToken {} -> "for" FromToken {} -> "from" GlobalToken {} -> "global" WithToken {} -> "with" AsToken {} -> "as" ElifToken {} -> "elif" YieldToken {} -> "yield" AssertToken {} -> "assert" ImportToken {} -> "import" PassToken {} -> "pass" BreakToken {} -> "break" ContinueToken {} -> "continue" DeleteToken {} -> "delete" ElseToken {} -> "else" NotToken {} -> "not" AndToken {} -> "and" OrToken {} -> "or" NonLocalToken {} -> "nonlocal" PrintToken {} -> "print" ExecToken {} -> "exec" AtToken {} -> "at" LeftRoundBracketToken {} -> "(" RightRoundBracketToken {} -> ")" LeftSquareBracketToken {} -> "[" RightSquareBracketToken {} -> "]" LeftBraceToken {} -> "{" RightBraceToken {} -> "}" DotToken {} -> "." CommaToken {} -> "," SemiColonToken {} -> ";" ColonToken {} -> ":" EllipsisToken {} -> "..." RightArrowToken {} -> "->" AssignToken {} -> "=" PlusAssignToken {} -> "+=" MinusAssignToken {} -> "-=" MultAssignToken {} -> "*=" DivAssignToken {} -> "/=" ModAssignToken {} -> "%=" PowAssignToken {} -> "**=" BinAndAssignToken {} -> "&=" BinOrAssignToken {} -> "|=" BinXorAssignToken {} -> "^=" LeftShiftAssignToken {} -> "<<=" RightShiftAssignToken {} -> ">>=" FloorDivAssignToken {} -> "//=" BackQuoteToken {} -> "`" PlusToken {} -> "+" MinusToken {} -> "-" MultToken {} -> "*" DivToken {} -> "/" GreaterThanToken {} -> ">" LessThanToken {} -> "<" EqualityToken {} -> "==" GreaterThanEqualsToken {} -> ">=" LessThanEqualsToken {} -> "<=" ExponentToken {} -> "**" BinaryOrToken {} -> "|" XorToken {} -> "^" BinaryAndToken {} -> "&" ShiftLeftToken {} -> "<<" ShiftRightToken {} -> ">>" ModuloToken {} -> "%" FloorDivToken {} -> "//" TildeToken {} -> "~" NotEqualsToken {} -> "!=" NotEqualsV2Token {} -> "<>" LineJoinToken {} -> "\\" EOFToken {} -> ""
codeq/language-py
src/Language/Py/Token.hs
Haskell
bsd-3-clause
18,123
{-# OPTIONS_HADDOCK hide, prune #-} module Import.BootstrapUtil where import Import bootstrapSelectFieldList :: (Eq a, RenderMessage site FormMessage) => [(Text, a)] -> Field (HandlerT site IO) a bootstrapSelectFieldList opts = Field { fieldParse = parse , fieldView = viewFunc , fieldEnctype = enc } where (Field parse view enc) = selectFieldList opts viewFunc id' name _attrs eitherText required = do let select = view id' name [("class", "form-control")] eitherText required [whamlet| <div .form-group> ^{select} |] -- based on https://www.stackage.org/haddock/lts-8.23/yesod-form-1.4.12/src/Yesod.Form.Fields.html#dayField bootstrapDayField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Day bootstrapDayField = Field { fieldParse = parseHelper $ parseDate . unpack , fieldView = \theId name attrs val isReq -> toWidget [hamlet| <div .form-group> <input .form-control id="#{theId}" name="#{name}" *{attrs} type="date" :isReq:required="" value="#{showVal val}" > |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . show)
achirkin/qua-kit
apps/hs/qua-server/src/Import/BootstrapUtil.hs
Haskell
mit
1,325
<?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="fr-FR"> <title>Plug-n-Hack | 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>Indice</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Rechercher</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/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_fr_FR/helpset_fr_FR.hs
Haskell
apache-2.0
978
<?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="tr-TR"> <title>SOAP Tarayıcısı | ZAP Uzantısı</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>İçerikler</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Dizin</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Arama</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoriler</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_tr_TR/helpset_tr_TR.hs
Haskell
apache-2.0
983
module Propellor.Property.OS ( cleanInstallOnce, Confirmation(..), preserveNetwork, preserveResolvConf, preserveRootSshAuthorized, oldOSRemoved, ) where import Propellor import qualified Propellor.Property.Debootstrap as Debootstrap import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Network as Network import qualified Propellor.Property.User as User import qualified Propellor.Property.File as File import qualified Propellor.Property.Reboot as Reboot import Propellor.Property.Mount import Propellor.Property.Chroot.Util (stdPATH) import System.Posix.Files (rename, fileExist) import Control.Exception (throw) -- | Replaces whatever OS was installed before with a clean installation -- of the OS that the Host is configured to have. -- -- This is experimental; use with caution! -- -- This can replace one Linux distribution with different one. -- But, it can also fail and leave the system in an unbootable state. -- -- To avoid this property being accidentially used, you have to provide -- a Confirmation containing the name of the host that you intend to apply -- the property to. -- -- This property only runs once. The cleanly installed system will have -- a file </etc/propellor-cleaninstall>, which indicates it was cleanly -- installed. -- -- The files from the old os will be left in </old-os> -- -- After the OS is installed, and if all properties of the host have -- been successfully satisfied, the host will be rebooted to properly load -- the new OS. -- -- You will typically want to run some more properties after the clean -- install succeeds, to bootstrap from the cleanly installed system to -- a fully working system. For example: -- -- > & os (System (Debian Unstable) "amd64") -- > & cleanInstallOnce (Confirmed "foo.example.com") -- > `onChange` propertyList "fixing up after clean install" -- > [ preserveNetwork -- > , preserveResolvConf -- > , preserveRootSshAuthorized -- > , Apt.update -- > -- , Grub.boots "/dev/sda" -- > -- `requires` Grub.installed Grub.PC -- > -- , oldOsRemoved (Confirmed "foo.example.com") -- > ] -- > & Hostname.sane -- > & Apt.installed ["linux-image-amd64"] -- > & Apt.installed ["ssh"] -- > & User.hasSomePassword "root" -- > & User.accountFor "joey" -- > & User.hasSomePassword "joey" -- > -- rest of system properties here cleanInstallOnce :: Confirmation -> Property NoInfo cleanInstallOnce confirmation = check (not <$> doesFileExist flagfile) $ go `requires` confirmed "clean install confirmed" confirmation where go = finalized `requires` -- easy to forget and system may not boot without shadow pw! User.shadowConfig True `requires` -- reboot at end if the rest of the propellor run succeeds Reboot.atEnd True (/= FailedChange) `requires` propellorbootstrapped `requires` flipped `requires` osbootstrapped osbootstrapped = withOS (newOSDir ++ " bootstrapped") $ \o -> case o of (Just d@(System (Debian _) _)) -> debootstrap d (Just u@(System (Ubuntu _) _)) -> debootstrap u _ -> error "os is not declared to be Debian or Ubuntu" debootstrap targetos = ensureProperty $ -- Ignore the os setting, and install debootstrap from -- source, since we don't know what OS we're running in yet. Debootstrap.built' Debootstrap.sourceInstall newOSDir targetos Debootstrap.DefaultConfig -- debootstrap, I wish it was faster.. -- TODO eatmydata to speed it up -- Problem: Installing eatmydata on some random OS like -- Fedora may be difficult. Maybe configure dpkg to not -- sync instead? -- This is the fun bit. flipped = property (newOSDir ++ " moved into place") $ liftIO $ do -- First, unmount most mount points, lazily, so -- they don't interfere with moving things around. devfstype <- fromMaybe "devtmpfs" <$> getFsType "/dev" mnts <- filter (`notElem` ("/": trickydirs)) <$> mountPoints -- reverse so that deeper mount points come first forM_ (reverse mnts) umountLazy renamesout <- map (\d -> (d, oldOSDir ++ d, pure $ d `notElem` (oldOSDir:newOSDir:trickydirs))) <$> dirContents "/" renamesin <- map (\d -> let dest = "/" ++ takeFileName d in (d, dest, not <$> fileExist dest)) <$> dirContents newOSDir createDirectoryIfMissing True oldOSDir massRename (renamesout ++ renamesin) removeDirectoryRecursive newOSDir -- Prepare environment for running additional properties, -- overriding old OS's environment. void $ setEnv "PATH" stdPATH True void $ unsetEnv "LANG" -- Remount /dev, so that block devices etc are -- available for other properties to use. unlessM (mount devfstype devfstype "/dev") $ do warningMessage $ "failed mounting /dev using " ++ devfstype ++ "; falling back to MAKEDEV generic" void $ boolSystem "sh" [Param "-c", Param "cd /dev && /sbin/MAKEDEV generic"] -- Mount /sys too, needed by eg, grub-mkconfig. unlessM (mount "sysfs" "sysfs" "/sys") $ warningMessage "failed mounting /sys" -- And /dev/pts, used by apt. unlessM (mount "devpts" "devpts" "/dev/pts") $ warningMessage "failed mounting /dev/pts" return MadeChange propellorbootstrapped = property "propellor re-debootstrapped in new os" $ return NoChange -- re-bootstrap propellor in /usr/local/propellor, -- (using git repo bundle, privdata file, and possibly -- git repo url, which all need to be arranged to -- be present in /old-os's /usr/local/propellor) -- TODO finalized = property "clean OS installed" $ do liftIO $ writeFile flagfile "" return MadeChange flagfile = "/etc/propellor-cleaninstall" trickydirs = -- /tmp can contain X's sockets, which prevent moving it -- so it's left as-is. [ "/tmp" -- /proc is left mounted , "/proc" ] -- Performs all the renames. If any rename fails, rolls back all -- previous renames. Thus, this either successfully performs all -- the renames, or does not change the system state at all. massRename :: [(FilePath, FilePath, IO Bool)] -> IO () massRename = go [] where go _ [] = return () go undo ((from, to, test):rest) = ifM test ( tryNonAsync (rename from to) >>= either (rollback undo) (const $ go ((to, from):undo) rest) , go undo rest ) rollback undo e = do mapM_ (uncurry rename) undo throw e data Confirmation = Confirmed HostName confirmed :: Desc -> Confirmation -> Property NoInfo confirmed desc (Confirmed c) = property desc $ do hostname <- asks hostName if hostname /= c then do warningMessage "Run with a bad confirmation, not matching hostname." return FailedChange else return NoChange -- | </etc/network/interfaces> is configured to bring up the network -- interface that currently has a default route configured, using -- the same (static) IP address. preserveNetwork :: Property NoInfo preserveNetwork = go `requires` Network.cleanInterfacesFile where go = property "preserve network configuration" $ do ls <- liftIO $ lines <$> readProcess "ip" ["route", "list", "scope", "global"] case words <$> headMaybe ls of Just ("default":"via":_:"dev":iface:_) -> ensureProperty $ Network.static iface _ -> do warningMessage "did not find any default ipv4 route" return FailedChange -- | </etc/resolv.conf> is copied from the old OS preserveResolvConf :: Property NoInfo preserveResolvConf = check (fileExist oldloc) $ property (newloc ++ " copied from old OS") $ do ls <- liftIO $ lines <$> readFile oldloc ensureProperty $ newloc `File.hasContent` ls where newloc = "/etc/resolv.conf" oldloc = oldOSDir ++ newloc -- | </root/.ssh/authorized_keys> has added to it any ssh keys that -- were authorized in the old OS. Any other contents of the file are -- retained. preserveRootSshAuthorized :: Property NoInfo preserveRootSshAuthorized = check (fileExist oldloc) $ property (newloc ++ " copied from old OS") $ do ks <- liftIO $ lines <$> readFile oldloc ensureProperties (map (Ssh.authorizedKey (User "root")) ks) where newloc = "/root/.ssh/authorized_keys" oldloc = oldOSDir ++ newloc -- Removes the old OS's backup from </old-os> oldOSRemoved :: Confirmation -> Property NoInfo oldOSRemoved confirmation = check (doesDirectoryExist oldOSDir) $ go `requires` confirmed "old OS backup removal confirmed" confirmation where go = property "old OS backup removed" $ do liftIO $ removeDirectoryRecursive oldOSDir return MadeChange oldOSDir :: FilePath oldOSDir = "/old-os" newOSDir :: FilePath newOSDir = "/new-os"
shosti/propellor
src/Propellor/Property/OS.hs
Haskell
bsd-2-clause
8,501
-- | -- Module : Data.Packer.Unsafe -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- Access to lower primitive that allow to use Packing and Unpacking, -- on mmap type of memory. Potentially unsafe, as it can't check if -- any of value passed are valid. -- module Data.Packer.Unsafe ( runPackingAt , runUnpackingAt ) where import Data.Word import Data.Packer.Internal import Foreign.Ptr import Foreign.ForeignPtr import Control.Monad import Control.Exception import Control.Concurrent.MVar (takeMVar, newMVar) -- | Run packing on an arbitrary buffer with a size. -- -- This is available, for example to run on mmap typed memory, and this is highly unsafe, -- as the user need to make sure the pointer and size passed to this function are correct. runPackingAt :: Ptr Word8 -- ^ Pointer to the beginning of the memory -> Int -- ^ Size of the memory -> Packing a -- ^ Packing action -> IO (a, Int) -- ^ Number of bytes filled runPackingAt ptr sz action = do mvar <- newMVar 0 (a, (Memory _ leftSz)) <- (runPacking_ action) (ptr,mvar) (Memory ptr sz) --(PackSt _ holes (Memory _ leftSz)) <- execStateT (runPacking_ action) (PackSt ptr 0 $ Memory ptr sz) holes <- takeMVar mvar when (holes > 0) (throwIO $ HoleInPacking holes) return (a, sz - leftSz) -- | Run unpacking on an arbitrary buffer with a size. -- -- This is available, for example to run on mmap typed memory, and this is highly unsafe, -- as the user need to make sure the pointer and size passed to this function are correct. runUnpackingAt :: ForeignPtr Word8 -- ^ The initial block of memory -> Int -- ^ Starting offset in the block of memory -> Int -- ^ Size -> Unpacking a -- ^ Unpacking action -> IO a runUnpackingAt fptr offset sz action = withForeignPtr fptr $ \ptr -> let m = Memory (ptr `plusPtr` offset) sz in fmap fst ((runUnpacking_ action) (fptr,m) m)
erikd/hs-packer
Data/Packer/Unsafe.hs
Haskell
bsd-2-clause
2,120
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , RankNTypes , MagicHash , UnboxedTuples , ScopedTypeVariables #-} {-# OPTIONS_GHC -Wno-deprecations #-} -- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN -- and Control.Concurrent.SampleVar imports. ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (concurrency) -- -- A common interface to a collection of useful concurrency -- abstractions. -- ----------------------------------------------------------------------------- module Control.Concurrent ( -- * Concurrent Haskell -- $conc_intro -- * Basic concurrency operations ThreadId, myThreadId, forkIO, forkFinally, forkIOWithUnmask, killThread, throwTo, -- ** Threads with affinity forkOn, forkOnWithUnmask, getNumCapabilities, setNumCapabilities, threadCapability, -- * Scheduling -- $conc_scheduling yield, -- ** Blocking -- $blocking -- ** Waiting threadDelay, threadWaitRead, threadWaitWrite, threadWaitConnect, threadWaitAccept, threadWaitReadSTM, threadWaitWriteSTM, -- * Communication abstractions module Control.Concurrent.MVar, module Control.Concurrent.Chan, module Control.Concurrent.QSem, module Control.Concurrent.QSemN, -- * Bound Threads -- $boundthreads rtsSupportsBoundThreads, forkOS, forkOSWithUnmask, isCurrentThreadBound, runInBoundThread, runInUnboundThread, -- * Weak references to ThreadIds mkWeakThreadId, -- * GHC's implementation of concurrency -- |This section describes features specific to GHC's -- implementation of Concurrent Haskell. -- ** Haskell threads and Operating System threads -- $osthreads -- ** Terminating the program -- $termination -- ** Pre-emption -- $preemption -- ** Deadlock -- $deadlock ) where import Control.Exception.Base as Exception import GHC.Conc hiding (threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM) import GHC.IO ( unsafeUnmask, catchException ) import GHC.IORef ( newIORef, readIORef, writeIORef ) import GHC.Base import System.Posix.Types ( Fd, Channel ) import Foreign.StablePtr import Foreign.C.Types import qualified GHC.Conc import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent.QSem import Control.Concurrent.QSemN {- $conc_intro The concurrency extension for Haskell is described in the paper /Concurrent Haskell/ <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>. Concurrency is \"lightweight\", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using 'forkOS' instead of 'forkIO'. Haskell threads can communicate via 'MVar's, a kind of synchronised mutable variable (see "Control.Concurrent.MVar"). Several common concurrency abstractions can be built from 'MVar's, and these are provided by the "Control.Concurrent" library. In GHC, threads may also communicate via exceptions. -} {- $conc_scheduling Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: > main = forkIO (write 'a') >> write 'b' > where write c = putChar c >> write c will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@, instead of some random interleaving of @a@s and @b@s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. -} {- $blocking Different Haskell implementations have different characteristics with regard to which operations block /all/ threads. Using GHC without the @-threaded@ option, all foreign calls will block all other Haskell threads in the system, although I\/O operations will not. With the @-threaded@ option, only foreign calls with the @unsafe@ attribute will block all other threads. -} -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- -- > forkFinally action and_then = -- > mask $ \restore -> -- > forkIO $ try (restore action) >>= and_then -- -- This function is useful for informing the parent when a child -- terminates, for example. -- -- @since 4.6.0.0 forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then -- --------------------------------------------------------------------------- -- Bound Threads {- $boundthreads #boundthreads# Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the /-threaded/ option when linking. Other Haskell systems do not currently support multiple operating system threads. A bound thread is a haskell thread that is /bound/ to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like @pthread_create@ or @CreateThread@. Bound threads can be created using the 'forkOS' function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the @main@ action of every Haskell program is run in a bound thread. Why do we need this? Because if a foreign library is called from a thread created using 'forkIO', it won't have access to any /thread-local state/ - state variables that have specific values for each OS thread (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some libraries (OpenGL, for example) will not work from a thread created using 'forkIO'. They work fine in threads created using 'forkOS' or when called from @main@ or from a @foreign export@. In terms of performance, 'forkOS' (aka bound) threads are much more expensive than 'forkIO' (aka unbound) threads, because a 'forkOS' thread is tied to a particular OS thread, whereas a 'forkIO' thread can be run by any OS thread. Context-switching between a 'forkOS' thread and a 'forkIO' thread is many times more expensive than between two 'forkIO' threads. Note in particular that the main program thread (the thread running @Main.main@) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using 'forkIO', and waiting for the results in the main thread. -} -- | 'True' if bound threads are supported. -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound' -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will -- fail. rtsSupportsBoundThreads :: Bool rtsSupportsBoundThreads = True {- | Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the first argument, and returns the 'ThreadId' of the newly created thread. However, 'forkOS' creates a /bound/ thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads"). Using 'forkOS' instead of 'forkIO' makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use 'forkOS' instead of 'forkIO' to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the @-threaded@ option when linking your program, and to make sure the foreign import is not marked @unsafe@. -} forkOS :: IO () -> IO ThreadId foreign export java forkOS_entry :: StablePtr (IO ()) -> IO () foreign import java "@static base.control.Concurrent.forkOS_entry" forkOS_entry_reimported :: StablePtr (IO ()) -> IO () forkOS_entry :: StablePtr (IO ()) -> IO () forkOS_entry stableAction = do action <- deRefStablePtr stableAction action foreign import java "@static eta.runtime.concurrent.Concurrent.forkOS_createThread" forkOS_createThread :: StablePtr (IO ()) -> IO CInt failNonThreaded :: IO a failNonThreaded = fail $ "RTS doesn't support multiple OS threads " ++"(use ghc -threaded when linking)" forkOS action0 | rtsSupportsBoundThreads = do mv <- newEmptyMVar b <- Exception.getMaskingState let -- async exceptions are masked in the child if they are masked -- in the parent, as for forkIO (see #1048). forkOS_createThread -- creates a thread with exceptions masked by default. action1 = case b of Unmasked -> unsafeUnmask action0 MaskedInterruptible -> action0 MaskedUninterruptible -> uninterruptibleMask_ action0 action_plus = Exception.catch action1 childHandler entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus) err <- forkOS_createThread entry when (err /= 0) $ fail "Cannot create OS thread." tid <- takeMVar mv freeStablePtr entry return tid | otherwise = failNonThreaded -- | Like 'forkIOWithUnmask', but the child thread is a bound thread, -- as with 'forkOS'. forkOSWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId forkOSWithUnmask io = forkOS (io unsafeUnmask) -- | Returns 'True' if the calling thread is /bound/, that is, if it is -- safe to use foreign libraries that rely on thread-local state from the -- calling thread. isCurrentThreadBound :: IO Bool isCurrentThreadBound = IO $ \ s# -> case isCurrentThreadBound# s# of (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #) {- | Run the 'IO' computation passed as the first argument. If the calling thread is not /bound/, a bound thread is created temporarily. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. You can wrap a series of foreign function calls that rely on thread-local state with @runInBoundThread@ so that you can use them without knowing whether the current thread is /bound/. -} runInBoundThread :: IO a -> IO a runInBoundThread action | rtsSupportsBoundThreads = do bound <- isCurrentThreadBound if bound then action else do ref <- newIORef undefined let action_plus = Exception.try action >>= writeIORef ref bracket (newStablePtr action_plus) freeStablePtr (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>= unsafeResult | otherwise = failNonThreaded {- | Run the 'IO' computation passed as the first argument. If the calling thread is /bound/, an unbound thread is created temporarily using 'forkIO'. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. Use this function /only/ in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need its main thread to be bound and makes /heavy/ use of concurrency (e.g. a web server), might want to wrap its @main@ action in @runInUnboundThread@. Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread. -} runInUnboundThread :: IO a -> IO a runInUnboundThread action = do bound <- isCurrentThreadBound if bound then do mv <- newEmptyMVar mask $ \restore -> do tid <- forkIO $ Exception.try (restore action) >>= putMVar mv let wait = takeMVar mv `catchException` \(e :: SomeException) -> Exception.throwTo tid e >> wait wait >>= unsafeResult else action unsafeResult :: Either SomeException a -> IO a unsafeResult = either Exception.throwIO return -- --------------------------------------------------------------------------- -- threadWaitRead/threadWaitWrite -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use -- 'GHC.Conc.closeFdWith'. threadWaitRead :: Channel -> IO () threadWaitRead fd = GHC.Conc.threadWaitRead fd -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use -- 'GHC.Conc.closeFdWith'. threadWaitWrite :: Channel -> IO () threadWaitWrite fd = GHC.Conc.threadWaitWrite fd -- | Returns an STM action that can be used to wait for data -- to read from a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitReadSTM :: Channel -> IO (STM (), IO ()) threadWaitReadSTM fd = GHC.Conc.threadWaitReadSTM fd -- | Returns an STM action that can be used to wait until data -- can be written to a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitWriteSTM :: Channel -> IO (STM (), IO ()) threadWaitWriteSTM fd = GHC.Conc.threadWaitWriteSTM fd -- --------------------------------------------------------------------------- -- More docs {- $osthreads #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the @-threaded@ option (to link against the multithreaded version of the runtime), a thread making a @safe@ foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these /worker/ threads so that multiple Haskell threads can be involved in external calls simultaneously. The "System.IO" library manages multiplexing in its own way. On Windows systems it uses @safe@ foreign calls to ensure that threads doing I\/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I\/O requests are managed by a single thread (the /IO manager thread/) using a mechanism such as @epoll@ or @kqueue@, depending on what is provided by the host operating system. The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see "Control.Concurrent#boundthreads"). If you don't use the @-threaded@ option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The "System.IO" library still does multiplexing, so there can be multiple threads doing I\/O, and this is handled internally by the runtime using @select@. -} {- $termination In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is \"daemonic threads\"). If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an 'MVar' when it completes, and have the main thread wait on all the 'MVar's before exiting: > myForkIO :: IO () -> IO (MVar ()) > myForkIO io = do > mvar <- newEmptyMVar > forkFinally io (\_ -> putMVar mvar ()) > return mvar Note that we use 'forkFinally' to make sure that the 'MVar' is written to even if the thread dies or is killed for some reason. A better method is to keep a global list of all child threads which we should wait for at the end of the program: > children :: MVar [MVar ()] > children = unsafePerformIO (newMVar []) > > waitForChildren :: IO () > waitForChildren = do > cs <- takeMVar children > case cs of > [] -> return () > m:ms -> do > putMVar children ms > takeMVar m > waitForChildren > > forkChild :: IO () -> IO ThreadId > forkChild io = do > mvar <- newEmptyMVar > childs <- takeMVar children > putMVar children (mvar:childs) > forkFinally io (\_ -> putMVar mvar ()) > > main = > later waitForChildren $ > ... The main thread principle also applies to calls to Haskell from outside, using @foreign export@. When the @foreign export@ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the @foreign export@ed function has returned. -} {- $preemption GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the @-i\<n\>@ RTS option. After a rescheduling \"tick\" the running thread is pre-empted as soon as possible. One final note: the @aaaa@ @bbbb@ example may not work too well on GHC (see Scheduling, above), due to the locking on a 'System.IO.Handle'. Only one thread may hold the lock on a 'System.IO.Handle' at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from @aaaa@ to @bbbbb@ happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) -} {- $deadlock GHC attempts to detect when threads are deadlocked using the garbage collector. A thread that is not reachable (cannot be found by following pointers from live objects) must be deadlocked, and in this case the thread is sent an exception. The exception is either 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', 'NonTermination', or 'Deadlock', depending on the way in which the thread is deadlocked. Note that this feature is intended for debugging, and should not be relied on for the correct operation of your program. There is no guarantee that the garbage collector will be accurate enough to detect your deadlock, and no guarantee that the garbage collector will run in a timely enough manner. Basically, the same caveats as for finalizers apply to deadlock detection. There is a subtle interaction between deadlock detection and finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the functions in "System.Mem.Weak"): if a thread is blocked waiting for a finalizer to run, then the thread will be considered deadlocked and sent an exception. So preferably don't do this, but if you have no alternative then it is possible to prevent the thread from being considered deadlocked by making a 'StablePtr' pointing to it. Don't forget to release the 'StablePtr' later with 'freeStablePtr'. -}
rahulmutt/ghcvm
libraries/base/Control/Concurrent.hs
Haskell
bsd-3-clause
22,020
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, ScopedTypeVariables, DeriveDataTypeable, GADTs #-} module CommonFFI where import Prelude hiding (catch) import qualified Data.ByteString as S import qualified Data.ByteString.Unsafe as S import qualified Data.ByteString.Lazy as L import Foreign.Marshal.Utils import Foreign import Foreign.C.String import Data.Data import Control.Exception import Control.Monad import qualified Data.ByteString.UTF8 as U import qualified Data.Aeson.Encode as E import GHC.Conc import JSONGeneric import Common data UrwebContext data Result a = EndUserFailure EndUserFailure | InternalFailure String | Success a deriving (Data, Typeable) -- here's how you parse this: first, you try parsing using -- the expected result type. If that doesn't work, try parsing -- using EndUserFailure. And then finally, parse as string. -- XXX this doesn't work if we have something that legitimately -- needs to return a string, although we can force fix that -- by adding a wrapper... result :: IO a -> IO (Result a) result m = liftM Success m `catches` [ Handler (return . EndUserFailure) , Handler (return . InternalFailure . (show :: SomeException -> String)) ] -- incoming string doesn't have to be Haskell managed -- outgoing string is on Urweb allocated memory, and -- is the unique outgoing one serialize :: Data a => Ptr UrwebContext -> IO a -> IO CString serialize ctx m = lazyByteStringToUrWebCString ctx . E.encode . toJSON =<< result m peekUTF8String :: CString -> IO String peekUTF8String = liftM U.toString . S.packCString lazyByteStringToUrWebCString :: Ptr UrwebContext -> L.ByteString -> IO CString lazyByteStringToUrWebCString ctx bs = do let s = S.concat (L.toChunks bs) -- XXX S.concat is really bad! Bad Edward! S.unsafeUseAsCStringLen s $ \(c,n) -> do x <- uw_malloc ctx (n+1) copyBytes x c n poke (plusPtr x n) (0 :: Word8) return x {- This is the right way to do it, which doesn't - involve copying everything, but it might be overkill -- XXX This would be a useful helper function for bytestring to have. let l = fromIntegral (L.length bs' + 1) -- XXX overflow x <- uw_malloc ctx l let f x c = ... foldlChunks f x -} foreign import ccall "urweb.h uw_malloc" uw_malloc :: Ptr UrwebContext -> Int -> IO (Ptr a) foreign export ccall ensureIOManagerIsRunning :: IO ()
diflying/logitext
CommonFFI.hs
Haskell
bsd-3-clause
2,463
-- Set up the data structures provided by 'Vectorise.Builtins'. module Vectorise.Builtins.Initialise ( -- * Initialisation initBuiltins, initBuiltinVars ) where import GhcPrelude import Vectorise.Builtins.Base import BasicTypes import TysPrim import DsMonad import TysWiredIn import DataCon import TyCon import Class import CoreSyn import Type import NameEnv import Name import Id import FastString import Outputable import Control.Monad import Data.Array -- |Create the initial map of builtin types and functions. -- initBuiltins :: DsM Builtins initBuiltins = do { -- 'PArray: representation type for parallel arrays ; parrayTyCon <- externalTyCon (fsLit "PArray") -- 'PData': type family mapping array element types to array representation types -- Not all backends use `PDatas`. ; pdataTyCon <- externalTyCon (fsLit "PData") ; pdatasTyCon <- externalTyCon (fsLit "PDatas") -- 'PR': class of basic array operators operating on 'PData' types ; prClass <- externalClass (fsLit "PR") ; let prTyCon = classTyCon prClass -- 'PRepr': type family mapping element types to representation types ; preprTyCon <- externalTyCon (fsLit "PRepr") -- 'PA': class of basic operations on arrays (parametrised by the element type) ; paClass <- externalClass (fsLit "PA") ; let paTyCon = classTyCon paClass [paDataCon] = tyConDataCons paTyCon paPRSel = classSCSelId paClass 0 -- Functions on array representations ; replicatePDVar <- externalVar (fsLit "replicatePD") ; replicate_vars <- mapM externalVar (suffixed "replicatePA" aLL_DPH_PRIM_TYCONS) ; emptyPDVar <- externalVar (fsLit "emptyPD") ; empty_vars <- mapM externalVar (suffixed "emptyPA" aLL_DPH_PRIM_TYCONS) ; packByTagPDVar <- externalVar (fsLit "packByTagPD") ; packByTag_vars <- mapM externalVar (suffixed "packByTagPA" aLL_DPH_PRIM_TYCONS) ; let combineNamesD = [("combine" ++ show i ++ "PD") | i <- [2..mAX_DPH_COMBINE]] ; let combineNamesA = [("combine" ++ show i ++ "PA") | i <- [2..mAX_DPH_COMBINE]] ; combines <- mapM externalVar (map mkFastString combineNamesD) ; combines_vars <- mapM (mapM externalVar) $ map (\name -> suffixed name aLL_DPH_PRIM_TYCONS) combineNamesA ; let replicatePD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS replicate_vars) emptyPD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS empty_vars) packByTagPD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS packByTag_vars) combinePDVars = listArray (2, mAX_DPH_COMBINE) combines combinePD_PrimVarss = listArray (2, mAX_DPH_COMBINE) [ mkNameEnv (zip aLL_DPH_PRIM_TYCONS vars) | vars <- combines_vars] -- 'Scalar': class moving between plain unboxed arrays and 'PData' representations ; scalarClass <- externalClass (fsLit "Scalar") -- N-ary maps ('zipWith' family) ; scalar_map <- externalVar (fsLit "scalar_map") ; scalar_zip2 <- externalVar (fsLit "scalar_zipWith") ; scalar_zips <- mapM externalVar (numbered "scalar_zipWith" 3 mAX_DPH_SCALAR_ARGS) ; let scalarZips = listArray (1, mAX_DPH_SCALAR_ARGS) (scalar_map : scalar_zip2 : scalar_zips) -- Types and functions for generic type representations ; voidTyCon <- externalTyCon (fsLit "Void") ; voidVar <- externalVar (fsLit "void") ; fromVoidVar <- externalVar (fsLit "fromVoid") ; sum_tcs <- mapM externalTyCon (numbered "Sum" 2 mAX_DPH_SUM) ; let sumTyCons = listArray (2, mAX_DPH_SUM) sum_tcs ; wrapTyCon <- externalTyCon (fsLit "Wrap") ; pvoidVar <- externalVar (fsLit "pvoid") ; pvoidsVar <- externalVar (fsLit "pvoids#") -- Types and functions for closure conversion ; closureTyCon <- externalTyCon (fsLit ":->") ; closureVar <- externalVar (fsLit "closure") ; liftedClosureVar <- externalVar (fsLit "liftedClosure") ; applyVar <- externalVar (fsLit "$:") ; liftedApplyVar <- externalVar (fsLit "liftedApply") ; closures <- mapM externalVar (numbered "closure" 1 mAX_DPH_SCALAR_ARGS) ; let closureCtrFuns = listArray (1, mAX_DPH_SCALAR_ARGS) closures -- Types and functions for selectors ; sel_tys <- mapM externalType (numbered "Sel" 2 mAX_DPH_SUM) ; sels_tys <- mapM externalType (numbered "Sels" 2 mAX_DPH_SUM) ; sels_length <- mapM externalFun (numbered_hash "lengthSels" 2 mAX_DPH_SUM) ; sel_replicates <- mapM externalFun (numbered_hash "replicateSel" 2 mAX_DPH_SUM) ; sel_tags <- mapM externalFun (numbered "tagsSel" 2 mAX_DPH_SUM) ; sel_elements <- mapM mk_elements [(i,j) | i <- [2..mAX_DPH_SUM], j <- [0..i-1]] ; let selTys = listArray (2, mAX_DPH_SUM) sel_tys selsTys = listArray (2, mAX_DPH_SUM) sels_tys selsLengths = listArray (2, mAX_DPH_SUM) sels_length selReplicates = listArray (2, mAX_DPH_SUM) sel_replicates selTagss = listArray (2, mAX_DPH_SUM) sel_tags selElementss = array ((2, 0), (mAX_DPH_SUM, mAX_DPH_SUM)) sel_elements -- Distinct local variable ; liftingContext <- liftM (\u -> mkSysLocalOrCoVar (fsLit "lc") u intPrimTy) newUnique ; return $ Builtins { parrayTyCon = parrayTyCon , pdataTyCon = pdataTyCon , pdatasTyCon = pdatasTyCon , preprTyCon = preprTyCon , prClass = prClass , prTyCon = prTyCon , paClass = paClass , paTyCon = paTyCon , paDataCon = paDataCon , paPRSel = paPRSel , replicatePDVar = replicatePDVar , replicatePD_PrimVars = replicatePD_PrimVars , emptyPDVar = emptyPDVar , emptyPD_PrimVars = emptyPD_PrimVars , packByTagPDVar = packByTagPDVar , packByTagPD_PrimVars = packByTagPD_PrimVars , combinePDVars = combinePDVars , combinePD_PrimVarss = combinePD_PrimVarss , scalarClass = scalarClass , scalarZips = scalarZips , voidTyCon = voidTyCon , voidVar = voidVar , fromVoidVar = fromVoidVar , sumTyCons = sumTyCons , wrapTyCon = wrapTyCon , pvoidVar = pvoidVar , pvoidsVar = pvoidsVar , closureTyCon = closureTyCon , closureVar = closureVar , liftedClosureVar = liftedClosureVar , applyVar = applyVar , liftedApplyVar = liftedApplyVar , closureCtrFuns = closureCtrFuns , selTys = selTys , selsTys = selsTys , selsLengths = selsLengths , selReplicates = selReplicates , selTagss = selTagss , selElementss = selElementss , liftingContext = liftingContext } } where suffixed :: String -> [Name] -> [FastString] suffixed pfx ns = [mkFastString (pfx ++ "_" ++ (occNameString . nameOccName) n) | n <- ns] -- Make a list of numbered strings in some range, eg foo3, foo4, foo5 numbered :: String -> Int -> Int -> [FastString] numbered pfx m n = [mkFastString (pfx ++ show i) | i <- [m..n]] numbered_hash :: String -> Int -> Int -> [FastString] numbered_hash pfx m n = [mkFastString (pfx ++ show i ++ "#") | i <- [m..n]] mk_elements :: (Int, Int) -> DsM ((Int, Int), CoreExpr) mk_elements (i,j) = do { v <- externalVar $ mkFastString ("elementsSel" ++ show i ++ "_" ++ show j ++ "#") ; return ((i, j), Var v) } -- |Get the mapping of names in the Prelude to names in the DPH library. -- initBuiltinVars :: Builtins -> DsM [(Var, Var)] -- FIXME: must be replaced by VECTORISE pragmas!!! initBuiltinVars (Builtins { }) = do cvars <- mapM externalVar cfs return $ zip (map dataConWorkId cons) cvars where (cons, cfs) = unzip preludeDataCons preludeDataCons :: [(DataCon, FastString)] preludeDataCons = [mk_tup n (mkFastString $ "tup" ++ show n) | n <- [2..5]] where mk_tup n name = (tupleDataCon Boxed n, name) -- Auxiliary look up functions ----------------------------------------------- -- |Lookup a variable given its name and the module that contains it. externalVar :: FastString -> DsM Var externalVar fs = dsLookupDPHRdrEnv (mkVarOccFS fs) >>= dsLookupGlobalId -- |Like `externalVar` but wrap the `Var` in a `CoreExpr`. externalFun :: FastString -> DsM CoreExpr externalFun fs = Var <$> externalVar fs -- |Lookup a 'TyCon' in 'Data.Array.Parallel.Prim', given its name. -- Panic if there isn't one. externalTyCon :: FastString -> DsM TyCon externalTyCon fs = dsLookupDPHRdrEnv (mkTcOccFS fs) >>= dsLookupTyCon -- |Lookup some `Type` in 'Data.Array.Parallel.Prim', given its name. externalType :: FastString -> DsM Type externalType fs = do tycon <- externalTyCon fs return $ mkTyConApp tycon [] -- |Lookup a 'Class' in 'Data.Array.Parallel.Prim', given its name. externalClass :: FastString -> DsM Class externalClass fs = do { tycon <- dsLookupDPHRdrEnv (mkClsOccFS fs) >>= dsLookupTyCon ; case tyConClass_maybe tycon of Nothing -> pprPanic "Vectorise.Builtins.Initialise" $ text "Data.Array.Parallel.Prim." <> ftext fs <+> text "is not a type class" Just cls -> return cls }
shlevy/ghc
compiler/vectorise/Vectorise/Builtins/Initialise.hs
Haskell
bsd-3-clause
10,351
{-# language OverloadedStrings #-} {-# language PackageImports #-} module Main where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "base" System.Environment ( getArgs ) import "base" Data.Semigroup ( (<>) ) import "HUnit" Test.HUnit.Base ( assertEqual ) import "test-framework" Test.Framework ( defaultMainWithOpts, interpretArgsOrExit, Test, testGroup ) import "test-framework-hunit" Test.Framework.Providers.HUnit ( testCase ) import "terminal-progress-bar" System.ProgressBar import qualified "text" Data.Text.Lazy as TL import "time" Data.Time.Clock ( UTCTime(..), NominalDiffTime ) -------------------------------------------------------------------------------- -- Test suite -------------------------------------------------------------------------------- main :: IO () main = do opts <- interpretArgsOrExit =<< getArgs defaultMainWithOpts tests opts tests :: [Test] tests = [ testGroup "Label padding" [ eqTest "no labels" "[]" mempty mempty 0 $ Progress 0 0 () , eqTest "pre" "pre []" (msg "pre") mempty 0 $ Progress 0 0 () , eqTest "post" "[] post" mempty (msg "post") 0 $ Progress 0 0 () , eqTest "pre & post" "pre [] post" (msg "pre") (msg "post") 0 $ Progress 0 0 () ] , testGroup "Bar fill" [ eqTest "empty" "[....]" mempty mempty 6 $ Progress 0 1 () , eqTest "almost half" "[=>..]" mempty mempty 6 $ Progress 49 100 () , eqTest "half" "[==>.]" mempty mempty 6 $ Progress 1 2 () , eqTest "almost full" "[===>]" mempty mempty 6 $ Progress 99 100 () , eqTest "full" "[====]" mempty mempty 6 $ Progress 1 1 () , eqTest "overfull" "[====]" mempty mempty 6 $ Progress 2 1 () ] , testGroup "Labels" [ testGroup "Percentage" [ eqTest " 0%" " 0% [....]" percentage mempty 11 $ Progress 0 1 () , eqTest "100%" "100% [====]" percentage mempty 11 $ Progress 1 1 () , eqTest " 50%" " 50% [==>.]" percentage mempty 11 $ Progress 1 2 () , eqTest "200%" "200% [====]" percentage mempty 11 $ Progress 2 1 () , labelTest "0 work todo" percentage (Progress 10 0 ()) "100%" ] , testGroup "Exact" [ eqTest "0/0" "0/0 [....]" exact mempty 10 $ Progress 0 0 () , eqTest "1/1" "1/1 [====]" exact mempty 10 $ Progress 1 1 () , eqTest "1/2" "1/2 [==>.]" exact mempty 10 $ Progress 1 2 () , eqTest "2/1" "2/1 [====]" exact mempty 10 $ Progress 2 1 () , labelTest "0 work todo" exact (Progress 10 0 ()) "10/0" ] , testGroup "Label Semigroup" [ eqTest "exact <> msg <> percentage" "1/2 - 50% [===>...]" (exact <> msg " - " <> percentage) mempty 20 $ Progress 1 2 () ] , testGroup "rendeRuration" [ renderDurationTest 42 "42" , renderDurationTest (5 * 60 + 42) "05:42" , renderDurationTest (8 * 60 * 60 + 5 * 60 + 42) "08:05:42" , renderDurationTest (123 * 60 * 60 + 59 * 60 + 59) "123:59:59" ] ] ] labelTest :: String -> Label () -> Progress () -> TL.Text -> Test labelTest testName label progress expected = testCase testName $ assertEqual expectationError expected $ runLabel label progress someTiming renderDurationTest :: NominalDiffTime -> TL.Text -> Test renderDurationTest dt expected = testCase ("renderDuration " <> show dt) $ assertEqual expectationError expected $ renderDuration dt eqTest :: String -> TL.Text -> Label () -> Label () -> Int -> Progress () -> Test eqTest name expected mkPreLabel mkPostLabel width progress = testCase name $ assertEqual expectationError expected actual where actual = renderProgressBar style progress someTiming style :: Style () style = defStyle { stylePrefix = mkPreLabel , stylePostfix = mkPostLabel , styleWidth = ConstantWidth width } someTime :: UTCTime someTime = UTCTime (toEnum 0) 0 someTiming :: Timing someTiming = Timing someTime someTime expectationError :: String expectationError = "Expected result doesn't match actual result"
ngzax/urbit
pkg/hs/terminal-progress-bar/test/test.hs
Haskell
mit
4,236
<?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="ru-RU"> <title>Интерфейсный сканер | Расширение ZAP </title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Содержание</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Индекс</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Поиск</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Избранное</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/frontendscanner/src/main/javahelp/org/zaproxy/zap/extension/frontendscanner/resources/help_ru_RU/helpset_ru_RU.hs
Haskell
apache-2.0
1,042
{- | The public face of Template Haskell For other documentation, refer to: <http://www.haskell.org/haskellwiki/Template_Haskell> -} module Language.Haskell.TH( -- * The monad and its operations Q, runQ, -- ** Administration: errors, locations and IO reportError, -- :: String -> Q () reportWarning, -- :: String -> Q () report, -- :: Bool -> String -> Q () recover, -- :: Q a -> Q a -> Q a location, -- :: Q Loc Loc(..), runIO, -- :: IO a -> Q a -- ** Querying the compiler -- *** Reify reify, -- :: Name -> Q Info reifyModule, thisModule, Info(..), ModuleInfo(..), InstanceDec, ParentName, Arity, Unlifted, -- *** Name lookup lookupTypeName, -- :: String -> Q (Maybe Name) lookupValueName, -- :: String -> Q (Maybe Name) -- *** Fixity lookup reifyFixity, -- *** Instance lookup reifyInstances, isInstance, -- *** Roles lookup reifyRoles, -- *** Annotation lookup reifyAnnotations, AnnLookup(..), -- * Typed expressions TExp, unType, -- * Names Name, NameSpace, -- Abstract -- ** Constructing names mkName, -- :: String -> Name newName, -- :: String -> Q Name -- ** Deconstructing names nameBase, -- :: Name -> String nameModule, -- :: Name -> Maybe String namePackage, -- :: Name -> Maybe String nameSpace, -- :: Name -> Maybe NameSpace -- ** Built-in names tupleTypeName, tupleDataName, -- Int -> Name unboxedTupleTypeName, unboxedTupleDataName, -- :: Int -> Name -- * The algebraic data types -- | The lowercase versions (/syntax operators/) of these constructors are -- preferred to these constructors, since they compose better with -- quotations (@[| |]@) and splices (@$( ... )@) -- ** Declarations Dec(..), Con(..), Clause(..), Strict(..), Foreign(..), Callconv(..), Safety(..), Pragma(..), Inline(..), RuleMatch(..), Phases(..), RuleBndr(..), AnnTarget(..), FunDep(..), FamFlavour(..), TySynEqn(..), Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence, -- ** Expressions Exp(..), Match(..), Body(..), Guard(..), Stmt(..), Range(..), Lit(..), -- ** Patterns Pat(..), FieldExp, FieldPat, -- ** Types Type(..), TyVarBndr(..), TyLit(..), Kind, Cxt, Pred, Syntax.Role(..), FamilyResultSig(..), Syntax.InjectivityAnn(..), -- * Library functions -- ** Abbreviations InfoQ, ExpQ, DecQ, DecsQ, ConQ, TypeQ, TyLitQ, CxtQ, PredQ, MatchQ, ClauseQ, BodyQ, GuardQ, StmtQ, RangeQ, StrictTypeQ, VarStrictTypeQ, PatQ, FieldPatQ, RuleBndrQ, TySynEqnQ, -- ** Constructors lifted to 'Q' -- *** Literals intPrimL, wordPrimL, floatPrimL, doublePrimL, integerL, rationalL, charL, stringL, stringPrimL, charPrimL, -- *** Patterns litP, varP, tupP, conP, uInfixP, parensP, infixP, tildeP, bangP, asP, wildP, recP, listP, sigP, viewP, fieldPat, -- *** Pattern Guards normalB, guardedB, normalG, normalGE, patG, patGE, match, clause, -- *** Expressions dyn, varE, conE, litE, appE, uInfixE, parensE, staticE, infixE, infixApp, sectionL, sectionR, lamE, lam1E, lamCaseE, tupE, condE, multiIfE, letE, caseE, appsE, listE, sigE, recConE, recUpdE, stringE, fieldExp, -- **** Ranges fromE, fromThenE, fromToE, fromThenToE, -- ***** Ranges with more indirection arithSeqE, fromR, fromThenR, fromToR, fromThenToR, -- **** Statements doE, compE, bindS, letS, noBindS, parS, -- *** Types forallT, varT, conT, appT, arrowT, infixT, uInfixT, parensT, equalityT, listT, tupleT, sigT, litT, promotedT, promotedTupleT, promotedNilT, promotedConsT, -- **** Type literals numTyLit, strTyLit, -- **** Strictness isStrict, notStrict, strictType, varStrictType, -- **** Class Contexts cxt, classP, equalP, normalC, recC, infixC, forallC, -- *** Kinds varK, conK, tupleK, arrowK, listK, appK, starK, constraintK, -- *** Roles nominalR, representationalR, phantomR, inferR, -- *** Top Level Declarations -- **** Data valD, funD, tySynD, dataD, newtypeD, -- **** Class classD, instanceD, sigD, standaloneDerivD, defaultSigD, -- **** Role annotations roleAnnotD, -- **** Type Family / Data Family dataFamilyD, openTypeFamilyD, closedTypeFamilyD, dataInstD, familyNoKindD, familyKindD, closedTypeFamilyNoKindD, closedTypeFamilyKindD, newtypeInstD, tySynInstD, typeFam, dataFam, tySynEqn, injectivityAnn, noSig, kindSig, tyVarSig, -- **** Foreign Function Interface (FFI) cCall, stdCall, cApi, prim, javaScript, unsafe, safe, forImpD, -- **** Pragmas ruleVar, typedRuleVar, pragInlD, pragSpecD, pragSpecInlD, pragSpecInstD, pragRuleD, pragAnnD, pragLineD, -- * Pretty-printer Ppr(..), pprint, pprExp, pprLit, pprPat, pprParendType ) where import Language.Haskell.TH.Syntax as Syntax import Language.Haskell.TH.Lib import Language.Haskell.TH.Ppr
AlexanderPankiv/ghc
libraries/template-haskell/Language/Haskell/TH.hs
Haskell
bsd-3-clause
5,474
<?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="id-ID"> <title>Kembali</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Konten</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Telusuri</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorit</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/revisit/src/main/javahelp/org/zaproxy/zap/extension/revisit/resources/help_id_ID/helpset_id_ID.hs
Haskell
apache-2.0
951
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NondecreasingIndentation #-} {-# LANGUAGE PatternGuards #-} import Test.Cabal.Workdir import Test.Cabal.Script import Test.Cabal.Server import Test.Cabal.Monad import Distribution.Verbosity (normal, verbose, Verbosity) import Distribution.Simple.Configure (getPersistBuildConfig) import Distribution.Simple.Utils (getDirectoryContentsRecursive) import Options.Applicative import Control.Concurrent.MVar import Control.Concurrent import Control.Concurrent.Async import Control.Exception import Control.Monad import qualified Control.Exception as E import GHC.Conc (numCapabilities) import Data.List import Data.Monoid import Text.Printf import qualified System.Clock as Clock import System.IO import System.FilePath import System.Exit import System.Process (callProcess, showCommandForUser) -- | Record for arguments that can be passed to @cabal-tests@ executable. data MainArgs = MainArgs { mainArgThreads :: Int, mainArgTestPaths :: [String], mainArgHideSuccesses :: Bool, mainArgVerbose :: Bool, mainArgQuiet :: Bool, mainArgDistDir :: Maybe FilePath, mainCommonArgs :: CommonArgs } -- | optparse-applicative parser for 'MainArgs' mainArgParser :: Parser MainArgs mainArgParser = MainArgs <$> option auto ( help "Number of threads to run" <> short 'j' <> showDefault <> value numCapabilities <> metavar "INT") <*> many (argument str (metavar "FILE")) <*> switch ( long "hide-successes" <> help "Do not print test cases as they are being run" ) <*> switch ( long "verbose" <> short 'v' <> help "Be verbose" ) <*> switch ( long "quiet" <> short 'q' <> help "Only output stderr on failure" ) <*> optional (option str ( help "Dist directory we were built with" <> long "builddir" <> metavar "DIR")) <*> commonArgParser main :: IO () main = do -- By default, stderr is not buffered. This isn't really necessary -- for us, and it causes problems on Windows, see: -- https://github.com/appveyor/ci/issues/1364 hSetBuffering stderr LineBuffering -- Parse arguments args <- execParser (info mainArgParser mempty) let verbosity = if mainArgVerbose args then verbose else normal -- To run our test scripts, we need to be able to run Haskell code -- linked against the Cabal library under test. The most efficient -- way to get this information is by querying the *host* build -- system about the information. -- -- Fortunately, because we are using a Custom setup, our Setup -- script is bootstrapped against the Cabal library we're testing -- against, so can use our dependency on Cabal to read out the build -- info *for this package*. -- -- NB: Currently assumes that per-component build is NOT turned on -- for Custom. dist_dir <- case mainArgDistDir args of Just dist_dir -> return dist_dir Nothing -> guessDistDir when (verbosity >= verbose) $ hPutStrLn stderr $ "Using dist dir: " ++ dist_dir lbi <- getPersistBuildConfig dist_dir -- Get ready to go! senv <- mkScriptEnv verbosity lbi let runTest runner path = runner Nothing [] path $ ["--builddir", dist_dir, path] ++ renderCommonArgs (mainCommonArgs args) case mainArgTestPaths args of [path] -> do -- Simple runner (real_path, real_args) <- runTest (runnerCommand senv) path hPutStrLn stderr $ showCommandForUser real_path real_args callProcess real_path real_args hPutStrLn stderr "OK" user_paths -> do -- Read out tests from filesystem hPutStrLn stderr $ "threads: " ++ show (mainArgThreads args) test_scripts <- if null user_paths then findTests else return user_paths -- NB: getDirectoryContentsRecursive is lazy IO, but it -- doesn't handle directories disappearing gracefully. Fix -- this! (single_tests, multi_tests) <- evaluate (partitionTests test_scripts) let all_tests = multi_tests ++ single_tests margin = maximum (map length all_tests) + 2 hPutStrLn stderr $ "tests to run: " ++ show (length all_tests) -- TODO: Get parallelization out of multitests by querying -- them for their modes and then making a separate worker -- for each. But for now, just run them earlier to avoid -- them straggling at the end work_queue <- newMVar all_tests unexpected_fails_var <- newMVar [] unexpected_passes_var <- newMVar [] chan <- newChan let logAll msg = writeChan chan (ServerLogMsg AllServers msg) logEnd = writeChan chan ServerLogEnd -- NB: don't use withAsync as we do NOT want to cancel this -- on an exception async_logger <- async (withFile "cabal-tests.log" WriteMode $ outputThread verbosity chan) -- Make sure we pump out all the logs before quitting (\m -> finally m (logEnd >> wait async_logger)) $ do -- NB: Need to use withAsync so that if the main thread dies -- (due to ctrl-c) we tear down all of the worker threads. let go server = do let split [] = return ([], Nothing) split (y:ys) = return (ys, Just y) logMeta msg = writeChan chan $ ServerLogMsg (ServerMeta (serverProcessId server)) msg mb_work <- modifyMVar work_queue split case mb_work of Nothing -> return () Just path -> do when (verbosity >= verbose) $ logMeta $ "Running " ++ path start <- getTime r <- runTest (runOnServer server) path end <- getTime let time = end - start code = serverResultExitCode r status | code == ExitSuccess = "OK" | code == ExitFailure skipExitCode = "SKIP" | code == ExitFailure expectedBrokenExitCode = "KNOWN FAIL" | code == ExitFailure unexpectedSuccessExitCode = "UNEXPECTED OK" | otherwise = "FAIL" unless (mainArgHideSuccesses args && status /= "FAIL") $ do logMeta $ path ++ replicate (margin - length path) ' ' ++ status ++ if time >= 0.01 then printf " (%.2fs)" time else "" when (status == "FAIL") $ do -- TODO: ADT let description | mainArgQuiet args = serverResultStderr r | otherwise = "$ " ++ serverResultCommand r ++ "\n" ++ "stdout:\n" ++ serverResultStdout r ++ "\n" ++ "stderr:\n" ++ serverResultStderr r ++ "\n" logMeta $ description ++ "*** unexpected failure for " ++ path ++ "\n\n" modifyMVar_ unexpected_fails_var $ \paths -> return (path:paths) when (status == "UNEXPECTED OK") $ modifyMVar_ unexpected_passes_var $ \paths -> return (path:paths) go server mask $ \restore -> do -- Start as many threads as requested by -j to spawn -- GHCi servers and start running tests off of the -- run queue. -- NB: we don't use 'withAsync' because it's more -- convenient to generate n threads this way (and when -- one fails, we can cancel everyone at once.) as <- replicateM (mainArgThreads args) (async (restore (withNewServer chan senv go))) restore (mapM_ wait as) `E.catch` \e -> do -- Be patient, because if you ^C again, you might -- leave some zombie GHCi processes around! logAll "Shutting down GHCi sessions (please be patient)..." -- Start cleanup on all threads concurrently. mapM_ (async . cancel) as -- Wait for the threads to finish cleaning up. NB: -- do NOT wait on the cancellation asynchronous actions; -- these complete when the message is *delivered*, not -- when cleanup is done. rs <- mapM waitCatch as -- Take a look at the returned exit codes, and figure out -- if something errored in an unexpected way. This -- could mean there's a zombie. forM_ rs $ \r -> case r of Left err | Just ThreadKilled <- fromException err -> return () | otherwise -> logAll ("Unexpected failure on GHCi exit: " ++ show e) _ -> return () -- Propagate the exception throwIO (e :: SomeException) unexpected_fails <- takeMVar unexpected_fails_var unexpected_passes <- takeMVar unexpected_passes_var if not (null (unexpected_fails ++ unexpected_passes)) then do unless (null unexpected_passes) . logAll $ "UNEXPECTED OK: " ++ intercalate " " unexpected_passes unless (null unexpected_fails) . logAll $ "UNEXPECTED FAIL: " ++ intercalate " " unexpected_fails exitFailure else logAll "OK" findTests :: IO [FilePath] findTests = getDirectoryContentsRecursive "." partitionTests :: [FilePath] -> ([FilePath], [FilePath]) partitionTests = go [] [] where go ts ms [] = (ts, ms) go ts ms (f:fs) = -- NB: Keep this synchronized with isTestFile case takeExtensions f of ".test.hs" -> go (f:ts) ms fs ".multitest.hs" -> go ts (f:ms) fs _ -> go ts ms fs outputThread :: Verbosity -> Chan ServerLogMsg -> Handle -> IO () outputThread verbosity chan log_handle = go "" where go prev_hdr = do v <- readChan chan case v of ServerLogEnd -> return () ServerLogMsg t msg -> do let ls = lines msg pre s c | verbosity >= verbose -- Didn't use printf as GHC 7.4 -- doesn't understand % 7s. = replicate (7 - length s) ' ' ++ s ++ " " ++ c : " " | otherwise = "" hdr = case t of AllServers -> "" ServerMeta s -> pre s ' ' ServerIn s -> pre s '<' ServerOut s -> pre s '>' ServerErr s -> pre s '!' ws = replicate (length hdr) ' ' mb_hdr l | hdr == prev_hdr = ws ++ l | otherwise = hdr ++ l ls' = case ls of [] -> [] r:rs -> mb_hdr r : map (ws ++) rs logmsg = unlines ls' hPutStr stderr logmsg hPutStr log_handle logmsg go hdr -- Cribbed from tasty type Time = Double getTime :: IO Time getTime = do t <- Clock.getTime Clock.Monotonic let ns = realToFrac $ Clock.toNanoSecs t return $ ns / 10 ^ (9 :: Int)
mydaum/cabal
cabal-testsuite/main/cabal-tests.hs
Haskell
bsd-3-clause
12,985
{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NondecreasingIndentation #-} -- | A GHC run-server, which supports running multiple GHC scripts -- without having to restart from scratch. module Test.Cabal.Server ( Server, serverProcessId, ServerLogMsg(..), ServerLogMsgType(..), ServerResult(..), withNewServer, runOnServer, runMain, ) where import Test.Cabal.Script import Prelude hiding (log) import Control.Concurrent.MVar import Control.Concurrent import Control.Concurrent.Async import System.Process import System.IO import System.Exit import Data.List import Distribution.Simple.Program.Db import Distribution.Simple.Program import Control.Exception import qualified Control.Exception as E import Control.Monad import Data.IORef import Data.Maybe import Distribution.Verbosity import System.Process.Internals #if mingw32_HOST_OS import qualified System.Win32.Process as Win32 #endif -- TODO: Compare this implementation with -- https://github.com/ndmitchell/ghcid/blob/master/src/Language/Haskell/Ghcid.hs -- which does something similar -- ----------------------------------------------------------------- -- -- Public API -- ----------------------------------------------------------------- -- -- | A GHCi server session, which we can ask to run scripts. -- It operates in a *fixed* runner environment as specified -- by 'serverScriptEnv'. data Server = Server { serverStdin :: Handle, serverStdout :: Handle, serverStderr :: Handle, serverProcessHandle :: ProcessHandle, serverProcessId :: ProcessId, serverScriptEnv :: ScriptEnv, -- | Accumulators which we use to keep tracking -- of stdout/stderr we've incrementally read out. In the event -- of an error we'll use this to give diagnostic information. serverStdoutAccum :: MVar [String], serverStderrAccum :: MVar [String], serverLogChan :: Chan ServerLogMsg } -- | Portable representation of process ID; just a string rendered -- number. type ProcessId = String data ServerLogMsg = ServerLogMsg ServerLogMsgType String | ServerLogEnd data ServerLogMsgType = ServerOut ProcessId | ServerErr ProcessId | ServerIn ProcessId | ServerMeta ProcessId | AllServers data ServerResult = ServerResult { -- Result serverResultExitCode :: ExitCode, serverResultCommand :: String, serverResultStdout :: String, serverResultStderr :: String } -- | With 'ScriptEnv', create a new GHCi 'Server' session. -- When @f@ returns, the server is terminated and no longer -- valid. withNewServer :: Chan ServerLogMsg -> ScriptEnv -> (Server -> IO a) -> IO a withNewServer chan senv f = bracketWithInit (startServer chan senv) initServer stopServer f -- | Like 'bracket', but with an initialization function on the resource -- which will be called, unmasked, on the resource to transform it -- in some way. If the initialization function throws an exception, the cleanup -- handler will get invoked with the original resource; if it succeeds, the -- cleanup handler will get invoked with the transformed resource. -- The cleanup handler must be able to handle both cases. -- -- This can help avoid race conditions in certain situations: with -- normal use of 'bracket', the resource acquisition function -- MUST return immediately after the resource is acquired. If it -- performs any interruptible actions afterwards, it could be -- interrupted and the exception handler not called. bracketWithInit :: IO a -> (a -> IO a) -> (a -> IO b) -> (a -> IO c) -> IO c bracketWithInit before initialize after thing = mask $ \restore -> do a0 <- before a <- restore (initialize a0) `onException` after a0 r <- restore (thing a) `onException` after a _ <- after a return r -- | Run an hs script on the GHCi server, returning the 'ServerResult' of -- executing the command. -- -- * The script MUST have an @hs@ or @lhs@ filename; GHCi -- will reject non-Haskell filenames. -- -- * If the script is not well-typed, the returned output -- will be of GHC's compile errors. -- -- * Inside your script, do not rely on 'getProgName' having -- a sensible value. -- -- * Current working directory and environment overrides -- are currently not implemented. -- runOnServer :: Server -> Maybe FilePath -> [(String, Maybe String)] -> FilePath -> [String] -> IO ServerResult runOnServer s mb_cwd env_overrides script_path args = do -- TODO: cwd not implemented when (isJust mb_cwd) $ error "runOnServer change directory not implemented" -- TODO: env_overrides not implemented unless (null env_overrides) $ error "runOnServer set environment not implemented" -- Set arguments returned by System.getArgs write s $ ":set args " ++ show args -- Output start sigil (do it here so we pick up compilation -- failures) write s $ "System.IO.hPutStrLn System.IO.stdout " ++ show start_sigil write s $ "System.IO.hPutStrLn System.IO.stderr " ++ show start_sigil _ <- readUntilSigil s start_sigil IsOut _ <- readUntilSigil s start_sigil IsErr -- Drain the output produced by the script as we are running so that -- we do not deadlock over a full pipe. withAsync (readUntilEnd s IsOut) $ \a_exit_out -> do withAsync (readUntilSigil s end_sigil IsErr) $ \a_err -> do -- NB: No :set prog; don't rely on this value in test scripts, -- we pass it in via the arguments -- NB: load drops all bindings, which is GOOD. Avoid holding onto -- garbage. write s $ ":load " ++ script_path -- Create a ref which will record the exit status of the command -- NB: do this after :load so it doesn't get dropped write s $ "ref <- Data.IORef.newIORef (System.Exit.ExitFailure 1)" -- TODO: What if an async exception gets raised here? At the -- moment, there is no way to recover until we get to the top-level -- bracket; then stopServer which correctly handles this case. -- If you do want to be able to abort this computation but KEEP -- USING THE SERVER SESSION, you will need to have a lot more -- sophisticated logic. write s $ "Test.Cabal.Server.runMain ref Main.main" -- Output end sigil. -- NB: We're line-oriented, so we MUST add an extra newline -- to ensure that we see the end sigil. write s $ "System.IO.hPutStrLn System.IO.stdout " ++ show "" write s $ "System.IO.hPutStrLn System.IO.stderr " ++ show "" write s $ "Data.IORef.readIORef ref >>= \\e -> " ++ " System.IO.hPutStrLn System.IO.stdout (" ++ show end_sigil ++ " ++ \" \" ++ show e)" write s $ "System.IO.hPutStrLn System.IO.stderr " ++ show end_sigil (code, out) <- wait a_exit_out err <- wait a_err -- Give the user some indication about how they could run the -- command by hand. (real_path, real_args) <- runnerCommand (serverScriptEnv s) mb_cwd env_overrides script_path args return ServerResult { serverResultExitCode = code, serverResultCommand = showCommandForUser real_path real_args, serverResultStdout = out, serverResultStderr = err } -- | Helper function which we use in the GHCi session to communicate -- the exit code of the process. runMain :: IORef ExitCode -> IO () -> IO () runMain ref m = do E.catch (m >> writeIORef ref ExitSuccess) serverHandler where serverHandler :: SomeException -> IO () serverHandler e = do -- TODO: Probably a few more cases you could handle; -- e.g., StackOverflow should return 2; also signals. writeIORef ref $ case fromException e of Just exit_code -> exit_code -- Only rethrow for non ExitFailure exceptions _ -> ExitFailure 1 case fromException e :: Maybe ExitCode of Just _ -> return () _ -> throwIO e -- ----------------------------------------------------------------- -- -- Initialize/tear down -- ----------------------------------------------------------------- -- -- | Start a new GHCi session. startServer :: Chan ServerLogMsg -> ScriptEnv -> IO Server startServer chan senv = do (prog, _) <- requireProgram verbosity ghcProgram (runnerProgramDb senv) let ghc_args = runnerGhcArgs senv ++ ["--interactive", "-v0", "-ignore-dot-ghci"] proc_spec = (proc (programPath prog) ghc_args) { create_group = True, -- Closing fds is VERY important to avoid -- deadlock; we won't see the end of a -- stream until everyone gives up. close_fds = True, std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe } -- printRawCommandAndArgsAndEnv (runnerVerbosity senv) (programPath prog) ghc_args Nothing when (verbosity >= verbose) $ writeChan chan (ServerLogMsg AllServers (showCommandForUser (programPath prog) ghc_args)) (Just hin, Just hout, Just herr, proch) <- createProcess proc_spec out_acc <- newMVar [] err_acc <- newMVar [] tid <- myThreadId return Server { serverStdin = hin, serverStdout = hout, serverStderr = herr, serverProcessHandle = proch, serverProcessId = show tid, serverLogChan = chan, serverStdoutAccum = out_acc, serverStderrAccum = err_acc, serverScriptEnv = senv } where verbosity = runnerVerbosity senv -- | Unmasked initialization for the server initServer :: Server -> IO Server initServer s0 = do -- NB: withProcessHandle reads an MVar and is interruptible #if mingw32_HOST_OS pid <- withProcessHandle (serverProcessHandle s0) $ \ph -> case ph of OpenHandle x -> fmap show (Win32.getProcessId x) ClosedHandle _ -> return (serverProcessId s0) #else pid <- withProcessHandle (serverProcessHandle s0) $ \ph -> case ph of OpenHandle x -> return (show x) -- TODO: handle OpenExtHandle? _ -> return (serverProcessId s0) #endif let s = s0 { serverProcessId = pid } -- We will read/write a line at a time, including for -- output; our demarcation tokens are an entire line. forM_ [serverStdin, serverStdout, serverStderr] $ \f -> do hSetBuffering (f s) LineBuffering hSetEncoding (f s) utf8 write s ":set prompt \"\"" write s "System.IO.hSetBuffering System.IO.stdout System.IO.LineBuffering" return s -- | Stop a GHCi session. stopServer :: Server -> IO () stopServer s = do -- This is quite a bit of funny business. -- On Linux, terminateProcess will send a SIGINT, which -- GHCi will swallow and actually only use to terminate -- whatever computation is going on at that time. So we -- have to follow up with an actual :quit command to -- finish it up (if you delete it, the processes will -- hang around). On Windows, this will just actually kill -- the process so the rest should be unnecessary. mb_exit <- getProcessExitCode (serverProcessHandle s) let hardKiller = do threadDelay 2000000 -- 2sec log ServerMeta s $ "Terminating..." terminateProcess (serverProcessHandle s) softKiller = do -- Ask to quit. If we're in the middle of a computation, -- this will buffer up (unless the program is intercepting -- stdin, but that should NOT happen.) ignore $ write s ":quit" -- NB: it's important that we used create_group. We -- run this AFTER write s ":quit" because if we C^C -- sufficiently early in GHCi startup process, GHCi -- will actually die, and then hClose will fail because -- the ":quit" command was buffered up but never got -- flushed. interruptProcessGroupOf (serverProcessHandle s) log ServerMeta s $ "Waiting..." -- Close input BEFORE waiting, close output AFTER waiting. -- If you get either order wrong, deadlock! hClose (serverStdin s) -- waitForProcess has race condition -- https://github.com/haskell/process/issues/46 waitForProcess $ serverProcessHandle s let drain f = do r <- hGetContents (f s) _ <- evaluate (length r) hClose (f s) return r withAsync (drain serverStdout) $ \a_out -> do withAsync (drain serverStderr) $ \a_err -> do r <- case mb_exit of Nothing -> do log ServerMeta s $ "Terminating GHCi" race hardKiller softKiller Just exit -> do log ServerMeta s $ "GHCi died unexpectedly" return (Right exit) -- Drain the output buffers rest_out <- wait a_out rest_err <- wait a_err if r /= Right ExitSuccess && r /= Right (ExitFailure (-2)) -- SIGINT; happens frequently for some reason then do withMVar (serverStdoutAccum s) $ \acc -> mapM_ (info ServerOut s) (reverse acc) info ServerOut s rest_out withMVar (serverStderrAccum s) $ \acc -> mapM_ (info ServerErr s) (reverse acc) info ServerErr s rest_err info ServerMeta s $ (case r of Left () -> "GHCi was forcibly terminated" Right exit -> "GHCi exited with " ++ show exit) ++ if verbosity < verbose then " (use -v for more information)" else "" else log ServerOut s rest_out log ServerMeta s $ "Done" return () where verbosity = runnerVerbosity (serverScriptEnv s) -- Using the procedure from -- https://www.schoolofhaskell.com/user/snoyberg/general-haskell/exceptions/catching-all-exceptions ignore :: IO () -> IO () ignore m = withAsync m $ \a -> void (waitCatch a) -- ----------------------------------------------------------------- -- -- Utility functions -- ----------------------------------------------------------------- -- log :: (ProcessId -> ServerLogMsgType) -> Server -> String -> IO () log ctor s msg = when (verbosity >= verbose) $ info ctor s msg where verbosity = runnerVerbosity (serverScriptEnv s) info :: (ProcessId -> ServerLogMsgType) -> Server -> String -> IO () info ctor s msg = writeChan chan (ServerLogMsg (ctor (serverProcessId s)) msg) where chan = serverLogChan s -- | Write a string to the prompt of the GHCi server. write :: Server -> String -> IO () write s msg = do log ServerIn s $ msg hPutStrLn (serverStdin s) msg hFlush (serverStdin s) -- line buffering should get it, but just for good luck accumulate :: MVar [String] -> String -> IO () accumulate acc msg = modifyMVar_ acc (\msgs -> return (msg:msgs)) flush :: MVar [String] -> IO [String] flush acc = modifyMVar acc (\msgs -> return ([], reverse msgs)) data OutOrErr = IsOut | IsErr serverHandle :: Server -> OutOrErr -> Handle serverHandle s IsOut = serverStdout s serverHandle s IsErr = serverStderr s serverAccum :: Server -> OutOrErr -> MVar [String] serverAccum s IsOut = serverStdoutAccum s serverAccum s IsErr = serverStderrAccum s outOrErrMsgType :: OutOrErr -> (ProcessId -> ServerLogMsgType) outOrErrMsgType IsOut = ServerOut outOrErrMsgType IsErr = ServerErr -- | Consume output from the GHCi server until we hit a "start -- sigil" (indicating that the subsequent output is for the -- command we want.) Call this only immediately after you -- send a command to GHCi to emit the start sigil. readUntilSigil :: Server -> String -> OutOrErr -> IO String readUntilSigil s sigil outerr = do l <- hGetLine (serverHandle s outerr) log (outOrErrMsgType outerr) s l if sigil `isPrefixOf` l -- NB: on Windows there might be extra goo at end then intercalate "\n" `fmap` flush (serverAccum s outerr) else do accumulate (serverAccum s outerr) l readUntilSigil s sigil outerr -- | Consume output from the GHCi server until we hit the -- end sigil. Return the consumed output as well as the -- exit code (which is at the end of the sigil). readUntilEnd :: Server -> OutOrErr -> IO (ExitCode, String) readUntilEnd s outerr = go [] where go rs = do l <- hGetLine (serverHandle s outerr) log (outOrErrMsgType outerr) s l if end_sigil `isPrefixOf` l -- NB: NOT unlines, we don't want the trailing newline! then do exit <- evaluate (parseExit l) _ <- flush (serverAccum s outerr) -- TODO: don't toss this out return (exit, intercalate "\n" (reverse rs)) else do accumulate (serverAccum s outerr) l go (l:rs) parseExit l = read (drop (length end_sigil) l) -- | The start and end sigils. This should be chosen to be -- reasonably unique, so that test scripts don't accidentally -- generate them. If these get spuriously generated, we will -- probably deadlock. start_sigil, end_sigil :: String start_sigil = "BEGIN Test.Cabal.Server" end_sigil = "END Test.Cabal.Server"
mydaum/cabal
cabal-testsuite/Test/Cabal/Server.hs
Haskell
bsd-3-clause
17,705
{- Type name: qualified names for register types Part of Mackerel: a strawman device definition DSL for Barrelfish Copyright (c) 2011, ETH Zurich. All rights reserved. This file is distributed under the terms in the attached LICENSE file. If you do not find this file, copies can be found by writing to: ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. -} module TypeName where import MackerelParser {-------------------------------------------------------------------- --------------------------------------------------------------------} -- Fully-qualified name of a type data Name = Name String String deriving (Show, Eq) fromParts :: String -> String -> Name fromParts dev typename = Name dev typename fromRef :: AST -> String -> Name fromRef (TypeRef tname (Just dname)) _ = Name dname tname fromRef (TypeRef tname Nothing) dname = Name dname tname toString :: Name -> String toString (Name d t) = d ++ "." ++ t devName :: Name -> String devName (Name d _) = d typeName :: Name -> String typeName (Name _ t) = t is_builtin_type :: Name -> Bool is_builtin_type (Name _ "uint8") = True is_builtin_type (Name _ "uint16") = True is_builtin_type (Name _ "uint32") = True is_builtin_type (Name _ "uint64") = True is_builtin_type _ = False null :: Name null = Name "" ""
daleooo/barrelfish
tools/mackerel/TypeName.hs
Haskell
mit
1,384
{- In order to test Hackage, we need to be able to send check for confirmation emails. In this module we provide a simple interface to do that. Currently we use mailinator, but the API is designed to be agnostic to the specific mail service used. -} module MailUtils ( Email(..) , testEmailAddress , checkEmail , getEmail , emailWithSubject , waitForEmailWithSubject ) where import Control.Concurrent (threadDelay) import Data.Maybe import Network.URI import Network.HTTP hiding (user) import qualified Text.XML.Light as XML import HttpUtils import Util testEmailAddress :: String -> String testEmailAddress user = user ++ "@mailinator.com" data Email = Email { emailTitle :: String , emailLink :: URI , emailSender :: String , emailDate :: String } deriving Show checkEmail :: String -> IO [Email] checkEmail user = do raw <- execRequest NoAuth (getRequest rssUrl) let rss = XML.onlyElems (XML.parseXML raw) items = concatMap (XML.filterElementsName $ simpleName "item") rss return (map parseEmail items) where rssUrl = "http://www.mailinator.com/feed?to=" ++ user parseEmail :: XML.Element -> Email parseEmail e = let [title] = XML.filterElementsName (simpleName "title") e [link] = XML.filterElementsName (simpleName "link") e [sender] = XML.filterElementsName (simpleName "creator") e [date] = XML.filterElementsName (simpleName "date") e in Email { emailTitle = XML.strContent title , emailLink = fromJust . parseURI . XML.strContent $ link , emailSender = XML.strContent sender , emailDate = XML.strContent date } simpleName :: String -> XML.QName -> Bool simpleName n = (== n) . XML.qName emailWithSubject :: String -> String -> IO (Maybe Email) emailWithSubject user subject = do emails <- checkEmail user return . listToMaybe . filter ((== subject) . emailTitle) $ emails waitForEmailWithSubject :: String -> String -> IO Email waitForEmailWithSubject user subject = f 10 where f :: Int -> IO Email f n = do info $ "Waiting for confirmation email at " ++ testEmailAddress user mEmail <- emailWithSubject user subject case mEmail of Just email -> return email Nothing | n == 0 -> die "Didn't get confirmation email" | otherwise -> do info "No confirmation email yet; will try again in 30 sec" threadDelay (30 * 1000000) f (n - 1) getEmail :: Email -> IO String getEmail email = execRequest NoAuth (getRequest url) where msgid = fromJust . lookup "msgid" . parseQuery . uriQuery . emailLink $ email url = "http://mailinator.com/rendermail.jsp?msgid=" ++ msgid ++ "&text=true"
ocharles/hackage-server
tests/MailUtils.hs
Haskell
bsd-3-clause
2,821
module GenUtils ( trace, assocMaybe, assocMaybeErr, arrElem, arrCond, memoise, Maybe(..), MaybeErr(..), mapMaybe, mapMaybeFail, maybeToBool, maybeToObj, maybeMap, joinMaybe, mkClosure, foldb, mapAccumL, sortWith, sort, cjustify, ljustify, rjustify, space, copy, combinePairs, formatText ) where import Data.Array -- 1.3 import Data.Ix -- 1.3 import Debug.Trace ( trace ) -- ------------------------------------------------------------------------- -- Here are two defs that everyone seems to define ... -- HBC has it in one of its builtin modules infix 1 =: -- 1.3 type Assoc a b = (a,b) -- 1.3 (=:) a b = (a,b) mapMaybe :: (a -> Maybe b) -> [a] -> [b] mapMaybe f [] = [] mapMaybe f (a:r) = case f a of Nothing -> mapMaybe f r Just b -> b : mapMaybe f r -- This version returns nothing, if *any* one fails. mapMaybeFail f (x:xs) = case f x of Just x' -> case mapMaybeFail f xs of Just xs' -> Just (x':xs') Nothing -> Nothing Nothing -> Nothing mapMaybeFail f [] = Just [] maybeToBool :: Maybe a -> Bool maybeToBool (Just _) = True maybeToBool _ = False maybeToObj :: Maybe a -> a maybeToObj (Just a) = a maybeToObj _ = error "Trying to extract object from a Nothing" maybeMap :: (a -> b) -> Maybe a -> Maybe b maybeMap f (Just a) = Just (f a) maybeMap f Nothing = Nothing joinMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a joinMaybe _ Nothing Nothing = Nothing joinMaybe _ (Just g) Nothing = Just g joinMaybe _ Nothing (Just g) = Just g joinMaybe f (Just g) (Just h) = Just (f g h) data MaybeErr a err = Succeeded a | Failed err deriving (Eq,Show{-was:Text-}) -- @mkClosure@ makes a closure, when given a comparison and iteration loop. -- Be careful, because if the functional always makes the object different, -- This will never terminate. mkClosure :: (a -> a -> Bool) -> (a -> a) -> a -> a mkClosure eq f = match . iterate f where match (a:b:c) | a `eq` b = a match (_:c) = match c -- fold-binary. -- It combines the element of the list argument in balanced mannerism. foldb :: (a -> a -> a) -> [a] -> a foldb f [] = error "can't reduce an empty list using foldb" foldb f [x] = x foldb f l = foldb f (foldb' l) where foldb' (x:y:x':y':xs) = f (f x y) (f x' y') : foldb' xs foldb' (x:y:xs) = f x y : foldb' xs foldb' xs = xs -- Merge two ordered lists into one ordered list. mergeWith :: (a -> a -> Bool) -> [a] -> [a] -> [a] mergeWith _ [] ys = ys mergeWith _ xs [] = xs mergeWith le (x:xs) (y:ys) | x `le` y = x : mergeWith le xs (y:ys) | otherwise = y : mergeWith le (x:xs) ys insertWith :: (a -> a -> Bool) -> a -> [a] -> [a] insertWith _ x [] = [x] insertWith le x (y:ys) | x `le` y = x:y:ys | otherwise = y:insertWith le x ys -- Sorting is something almost every program needs, and this is the -- quickest sorting function I know of. sortWith :: (a -> a -> Bool) -> [a] -> [a] sortWith le [] = [] sortWith le lst = foldb (mergeWith le) (splitList lst) where splitList (a1:a2:a3:a4:a5:xs) = insertWith le a1 (insertWith le a2 (insertWith le a3 (insertWith le a4 [a5]))) : splitList xs splitList [] = [] splitList (r:rs) = [foldr (insertWith le) [r] rs] sort :: (Ord a) => [a] -> [a] sort = sortWith (<=) -- Gofer-like stuff: cjustify, ljustify, rjustify :: Int -> String -> String cjustify n s = space halfm ++ s ++ space (m - halfm) where m = n - length s halfm = m `div` 2 ljustify n s = s ++ space (max 0 (n - length s)) rjustify n s = space (max 0 (n - length s)) ++ s space :: Int -> String space n = copy n ' ' copy :: Int -> a -> [a] -- make list of n copies of x copy n x = take n xs where xs = x:xs combinePairs :: (Ord a) => [(a,b)] -> [(a,[b])] combinePairs xs = combine [ (a,[b]) | (a,b) <- sortWith (\ (a,_) (b,_) -> a <= b) xs] where combine [] = [] combine ((a,b):(c,d):r) | a == c = combine ((a,b++d) : r) combine (a:r) = a : combine r assocMaybe :: (Eq a) => [(a,b)] -> a -> Maybe b assocMaybe env k = case [ val | (key,val) <- env, k == key] of [] -> Nothing (val:vs) -> Just val assocMaybeErr :: (Eq a) => [(a,b)] -> a -> MaybeErr b String assocMaybeErr env k = case [ val | (key,val) <- env, k == key] of [] -> Failed "assoc: " (val:vs) -> Succeeded val deSucc (Succeeded e) = e mapAccumL :: (a -> b -> (c,a)) -> a -> [b] -> ([c],a) mapAccumL f s [] = ([],s) mapAccumL f s (b:bs) = (c:cs,s'') where (c,s') = f s b (cs,s'') = mapAccumL f s' bs -- Now some utilities involving arrays. -- Here is a version of @elem@ that uses partial application -- to optimise lookup. arrElem :: (Ix a) => [a] -> a -> Bool arrElem obj = \x -> inRange size x && arr ! x where size = (maximum obj,minimum obj) arr = listArray size [ i `elem` obj | i <- range size ] -- Here is the functional version of a multi-way conditional, -- again using arrays, of course. Remember @b@ can be a function ! -- Note again the use of partiual application. arrCond :: (Ix a) => (a,a) -- the bounds -> [(Assoc [a] b)] -- the simple lookups -> [(Assoc (a -> Bool) b)] -- the functional lookups -> b -- the default -> a -> b -- the (functional) result arrCond bds pairs fnPairs def = (!) arr' where arr' = array bds [ t =: head ([ r | (p, r) <- pairs, elem t p ] ++ [ r | (f, r) <- fnPairs, f t ] ++ [ def ]) | t <- range bds ] memoise :: (Ix a) => (a,a) -> (a -> b) -> a -> b memoise bds f = (!) arr where arr = array bds [ t =: f t | t <- range bds ] -- Quite neat this. Formats text to fit in a column. formatText :: Int -> [String] -> [String] formatText n = map unwords . cutAt n [] where cutAt :: Int -> [String] -> [String] -> [[String]] cutAt m wds [] = [reverse wds] cutAt m wds (wd:rest) = if len <= m || null wds then cutAt (m-(len+1)) (wd:wds) rest else reverse wds : cutAt n [] (wd:rest) where len = length wd
ezyang/ghc
testsuite/tests/programs/andy_cherry/GenUtils.hs
Haskell
bsd-3-clause
6,771
{-# LANGUAGE RecordWildCards #-} module T9436 where data T = T { x :: Int } f :: T -> Int f (T' { .. }) = x + 1
ezyang/ghc
testsuite/tests/rename/should_fail/T9436.hs
Haskell
bsd-3-clause
115
module WykopStream ( indexStream , module WykopTypes ) where import WykopTypes import WykopUtils indexStream :: Keys -> Maybe Int -> IO (Maybe [Entry]) indexStream k page = get k [] (mPageToGet page) "stream/index"
mikusp/hwykop
WykopStream.hs
Haskell
mit
231
{-# htermination minFM :: FiniteMap Int b -> Maybe Int #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_minFM_5.hs
Haskell
mit
76
module Problem6 where main :: IO () main = print $ squareSums [1..100] - sumSquares [1..100] squareSums :: Integral n => [n] -> n squareSums xs = (sum xs) ^ 2 sumSquares :: Integral n => [n] -> n sumSquares xs = sum $ map (^2) xs
DevJac/haskell-project-euler
src/Problem6.hs
Haskell
mit
236
module Robot ( Bearing(East,North,South,West) , bearing , coordinates , mkRobot , move ) where data Bearing = North | East | South | West deriving (Eq, Show) data Robot = Dummy bearing :: Robot -> Bearing bearing robot = error "You need to implement this function." coordinates :: Robot -> (Integer, Integer) coordinates robot = error "You need to implement this function." mkRobot :: Bearing -> (Integer, Integer) -> Robot mkRobot direction coordinates = error "You need to implement this function." move :: Robot -> String -> Robot move robot instructions = error "You need to implement this function."
exercism/xhaskell
exercises/practice/robot-simulator/src/Robot.hs
Haskell
mit
687
-- Экспортирование -- http://www.haskell.org/onlinereport/haskell2010/haskellch5.html#x11-1000005.2 module Chapter5.Section52 where -- exports → ( export1 , … , exportn [ , ] ) (n ≥ 0) -- -- export → qvar -- | qtycon [(..) | ( cname1 , … , cnamen )] (n ≥ 0) -- | qtycls [(..) | ( var1 , … , varn )] (n ≥ 0) -- | module modid -- -- cname → var | con -- По умолчанию экспортируются вся область видимости модуля data TheTest = A | B
mrLSD/HaskellTutorials
src/Chapter5/Section52.hs
Haskell
mit
539
{-# LANGUAGE RebindableSyntax, OverloadedStrings, CPP, TypeOperators #-} module Cochon.View where import Prelude hiding ((>>), return) import qualified Data.Foldable as Foldable import Data.Monoid import Data.String import Data.Text (Text) import qualified Data.Text as T import Data.Void import Lens.Family2 import React hiding (key) import qualified React import React.DOM import React.GHCJS import React.Rebindable import Cochon.Controller import Cochon.Imports import Cochon.Model import Cochon.Reactify import Distillation.Distiller import Distillation.Scheme import Evidences.Tm import Kit.BwdFwd import Kit.ListZip import NameSupply.NameSupply import ProofState.Edition.ProofContext import ProofState.Structure.Developments -- handlers constTransition :: trans -> MouseEvent -> Maybe trans constTransition = const . Just handleEntryToggle :: Name -> MouseEvent -> Maybe TermTransition handleEntryToggle = constTransition . ToggleTerm handleEntryGoTo :: Name -> MouseEvent -> Maybe TermTransition handleEntryGoTo = constTransition . GoToTerm handleToggleAnnotate :: Name -> MouseEvent -> Maybe TermTransition handleToggleAnnotate = constTransition . ToggleAnnotate -- TODO(joel) - stop faking this handleAddConstructor :: Name -> MouseEvent -> Maybe TermTransition handleAddConstructor _ _ = Nothing -- handleToggleEntry :: Name -> MouseEvent -> Maybe Transition -- handleToggleEntry name _ = Just $ ToggleEntry name -- handleToggleEntry = constTransition . ToggleEntry -- TODO(joel) this and handleEntryClick duplicate functionality -- handleGoTo :: Name -> MouseEvent -> Maybe Transition -- handleGoTo = constTransition . GoTo -- views page_ :: InteractionState -> ReactNode a page_ initialState = let cls = smartClass { React.name = "Page" , transition = \(state, trans) -> (dispatch trans state, Nothing) , initialState = initialState , renderFn = \() state -> pageLayout_ $ do editView_ (state^.proofCtx) messages_ (state^.messages) -- testing only -- locally $ paramLayout_ -- (ctName dataTac) -- (do text_ (ctMessage dataTac) -- tacticFormat_ (ctDesc dataTac) -- ) } in classLeaf cls () messages_ :: [UserMessage] -> ReactNode Transition messages_ = classLeaf $ smartClass { React.name = "Messages" , transition = \(state, trans) -> (state, Just trans) , renderFn = \msgs _ -> messagesLayout_ $ forReact msgs message_ } message_ :: UserMessage -> ReactNode Transition message_ = classLeaf $ smartClass { React.name = "Message" , transition = \(state, trans) -> (state, Just trans) , renderFn = \(UserMessage parts) _ -> locally $ messageLayout_ $ forReact parts messagePart_ } messagePart_ :: UserMessagePart -> ReactNode Void messagePart_ (UserMessagePart text maybeName stack maybeTerm severity) = messagePartLayout_ text (fromString (show severity)) -- Top-level views: -- * develop / debug / chiusano edit -- * node history (better: node focus?) -- * edit editView_ :: Bwd ProofContext -> ReactNode Transition editView_ = classLeaf $ smartClass { React.name = "Edit View" , transition = \(state, trans) -> (state, Just trans) , renderFn = \pc _ -> case pc of B0 -> "Red alert - empty proof context" (_ :< pc@(PC _ dev _)) -> locally $ dev_ pc dev } dev_ :: ProofContext -> Dev Bwd -> ReactNode TermTransition dev_ pc (Dev entries tip nSupply suspendState) = devLayout_ $ do fromString (show suspendState) entriesLayout_ $ forReact entries (entry_ pc) entry_ :: ProofContext -> Entry Bwd -> ReactNode TermTransition entry_ pc (EEntity ref lastName entity ty meta) = entryEntityLayout_ $ do entryHeaderLayout_ $ do ref_ pc ref metadata_ meta intm_ pc (SET :>: ty) entity_ pc entity entry_ pc (EModule name dev purpose meta) = entryModuleLayout_ $ do moduleHeaderLayout_ $ do locally $ name_ name purpose_ purpose metadata_ meta dev_ pc dev intm_ :: ProofContext -> (TY :>: INTM) -> ReactNode TermTransition intm_ pc tm = case runProofState (distillHere tm) pc of Left err -> "ERR: runProofState" Right (inTmRn :=>: _, _) -> dInTmRN_ inTmRn ref_ :: ProofContext -> REF -> ReactNode TermTransition ref_ pc (name := rKind :<: ty) = refLayout_ $ do locally $ name_ name -- TODO rKind intm_ pc (SET :>: ty) name_ :: Name -> ReactNode Void name_ n = nameLayout_ (forReact n namePiece_) namePiece_ :: (String, Int) -> ReactNode Void namePiece_ (str, n) = namePieceLayout_ (T.pack str) (T.pack (show n)) purpose_ :: ModulePurpose -> ReactNode a purpose_ p = fromString (show p) metadata_ :: Metadata -> ReactNode a metadata_ m = fromString (show m) entity_ :: ProofContext -> Entity Bwd -> ReactNode TermTransition entity_ pc (Parameter pKind) = parameterLayout_ (fromString (show pKind)) entity_ pc (Definition dKind dev) = definitionLayout_ $ do dev_ pc dev case dKind of LETG -> "LETG" PROG sch -> case runProofState (distillSchemeHere sch) pc of Left err -> "PROGERR" Right (sch', _) -> "PROG" <> scheme_ sch'
kwangkim/pigment
src-web/hs/Cochon/View.hs
Haskell
mit
5,329
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGMaskElement (js_getMaskUnits, getMaskUnits, js_getMaskContentUnits, getMaskContentUnits, js_getX, getX, js_getY, getY, js_getWidth, getWidth, js_getHeight, getHeight, SVGMaskElement, castToSVGMaskElement, gTypeSVGMaskElement) 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[\"maskUnits\"]" js_getMaskUnits :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedEnumeration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.maskUnits Mozilla SVGMaskElement.maskUnits documentation> getMaskUnits :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedEnumeration) getMaskUnits self = liftIO ((js_getMaskUnits (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"maskContentUnits\"]" js_getMaskContentUnits :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedEnumeration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.maskContentUnits Mozilla SVGMaskElement.maskContentUnits documentation> getMaskContentUnits :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedEnumeration) getMaskContentUnits self = liftIO ((js_getMaskContentUnits (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"x\"]" js_getX :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.x Mozilla SVGMaskElement.x documentation> getX :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getX self = liftIO ((js_getX (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"y\"]" js_getY :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.y Mozilla SVGMaskElement.y documentation> getY :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getY self = liftIO ((js_getY (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.width Mozilla SVGMaskElement.width documentation> getWidth :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getWidth self = liftIO ((js_getWidth (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.height Mozilla SVGMaskElement.height documentation> getHeight :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getHeight self = liftIO ((js_getHeight (unSVGMaskElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGMaskElement.hs
Haskell
mit
3,686
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.Storage (key, key_, keyUnsafe, keyUnchecked, getItem, getItem_, getItemUnsafe, getItemUnchecked, setItem, removeItem, clear, getLength, Storage(..), gTypeStorage) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> key :: (MonadDOM m, FromJSString result) => Storage -> Word -> m (Maybe result) key self index = liftDOM ((self ^. jsf "key" [toJSVal index]) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> key_ :: (MonadDOM m) => Storage -> Word -> m () key_ self index = liftDOM (void (self ^. jsf "key" [toJSVal index])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> keyUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => Storage -> Word -> m result keyUnsafe self index = liftDOM (((self ^. jsf "key" [toJSVal index]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> keyUnchecked :: (MonadDOM m, FromJSString result) => Storage -> Word -> m result keyUnchecked self index = liftDOM ((self ^. jsf "key" [toJSVal index]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItem :: (MonadDOM m, ToJSString key, FromJSString result) => Storage -> key -> m (Maybe result) getItem self key = liftDOM ((self ! key) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItem_ :: (MonadDOM m, ToJSString key) => Storage -> key -> m () getItem_ self key = liftDOM (void (self ! key)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItemUnsafe :: (MonadDOM m, ToJSString key, HasCallStack, FromJSString result) => Storage -> key -> m result getItemUnsafe self key = liftDOM (((self ! key) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItemUnchecked :: (MonadDOM m, ToJSString key, FromJSString result) => Storage -> key -> m result getItemUnchecked self key = liftDOM ((self ! key) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.setItem Mozilla Storage.setItem documentation> setItem :: (MonadDOM m, ToJSString key, ToJSString data') => Storage -> key -> data' -> m () setItem self key data' = liftDOM (void (self ^. jsf "setItem" [toJSVal key, toJSVal data'])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.removeItem Mozilla Storage.removeItem documentation> removeItem :: (MonadDOM m, ToJSString key) => Storage -> key -> m () removeItem self key = liftDOM (void (self ^. jsf "removeItem" [toJSVal key])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.clear Mozilla Storage.clear documentation> clear :: (MonadDOM m) => Storage -> m () clear self = liftDOM (void (self ^. jsf "clear" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.length Mozilla Storage.length documentation> getLength :: (MonadDOM m) => Storage -> m Word getLength self = liftDOM (round <$> ((self ^. js "length") >>= valToNumber))
ghcjs/jsaddle-dom
src/JSDOM/Generated/Storage.hs
Haskell
mit
4,607
{-# LANGUAGE LambdaCase #-} module Control.Monad.Evented where import Control.Monad.IO.Class import Control.Monad.Trans.Class newtype EventT m b = EventT { runEventT :: m (Either b (EventT m b)) } -------------------------------------------------------------------------------- -- Constructors -------------------------------------------------------------------------------- done :: Monad m => a -> EventT m a done = EventT . return . Left next :: Monad m => EventT m a -> EventT m a next = EventT . return . Right -------------------------------------------------------------------------------- -- Combinators -------------------------------------------------------------------------------- -- | Waits a number of frames. wait :: Monad m => Int -> EventT m () wait 0 = done () wait n = next $ wait $ n - 1 -- | Runs both evented computations (left and then right) each frame and returns -- the first computation that completes. withEither :: Monad m => EventT m a -> EventT m b -> EventT m (Either a b) withEither ea eb = lift ((,) <$> runEventT ea <*> runEventT eb) >>= \case (Left a,_) -> done $ Left a (_,Left b) -> done $ Right b (Right a, Right b) -> next $ withEither a b -- | Runs all evented computations (left to right) on each frame and returns -- the first computation that completes. withAny :: Monad m => [EventT m a] -> EventT m a withAny ts0 = do es <- lift $ mapM runEventT ts0 case foldl f (Right []) es of Right ts -> next $ withAny ts Left a -> done a where f (Left a) _ = Left a f (Right ts) (Right t) = Right $ ts ++ [t] f _ (Left a) = Left a -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance Monad m => Functor (EventT m) where fmap f (EventT g) = EventT $ g >>= \case Right ev -> return $ Right $ fmap f ev Left c -> return $ Left $ f c instance Monad m => Applicative (EventT m) where pure = done ef <*> ex = do f <- ef x <- ex return $ f x instance Monad m => Monad (EventT m) where (EventT g) >>= fev = EventT $ g >>= \case Right ev -> return $ Right $ ev >>= fev Left c -> runEventT $ fev c return = done instance MonadTrans EventT where lift f = EventT $ f >>= return . Left instance MonadIO m => MonadIO (EventT m) where liftIO = lift . liftIO
schell/odin
src/Control/Monad/Evented.hs
Haskell
mit
2,453
{-# LANGUAGE Rank2Types, TypeFamilies #-} module TestInference where import Data.AEq import Numeric.Log import Control.Monad.Bayes.Class import Control.Monad.Bayes.Enumerator import Control.Monad.Bayes.Sampler import Control.Monad.Bayes.Population import Control.Monad.Bayes.Inference.SMC import Sprinkler sprinkler :: MonadInfer m => m Bool sprinkler = Sprinkler.soft -- | Count the number of particles produced by SMC checkParticles :: Int -> Int -> IO Int checkParticles observations particles = sampleIOfixed (fmap length (runPopulation $ smcMultinomial observations particles Sprinkler.soft)) checkParticlesSystematic :: Int -> Int -> IO Int checkParticlesSystematic observations particles = sampleIOfixed (fmap length (runPopulation $ smcSystematic observations particles Sprinkler.soft)) checkTerminateSMC :: IO [(Bool, Log Double)] checkTerminateSMC = sampleIOfixed (runPopulation $ smcMultinomial 2 5 sprinkler) checkPreserveSMC :: Bool checkPreserveSMC = (enumerate . collapse . smcMultinomial 2 2) sprinkler ~== enumerate sprinkler
adscib/monad-bayes
test/TestInference.hs
Haskell
mit
1,082
-- | Reexports all @Manager@ utilities. module Control.TimeWarp.Manager ( module Control.TimeWarp.Manager.Job ) where import Control.TimeWarp.Manager.Job
serokell/time-warp
src/Control/TimeWarp/Manager.hs
Haskell
mit
180
{-# LANGUAGE OverloadedStrings #-} import Data.List import System.CPUTime notWhole :: Double -> Bool notWhole x = fromIntegral (round x) /= x cat :: Double -> Double -> Double cat l m | m < 0 = 3.1 | l == 0 = 3.1 | notWhole l = 3.1 | notWhole m = 3.1 | otherwise = read (show (round l) ++ show (round m)) f :: Double -> String f x = show (round x) scoreDiv :: (Eq a, Fractional a) => a -> a -> a scoreDiv az bz | bz == 0 = 99999 | otherwise = (/) az bz ops = [cat, (+), (-), (*), scoreDiv] calc :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op2 (op1 a' b') c' == 20] calc2 :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc2 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op2 a' (op1 b' c') == 20] calc3 :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc3 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 (op1 a' b') (op2 c' d') == 20] calc4 :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc4 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 (op2 (op1 a' b') c') d' == 20] calc5 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 (op2 a' (op1 b' c')) d' == 20] calc6 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 a' (op2 (op1 b' c') d') == 20] calc7 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 a' (op2 b' (op1 c' d')) == 20] only_calc = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, not (null $ calc a b c d), null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc2 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, not (null $ calc2 a b c d), null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc3 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, not (null $ calc3 a b c d), null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc4 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, not (null $ calc4 a b c d), null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc5 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, not (null $ calc5 a b c d), null $ calc6 a b c d, null $ calc7 a b c d ] only_calc6 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, not (null $ calc6 a b c d), null $ calc7 a b c d ] only_calc7 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, not (null $ calc7 a b c d )] main = do print "*****************************___only_calc" t1 <- getCPUTime mapM_ print only_calc print " " print "*****************************___only_calc2" mapM_ print only_calc2 print " " print "*****************************___only_calc3" mapM_ print only_calc3 print " " print "*****************************___only_calc4" mapM_ print only_calc4 print " " print "*****************************___only_calc5" mapM_ print only_calc5 print " " print "*****************************___only_calc6" mapM_ print only_calc6 print " " print "*****************************___only_calc7" mapM_ print only_calc7 t2 <- getCPUTime let t = fromIntegral (t2-t1) * 1e-12 print t print " "
dschalk/score3
analysis_A.hs
Haskell
mit
6,109
-------------------------------------------------------------------- -- File Name: xmonad.hs -- Purpose: Configure the Xmonad tiled window manager -- Creation Date: Sat Jul 07 07:13:31 CDT 2016 -- Last Modified: Sun Jan 22 17:21:02 CST 2017 -- Created By: Ivan Guerra <Ivan.E.Guerra-1@ou.edu> -------------------------------------------------------------------- import XMonad import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.SetWMName import Graphics.X11.ExtraTypes.XF86 (xF86XK_AudioLowerVolume, xF86XK_AudioRaiseVolume, xF86XK_AudioMute, xF86XK_MonBrightnessDown, xF86XK_MonBrightnessUp) import XMonad.Util.Run(spawnPipe) import XMonad.Util.EZConfig(additionalKeys) import XMonad.Actions.CycleWS import XMonad.Layout.BorderResize import System.IO main = do xmproc <- spawnPipe "xmobar" xmonad $ defaultConfig { manageHook = manageDocks <+> manageHook defaultConfig , layoutHook = avoidStruts $ layoutHook defaultConfig , handleEventHook = handleEventHook defaultConfig <+> docksEventHook , logHook = dynamicLogWithPP xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor "#bdbdbd" "" . shorten 50 } , modMask = mod4Mask -- Rebind Mod to the Windows key , terminal = "xfce4-terminal" -- Set the default terminal to the Xfce terminal , normalBorderColor = "black" , focusedBorderColor = "#bdbdbd" , startupHook = setWMName "LG3D" <+> spawn "compton --backend glx -fcC" } `additionalKeys` [ ((mod4Mask .|. controlMask, xK_l), spawn "slock") -- Call slock to lock the screen , ((mod4Mask .|. controlMask, xK_b), spawn "chromium") -- Launch a Chromium browser instance , ((mod4Mask .|. controlMask, xK_g), spawn "emacs") -- Launch an Emacs instance , ((mod4Mask, xK_Right), nextWS) -- Map Mod and right key to move to next workspace , ((mod4Mask, xK_Left), prevWS) -- Map Mod and left key to move to previous workspace , ((0 , xF86XK_AudioLowerVolume), spawn "amixer set Master 4-") -- use the function keys to decrease the volume , ((0 , xF86XK_AudioRaiseVolume), spawn "amixer set Master 4+") -- use the function keys to increase the volume , ((0, xF86XK_MonBrightnessDown), spawn "xbacklight -10") -- use the function keys to decrease screen brightness , ((0, xF86XK_MonBrightnessUp), spawn "xbacklight +10") -- use the function keys to increase screen brightness , ((mod4Mask .|. controlMask, xK_F4), spawn "sudo shutdown -h now") -- shutdown the machine , ((mod4Mask .|. controlMask, xK_F5), spawn "sudo shutdown -r now") -- restart the machine ]
ivan-guerra/config_files
xmonad.hs
Haskell
mit
3,086
import System.IO import Data.List import Debug.Trace enumerate = zip [0..] discatenate :: [a] -> [[a]] discatenate xs = map (\a -> [a]) xs format :: (Int, Int) -> String format (i, n) = "Case #" ++ (show (i + 1)) ++ ": " ++ (show n) rsort :: (Ord a) => [a] -> [a] rsort = reverse . sort split :: [Int] -> Int -> [Int] split [] _ = [] split (x:xs) 0 = let small = x `div` 2 big = x - small in big : small : xs split (x:xs) n = x : (split xs (n - 1)) advance :: [Int] -> [Int] advance xs = map (\x -> x - 1) xs removeFinished :: [Int] -> [Int] removeFinished = filter (>0) step :: (Int, [[Int]]) -> (Int, [[Int]]) step (count, xss) = (count + 1, newXss) where len = length xss indices = [0..(len-1)] splits = nub $ concatMap (\xs -> map (rsort . (split xs)) [0..(length xs)]) xss advances = map advance xss together = map removeFinished $ splits ++ advances newXss = if any null together then [] else together solveCase :: ([Int], [String]) -> ([Int], [String]) solveCase (results, input) = (results ++ [result], drop 2 input) where num = read $ head input :: Int plates = rsort $ map read $ words (input !! 1) :: [Int] (result, _) = until (\(_, xs) -> null xs) step (0, [plates]) solveCases :: [String] -> [Int] solveCases input = result where (result, _) = until (\(_, is) -> null is) solveCase ([], input) main = do input <- openFile "d.in" ReadMode >>= hGetContents >>= return . lines let numCases = read $ head input :: Int let solved = solveCases $ tail input mapM_ putStrLn $ map format (enumerate solved)
davidrusu/Google-Code-Jam
2015/qualifiers/B/brute.hs
Haskell
mit
1,663
--matchTypes.hs module MatchTypes where import Data.List (sort) i :: Num a => a i = 1 f :: RealFrac a => a f = 1.0 freud :: Ord a => a -> a freud x = x freud' :: Int -> Int freud' x = x myX = 1 :: Int sigmund :: Int -> Int sigmund x = myX sigmund' :: Int -> Int sigmund' x = myX jung :: [Int] -> Int jung xs = head (sort xs) young :: Ord a => [a] -> a young xs = head (sort xs) mySort :: [Char] -> [Char] mySort = sort signifier :: [Char] -> Char signifier xs = head (mySort xs)
deciduously/Haskell-First-Principles-Exercises
2-Defining and combining/6-Typeclasses/code/matchTypes.hs
Haskell
mit
491
{-| Module : IREvaluator Description : EBNF IR evaluation Copyright : (c) chop-lang, 2015 License : MIT Maintainer : carterhinsley@gmail.com -} module IREvaluator ( PTerminal , PToken(..) , PAST , evaluate , createEvaluator ) where import Data.Text (Text(..)) import IRGenerator ( IRTerminal(..) , IRToken(..) , IRAlternation , IRContent , IRForm , IR ) data EToken = ETContainer EContent | ETTerminal ETerminal deriving (Eq, Show) type EAlternation = [EToken] type EContent = [EAlternation] type EForm = (Text, EContent) type ER = [EForm] -- | A product AST terminal, its first element being a descriptor of the -- terminal and its second element being the terminal content. type PTerminal = (Text, Text) -- | A product AST token, either containing another product AST or comprising -- a PTerminal. data PToken = PTContainer PAST | PTTerminal PTerminal deriving (Eq, Show) -- | The final product AST of the parsing process. type PAST = [PToken] -- | Accept an EBNF IR and some source text and product a product AST. evaluate :: IR -> Text -> PAST -- | Accept an EBNF IR and produce an evaluator representation. createEvaluator :: IR -> ER
chop-lang/parsebnf
src/IREvaluator.hs
Haskell
mit
1,309
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Main where import Action import Control.Applicative import Control.Concurrent import Control.Lens import Control.Monad import Control.Monad.IO.Class import Control.Monad.State import Data.ByteString.Char8 (pack, unpack, ByteString) import qualified Data.Map as M import Data.Maybe (fromJust, isNothing) import Debug.Trace import MainHelper import Mana import qualified Snap import Snap hiding (writeBS, state) import Snap.Util.FileServe (serveDirectory) import State import System.Log.Logger import Cards -- debugging purposes --writeBS str = trace (take 50 $ show str) (Snap.writeBS str) writeBS :: ByteString -> Snap () writeBS = Snap.writeBS type GSHandler = MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> Snap () setupGame :: GameState -> IO GameState setupGame = execStateT defaultGame' where defaultGame' = do forM_ [1..7] $ \_ -> drawCard 1 forM_ [1..6] $ \_ -> drawCard 0 processGameState nickDeck :: String nickDeck = "20 x Swamp\n40 x Tenacious Dead" --nickDeck = "3 x Battle Sliver\n11 x Mountain\n12 x Forest\n2 x Blur Sliver\n2 x Groundshaker Sliver\n3 x Manaweft Sliver\n2 x Megantic Sliver\n3 x Predatory Sliver\n4 x Striking Sliver\n3 x Thorncaster Sliver\n3 x Giant Growth\n3 x Fog\n2 x Naturalize\n3 x Shock\n4 x Enlarge" --mitchellDeck = "30 x Mountain\n6 x Regathan Firecat\n8 x Lava Axe\n6 x Battle Sliver\n4 x Blur Sliver\n4 x Shock\n4 x Thunder Strike" mitchellDeck :: String mitchellDeck = "13 x Mountain\n1 x Canyon Minotaur\n1 x Dragon Hatchling\n2 x Goblin Shortcutter\n2 x Pitchburn Devils\n2 x Regathan Firecat\n3 x Chandra's Outrage\n2 x Lava Axe\n1 x Seismic Stomp\n1 x Shock\n2 x Thunder Strike" main :: IO () main = do updateGlobalLogger "Game" (setLevel DEBUG) updateGlobalLogger "MVar" (setLevel DEBUG) stateMVar <- newEmptyMVar input <- newMVar (Nothing, IOReqPriority 0) output <- newEmptyMVar :: IO (MVar GameAction) gameState <- setupGame =<< buildGame stateMVar input output "Nicholas" nickDeck "Mitchell" mitchellDeck debugM "MVar" "main putting initial game state" putMVar stateMVar gameState threadID <- spawnLogicThread stateMVar output input tID <- newMVar threadID quickHttpServe $ site stateMVar input output tID site :: MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> MVar ThreadId -> Snap () site stateMVar input output tID = ifTop (writeBS "Magic: the Gathering, yo!") <|> route [("gameBoard", gameBoardHandler stateMVar input output) ,("clickCard", clickCardHandler stateMVar input output) ,("useAbility", useAbilityHandler stateMVar input output) ,("pass", passPriority stateMVar input output) ,("targetPlayer", targetPlayerHandler stateMVar input output) ,("chooseColor", chooseColorHandler stateMVar input output) ,("decideYes", youMayHandler DecideYes stateMVar input output) ,("decideNo", youMayHandler DecideNo stateMVar input output) ,("debug", printState stateMVar) ,("/static", serveDirectory "./M14/") ,("/client", serveDirectory "../magic-spieler/web-client/") ,("/newGame", newGame tID stateMVar input output) -- ,("/setupPlayer", runHandler setupPlayer state) ] printState :: MVar GameState -> Snap () printState stateMVar = liftIO $ print =<< readMVar stateMVar clickCardHandler :: GSHandler clickCardHandler state input output = do noInput <- liftIO $ isEmptyMVar input if noInput then writeBS "Waiting on server..." else do params <- getParams let lookups = do pID <- "playerID" `M.lookup` params cID <- "cardID" `M.lookup` params return (head pID, head cID) case lookups of Nothing -> writeBS "Error! Please pass in playerID, cardID" Just (playerID :: ByteString, cardID :: ByteString) -> clickCard state input output (read $ unpack playerID) (read $ unpack cardID) clickCard :: MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> Int -> Int -> Snap () clickCard stateMVar input output playerID cardID = do s <- liftIO $ readMVar stateMVar inputVal@(_, ioreq) <- liftIO $ takeMVar input case ioreq of IOReqChooseBlocker -> if playerID == (s^.currentPlayerID) then do writeBS "You can't block yourself!" liftIO $ putMVar input inputVal else doAction input output (DeclareIsBlocker playerID cardID) IOReqChooseBlockee blockerID | playerID == (s^.currentPlayerID) -> do writeBS "You can't block yourself!" liftIO $ putMVar input inputVal | cardID `notElem` (s^.attackers) -> do writeBS "That isn't attacking. Choose who to block." liftIO $ putMVar input inputVal | otherwise -> doAction input output (DeclareBlocker playerID (blockerID, cardID)) IOReqPriority _ -> doAction input output $ actionForClick playerID (s^.card cardID) s IOReqTargeting pID pred cID -> let valid = evalState (pred cID (CardTarget cardID)) s in if valid then doAction input output (TargetCard playerID cardID) else do writeBS "Invalid target choice. Pick another target." liftIO $ putMVar input inputVal _ -> error $ "Unknown IORequest " ++ show ioreq doAction :: MVar (Maybe String, IORequest) -> MVar GameAction -> GameAction -> Snap () doAction input output action = do -- Sanity checks inputEmpty <- liftIO (isEmptyMVar input) outputEmpty <- liftIO (isEmptyMVar output) unless inputEmpty $ error ("doAction " ++ show action ++ " - input not empty") unless outputEmpty $ error ("doAction " ++ show action ++ " - output not empty") liftIO $ debugM "MVar" "doAction putting output MVar" liftIO $ putMVar output action liftIO $ debugM "MVar" "doAction reading input MVar" (maybeError, ioreq) <- liftIO $ readMVar input case maybeError of Just err -> writeBS (pack err) Nothing -> let message = case ioreq of IOReqPriority _ -> "OK" IOReqTargeting _ _ _ -> "Select a target" IOReqBlocking _ _ -> "IOReqBlocking - shouldn't be used..." IOReqChooseBlocker -> "Choose a blocker" IOReqChooseBlockee _ -> "Choose who to block" IOReqChooseCard _ _ -> "Choose a card" IOReqChooseColor _ -> "Choose a color" IOReqYouMay _ _ -> "Choose an option" in writeBS message useAbilityHandler :: MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> Snap () useAbilityHandler stateMvar input output = do params <- getParams liftIO $ debugM "MVar" "useAbilityHandler reading state MVar, taking input MVar" state <- liftIO $ readMVar stateMvar ioreq <- liftIO $ tryTakeMVar input let lookups = do pID <- "playerID" `M.lookup` params cID <- "cardID" `M.lookup` params aID <- "abilityID" `M.lookup` params return ((read . unpack . head) pID, (read . unpack . head) cID, (read . unpack . head) aID) case ioreq of Nothing -> writeBS "Ability use canceled, waiting on server..." Just ioreq'@(_, IOReqPriority _) -> case lookups of Nothing -> do writeBS "Invalid call to useAbility" liftIO $ putMVar input ioreq' Just (pID, cID, aID) -> do let cardAbilities = state^.card cID.abilities maybeAbility = cardAbilities^?ix aID case maybeAbility of Nothing -> do writeBS "Invalid ability index - programmer error" liftIO $ putMVar input ioreq' Just ability -> -- liftIO $ -- putMVar output (DoAbility pID cID ability) doAction input output (DoAbility pID cID ability) _ -> error "Unknown IORequest in useAbilityHandler" chooseColorHandler :: GSHandler chooseColorHandler _ input output = do params <- getParams liftIO $ debugM "MVar" "chooseColorHandler reading state MVar, taking input MVar" ioreq <- liftIO $ tryTakeMVar input let lookups = do pID <- "playerID" `M.lookup` params color <- "color" `M.lookup` params return ((read . unpack . head) pID, (unpack . head) color) case ioreq of Just ioreq'@(_, IOReqChooseColor reqID) -> case lookups of Nothing -> writeBS "Invalid call to chooseColor" Just (pID, colorString) -> let color = parseManaCost colorString in if (pID /= reqID) || length color /= 1 then do writeBS "Please choose exactly 1 color." liftIO $ putMVar input ioreq' else doAction input output (ChooseColor $ head color) Just ioreq' -> do writeBS "Not looking for a color right now." liftIO $ putMVar input ioreq' Nothing -> writeBS "Not looking for a color right now." youMayHandler :: GameAction -> GSHandler youMayHandler action _ input output = do params <- getParams liftIO $ debugM "MVar" "youMayHandler reading state MVar, taking input MVar" ioreq <- liftIO $ tryTakeMVar input let maybePID = do pID <- "playerID" `M.lookup` params return $ (read . unpack . head) pID case ioreq of Just ioreq'@(_, IOReqYouMay reqID _) -> case maybePID of Nothing -> writeBS "Invalid call to decide{Yes,No}" Just pID -> if (pID /= reqID) then do writeBS "It is not your decision." liftIO $ putMVar input ioreq' else doAction input output action Just ioreq' -> do writeBS "Not looking for a decision right now." liftIO $ putMVar input ioreq' Nothing -> writeBS "Not looking for a decision right now." targetPlayerHandler :: GSHandler targetPlayerHandler stateMVar input output = do params <- getParams liftIO $ debugM "MVar" "targetPlayerHandler reading state MVar, taking input MVar" state <- liftIO $ readMVar stateMVar ioreq <- liftIO $ tryTakeMVar input let lookups = do pID <- "sourceID" `M.lookup` params tID <- "targetID" `M.lookup` params return ((read . unpack . head) pID, (read . unpack . head) tID) case ioreq of Just ioreq'@(_, IOReqTargeting _ pred cID) -> case lookups of Nothing -> writeBS "Invalid call to targetPlayer" Just (pID, tID) -> let valid = evalState (pred cID (PlayerTarget tID)) state in if not valid then do writeBS "Invalid Choice" liftIO $ putMVar input ioreq' else doAction input output (TargetPlayer pID tID) Just ioreq' -> do writeBS "Not looking for a target right now." liftIO $ putMVar input ioreq' Nothing -> writeBS "Not looking for a target right now." attacker :: Integer attacker = 0 -- TODO - how to do this? errorAction :: GameAction errorAction = PayCost 0 0 (ManaCost $ replicate 9001 B) actionForClick :: Int -> Card -> GameState -> GameAction actionForClick pID c s | c^.cardID `elem` s^.playerWithID pID.hand = PlayCard pID (c^.cardID) | Land `elem` (c^.cardType) = DoAbility pID (c^.cardID) (head $ c^.abilities) | Creature `elem` (c^.cardType) = if s^.currentPlayerID == pID then DeclareAttacker pID (c^.cardID) else errorAction --DeclareBlocker pID (c^.cardID, attacker) | otherwise = errorAction gameBoardHandler :: GSHandler gameBoardHandler stateMVar _ _ = do state <- liftIO (readMVar stateMVar) xml <- liftIO $ toXML state writeBS . pack $ xml passPriority :: GSHandler passPriority stateMVar input output = do params <- getParams liftIO $ debugM "MVar" "passPriority reading state MVar, taking input MVar" s <- liftIO $ readMVar stateMVar (_, ioreq) <- liftIO $ readMVar input let callingPIDList = "playerID" `M.lookup` params if isNothing callingPIDList then writeBS "Error - No pID sent with \"pass\" command" else do let callingPID = read . unpack . head . fromJust $ callingPIDList case ioreq of IOReqPriority pID -> if callingPID == pID then do _ <- liftIO $ takeMVar input doAction input output (PassAction callingPID) else writeBS "Please wait for your opponent." IOReqChooseBlocker -> if s^.currentPlayerID /= callingPID then do _ <- liftIO $ takeMVar input doAction input output (PassAction callingPID) else writeBS "Please wait for your opponent." _ -> writeBS $ pack $ "You can't pass - waiting on " ++ show ioreq newGame :: MVar ThreadId -> GSHandler newGame tID state input output = do params <- getParams let lookups = do p1Name <- "p1Name" `M.lookup` params p1Deck <- "p1Deck" `M.lookup` params p2Name <- "p2Name" `M.lookup` params p2Deck <- "p2Deck" `M.lookup` params return (p1Name, p1Deck, p2Name, p2Deck) case lookups of Nothing -> writeBS "Incorrect call to newGame" Just (p1Name, p1Deck, p2Name, p2Deck) -> liftIO $ do threadID <- takeMVar tID killThread threadID _ <- tryTakeMVar input _ <- tryTakeMVar output _ <- tryTakeMVar state putMVar input (Nothing, IOReqPriority 0) gameState <- setupGame =<< buildGame state input output (unpack $ head p1Name) (unpack $ head p1Deck) (unpack $ head p2Name) (unpack $ head p2Deck) putMVar state gameState threadID' <- spawnLogicThread state output input putMVar tID threadID'
mplamann/magic-spieler
src/SnapServer.hs
Haskell
mit
14,387
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} module Rx.Disposable ( emptyDisposable , dispose , disposeCount , disposeErrorCount , newDisposable , newBooleanDisposable , newSingleAssignmentDisposable , toList , wrapDisposable , wrapDisposableIO , BooleanDisposable , Disposable , SingleAssignmentDisposable , SetDisposable (..) , ToDisposable (..) , IDisposable (..) , DisposeResult ) where import Prelude.Compat import Control.Arrow (first) import Control.Exception (SomeException, try) import Control.Monad (liftM, void) -- import Data.List (foldl') import Data.Typeable (Typeable) import Control.Concurrent.MVar (MVar, modifyMVar, newMVar, putMVar, readMVar, swapMVar, takeMVar) -------------------------------------------------------------------------------- type DisposableDescription = String data DisposeResult = DisposeBranch DisposableDescription DisposeResult | DisposeLeaf DisposableDescription (Maybe SomeException) | DisposeResult [DisposeResult] deriving (Show, Typeable) newtype Disposable = Disposable [IO DisposeResult] deriving (Typeable) newtype BooleanDisposable = BooleanDisposable (MVar Disposable) deriving (Typeable) newtype SingleAssignmentDisposable = SingleAssignmentDisposable (MVar (Maybe Disposable)) deriving (Typeable) -------------------------------------------------------------------------------- class IDisposable d where disposeVerbose :: d -> IO DisposeResult class ToDisposable d where toDisposable :: d -> Disposable class SetDisposable d where setDisposable :: d -> Disposable -> IO () -------------------------------------------------------------------------------- instance Monoid DisposeResult where mempty = DisposeResult [] (DisposeResult as) `mappend` (DisposeResult bs) = DisposeResult (as `mappend` bs) a@(DisposeResult coll) `mappend` b = DisposeResult (coll ++ [b]) a `mappend` b@(DisposeResult coll) = DisposeResult (a:coll) a `mappend` b = DisposeResult [a, b] -------------------- instance Monoid Disposable where mempty = Disposable [] (Disposable as) `mappend` (Disposable bs) = Disposable (as `mappend` bs) instance IDisposable Disposable where disposeVerbose (Disposable actions) = mconcat `fmap` sequence actions instance ToDisposable Disposable where toDisposable = id -------------------- instance IDisposable BooleanDisposable where disposeVerbose (BooleanDisposable disposableVar) = do disposable <- readMVar disposableVar disposeVerbose disposable instance ToDisposable BooleanDisposable where toDisposable booleanDisposable = Disposable [disposeVerbose booleanDisposable] instance SetDisposable BooleanDisposable where setDisposable (BooleanDisposable currentVar) disposable = do oldDisposable <- swapMVar currentVar disposable void $ disposeVerbose oldDisposable -------------------- instance IDisposable SingleAssignmentDisposable where disposeVerbose (SingleAssignmentDisposable disposableVar) = do mdisposable <- readMVar disposableVar maybe (return mempty) disposeVerbose mdisposable instance ToDisposable SingleAssignmentDisposable where toDisposable singleAssignmentDisposable = Disposable [disposeVerbose singleAssignmentDisposable] instance SetDisposable SingleAssignmentDisposable where setDisposable (SingleAssignmentDisposable disposableVar) disposable = do mdisposable <- takeMVar disposableVar case mdisposable of Nothing -> putMVar disposableVar (Just disposable) Just _ -> error $ "ERROR: called 'setDisposable' more " ++ "than once on SingleAssignmentDisposable" -------------------------------------------------------------------------------- foldDisposeResult :: (DisposableDescription -> Maybe SomeException -> acc -> acc) -> (DisposableDescription -> acc -> acc) -> ([acc] -> acc) -> acc -> DisposeResult -> acc foldDisposeResult fLeaf _ _ acc (DisposeLeaf desc mErr) = fLeaf desc mErr acc foldDisposeResult fLeaf fBranch fList acc (DisposeBranch desc disposeResult) = fBranch desc (foldDisposeResult fLeaf fBranch fList acc disposeResult) foldDisposeResult fLeaf fBranch fList acc (DisposeResult ds) = let acc1 = map (foldDisposeResult fLeaf fBranch fList acc) ds in fList acc1 disposeCount :: DisposeResult -> Int disposeCount = foldDisposeResult (\_ _ acc -> acc + 1) (const id) sum 0 {-# INLINE disposeCount #-} disposeErrorCount :: DisposeResult -> Int disposeErrorCount = foldDisposeResult (\_ mErr acc -> acc + maybe 0 (const 1) mErr) (const id) sum 0 {-# INLINE disposeErrorCount #-} toList :: DisposeResult -> [([DisposableDescription], Maybe SomeException)] toList = foldDisposeResult (\desc res acc -> (([desc], res) : acc)) (\desc acc -> map (first (desc :)) acc) concat [] dispose :: IDisposable disposable => disposable -> IO () dispose = void . disposeVerbose {-# INLINE dispose #-} emptyDisposable :: IO Disposable emptyDisposable = return mempty {-# INLINE emptyDisposable #-} newDisposable :: DisposableDescription -> IO () -> IO Disposable newDisposable desc disposingAction = do disposeResultVar <- newMVar Nothing return $ Disposable [modifyMVar disposeResultVar $ \disposeResult -> case disposeResult of Just result -> return (Just result, result) Nothing -> do disposingResult <- try disposingAction let result = DisposeLeaf desc (either Just (const Nothing) disposingResult) return (Just result, result)] wrapDisposableIO :: DisposableDescription -> IO Disposable -> IO Disposable wrapDisposableIO desc getDisposable = do disposeResultVar <- newMVar Nothing return $ Disposable [modifyMVar disposeResultVar $ \disposeResult -> case disposeResult of Just result -> return (Just result, result) Nothing -> do disposable <- getDisposable innerResult <- disposeVerbose disposable let result = DisposeBranch desc innerResult return (Just result, result)] {-# INLINE wrapDisposableIO #-} wrapDisposable :: DisposableDescription -> Disposable -> IO Disposable wrapDisposable desc = wrapDisposableIO desc . return {-# INLINE wrapDisposable #-} newBooleanDisposable :: IO BooleanDisposable newBooleanDisposable = liftM BooleanDisposable (newMVar mempty) {-# INLINE newBooleanDisposable #-} newSingleAssignmentDisposable :: IO SingleAssignmentDisposable newSingleAssignmentDisposable = liftM SingleAssignmentDisposable (newMVar Nothing) {-# INLINE newSingleAssignmentDisposable #-}
roman/Haskell-Reactive-Extensions
rx-disposable/src/Rx/Disposable.hs
Haskell
mit
7,151
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.AudioDestinationNode (js_getMaxChannelCount, getMaxChannelCount, AudioDestinationNode, castToAudioDestinationNode, gTypeAudioDestinationNode) 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[\"maxChannelCount\"]" js_getMaxChannelCount :: JSRef AudioDestinationNode -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioDestinationNode.maxChannelCount Mozilla AudioDestinationNode.maxChannelCount documentation> getMaxChannelCount :: (MonadIO m) => AudioDestinationNode -> m Word getMaxChannelCount self = liftIO (js_getMaxChannelCount (unAudioDestinationNode self))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/AudioDestinationNode.hs
Haskell
mit
1,460
module Language.Binal.Util.TyKind where import Control.Monad.State import qualified Data.List as List import qualified Data.HashMap.Strict as HashMap import Language.Binal.Types import qualified Language.Binal.Util.Gen as Gen freeVariables :: TyKind -> [Variable] freeVariables (VarTy i) = [i] freeVariables (RecTy i ty) = filter (/=i) (freeVariables ty) freeVariables SymTy = [] freeVariables StrTy = [] freeVariables NumTy = [] freeVariables BoolTy = [] freeVariables (ArrTy x y) = freeVariables x ++ freeVariables y freeVariables (ListTy xs) = concatMap freeVariables xs freeVariables (EitherTy xs) = concatMap freeVariables xs freeVariables (ObjectTy _ m) = concatMap freeVariables (HashMap.elems m) freeVariables (MutableTy ty) = freeVariables ty extractVarTy :: TyKind -> Maybe Variable extractVarTy (VarTy i) = Just i extractVarTy _ = Nothing extractListTy :: TyKind -> Maybe [TyKind] extractListTy (ListTy xs) = Just xs extractListTy _ = Nothing flatListTy' :: [TyKind] -> [TyKind] flatListTy' [] = [] flatListTy' xs = do case last xs of ListTy [] -> xs ListTy ys -> init xs ++ flatListTy' ys _ -> xs flatListTy :: TyKind -> TyKind flatListTy (VarTy i) = VarTy i flatListTy (RecTy i ty) = RecTy i (flatListTy ty) flatListTy SymTy = SymTy flatListTy StrTy = StrTy flatListTy NumTy = NumTy flatListTy BoolTy = BoolTy flatListTy (ArrTy ty1 ty2) = ArrTy (flatListTy ty1) (flatListTy ty2) flatListTy (ListTy tys) = case flatListTy' tys of [ty] -> ty tys' -> ListTy tys' flatListTy (EitherTy xs) = EitherTy (map flatListTy xs) flatListTy (ObjectTy i m) = ObjectTy i (HashMap.map flatListTy m) flatListTy (MutableTy ty) = MutableTy (flatListTy ty) flatEitherTy' :: Variable -> [TyKind] -> [TyKind] flatEitherTy' _ [] = [] flatEitherTy' i xs = do List.nub (concatMap (\x -> case x of VarTy j | i == j -> [] | otherwise -> [VarTy j] ty -> [ty]) xs) flatEitherTy :: Variable -> TyKind -> TyKind flatEitherTy i (EitherTy xs) = case flatEitherTy' i xs of [ty] -> ty tys -> EitherTy tys flatEitherTy _ ty = ty showTy' :: TyKind -> State (HashMap.HashMap Variable String, [String]) String showTy' (VarTy i) = do (mp, varList) <- get case HashMap.lookup i mp of Just s -> return ('\'':s) Nothing -> do let (v, varList') = case varList of [] -> (show i, []) (s:ss) -> (s, ss) let mp' = HashMap.insert i v mp put (mp', varList') return ('\'':v) showTy' (RecTy i ty) = do x <- showTy' (VarTy i) y <- showTy' ty return ("(recur " ++ x ++ " " ++ y ++ ")") showTy' SymTy = return "symbol" showTy' StrTy = return "string" showTy' NumTy = return "number" showTy' BoolTy = return "bool" showTy' (ArrTy ty1 ty2) = do ty1S <- showTy' ty1 ty2S <- showTy' ty2 case (length (lines ty1S), length (lines ty2S)) of (1, 1) -> return ("(-> " ++ ty1S ++ " " ++ ty2S ++ ")") _ -> return ("(-> " ++ drop 4 (Gen.indent 4 ty1S) ++ "\n" ++ Gen.indent 4 ty2S ++ ")") showTy' (ListTy xs) = do ss <- mapM showTy' xs if all (\x -> 1 == length (lines x)) ss then return ("(" ++ unwords ss ++ ")") else return ("(" ++ drop 1 (Gen.indent 1 (unlines ss)) ++ ")") showTy' (EitherTy xs) = do ss <- mapM showTy' xs if all (\x -> 1 == length (lines x)) ss then return ("(| " ++ unwords ss ++ ")") else return ("(| " ++ drop 3 (Gen.indent 3 (unlines ss)) ++ ")") showTy' (ObjectTy _ m) | HashMap.null m = return "(obj)" | otherwise = do let maxLen = foldr1 max (map length (HashMap.keys m)) ss <- mapM (\(key, val) -> do x <- showTy' val return ["\n", key, drop (length key) (Gen.indent (maxLen + 1) x)]) (HashMap.toList m) return ("(obj " ++ drop 5 (Gen.indent 5 (tail (concat (concat ss)))) ++ ")") showTy' (MutableTy ty) = do s <- showTy' ty case length (lines s) of 1 -> do return ("(mutable " ++ s ++ ")") _ -> do return ("(mutable" ++ drop 8 (Gen.indent 9 s) ++ ")") showTy :: TyKind -> String showTy ty = evalState (showTy' ty) (HashMap.empty, map (\ch -> [ch]) ['a'..'z']) showTy2 :: TyKind -> TyKind -> (String, String) showTy2 ty1 ty2 = evalState (do { x <- showTy' ty1; y <- showTy' ty2; return (x, y) }) (HashMap.empty, map (\ch -> [ch]) ['a'..'z']) traverseVarTyM :: Monad m => (TyKind -> m ()) -> TyKind -> m () traverseVarTyM f ty@(VarTy _) = f ty traverseVarTyM _ SymTy = return () traverseVarTyM _ StrTy = return () traverseVarTyM _ NumTy = return () traverseVarTyM _ BoolTy = return () traverseVarTyM f (ArrTy ty1 ty2) = traverseVarTyM f ty1 >> traverseVarTyM f ty2 traverseVarTyM f (ListTy tys) = mapM_ (traverseVarTyM f) tys traverseVarTyM f (EitherTy tys) = mapM_ (traverseVarTyM f) tys traverseVarTyM f (ObjectTy _ x) = mapM_ (traverseVarTyM f) (HashMap.elems x) traverseVarTyM f (RecTy _ ty) = traverseVarTyM f ty traverseVarTyM f (MutableTy ty) = traverseVarTyM f ty
pasberth/binal1
Language/Binal/Util/TyKind.hs
Haskell
mit
5,038
{-# LANGUAGE RecordWildCards #-} module Game.Graphics.Font ( FontText(..) , Font, loadFont , drawFontText ) where import Graphics.Rendering.FTGL import Game.Graphics.AffineTransform (AffineTransform, withTransformRasterGl) data FontText = FontText { getFont :: Font , getString :: String } loadFont :: String -> IO Font loadFont = createPixmapFont drawFontText :: AffineTransform -> FontText -> IO Bool drawFontText trans FontText{..} = do setFontFaceSize getFont 24 72 withTransformRasterGl trans $ renderFont getFont getString Front return True
caryoscelus/graphics
src/Game/Graphics/Font.hs
Haskell
mit
625
{-# LANGUAGE BangPatterns, ConstraintKinds, FlexibleContexts, GeneralizedNewtypeDeriving, MultiParamTypeClasses, StandaloneDeriving, TupleSections #-} {- | Module : Data.Graph.Unordered.Algorithms.Clustering Description : Graph partitioning Copyright : (c) Ivan Lazar Miljenovic License : MIT Maintainer : Ivan.Miljenovic@gmail.com -} module Data.Graph.Unordered.Algorithms.Clustering (bgll ,EdgeMergeable ) where import Data.Graph.Unordered import Data.Graph.Unordered.Internal import Control.Arrow (first, (***)) import Control.Monad (void) import Data.Bool (bool) import Data.Function (on) import Data.Hashable (Hashable) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.List (delete, foldl', foldl1', group, maximumBy, sort) import Data.Maybe (fromMaybe, mapMaybe) import Data.Proxy (Proxy (Proxy)) -- ----------------------------------------------------------------------------- -- | Find communities in weighted graphs using the algorithm by -- Blondel, Guillaume, Lambiotte and Lefebvre in their paper -- <http://arxiv.org/abs/0803.0476 Fast unfolding of communities in large networks>. bgll :: (ValidGraph et n, EdgeMergeable et, Fractional el, Ord el) => Graph et n nl el -> [[n]] bgll g = maybe [nodes g] nodes (recurseUntil pass g') where pass = fmap phaseTwo . phaseOne -- HashMap doesn't allow directly mapping the keys g' = Gr { nodeMap = HM.fromList . map ((: []) *** void) . HM.toList $ nodeMap g , edgeMap = HM.map (first (fmap (: []))) (edgeMap g) , nextEdge = nextEdge g } data CGraph et n el = CG { comMap :: HashMap Community (Set [n]) , cGraph :: Graph et [n] Community el } deriving (Show, Read) deriving instance (Eq n, Eq el, Eq (et [n])) => Eq (CGraph et n el) newtype Community = C Word deriving (Eq, Ord, Show, Read, Enum, Bounded, Hashable) type ValidC et n el = (ValidGraph et n, EdgeMergeable et, Fractional el, Ord el) phaseOne :: (ValidC et n el) => Graph et [n] nl el -> Maybe (CGraph et n el) phaseOne = recurseUntil moveAll . initCommunities initCommunities :: (ValidC et n el) => Graph et [n] nl el -> CGraph et n el initCommunities g = CG { comMap = cm , cGraph = Gr { nodeMap = nm' , edgeMap = edgeMap g , nextEdge = nextEdge g } } where nm = nodeMap g ((_,cm),nm') = mapAccumWithKeyL go (C minBound, HM.empty) nm go (!c,!cs) ns al = ( (succ c, HM.insert c (HM.singleton ns ()) cs) , c <$ al ) moveAll :: (ValidC et n el) => CGraph et n el -> Maybe (CGraph et n el) moveAll cg = uncurry (bool Nothing . Just) $ foldl' go (cg,False) (nodes (cGraph cg)) where go pr@(cg',_) = maybe pr (,True) . tryMove cg' tryMove :: (ValidC et n el) => CGraph et n el -> [n] -> Maybe (CGraph et n el) tryMove cg ns = moveTo <$> bestMove cg ns where cm = comMap cg g = cGraph cg currentC = getC g ns currentCNs = cm HM.! currentC moveTo c = CG { comMap = HM.adjust (HM.insert ns ()) c cm' , cGraph = nmapFor (const c) g ns } where currentCNs' = HM.delete ns currentCNs cm' | HM.null currentCNs' = HM.delete currentC cm | otherwise = HM.adjust (const currentCNs') currentC cm bestMove :: (ValidC et n el) => CGraph et n el -> [n] -> Maybe Community bestMove cg n | null vs = Nothing | null cs = Nothing | maxDQ <= 0 = Nothing | otherwise = Just maxC where g = cGraph cg c = getC g n vs = neighbours g n cs = delete c . map head . group . sort . map (getC g) $ vs (maxC, maxDQ) = maximumBy (compare`on`snd) . map ((,) <*> diffModularity cg n) $ cs getC :: (ValidC et n el) => Graph et [n] Community el -> [n] -> Community getC g = fromMaybe (error "Node doesn't have a community!") . nlab g -- This is the 𝝙Q function. Assumed that @i@ is not within the community @c@. diffModularity :: (ValidC et n el) => CGraph et n el -> [n] -> Community -> el diffModularity cg i c = ((sumIn + kiIn)/m2 - sq ((sumTot + ki)/m2)) - (sumIn/m2 - sq (sumTot/m2) - sq (ki/m2)) where g = cGraph cg nm = nodeMap g em = edgeMap g -- Nodes within the community cNs = fromMaybe HM.empty (HM.lookup c (comMap cg)) -- Edges solely within the community cEMap = HM.filter (all (`HM.member`cNs) . edgeNodes . fst) em -- All edges incident with C incEs = HM.filter (any (`HM.member`cNs) . edgeNodes . fst) em -- Twice the weight of all edges in the graph (take into account both directions) m2 = eTot em -- Sum of weights of all edges within the community sumIn = eTot cEMap -- Sum of weights of all edges incident with the community sumTot = eTot incEs iAdj = maybe HM.empty fst $ HM.lookup i nm ki = kTot . HM.intersection em $ iAdj kiIn = kTot . HM.intersection incEs $ iAdj -- 2* because the EdgeMap only contains one copy of each edge. eTot = (2*) . kTot kTot = (2*) . sum . map snd . HM.elems sq x = x * x phaseTwo :: (ValidC et n el) => CGraph et n el -> Graph et [n] () el phaseTwo cg = mkGraph ns es where nsCprs = map ((,) <*> concat . HM.keys) . HM.elems $ comMap cg nsToC = HM.fromList . concatMap (\(vs,c) -> map (,c) (HM.keys vs)) $ nsCprs emNCs = HM.map (first (fmap (nsToC HM.!))) (edgeMap (cGraph cg)) es = compressEdgeMap Proxy emNCs ns = map (,()) (map snd nsCprs) -- eM' = map toCE -- . groupBy ((==)`on`fst) -- . sortBy (compare`on`fst) -- . map (first edgeNodes) -- . HM.elems -- $ edgeMap (cGraph cg) -- d -- toCE es = let ([u,v],_) = head es -- in (u,v, sum (map snd es)) -- The resultant (n,n) pairings will be unique compressEdgeMap :: (ValidC et n el) => Proxy et -> EdgeMap et [n] el -> [([n],[n],el)] compressEdgeMap p em = concatMap (\(u,vels) -> map (uncurry $ mkE u) (HM.toList vels)) (HM.toList esUndir) where -- Mapping on edge orders as created esDir = foldl1' (HM.unionWith (HM.unionWith (+))) . map ((\(u,v,el) -> HM.singleton u (HM.singleton v el)) . edgeTriple) $ HM.elems em esUndir = fst $ foldl' checkOpp (HM.empty, esDir) (HM.keys esDir) mkE u v el | el < 0 = (v,u,applyOpposite p el) | otherwise = (u,v,el) checkOpp (esU,esD) u | HM.null uVs = (esU , esD' ) | otherwise = (esU', esD'') where uVs = esD HM.! u -- So we don't worry about loops. esD' = HM.delete u esD uAdj = mapMaybe (\v -> fmap (v,) . HM.lookup u =<< (HM.lookup v esD')) (HM.keys (esD' `HM.intersection` uVs)) esD'' = foldl' (flip $ HM.adjust (HM.delete u)) esD' (map fst uAdj) uVs' = foldl' toE uVs uAdj toE m (v,el) = HM.insertWith (+) v (applyOpposite p el) m esU' = HM.insert u uVs' esU class (EdgeType et) => EdgeMergeable et where applyOpposite :: (Fractional el) => Proxy et -> el -> el instance EdgeMergeable DirEdge where applyOpposite _ = negate instance EdgeMergeable UndirEdge where applyOpposite _ = id -- ----------------------------------------------------------------------------- -- StateL was copied from the source of Data.Traversable in base-4.8.1.0 mapAccumWithKeyL :: (a -> k -> v -> (a, y)) -> a -> HashMap k v -> (a, HashMap k y) mapAccumWithKeyL f a m = runStateL (HM.traverseWithKey f' m) a where f' k v = StateL $ \s -> f s k v -- left-to-right state transformer newtype StateL s a = StateL { runStateL :: s -> (s, a) } instance Functor (StateL s) where fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v) instance Applicative (StateL s) where pure x = StateL (\ s -> (s, x)) StateL kf <*> StateL kv = StateL $ \ s -> let (s', f) = kf s (s'', v) = kv s' in (s'', f v) -- ----------------------------------------------------------------------------- recurseUntil :: (a -> Maybe a) -> a -> Maybe a recurseUntil f = fmap go . f where go a = maybe a go (f a)
ivan-m/unordered-graphs
src/Data/Graph/Unordered/Algorithms/Clustering.hs
Haskell
mit
8,702
-- | Exercises for chapter 3. module Chapter03 ( xs0, xs1, xs2, xs3, t0, t1, twice, palindrome, double, pair, swap, second ) where -- * Exercise 1 xs0 :: [Int] xs0 = [0, 1] -- Define the values below and give them types. -- | TODO: define as @['a','b','c']@ xs1 = undefined -- | TODO: define as @('a','b','c')@ t0 = undefined -- | TODO: define as @[(False,'0'),(True,'1')]@ xs2 = undefined -- | TODO: define as @([False,True],['0','1'])@ t1 = undefined -- | TODO: define as @[tail,init,reverse]@ xs3 = undefined -- * Exercise 2 -- Define the values below and give them types. -- | Returns the second element of a list. -- -- TODO: give it a type and implement. second xs = undefined -- | Swap the elements of a tuple. -- -- TODO: give it a type and implement. swap (x,y) = undefined -- | Constructs a pair with the given elements, in the order in which the -- parameters appear. -- -- TODO: give it a type and implement. pair x y = undefined -- | Multiplies the given argument by 2. -- -- TODO: give it a type and implement. double x = undefined -- | Determine wether the given list is a palindrome. -- -- TODO: give it a type and implement. palindrome xs = undefined -- | Apply the given function twice to the given argument. -- -- TODO: give it a type and implement. twice f x = undefined
EindhovenHaskellMeetup/meetup
courses/programming-in-haskell/pih-exercises/src/Chapter03.hs
Haskell
mit
1,312