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
import Test.Hspec import Test.QuickCheck import Lib main :: IO () main = hspec $ do describe "Prelude.head" $ do it "returns the first element of a list" $ do head [23..] `shouldBe` (23 :: Int) it "returns the first element of an *arbitrary* list" $ property $ \x xs -> head (x:xs) == (x :: Int)
kazeula/haskell-json-sample
test/Spec.hs
Haskell
bsd-3-clause
322
{- | Module : SAWScript.SBVModel Description : Abstract representation for .sbv file format. Maintainer : jhendrix Stability : provisional -} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} module SAWScript.SBVModel where import Data.Binary import Data.List(sortBy) import Control.Monad (liftM, liftM2, liftM3) import System.IO (openBinaryFile, IOMode(..), hClose) import qualified Data.ByteString.Lazy as B -- Auxiliary Cryptol types type Major = Int type Minor = Int data Version = Version Major Minor deriving Show type TyCon = String type Name = String data Loc = Loc String Int{-line-} Int{-col-} | LocPrim String | LocDefault String | LocExpr | LocInternal | LocNone deriving Show data Scheme a = Scheme [String] [a] [Predicate a] (Type a) deriving Show schemeType :: Scheme a -> Type a schemeType (Scheme _ _ _ t) = t embedScheme :: Type a -> Scheme a embedScheme t = Scheme [] [] [] t data Predicate a = PredEq (Type a) (Type a) (Maybe (Predicate a)) [Loc] | PredSubst a (Type a) [Loc] | PredGrEq (Type a) (Type a) [Loc] | PredFin (Type a) [Loc] | PredImplied (Predicate a) deriving Show data Type a = TVar a | TInt Integer | TApp TyCon [Type a] | TRecord [(Name, Scheme a)] deriving Show type IRTyVar = TyVar Int data TyVar a = TyVar { tyvarName :: a, tyvarKind :: Kind , tyvarIgnorable :: Bool, tyvarDefaultable :: Bool } deriving Show type IRType = Type IRTyVar data Kind = KStar | KSize | KShape deriving Show -- SBV programs type Size = Integer type GroundVal = Integer type NodeId = Int data SBV = SBV !Size !(Either GroundVal NodeId) deriving Show data SBVCommand = Decl CtrlPath !SBV (Maybe SBVExpr) | Output !SBV deriving Show data Operator = BVAdd | BVSub | BVMul | BVDiv Loc | BVMod Loc | BVPow | BVIte | BVShl | BVShr | BVRol | BVRor | BVExt !Integer !Integer -- hi lo | BVAnd | BVOr | BVXor | BVNot | BVEq | BVGeq | BVLeq | BVGt | BVLt | BVApp -- append -- following is not essential, but simplifies lookups | BVLkUp !Integer !Integer -- index size, result size -- Uninterpreted constants | BVUnint Loc [(String, String)] (String, IRType) -- loc, code-gen info, name/type deriving Show data SBVExpr = SBVAtom !SBV | SBVApp !Operator ![SBV] deriving Show type CtrlPath = [Either SBV SBV] type VC = ( CtrlPath -- path to the VC , SBVExpr -- stipulated trap; need to prove this expr is not true , String) -- associated error message data SBVPgm = SBVPgm (Version, IRType, [SBVCommand], [VC] , [String] -- warnings , [((String, Loc), IRType, [(String, String)])] -- uninterpeted functions and code ) deriving Show -- make it an instance of Binary instance Binary Loc where put (Loc s i j) = putWord8 0 >> put s >> put i >> put j put (LocPrim s) = putWord8 1 >> put s put (LocDefault s) = putWord8 2 >> put s put LocExpr = putWord8 3 put LocInternal = putWord8 4 put LocNone = putWord8 5 get = do tag <- getWord8 case tag of 0 -> liftM3 Loc get get get 1 -> liftM LocPrim get 2 -> liftM LocDefault get 3 -> return LocExpr 4 -> return LocInternal 5 -> return LocNone n -> error $ "Binary.Loc: " ++ show n instance Binary Version where put (Version ma mi) = put ma >> put mi get = liftM2 Version get get instance Binary SBVPgm where put (SBVPgm cmds) = put cmds get = liftM SBVPgm get -- only monomorphic types supported below sortUnder :: (Ord b) => (a -> b) -> [a] -> [a] sortUnder f = sortBy (\a b -> compare (f a) (f b)) instance Binary IRType where put (TInt i) = putWord8 0 >> put i put (TApp t ts) = putWord8 1 >> put t >> put ts put (TRecord nss) = putWord8 2 >> put [(n, schemeType s) | (n, s) <- sortUnder fst nss] put TVar{} = error $ "internal: put not defined on TVar" get = do tag <- getWord8 case tag of 0 -> liftM TInt get 1 -> liftM2 TApp get get 2 -> do nts <- get return (TRecord [(n, embedScheme t) | (n, t) <- nts]) n -> error $ "Binary.IRType: " ++ show n instance Binary SBV where put (SBV i esn) = put i >> put esn get = liftM2 SBV get get instance Binary SBVCommand where put (Decl path v mbe) = putWord8 0 >> put path >> put v >> put mbe put (Output v) = putWord8 1 >> put v get = do tag <- getWord8 case tag of 0 -> liftM3 Decl get get get 1 -> liftM Output get n -> error $ "Binary.SBVCommand: " ++ show n instance Binary SBVExpr where put (SBVAtom s) = putWord8 0 >> put s put (SBVApp o es) = putWord8 1 >> put o >> put es get = do tag <- getWord8 case tag of 0 -> liftM SBVAtom get 1 -> liftM2 SBVApp get get n -> error $ "Binary.SBVExpr: " ++ show n instance Binary Operator where put BVAdd = putWord8 0 put BVSub = putWord8 1 put BVMul = putWord8 2 put (BVDiv l) = putWord8 3 >> put l put (BVMod l) = putWord8 4 >> put l put BVPow = putWord8 5 put BVIte = putWord8 6 put BVShl = putWord8 7 put BVShr = putWord8 8 put BVRol = putWord8 9 put BVRor = putWord8 10 put (BVExt hi lo) = putWord8 11 >> put hi >> put lo put BVAnd = putWord8 12 put BVOr = putWord8 13 put BVXor = putWord8 14 put BVNot = putWord8 15 put BVEq = putWord8 16 put BVGeq = putWord8 17 put BVLeq = putWord8 18 put BVGt = putWord8 19 put BVLt = putWord8 20 put BVApp = putWord8 21 put (BVLkUp i r) = putWord8 22 >> put i >> put r put (BVUnint l cgs nt) = putWord8 23 >> put l >> put cgs >> put nt get = do tag <- getWord8 case tag of 0 -> return BVAdd 1 -> return BVSub 2 -> return BVMul 3 -> liftM BVDiv get 4 -> liftM BVMod get 5 -> return BVPow 6 -> return BVIte 7 -> return BVShl 8 -> return BVShr 9 -> return BVRol 10 -> return BVRor 11 -> liftM2 BVExt get get 12 -> return BVAnd 13 -> return BVOr 14 -> return BVXor 15 -> return BVNot 16 -> return BVEq 17 -> return BVGeq 18 -> return BVLeq 19 -> return BVGt 20 -> return BVLt 21 -> return BVApp 22 -> liftM2 BVLkUp get get 23 -> liftM3 BVUnint get get get n -> error $ "Binary.Operator: " ++ show n loadSBV :: FilePath -> IO SBVPgm loadSBV f = do h <- openBinaryFile f ReadMode pgm <- B.hGetContents h B.length pgm `seq` hClose h -- oh, the horror.. return (decode pgm)
GaloisInc/saw-script
src/SAWScript/SBVModel.hs
Haskell
bsd-3-clause
7,300
{-# LANGUAGE CPP #-} -- #hide -------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.Types -- Copyright : (c) Sven Panne 2009 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : sven.panne@aedion.de -- Stability : stable -- Portability : portable -- -- All types from the OpenGL 3.1 core, see <http://www.opengl.org/registry/>. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.Types where import Data.Int import Data.Word import Foreign.C.Types import Foreign.Ptr type GLboolean = CUChar type GLubyte = CUChar type GLbyte = CSChar type GLchar = CChar type GLclampd = CDouble type GLdouble = CDouble type GLclampf = CFloat type GLfloat = CFloat type GLbitfield = CUInt type GLenum = CUInt type GLuint = CUInt type GLint = CInt type GLsizei = CInt type GLhalf = CUShort type GLushort = CUShort type GLshort = CShort type GLintptr = CPtrdiff type GLsizeiptr = CPtrdiff type GLint64 = Int64 type GLuint64 = Word64 -- Not part of the core, but it is very handy to define this here type GLhandle = CUInt type GLsync = Ptr () type GLvdpauSurface = GLintptr -- | Fixed point type for OES_fixed_point extension. type GLfixed = CInt newtype CLevent = CLEvent (Ptr CLevent) newtype CLcontext = CLContext (Ptr CLcontext) -- both are actually function pointers type GLdebugproc = FunPtr (GLenum -> GLenum -> GLuint -> GLenum -> GLsizei -> Ptr GLchar -> Ptr () -> IO ())
Laar/OpenGLRawgen
BuildSources/Types.hs
Haskell
bsd-3-clause
1,632
import System.Environment (getArgs) import Data.List.Split (splitOn) import Data.List (intercalate, intersect) doIntersect :: Eq a => [[a]] -> [a] doIntersect l = intersect (head l) (last l) main :: IO () main = do [inpFile] <- getArgs input <- readFile inpFile putStr . unlines . map (intercalate "," . doIntersect . map (splitOn ",") . splitOn ";") $ lines input
nikai3d/ce-challenges
easy/intersection.hs
Haskell
bsd-3-clause
380
module Render.Stmts.Poke.SiblingInfo where import Prettyprinter import Polysemy import Polysemy.Input import Relude import Error import Marshal.Scheme import Spec.Name data SiblingInfo a = SiblingInfo { siReferrer :: Doc () -- ^ How to refer to this sibling in code , siScheme :: MarshalScheme a -- ^ What type is this sibling } type HasSiblingInfo a r = Member (Input (CName -> Maybe (SiblingInfo a))) r getSiblingInfo :: forall a r . (HasErr r, HasSiblingInfo a r) => CName -> Sem r (SiblingInfo a) getSiblingInfo n = note ("Unable to find info for: " <> unCName n) . ($ n) =<< input
expipiplus1/vulkan
generate-new/src/Render/Stmts/Poke/SiblingInfo.hs
Haskell
bsd-3-clause
688
{-# LANGUAGE PackageImports #-} module Camera where import "linear" Linear d0 = V3 0 (-1) 0 u0 = V3 0 0 (-1) s0 p = (p,zero,zero,(0,0)) calcCam dt (dmx,dmy) (left,up,down,right,turbo) (p0,_,_,(mx,my)) = (p',p' + d,u,(mx',my')) where nil c n = if c then n else zero p' = nil left (v ^* (-t)) + nil up (d ^* t) + nil down (d ^* (-t)) + nil right (v ^* t) + p0 k = if turbo then 500 else 100 t = k * realToFrac dt mx' = dmx-- + mx my' = dmy-- + my rm = rotationEuler $ V3 (-mx' / 100) (-my' / 100) 0 d = rotate rm d0 u = rotate rm u0 v = signorm $ d `cross` u rotationEuler :: V3 Float -> Quaternion Float rotationEuler (V3 a b c) = axisAngle (V3 0 0 1) a * axisAngle (V3 1 0 0) b * axisAngle (V3 0 1 0) (c)
csabahruska/gpipe-quake3
Camera.hs
Haskell
bsd-3-clause
763
{-# LANGUAGE UnicodeSyntax #-} import Prelude.Unicode paths ∷ Eq a ⇒ a → a → [(a, a)] → [[a]] paths source sink edges | source ≡ sink = [[sink]] | otherwise = [[source] ++ path | edge ← edges, (fst edge) ≡ source, path ← (paths (snd edge) sink [e | e ← edges, e ≢ edge]) ]
m00nlight/99-problems
haskell/p-81.hs
Haskell
bsd-3-clause
362
{-# LANGUAGE OverloadedStrings #-} module PersistenceSpec (spec) where import Data.Foldable import Test.Hspec import Test.Hspec.QuickCheck (prop) import Test.QuickCheck.Instances () import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy.Char8 as LBS8 import OrphanInstances () import Store (Modification (..)) import qualified Store spec :: Spec spec = do describe "Store.Modification" $ do prop "does not contain new lines when serialized" $ \op -> let jsonStr = Aeson.encode (op :: Modification) in '\n' `LBS8.notElem` jsonStr prop "round trips serialization" $ \op -> let jsonStr = Aeson.encode (op :: Modification) decoded = Aeson.decode jsonStr in Just op == decoded describe "Journaling" $ do prop "journal is idempotent" $ \ops initial -> let replay value = foldl' (flip Store.applyModification) value (ops :: [Modification]) in replay initial == replay (replay initial)
channable/icepeak
server/tests/PersistenceSpec.hs
Haskell
bsd-3-clause
966
----------------------------------------------------------------------------- -- -- Building info tables. -- -- (c) The University of Glasgow 2004-2006 -- ----------------------------------------------------------------------------- module StgCmmLayout ( mkArgDescr, emitCall, emitReturn, adjustHpBackwards, emitClosureProcAndInfoTable, emitClosureAndInfoTable, slowCall, directCall, mkVirtHeapOffsets, mkVirtConstrOffsets, getHpRelOffset, hpRel, ArgRep(..), toArgRep, argRepSizeW -- re-exported from StgCmmArgRep ) where #include "HsVersions.h" import StgCmmClosure import StgCmmEnv import StgCmmArgRep -- notably: ( slowCallPattern ) import StgCmmTicky import StgCmmMonad import StgCmmUtils import StgCmmProf (curCCS) import MkGraph import SMRep import Cmm import CmmUtils import CmmInfo import CLabel import StgSyn import Id import TyCon ( PrimRep(..) ) import BasicTypes ( RepArity ) import DynFlags import Module import Util import Data.List import Outputable import FastString import Control.Monad ------------------------------------------------------------------------ -- Call and return sequences ------------------------------------------------------------------------ -- | Return multiple values to the sequel -- -- If the sequel is @Return@ -- -- > return (x,y) -- -- If the sequel is @AssignTo [p,q]@ -- -- > p=x; q=y; -- emitReturn :: [CmmExpr] -> FCode ReturnKind emitReturn results = do { dflags <- getDynFlags ; sequel <- getSequel ; updfr_off <- getUpdFrameOff ; case sequel of Return _ -> do { adjustHpBackwards ; let e = CmmLoad (CmmStackSlot Old updfr_off) (gcWord dflags) ; emit (mkReturn dflags (entryCode dflags e) results updfr_off) } AssignTo regs adjust -> do { when adjust adjustHpBackwards ; emitMultiAssign regs results } ; return AssignedDirectly } -- | @emitCall conv fun args@ makes a call to the entry-code of @fun@, -- using the call/return convention @conv@, passing @args@, and -- returning the results to the current sequel. -- emitCall :: (Convention, Convention) -> CmmExpr -> [CmmExpr] -> FCode ReturnKind emitCall convs fun args = emitCallWithExtraStack convs fun args noExtraStack -- | @emitCallWithExtraStack conv fun args stack@ makes a call to the -- entry-code of @fun@, using the call/return convention @conv@, -- passing @args@, pushing some extra stack frames described by -- @stack@, and returning the results to the current sequel. -- emitCallWithExtraStack :: (Convention, Convention) -> CmmExpr -> [CmmExpr] -> [CmmExpr] -> FCode ReturnKind emitCallWithExtraStack (callConv, retConv) fun args extra_stack = do { dflags <- getDynFlags ; adjustHpBackwards ; sequel <- getSequel ; updfr_off <- getUpdFrameOff ; case sequel of Return _ -> do emit $ mkJumpExtra dflags callConv fun args updfr_off extra_stack return AssignedDirectly AssignTo res_regs _ -> do k <- newLabelC let area = Young k (off, _, copyin) = copyInOflow dflags retConv area res_regs [] copyout = mkCallReturnsTo dflags fun callConv args k off updfr_off extra_stack emit (copyout <*> mkLabel k <*> copyin) return (ReturnedTo k off) } adjustHpBackwards :: FCode () -- This function adjusts and heap pointers just before a tail call or -- return. At a call or return, the virtual heap pointer may be less -- than the real Hp, because the latter was advanced to deal with -- the worst-case branch of the code, and we may be in a better-case -- branch. In that case, move the real Hp *back* and retract some -- ticky allocation count. -- -- It *does not* deal with high-water-mark adjustment. -- That's done by functions which allocate heap. adjustHpBackwards = do { hp_usg <- getHpUsage ; let rHp = realHp hp_usg vHp = virtHp hp_usg adjust_words = vHp -rHp ; new_hp <- getHpRelOffset vHp ; emit (if adjust_words == 0 then mkNop else mkAssign hpReg new_hp) -- Generates nothing when vHp==rHp ; tickyAllocHeap False adjust_words -- ...ditto ; setRealHp vHp } ------------------------------------------------------------------------- -- Making calls: directCall and slowCall ------------------------------------------------------------------------- -- General plan is: -- - we'll make *one* fast call, either to the function itself -- (directCall) or to stg_ap_<pat>_fast (slowCall) -- Any left-over arguments will be pushed on the stack, -- -- e.g. Sp[old+8] = arg1 -- Sp[old+16] = arg2 -- Sp[old+32] = stg_ap_pp_info -- R2 = arg3 -- R3 = arg4 -- call f() return to Nothing updfr_off: 32 directCall :: Convention -> CLabel -> RepArity -> [StgArg] -> FCode ReturnKind -- (directCall f n args) -- calls f(arg1, ..., argn), and applies the result to the remaining args -- The function f has arity n, and there are guaranteed at least n args -- Both arity and args include void args directCall conv lbl arity stg_args = do { argreps <- getArgRepsAmodes stg_args ; direct_call "directCall" conv lbl arity argreps } slowCall :: CmmExpr -> [StgArg] -> FCode ReturnKind -- (slowCall fun args) applies fun to args, returning the results to Sequel slowCall fun stg_args = do { dflags <- getDynFlags ; argsreps <- getArgRepsAmodes stg_args ; let (rts_fun, arity) = slowCallPattern (map fst argsreps) ; r <- direct_call "slow_call" NativeNodeCall (mkRtsApFastLabel rts_fun) arity ((P,Just fun):argsreps) ; emitComment $ mkFastString ("slow_call for " ++ showSDoc dflags (ppr fun) ++ " with pat " ++ unpackFS rts_fun) ; return r } -------------- direct_call :: String -> Convention -- e.g. NativeNodeCall or NativeDirectCall -> CLabel -> RepArity -> [(ArgRep,Maybe CmmExpr)] -> FCode ReturnKind direct_call caller call_conv lbl arity args | debugIsOn && real_arity > length args -- Too few args = do -- Caller should ensure that there enough args! pprPanic "direct_call" $ text caller <+> ppr arity <+> ppr lbl <+> ppr (length args) <+> ppr (map snd args) <+> ppr (map fst args) | null rest_args -- Precisely the right number of arguments = emitCall (call_conv, NativeReturn) target (nonVArgs args) | otherwise -- Note [over-saturated calls] = do dflags <- getDynFlags emitCallWithExtraStack (call_conv, NativeReturn) target (nonVArgs fast_args) (nonVArgs (stack_args dflags)) where target = CmmLit (CmmLabel lbl) (fast_args, rest_args) = splitAt real_arity args stack_args dflags = slowArgs dflags rest_args real_arity = case call_conv of NativeNodeCall -> arity+1 _ -> arity -- When constructing calls, it is easier to keep the ArgReps and the -- CmmExprs zipped together. However, a void argument has no -- representation, so we need to use Maybe CmmExpr (the alternative of -- using zeroCLit or even undefined would work, but would be ugly). -- getArgRepsAmodes :: [StgArg] -> FCode [(ArgRep, Maybe CmmExpr)] getArgRepsAmodes = mapM getArgRepAmode where getArgRepAmode arg | V <- rep = return (V, Nothing) | otherwise = do expr <- getArgAmode (NonVoid arg) return (rep, Just expr) where rep = toArgRep (argPrimRep arg) nonVArgs :: [(ArgRep, Maybe CmmExpr)] -> [CmmExpr] nonVArgs [] = [] nonVArgs ((_,Nothing) : args) = nonVArgs args nonVArgs ((_,Just arg) : args) = arg : nonVArgs args {- Note [over-saturated calls] The natural thing to do for an over-saturated call would be to call the function with the correct number of arguments, and then apply the remaining arguments to the value returned, e.g. f a b c d (where f has arity 2) --> r = call f(a,b) call r(c,d) but this entails - saving c and d on the stack - making a continuation info table - at the continuation, loading c and d off the stack into regs - finally, call r Note that since there are a fixed number of different r's (e.g. stg_ap_pp_fast), we can also pre-compile continuations that correspond to each of them, rather than generating a fresh one for each over-saturated call. Not only does this generate much less code, it is faster too. We will generate something like: Sp[old+16] = c Sp[old+24] = d Sp[old+32] = stg_ap_pp_info call f(a,b) -- usual calling convention For the purposes of the CmmCall node, we count this extra stack as just more arguments that we are passing on the stack (cml_args). -} -- | 'slowArgs' takes a list of function arguments and prepares them for -- pushing on the stack for "extra" arguments to a function which requires -- fewer arguments than we currently have. slowArgs :: DynFlags -> [(ArgRep, Maybe CmmExpr)] -> [(ArgRep, Maybe CmmExpr)] slowArgs _ [] = [] slowArgs dflags args -- careful: reps contains voids (V), but args does not | gopt Opt_SccProfilingOn dflags = save_cccs ++ this_pat ++ slowArgs dflags rest_args | otherwise = this_pat ++ slowArgs dflags rest_args where (arg_pat, n) = slowCallPattern (map fst args) (call_args, rest_args) = splitAt n args stg_ap_pat = mkCmmRetInfoLabel rtsPackageId arg_pat this_pat = (N, Just (mkLblExpr stg_ap_pat)) : call_args save_cccs = [(N, Just (mkLblExpr save_cccs_lbl)), (N, Just curCCS)] save_cccs_lbl = mkCmmRetInfoLabel rtsPackageId (fsLit "stg_restore_cccs") ------------------------------------------------------------------------- ---- Laying out objects on the heap and stack ------------------------------------------------------------------------- -- The heap always grows upwards, so hpRel is easy hpRel :: VirtualHpOffset -- virtual offset of Hp -> VirtualHpOffset -- virtual offset of The Thing -> WordOff -- integer word offset hpRel hp off = off - hp getHpRelOffset :: VirtualHpOffset -> FCode CmmExpr getHpRelOffset virtual_offset = do dflags <- getDynFlags hp_usg <- getHpUsage return (cmmRegOffW dflags hpReg (hpRel (realHp hp_usg) virtual_offset)) mkVirtHeapOffsets :: DynFlags -> Bool -- True <=> is a thunk -> [(PrimRep,a)] -- Things to make offsets for -> (WordOff, -- _Total_ number of words allocated WordOff, -- Number of words allocated for *pointers* [(NonVoid a, VirtualHpOffset)]) -- Things with their offsets from start of object in order of -- increasing offset; BUT THIS MAY BE DIFFERENT TO INPUT ORDER -- First in list gets lowest offset, which is initial offset + 1. -- -- Void arguments are removed, so output list may be shorter than -- input list -- -- mkVirtHeapOffsets always returns boxed things with smaller offsets -- than the unboxed things mkVirtHeapOffsets dflags is_thunk things = let non_void_things = filterOut (isVoidRep . fst) things (ptrs, non_ptrs) = partition (isGcPtrRep . fst) non_void_things (wds_of_ptrs, ptrs_w_offsets) = mapAccumL computeOffset 0 ptrs (tot_wds, non_ptrs_w_offsets) = mapAccumL computeOffset wds_of_ptrs non_ptrs in (tot_wds, wds_of_ptrs, ptrs_w_offsets ++ non_ptrs_w_offsets) where hdr_size | is_thunk = thunkHdrSize dflags | otherwise = fixedHdrSize dflags computeOffset wds_so_far (rep, thing) = (wds_so_far + argRepSizeW dflags (toArgRep rep), (NonVoid thing, hdr_size + wds_so_far)) mkVirtConstrOffsets :: DynFlags -> [(PrimRep,a)] -> (WordOff, WordOff, [(NonVoid a, VirtualHpOffset)]) -- Just like mkVirtHeapOffsets, but for constructors mkVirtConstrOffsets dflags = mkVirtHeapOffsets dflags False ------------------------------------------------------------------------- -- -- Making argument descriptors -- -- An argument descriptor describes the layout of args on the stack, -- both for * GC (stack-layout) purposes, and -- * saving/restoring registers when a heap-check fails -- -- Void arguments aren't important, therefore (contrast constructSlowCall) -- ------------------------------------------------------------------------- -- bring in ARG_P, ARG_N, etc. #include "../includes/rts/storage/FunTypes.h" mkArgDescr :: DynFlags -> [Id] -> ArgDescr mkArgDescr dflags args = let arg_bits = argBits dflags arg_reps arg_reps = filter isNonV (map idArgRep args) -- Getting rid of voids eases matching of standard patterns in case stdPattern arg_reps of Just spec_id -> ArgSpec spec_id Nothing -> ArgGen arg_bits argBits :: DynFlags -> [ArgRep] -> [Bool] -- True for non-ptr, False for ptr argBits _ [] = [] argBits dflags (P : args) = False : argBits dflags args argBits dflags (arg : args) = take (argRepSizeW dflags arg) (repeat True) ++ argBits dflags args ---------------------- stdPattern :: [ArgRep] -> Maybe Int stdPattern reps = case reps of [] -> Just ARG_NONE -- just void args, probably [N] -> Just ARG_N [P] -> Just ARG_P [F] -> Just ARG_F [D] -> Just ARG_D [L] -> Just ARG_L [V16] -> Just ARG_V16 [V32] -> Just ARG_V32 [V64] -> Just ARG_V64 [N,N] -> Just ARG_NN [N,P] -> Just ARG_NP [P,N] -> Just ARG_PN [P,P] -> Just ARG_PP [N,N,N] -> Just ARG_NNN [N,N,P] -> Just ARG_NNP [N,P,N] -> Just ARG_NPN [N,P,P] -> Just ARG_NPP [P,N,N] -> Just ARG_PNN [P,N,P] -> Just ARG_PNP [P,P,N] -> Just ARG_PPN [P,P,P] -> Just ARG_PPP [P,P,P,P] -> Just ARG_PPPP [P,P,P,P,P] -> Just ARG_PPPPP [P,P,P,P,P,P] -> Just ARG_PPPPPP _ -> Nothing ------------------------------------------------------------------------- -- -- Generating the info table and code for a closure -- ------------------------------------------------------------------------- -- Here we make an info table of type 'CmmInfo'. The concrete -- representation as a list of 'CmmAddr' is handled later -- in the pipeline by 'cmmToRawCmm'. -- When loading the free variables, a function closure pointer may be tagged, -- so we must take it into account. emitClosureProcAndInfoTable :: Bool -- top-level? -> Id -- name of the closure -> LambdaFormInfo -> CmmInfoTable -> [NonVoid Id] -- incoming arguments -> ((Int, LocalReg, [LocalReg]) -> FCode ()) -- function body -> FCode () emitClosureProcAndInfoTable top_lvl bndr lf_info info_tbl args body = do { dflags <- getDynFlags -- Bind the binder itself, but only if it's not a top-level -- binding. We need non-top let-bindings to refer to the -- top-level binding, which this binding would incorrectly shadow. ; node <- if top_lvl then return $ idToReg dflags (NonVoid bndr) else bindToReg (NonVoid bndr) lf_info ; let node_points = nodeMustPointToIt dflags lf_info ; arg_regs <- bindArgsToRegs args ; let args' = if node_points then (node : arg_regs) else arg_regs conv = if nodeMustPointToIt dflags lf_info then NativeNodeCall else NativeDirectCall (offset, _, _) = mkCallEntry dflags conv args' [] ; emitClosureAndInfoTable info_tbl conv args' $ body (offset, node, arg_regs) } -- Data constructors need closures, but not with all the argument handling -- needed for functions. The shared part goes here. emitClosureAndInfoTable :: CmmInfoTable -> Convention -> [LocalReg] -> FCode () -> FCode () emitClosureAndInfoTable info_tbl conv args body = do { blks <- getCode body ; let entry_lbl = toEntryLbl (cit_lbl info_tbl) ; emitProcWithConvention conv (Just info_tbl) entry_lbl args blks }
ekmett/ghc
compiler/codeGen/StgCmmLayout.hs
Haskell
bsd-3-clause
16,801
{-# LANGUAGE DataKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeOperators #-} import Data.Functor.Identity import Data.Proxy import Data.Vinyl import Diagrams.Backend.SVG import Diagrams.Backend.SVG.CmdLine import Diagrams.Prelude hiding ((:&)) -- import Graphite -- import Graphite.Diagrams import Graphite.Types (Graphite) import qualified Graphite.Combinators as Graphite import Diagrams.Graph.Combinators import Control.Arrow -- import StackedBarGraph main :: IO () -- main = mainWith $ sideBySideAxis main = mainWith $ (pad 1.2 $ centerXY $ Graphite.build (allAges :& allGenders :& RNil) funcData2 graphC) -- === -- (pad 1.2 $ centerXY $ build (allGenders :& allAges :& RNil) (funcData2 . rcast) graphD) -- main = mainWith $ pad 1.4 $ centerXY $ showOrigin $ build (allGenders :& RNil) funcDataGender graphB test :: Diagram B test = hcat (replicate 5 myRect) # center # showOrigin myRect :: Diagram B myRect = rect 44 66 # padX 1.1 -- graphA :: Graphite Int (Diagram B) '[] '[Gender] -- graphA = id -- $ sideBySideAxis 1.2 show -- $ bar 10 fromIntegral -- -- graphB :: Graphite Int (Diagram B) '[] '[Gender] -- graphB = id -- $ sideBySide 0 -- -- $ barTopLabel 10 fromIntegral (show . runIdentity . rget (Proxy :: Proxy Gender)) -- $ liftFigureChange (lineOnBottom . padX 1.1) -- $ labelTop (show . runIdentity . rget (Proxy :: Proxy Gender)) -- $ bar 10 fromIntegral graphC :: Graphite Int (Diagram B) '[] '[Age,Gender] graphC = id $ Graphite.figure (\_ _ ds -> let d = alignL (hcat ds) in mappend d $ alignBL $ createYAxis (width d) 0 3 12 fromIntegral show (lc (blend 0.3 white purple) . lw thin . dashingG [0.7,0.7] 0) id ) $ Graphite.pop $ Graphite.figure (\r _ d -> let age = runIdentity $ rget (Proxy :: Proxy Age) r in d & hsep 0 . map alignB & center & padX 1.1 & lineOnBottom & besideText unit_Y (show age) ) $ Graphite.pop $ Graphite.figure (\r _ d -> let gender = runIdentity $ rget (Proxy :: Proxy Gender) r in d & fc (genderColour gender) & besideText unitY (show gender) & center & padX 1.1 & fontSizeL 2 ) $ Graphite.start' (\res -> rect 10 (fromIntegral res)) -- graphD :: Graphite Int (Diagram B) '[] '[Gender, Age] -- graphD = id -- $ liftFigureChange (\fig -> mappend fig $ lw thin $ lineOnRight (createYAxis 1.0 0 3 12 fromIntegral show (lw thin))) -- -- $ liftFigureChange -- -- (\f -> mappend f (alignBL $ createYAxis (width f) 0 3 12 fromIntegral show -- -- (lc (blend 0.3 white purple) . lw thin . dashingG [0.7,0.7] 0) -- -- )) -- $ modifyFigureFull -- (\r l fig -> mappend fig $ -- createXAxis 1.0 10.0 (rget (Proxy :: Proxy Age) l) show (lw thin) -- ) -- $ modifyFigureFull -- (\r l fig -> mappend fig -- $ lw thin -- $ horizontalLine (10.0 * fromIntegral (length (rget (Proxy :: Proxy Age) l) - 1)) -- ) -- $ overlapped -- -- $ modifyFigure (\r -> lc $ darken 0.6 $ genderColour $ runIdentity $ rget (Proxy :: Proxy Gender) r) -- $ connected 10.0 -- -- $ modifyFigure (\r -> first $ fc $ genderColour $ runIdentity $ rget (Proxy :: Proxy Gender) r) -- $ singlePoint 1 fromIntegral data Gender = Male | Female | Unknown deriving (Eq,Ord,Bounded,Enum,Show) data Age = Young | Middle | Old | VeryOld deriving (Eq,Ord,Bounded,Enum,Show) allAges :: [Age] allAges = enumFromTo minBound maxBound allGenders :: [Gender] allGenders = enumFromTo minBound maxBound genderColour :: Gender -> Colour Double genderColour g = case g of Male -> blue Female -> magenta Unknown -> grey -- myGraphA,myGraphB :: Graphite '[Age,Gender] Int -- myGraphA = intervals 16 allAges $ grouped 1 allGenders $ bar fromIntegral 4 id -- myGraphB = id -- $ intervalsWithAxis 16 show (zip allAges (repeat id)) -- -- $ stacked allGenders -- $ stackedWith [ (Male,fc purple . atop (text "Male" & fontSizeL 2 & fc white)) -- , (Female, fc blue . atop (text "Female" & fontSizeL 2 & fc white)) -- , (Unknown, fc green . atop (text "N/A" & fontSizeL 2 & fc white)) -- ] -- $ bar fromIntegral 6.0 id -- -- myGraphC :: Graphite '[Gender] Int -- myGraphC = intervals 16 allGenders $ bar fromIntegral 4.0 (fc blue) -- -- myGraphD :: Graphite '[Gender] Int -- myGraphD = lineGraph fromIntegral 16.0 allGenders (fc blue) funcDataGender :: Rec Identity '[Gender] -> Int funcDataGender (Identity gender :& RNil) = case gender of Male -> 11 Female -> 14 Unknown -> 2 funcData :: Rec Identity '[Age,Gender] -> Int funcData (Identity age :& Identity gender :& RNil) = fAge age * fGender gender where fAge Young = 6 fAge Middle = 7 fAge Old = 8 fGender Male = 4 fGender Female = 5 fGender Unknown = 1 funcData2 :: Rec Identity '[Age,Gender] -> Int funcData2 (Identity age :& Identity gender :& RNil) = case age of Young -> case gender of Male -> 18 Female -> 16 Unknown -> 30 Middle -> case gender of Male -> 12 Female -> 18 Unknown -> 22 Old -> case gender of Male -> 4 Female -> 26 Unknown -> 20 VeryOld -> case gender of Male -> 2 Female -> 22 Unknown -> 10 -- myGraphE :: Graphite (Diagram B) r '[Gender] Int -- myGraphE = stacked id $ bar 4.0 -- -- myGraphF :: Graphite (Diagram B) r '[Age,Gender] Int -- myGraphF = paddedBy 12.0 id $ stacked id $ barColoured 4.0 genderColour -- -- myGraphH :: Graphite (Diagram B) r '[Gender] Int -- myGraphH = connected 4 $ gvalue -- -- myGraphI :: Graphite (Diagram B) r '[Age,Gender] Int -- myGraphI = overlapped $ connected 16.0 $ gvalue -- -- myGraphJ :: Graphite (Diagram B) r '[Age,Gender] Int -- myGraphJ = id -- -- $ overlapped -- $ connectedFiguresMany 16.0 -- $ figureAt (\val gender -> mconcat -- [ text (show val) -- , hexagon 1.0 # fc (genderColour gender) -- ] -- ) -- -- myGraphK :: Graphite (Diagram B) r '[Gender,Age] Int -- myGraphK = id -- -- $ overlapped -- $ connectedFiguresMany 16.0 -- $ figureAt (\val _ -> mconcat -- [ text (show val) -- , hexagon 1.0 -- ] -- ) -- -- myGraphL :: Graphite (Diagram B) r '[Age,Gender] Int -- myGraphL = id -- $ yAxisFromZero HorizontalRight 10 4 (*) show -- $ xAxisFromZero HorizontalRight show -- $ graphiteCast (Proxy :: Proxy '[Gender,Age]) (Proxy :: Proxy '[Age,Gender]) -- $ overlapped -- $ basicConnectedFigures -- (\g v a -> mconcat [text (show a) & fc white & fontSize 10, hexagon 2.0 & fc (genderColour g)]) -- (\g -> connectOutside' (with { _arrowHead = noHead, _shaftStyle = lc purple mempty} )) -- padX :: (Metric v, OrderedField n, Monoid' m, R2 v) -- => n -> QDiagram b v n m -> QDiagram b v n m -- padX s d = withEnvelope (d # scaleX s) d -- main = mainWith $ showOrigin $ runGraphite myGraphH fromIntegral funcDataGender (allGenders :& RNil) () -- main = mainWith $ showOrigin $ runGraphite myGraphF fromIntegral funcData2 (allAges :& allGenders :& RNil) () -- main = mainWith $ pad 1.3 $ centerXY $ showOrigin -- $ runGraphite myGraphL (\i -> fromIntegral i * 2) (funcData2 . rcast) -- (rcast $ allAges :& allGenders :& RNil) () -- ( build myGraphA funcData -- === -- axisX 16 (map show allAges) -- === -- square 4 -- ) ||| -- ( axisY 16 ["1","2","3","4","5"] ||| build myGraphB funcData) ||| -- ( build myGraphD funcDataGender -- === -- axisX 16 (map show allGenders) -- === -- square 4 -- )
andrewthad/graphite
example/main.hs
Haskell
bsd-3-clause
7,763
module Main where import System.Console.Haskeline import System.IO import System.Environment import System.Exit import System.FilePath ((</>), addTrailingPathSeparator) import Data.Maybe import Data.Version import Control.Monad.Trans.Error ( ErrorT(..) ) import Control.Monad.Trans.State.Strict ( execStateT, get, put ) import Control.Monad ( when ) import Idris.Core.TT import Idris.Core.Typecheck import Idris.Core.Evaluate import Idris.Core.Constraints import Idris.AbsSyntax import Idris.Parser import Idris.REPL import Idris.ElabDecls import Idris.Primitives import Idris.Imports import Idris.Error import IRTS.System ( getLibFlags, getIdrisLibDir, getIncFlags ) import Util.DynamicLinker import Pkg.Package import Paths_idris -- Main program reads command line options, parses the main program, and gets -- on with the REPL. main = do xs <- getArgs let opts = parseArgs xs result <- runErrorT $ execStateT (runIdris opts) idrisInit case result of Left err -> putStrLn $ "Uncaught error: " ++ show err Right _ -> return () runIdris :: [Opt] -> Idris () runIdris [Client c] = do setVerbose False setQuiet True runIO $ runClient c runIdris opts = do when (Ver `elem` opts) $ runIO showver when (Usage `elem` opts) $ runIO usage when (ShowIncs `elem` opts) $ runIO showIncs when (ShowLibs `elem` opts) $ runIO showLibs when (ShowLibdir `elem` opts) $ runIO showLibdir case opt getPkgCheck opts of [] -> return () fs -> do runIO $ mapM_ (checkPkg (WarnOnly `elem` opts)) fs runIO $ exitWith ExitSuccess case opt getPkgClean opts of [] -> return () fs -> do runIO $ mapM_ cleanPkg fs runIO $ exitWith ExitSuccess case opt getPkg opts of [] -> idrisMain opts -- in Idris.REPL fs -> runIO $ mapM_ (buildPkg (WarnOnly `elem` opts)) fs usage = do putStrLn usagemsg exitWith ExitSuccess showver = do putStrLn $ "Idris version " ++ ver exitWith ExitSuccess showLibs = do libFlags <- getLibFlags putStrLn libFlags exitWith ExitSuccess showLibdir = do dir <- getIdrisLibDir putStrLn dir exitWith ExitSuccess showIncs = do incFlags <- getIncFlags putStrLn incFlags exitWith ExitSuccess usagemsghdr = "Idris version " ++ ver ++ ", (C) The Idris Community 2014" usagemsg = usagemsghdr ++ "\n" ++ map (\x -> '-') usagemsghdr ++ "\n" ++ "idris [OPTIONS] [FILE]\n\n" ++ "Common flags:\n" ++ "\t --install=IPKG Install package\n" ++ "\t --clean=IPKG Clean package\n" ++ "\t --build=IPKG Build package\n" ++ "\t --exec=EXPR Execute as idris\n" ++ "\t --libdir Display library directory\n" ++ "\t --link Display link directory\n" ++ "\t --include Display the includes directory\n" ++ "\t --nobanner Suppress the banner\n" ++ "\t --color, --colour Force coloured output\n" ++ "\t --nocolor, --nocolour Disable coloured output\n" ++ "\t --errorcontent Undocumented\n" ++ "\t --nocoverage Undocumented\n" ++ "\t -o --output=FILE Specify output file\n" ++ "\t --check Undocumented\n" ++ "\t --total Require functions to be total by default\n" ++ "\t --partial Undocumented\n" ++ "\t --warnpartial Warn about undeclared partial functions.\n" ++ "\t --warn Undocumented\n" ++ "\t --typecase Undocumented\n" ++ "\t --typeintype Undocumented\n" ++ "\t --nobasepkgs Undocumented\n" ++ "\t --noprelude Undocumented\n" ++ "\t --nobuiltins Undocumented\n" ++ "\t -O --level=LEVEL Undocumented\n" ++ "\t -i --idrispath=DIR Add directory to the list of import paths\n" ++ "\t --package=ITEM Undocumented\n" ++ "\t --ibcsubdir=FILE Write IBC files into sub directory\n" ++ "\t --codegen=TARGET Select code generator: C, Java, bytecode,\n" ++ "\t javascript, node, or llvm\n" ++ "\t --mvn Create a maven project (for Java codegen)\n" ++ "\t --cpu=CPU Select tartget CPU e.g. corei7 or cortex-m3\n" ++ "\t (for LLVM codegen)\n" ++ "\t --target=TRIPLE Select target triple (for llvm codegen)\n" ++ "\t -S --codegenonly Do no further compilation of code generator output\n" ++ "\t -c --compileonly Compile to object files rather than an executable\n" ++ "\t -X --extension=ITEM Undocumented\n" ++ "\t --dumpdefuns Undocumented\n" ++ "\t --dumpcases Undocumented\n" ++ "\t --log=LEVEL --loglevel Debugging log level\n" ++ "\t --ideslave Undocumented\n" ++ "\t --client Undocumented\n" ++ "\t -h --help Display help message\n" ++ "\t -v --version Print version information\n" ++ "\t -V --verbose Loud verbosity\n" ++ "\t -q --quiet Quiet verbosity\n"
ctford/Idris-Elba-dev
main/Main.hs
Haskell
bsd-3-clause
5,886
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} module Test.Ambiata.Cli where import qualified Data.Text as T import P import System.IO import Turtle testShell :: [Text] -> Shell Text -> IO (ExitCode, Text) testShell args = shellStrict args' where args' = T.intercalate " " args testShell' :: [Text] -> IO (ExitCode, Text) testShell' = flip testShell empty
ambiata/tatooine-cli
test/Test/Ambiata/Cli.hs
Haskell
apache-2.0
429
<?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="si-LK"> <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>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_si_LK/helpset_si_LK.hs
Haskell
apache-2.0
973
-- |Make URI an instance of Read and Ord, and add functions to -- manipulate the uriQuery. module Extra.URI ( module Network.URI , relURI , setURIPort , parseURIQuery , modifyURIQuery , setURIQuery , setURIQueryAttr , deleteURIQueryAttr ) where import Network.URI -- (URIAuth(..), URI(..), parseURI, uriToString, escapeURIString, isUnreserved, unEscapeString) import Data.List(intersperse, groupBy, inits) import Data.Maybe(isJust, isNothing, catMaybes) import Control.Arrow(second) -- |Create a relative URI with the given query. relURI :: FilePath -> [(String, String)] -> URI relURI path pairs = URI {uriScheme = "", uriAuthority = Nothing, uriPath = path, uriQuery = formatURIQuery pairs, uriFragment = ""} -- |Set the port number in the URI authority, creating it if necessary. setURIPort port uri = uri {uriAuthority = Just auth'} where auth' = auth {uriPort = port} auth = maybe nullAuth id (uriAuthority uri) nullAuth = URIAuth {uriUserInfo = "", uriRegName = "", uriPort = ""} -- |Return the pairs in a URI's query parseURIQuery :: URI -> [(String, String)] parseURIQuery uri = case uriQuery uri of "" -> [] '?' : attrs -> map (second (unEscapeString . tail) . break (== '=')) (filter (/= "&") (groupBy (\ a b -> a /= '&' && b /= '&') attrs)) x -> error $ "Invalid URI query: " ++ x -- |Modify a URI's query by applying a function to the pairs modifyURIQuery :: ([(String, String)] -> [(String, String)]) -> URI -> URI modifyURIQuery f uri = uri {uriQuery = formatURIQuery (f (parseURIQuery uri))} setURIQuery :: [(String, String)] -> URI -> URI setURIQuery pairs = modifyURIQuery (const pairs) setURIQueryAttr :: String -> String -> URI -> URI setURIQueryAttr name value uri = modifyURIQuery f uri where f pairs = (name, value) : filter ((/= name) . fst) pairs deleteURIQueryAttr :: String -> URI -> URI deleteURIQueryAttr name uri = modifyURIQuery f uri where f pairs = filter ((/= name) . fst) pairs -- |Turn a list of attribute value pairs into a uriQuery. formatURIQuery :: [(String, String)] -> String formatURIQuery [] = "" formatURIQuery attrs = '?' : concat (intersperse "&" (map (\ (a, b) -> a ++ "=" ++ escapeURIForQueryValue b) attrs)) -- |Escape a value so it can safely appear on the RHS of an element of -- the URI query. The isUnreserved predicate is the set of characters -- that can appear in a URI which don't have any special meaning. -- Everything else gets escaped. escapeURIForQueryValue = escapeURIString isUnreserved -- Make URI an instance of Read. This will throw an error if no -- prefix up to ten characters long of the argument string looks like -- a URI. If such a prefix is found, it will continue trying longer -- and longer prefixes until the result no longer looks like a URI. instance Read URI where readsPrec _ s = let allURIs = map parseURI (inits s) in -- If nothing in the first ten characters looks like a URI, give up case catMaybes (take 10 allURIs) of [] -> fail "read URI: no parse" -- Return the last element that still looks like a URI _ -> [(longestURI, drop (length badURIs + length goodURIs - 1) s)] where longestURI = case reverse (catMaybes goodURIs) of [] -> error $ "Invalid URI: " ++ s (a : _) -> a goodURIs = takeWhile isJust moreURIs (badURIs, moreURIs) = span isNothing allURIs
eigengrau/haskell-extra
Extra/URI.hs
Haskell
bsd-3-clause
3,659
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} module Main where import Headings import PropertyDrawer import Test.Tasty import Timestamps import Document main :: IO () main = defaultMain tests tests :: TestTree tests = testGroup "OrgMode Parser Tests" [ parserHeadingTests , parserPropertyDrawerTests , parserTimestampTests , parserSmallDocumentTests , parserWeekdayTests ]
imalsogreg/orgmode-parse
test/Test.hs
Haskell
bsd-3-clause
522
data BinaryTree a = Node a (BinaryTree a) (BinaryTree a) | Empty createTree :: Int -> [[Int]] -> BinaryTree Int createTree n arr = head subtrees where subtrees = [getSubtree x | x <- [0..n - 1]] getSubtree x = (\[l, r] -> Node (x + 1) l r) . map (\x -> if x == -1 then Empty else subtrees !! (x - 1)) $ arr !! x swapTree :: Int -> BinaryTree Int -> BinaryTree Int swapTree k = swap 1 where swap _ Empty = Empty swap h (Node x l r) | h `rem` k == 0 = Node x (swap (h + 1) r) (swap (h + 1) l) | otherwise = Node x (swap (h + 1) l) (swap (h + 1) r) inorder :: BinaryTree Int -> [Int] inorder Empty = [] inorder (Node x l r) = inorder l ++ [x] ++ inorder r solve :: [Int] -> BinaryTree Int -> IO () solve [] tree = return () solve (k:ks) tree = putStrLn (unwords . map show . inorder $ ans) >> solve ks ans where ans = swapTree k tree validate :: [[Int]] -> IO () validate ([n]:rest) = solve k tree where (arr, t:k) = (\(f, s) -> (f, concat s)) . splitAt n $ rest tree = createTree n arr main :: IO () main = getContents >>= validate . map (map read . words) . lines
EdisonAlgorithms/HackerRank
practice/fp/ds/swap-nodes/swap-nodes.hs
Haskell
mit
1,189
{-# LANGUAGE CPP #-} module Main where import HList rev :: [a] -> [a] rev [] = [] rev (y:ys) = rev ys ++ [y] main :: IO () main = print $ rev [1..10] -- Should be in the "List" module {-# RULES "++ []" forall xs . xs ++ [] = xs #-} {-# RULES "++ strict" (++) undefined = undefined #-} -- The "Algebra" for repH {-# RULES "repH ++" forall xs ys . repH (xs ++ ys) = repH xs . repH ys #-} {-# RULES "repH []" repH [] = id #-} {-# RULES "repH (:)" forall x xs . repH (x:xs) = ((:) x) . repH xs #-}
beni55/hermit
examples/concatVanishes/Rev.hs
Haskell
bsd-2-clause
571
{-# LANGUAGE OverloadedStrings #-} module Bead.View.Content.Assignment.Page ( newGroupAssignment , newCourseAssignment , modifyAssignment , viewAssignment , newGroupAssignmentPreview , newCourseAssignmentPreview , modifyAssignmentPreview ) where import Control.Monad.Error import qualified Data.Map as Map import Data.Time (getCurrentTime) import qualified Bead.Controller.UserStories as S import qualified Bead.Domain.Entity.Assignment as Assignment import Bead.View.Content import Bead.View.ContentHandler (getJSONParameters) import Bead.View.RequestParams import Bead.View.Content.Assignment.Data import Bead.View.Content.Assignment.View import Bead.View.Fay.Hooks -- * Content Handlers newCourseAssignment = ViewModifyHandler newCourseAssignmentPage postCourseAssignment newGroupAssignment = ViewModifyHandler newGroupAssignmentPage postGroupAssignment modifyAssignment = ViewModifyHandler modifyAssignmentPage postModifyAssignment viewAssignment = ViewHandler viewAssignmentPage newCourseAssignmentPreview = UserViewHandler newCourseAssignmentPreviewPage newGroupAssignmentPreview = UserViewHandler newGroupAssignmentPreviewPage modifyAssignmentPreview = UserViewHandler modifyAssignmentPreviewPage -- * Course Assignment newCourseAssignmentPage :: GETContentHandler newCourseAssignmentPage = do ck <- getParameter (customCourseKeyPrm courseKeyParamName) (c, tss, ufs) <- userStory $ do S.isAdministratedCourse ck (course, _groupKeys) <- S.loadCourse ck tss' <- S.testScriptInfosOfCourse ck ufs <- map fst <$> S.listUsersFiles return ((ck, course), nonEmptyList tss', ufs) now <- liftIO $ getCurrentTime tz <- userTimeZoneToLocalTimeConverter return $ newAssignmentContent $ PD_Course tz now c tss ufs postCourseAssignment :: POSTContentHandler postCourseAssignment = do CreateCourseAssignment <$> getParameter (customCourseKeyPrm (fieldName selectedCourse)) <*> getAssignment <*> readTCCreation newCourseAssignmentPreviewPage :: ViewPOSTContentHandler newCourseAssignmentPreviewPage = do ck <- getParameter (customCourseKeyPrm courseKeyParamName) assignment <- getAssignment tc <- readTCCreationParameters (c, tss, ufs) <- userStory $ do S.isAdministratedCourse ck (course, _groupKeys) <- S.loadCourse ck tss' <- S.testScriptInfosOfCourse ck ufs <- map fst <$> S.listUsersFiles return ((ck, course), nonEmptyList tss', ufs) now <- liftIO $ getCurrentTime tz <- userTimeZoneToLocalTimeConverter return $ newAssignmentContent $ PD_Course_Preview tz now c tss ufs assignment tc -- Tries to create a TCCreation descriptive value. If the test script, usersfile and testcase -- parameters are included returns Just tccreation otherwise Nothing readTCCreation :: ContentHandler TCCreation readTCCreation = do (mTestScript, mZippedTestCaseName, mPlainTestCase) <- readTCCreationParameters case tcCreation mTestScript mZippedTestCaseName mPlainTestCase of Left e -> throwError . strMsg $ "Some error in test case parameters " ++ e Right tc -> return tc readTCCreationParameters :: ContentHandler TCCreationParameters readTCCreationParameters = do mTestScript <- getOptionalParameter (jsonParameter (fieldName assignmentTestScriptField) "Test Script") mZippedTestCaseName <- getOptionalOrNonEmptyParameter (jsonParameter (fieldName assignmentUsersFileField) "Test Script File") mPlainTestCase <- getOptionalParameter (stringParameter (fieldName assignmentTestCaseField) "Test Script") return (mTestScript, mZippedTestCaseName, mPlainTestCase) tcCreation :: Maybe (Maybe TestScriptKey) -> Maybe UsersFile -> Maybe String -> Either String TCCreation tcCreation Nothing _ _ = Right NoCreation tcCreation (Just Nothing) _ _ = Right NoCreation tcCreation (Just (Just tsk)) (Just uf) _ = Right $ FileCreation tsk uf tcCreation (Just (Just tsk)) _ (Just t) = Right $ TextCreation tsk t tcCreation (Just (Just _tsk)) Nothing Nothing = Left "#1" readTCModificationParameters :: ContentHandler TCModificationParameters readTCModificationParameters = do mTestScript <- getOptionalParameter (jsonParameter (fieldName assignmentTestScriptField) "Test Script") mZippedTestCaseName <- getOptionalOrNonEmptyParameter (jsonParameter (fieldName assignmentUsersFileField) "Test Script File") mPlainTestCase <- getOptionalParameter (stringParameter (fieldName assignmentTestCaseField) "Test Script") return (mTestScript,mZippedTestCaseName,mPlainTestCase) readTCModification :: ContentHandler TCModification readTCModification = do (mTestScript,mZippedTestCaseName,mPlainTestCase) <- readTCModificationParameters case tcModification mTestScript mZippedTestCaseName mPlainTestCase of Nothing -> throwError $ strMsg "Some error in test case parameters" Just tm -> return tm tcModification :: Maybe (Maybe TestScriptKey) -> Maybe (Either () UsersFile) -> Maybe String -> Maybe TCModification tcModification Nothing _ _ = Just NoModification tcModification (Just Nothing) _ _ = Just TCDelete tcModification (Just (Just _tsk)) (Just (Left ())) _ = Just NoModification tcModification (Just (Just tsk)) (Just (Right uf)) _ = Just $ FileOverwrite tsk uf tcModification (Just (Just tsk)) _ (Just t) = Just $ TextOverwrite tsk t tcModification _ _ _ = Nothing -- * Group Assignment newGroupAssignmentPage :: GETContentHandler newGroupAssignmentPage = do now <- liftIO $ getCurrentTime gk <- getParameter (customGroupKeyPrm groupKeyParamName) (g,tss,ufs) <- userStory $ do S.isAdministratedGroup gk group <- S.loadGroup gk tss' <- S.testScriptInfosOfGroup gk ufs <- map fst <$> S.listUsersFiles return ((gk, group), nonEmptyList tss', ufs) tz <- userTimeZoneToLocalTimeConverter return $ newAssignmentContent $ PD_Group tz now g tss ufs postGroupAssignment :: POSTContentHandler postGroupAssignment = do CreateGroupAssignment <$> getParameter (customGroupKeyPrm (fieldName selectedGroup)) <*> getAssignment <*> readTCCreation newGroupAssignmentPreviewPage :: ViewPOSTContentHandler newGroupAssignmentPreviewPage = do gk <- getParameter (customGroupKeyPrm groupKeyParamName) assignment <- getAssignment tc <- readTCCreationParameters (g,tss,ufs) <- userStory $ do S.isAdministratedGroup gk group <- S.loadGroup gk tss' <- S.testScriptInfosOfGroup gk ufs <- map fst <$> S.listUsersFiles return ((gk, group), nonEmptyList tss', ufs) tz <- userTimeZoneToLocalTimeConverter now <- liftIO $ getCurrentTime return $ newAssignmentContent $ PD_Group_Preview tz now g tss ufs assignment tc -- * Modify Assignment modifyAssignmentPage :: GETContentHandler modifyAssignmentPage = do ak <- getAssignmentKey (as,tss,ufs,tc,ev) <- userStory $ do S.isAdministratedAssignment ak as <- S.loadAssignment ak tss' <- S.testScriptInfosOfAssignment ak ufs <- map fst <$> S.listUsersFiles tc <- S.testCaseOfAssignment ak ev <- not <$> S.isThereASubmission ak return (as, nonEmptyList tss', ufs, tc, ev) tz <- userTimeZoneToLocalTimeConverter return $ newAssignmentContent $ PD_Assignment tz ak as tss ufs tc ev postModifyAssignment :: POSTContentHandler postModifyAssignment = do ModifyAssignment <$> getAssignmentKey <*> getAssignment <*> readTCModification modifyAssignmentPreviewPage :: ViewPOSTContentHandler modifyAssignmentPreviewPage = do ak <- getAssignmentKey as <- getAssignment tm <- readTCModificationParameters (tss,ufs,tc,ev) <- userStory $ do S.isAdministratedAssignment ak tss' <- S.testScriptInfosOfAssignment ak ufs <- map fst <$> S.listUsersFiles tc <- S.testCaseOfAssignment ak ev <- not <$> S.isThereASubmission ak return (nonEmptyList tss', ufs, tc, ev) tz <- userTimeZoneToLocalTimeConverter return $ newAssignmentContent $ PD_Assignment_Preview tz ak as tss ufs tc tm ev viewAssignmentPage :: GETContentHandler viewAssignmentPage = do ak <- getAssignmentKey (as,tss,tc) <- userStory $ do S.isAdministratedAssignment ak as <- S.loadAssignment ak tss' <- S.testScriptInfosOfAssignment ak ts <- S.testCaseOfAssignment ak return (as, tss', ts) tz <- userTimeZoneToLocalTimeConverter let ti = do (_tck, _tc, tsk) <- tc Map.lookup tsk $ Map.fromList tss return $ newAssignmentContent $ PD_ViewAssignment tz ak as ti tc -- * Helpers -- | Returns Nothing if the given list was empty, otherwise Just list nonEmptyList [] = Nothing nonEmptyList xs = Just xs -- Get Assignment Value getAssignment = do converter <- userTimeZoneToUTCTimeConverter startDate <- converter <$> getParameter assignmentStartPrm endDate <- converter <$> getParameter assignmentEndPrm when (endDate < startDate) . throwError $ strMsg "The assignment starts later than it ends" pwd <- getParameter (stringParameter (fieldName assignmentPwdField) "Password") noOfTries <- getParameter (stringParameter (fieldName assignmentNoOfTriesField) "Number of tries") asp <- Assignment.aspectsFromList <$> getJSONParameters (fieldName assignmentAspectField) "Aspect parameter" stype <- getJSONParam (fieldName assignmentSubmissionTypeField) "Submission type" let asp1 = if stype == Assignment.TextSubmission then Assignment.clearZippedSubmissions asp else Assignment.setZippedSubmissions asp let asp2 = if Assignment.isPasswordProtected asp1 then Assignment.setPassword pwd asp1 else asp1 let asp3 = if Assignment.isNoOfTries asp2 then Assignment.setNoOfTries (read noOfTries) asp2 else asp2 Assignment.assignmentAna (getParameter (stringParameter (fieldName assignmentNameField) "Name")) (getParameter (stringParameter (fieldName assignmentDescField) "Description")) (return asp3) (return startDate) (return endDate) (getParameter (evalConfigPrm assignmentEvTypeHook)) getAssignmentKey = getParameter assignmentKeyPrm
pgj/bead
src/Bead/View/Content/Assignment/Page.hs
Haskell
bsd-3-clause
10,185
{-# LANGUAGE OverloadedStrings #-} module Yesod.Form.I18n.Japanese where import Yesod.Form.Types (FormMessage (..)) import Data.Monoid (mappend) import Data.Text (Text) japaneseFormMessage :: FormMessage -> Text japaneseFormMessage (MsgInvalidInteger t) = "無効な整数です: " `Data.Monoid.mappend` t japaneseFormMessage (MsgInvalidNumber t) = "無効な数値です: " `mappend` t japaneseFormMessage (MsgInvalidEntry t) = "無効な入力です: " `mappend` t japaneseFormMessage MsgInvalidTimeFormat = "無効な時刻です。HH:MM[:SS]フォーマットで入力してください" japaneseFormMessage MsgInvalidDay = "無効な日付です。YYYY-MM-DDフォーマットで入力してください" japaneseFormMessage (MsgInvalidUrl t) = "無効なURLです: " `mappend` t japaneseFormMessage (MsgInvalidEmail t) = "無効なメールアドレスです: " `mappend` t japaneseFormMessage (MsgInvalidHour t) = "無効な時間です: " `mappend` t japaneseFormMessage (MsgInvalidMinute t) = "無効な分です: " `mappend` t japaneseFormMessage (MsgInvalidSecond t) = "無効な秒です: " `mappend` t japaneseFormMessage MsgCsrfWarning = "CSRF攻撃を防ぐため、フォームの入力を確認してください" japaneseFormMessage MsgValueRequired = "値は必須です" japaneseFormMessage (MsgInputNotFound t) = "入力が見つかりません: " `mappend` t japaneseFormMessage MsgSelectNone = "<なし>" japaneseFormMessage (MsgInvalidBool t) = "無効なbool値です: " `mappend` t japaneseFormMessage MsgBoolYes = "はい" japaneseFormMessage MsgBoolNo = "いいえ" japaneseFormMessage MsgDelete = "削除しますか?"
s9gf4ult/yesod
yesod-form/Yesod/Form/I18n/Japanese.hs
Haskell
mit
1,650
{-# LANGUAGE ScopedTypeVariables #-} module Stackage.LoadDatabase where import qualified Codec.Archive.Tar as Tar import qualified Codec.Compression.GZip as GZip import Control.Exception (IOException, handle) import Control.Monad (guard, foldM) import qualified Data.ByteString.Lazy as L import qualified Data.ByteString.Lazy.Char8 as L8 import Data.List (stripPrefix) import qualified Data.Map as Map import Data.Maybe (catMaybes, listToMaybe, mapMaybe, fromMaybe) import Data.Monoid (Monoid (..)) import Data.Set (member) import qualified Data.Set as Set import Distribution.Compiler (CompilerFlavor (GHC)) import Distribution.Package (Dependency (Dependency)) import Distribution.PackageDescription (Condition (..), ConfVar (..), FlagName (FlagName), RepoType (Git), SourceRepo (..), benchmarkBuildInfo, buildInfo, buildTools, condBenchmarks, condExecutables, condLibrary, condTestSuites, condTreeComponents, condTreeConstraints, condTreeData, flagDefault, flagName, genPackageFlags, homepage, libBuildInfo, packageDescription, sourceRepos, testBuildInfo) import Distribution.PackageDescription.Parse (ParseResult (ParseOk), parsePackageDescription) import Distribution.System (buildArch, buildOS) import Distribution.Text (simpleParse) import Distribution.Version (Version (Version), unionVersionRanges, withinRange) import Stackage.Config (convertGithubUser) import Stackage.Types import Stackage.Util import System.Directory (doesFileExist, getDirectoryContents) import System.FilePath ((<.>), (</>)) -- | Load the raw package database. -- -- We want to put in some restrictions: -- -- * Drop all core packages. We never want to install a new version of -- those, nor include them in the package list. -- -- * For packages with a specific version bound, find the maximum matching -- version. -- -- * For other packages, select the maximum version number. loadPackageDB :: SelectSettings -> Map PackageName Version -- ^ core packages from HP file -> Set PackageName -- ^ all core packages, including extras -> Map PackageName (VersionRange, Maintainer) -- ^ additional deps -> Set PackageName -- ^ underlay packages to exclude -> IO PackageDB loadPackageDB settings coreMap core deps underlay = do tarName <- getTarballName lbs <- L.readFile tarName pdb <- addEntries mempty $ Tar.read lbs contents <- handle (\(_ :: IOException) -> return []) $ getDirectoryContents $ selectTarballDir settings pdb' <- foldM addTarball pdb $ mapMaybe stripTarGz contents return $ excludeUnderlay pdb' where addEntries _ (Tar.Fail e) = error $ show e addEntries db Tar.Done = return db addEntries db (Tar.Next e es) = addEntry db e >>= flip addEntries es stripTarGz = fmap reverse . stripPrefix (reverse ".tar.gz") . reverse ghcVersion' = let GhcMajorVersion x y = selectGhcVersion settings in Version [x, y, 2] [] addEntry :: PackageDB -> Tar.Entry -> IO PackageDB addEntry pdb e = case getPackageVersion e of Nothing -> return pdb Just (p, v) | p `member` core -> return pdb | otherwise -> case Map.lookup p deps of Just (vrange, _maintainer) | not $ withinRange v vrange -> return pdb _ -> do let pkgname = packageVersionString (p, v) tarball = selectTarballDir settings </> pkgname <.> "tar.gz" case Tar.entryContent e of Tar.NormalFile bs _ -> addPackage p v bs pdb _ -> return pdb addTarball :: PackageDB -> FilePath -> IO PackageDB addTarball pdb tarball' = do lbs <- L.readFile tarball let (v', p') = break (== '-') $ reverse tarball' p = PackageName $ reverse $ drop 1 p' v <- maybe (error $ "Invalid tarball name: " ++ tarball) return $ simpleParse $ reverse v' case Map.lookup p deps of Just (vrange, _) | not $ withinRange v vrange -> return pdb _ -> findCabalAndAddPackage tarball p v pdb $ Tar.read $ GZip.decompress lbs where tarball = selectTarballDir settings </> tarball' <.> "tar.gz" excludeUnderlay :: PackageDB -> PackageDB excludeUnderlay (PackageDB pdb) = PackageDB $ Map.filterWithKey (\k _ -> Set.notMember k underlay) pdb skipTests p = p `Set.member` skippedTests settings -- Find the relevant cabal file in the given entries and add its contents -- to the package database findCabalAndAddPackage tarball p v pdb = loop where fixPath '\\' = '/' fixPath c = c expectedPath = let PackageName p' = p in concat [ packageVersionString (p, v) , "/" , p' , ".cabal" ] loop Tar.Done = error $ concat [ "Missing cabal file " , show expectedPath , " in tarball: " , show tarball ] loop (Tar.Fail e) = error $ concat [ "Unable to read tarball " , show tarball , ": " , show e ] loop (Tar.Next entry rest) | map fixPath (Tar.entryPath entry) == expectedPath = case Tar.entryContent entry of Tar.NormalFile bs _ -> addPackage p v bs pdb _ -> error $ concat [ "In tarball " , show tarball , " the cabal file " , show expectedPath , " was not a normal file" ] | otherwise = loop rest addPackage p v lbs pdb = do let (deps', hasTests, buildToolsExe', buildToolsOther', mgpd, execs, mgithub) = parseDeps p lbs return $ mappend pdb $ PackageDB $ Map.singleton p PackageInfo { piVersion = v , piDeps = deps' , piHasTests = hasTests , piBuildToolsExe = buildToolsExe' , piBuildToolsAll = buildToolsExe' `Set.union` buildToolsOther' , piGPD = mgpd , piExecs = execs , piGithubUser = fromMaybe [] mgithub } parseDeps p lbs = case parsePackageDescription $ L8.unpack lbs of ParseOk _ gpd -> (mconcat [ maybe mempty (go gpd) $ condLibrary gpd , mconcat $ map (go gpd . snd) $ condExecutables gpd , if skipTests p then mempty else mconcat $ map (go gpd . snd) $ condTestSuites gpd -- FIXME , mconcat $ map (go gpd . snd) $ condBenchmarks gpd ], not $ null $ condTestSuites gpd , Set.fromList $ map depName $ libExeBuildInfo gpd , Set.fromList $ map depName $ testBenchBuildInfo gpd , Just gpd , Set.fromList $ map (Executable . fst) $ condExecutables gpd , fmap convertGithubUser $ listToMaybe $ catMaybes $ parseGithubUserHP (homepage $ packageDescription gpd) : map parseGithubUserSR (sourceRepos $ packageDescription gpd) ) _ -> (mempty, defaultHasTestSuites, Set.empty, Set.empty, Nothing, Set.empty, Nothing) where libExeBuildInfo gpd = concat [ maybe mempty (goBI libBuildInfo) $ condLibrary gpd , concat $ map (goBI buildInfo . snd) $ condExecutables gpd ] testBenchBuildInfo gpd = concat [ if skipTests p then [] else concat $ map (goBI testBuildInfo . snd) $ condTestSuites gpd , concat $ map (goBI benchmarkBuildInfo . snd) $ condBenchmarks gpd ] goBI f x = buildTools $ f $ condTreeData x depName (Dependency (PackageName pn) _) = Executable pn go gpd tree = Map.filterWithKey (\k _ -> not $ ignoredDep k) $ Map.unionsWith unionVersionRanges $ Map.fromList (map (\(Dependency pn vr) -> (pn, vr)) $ condTreeConstraints tree) : map (go gpd) (mapMaybe (checkCond gpd) $ condTreeComponents tree) -- Some specific overrides for cases where getting Stackage to be smart -- enough to handle things would be too difficult. ignoredDep :: PackageName -> Bool ignoredDep dep -- The flag logic used by text-stream-decode confuses Stackage. | dep == PackageName "text" && p == PackageName "text-stream-decode" = True | otherwise = False checkCond gpd (cond, tree, melse) | checkCond' cond = Just tree | otherwise = melse where checkCond' (Var (OS os)) = os == buildOS checkCond' (Var (Arch arch)) = arch == buildArch -- Sigh... the small_base flag on mersenne-random-pure64 is backwards checkCond' (Var (Flag (FlagName "small_base"))) | p == PackageName "mersenne-random-pure64" = False checkCond' (Var (Flag flag@(FlagName flag'))) = flag' `Set.notMember` disabledFlags settings && flag `elem` flags' checkCond' (Var (Impl compiler range)) = compiler == GHC && withinRange ghcVersion' range checkCond' (Lit b) = b checkCond' (CNot c) = not $ checkCond' c checkCond' (COr c1 c2) = checkCond' c1 || checkCond' c2 checkCond' (CAnd c1 c2) = checkCond' c1 && checkCond' c2 flags' = map flagName (filter flagDefault $ genPackageFlags gpd) ++ (map FlagName $ Set.toList $ Stackage.Types.flags settings coreMap) -- | Attempt to grab the Github username from a homepage. parseGithubUserHP :: String -> Maybe String parseGithubUserHP url1 = do url2 <- listToMaybe $ mapMaybe (flip stripPrefix url1) [ "http://github.com/" , "https://github.com/" ] let x = takeWhile (/= '/') url2 guard $ not $ null x Just x -- | Attempt to grab the Github username from a source repo. parseGithubUserSR :: SourceRepo -> Maybe String parseGithubUserSR sr = case (repoType sr, repoLocation sr) of (Just Git, Just s) -> parseGithubUserHP s _ -> Nothing
Tarrasch/stackage
Stackage/LoadDatabase.hs
Haskell
mit
12,417
{-# LANGUAGE PatternGuards #-} ----------------------------------------------------------------------------- -- | -- Module : XMonad.Util.NamedScratchpad -- Copyright : (c) Konstantin Sobolev <konstantin.sobolev@gmail.com> -- License : BSD-style (see LICENSE) -- -- Maintainer : Konstantin Sobolev <konstantin.sobolev@gmail.com> -- Stability : unstable -- Portability : unportable -- -- Named scratchpads that support several arbitrary applications at the same time. -- ----------------------------------------------------------------------------- module XMonad.Util.NamedScratchpad ( -- * Usage -- $usage NamedScratchpad(..), nonFloating, defaultFloating, customFloating, NamedScratchpads, namedScratchpadAction, allNamedScratchpadAction, namedScratchpadManageHook, namedScratchpadFilterOutWorkspace, namedScratchpadFilterOutWorkspacePP ) where import XMonad import XMonad.Hooks.ManageHelpers (doRectFloat) import XMonad.Actions.DynamicWorkspaces (addHiddenWorkspace) import XMonad.Hooks.DynamicLog (PP, ppSort) import Control.Monad (filterM) import Data.Maybe (listToMaybe) import qualified XMonad.StackSet as W -- $usage -- Allows to have several floating scratchpads running different applications. -- Bind a key to 'namedScratchpadSpawnAction'. -- Pressing it will spawn configured application, or bring it to the current -- workspace if it already exists. -- Pressing the key with the application on the current workspace will -- send it to a hidden workspace called @NSP@. -- -- If you already have a workspace called @NSP@, it will use that. -- @NSP@ will also appear in xmobar and dzen status bars. You can tweak your -- @dynamicLog@ settings to filter it out if you like. -- -- Create named scratchpads configuration in your xmonad.hs like this: -- -- > import XMonad.StackSet as W -- > import XMonad.ManageHook -- > import XMonad.Util.NamedScratchpad -- > -- > scratchpads = [ -- > -- run htop in xterm, find it by title, use default floating window placement -- > NS "htop" "xterm -e htop" (title =? "htop") defaultFloating , -- > -- > -- run stardict, find it by class name, place it in the floating window -- > -- 1/6 of screen width from the left, 1/6 of screen height -- > -- from the top, 2/3 of screen width by 2/3 of screen height -- > NS "stardict" "stardict" (className =? "Stardict") -- > (customFloating $ W.RationalRect (1/6) (1/6) (2/3) (2/3)) , -- > -- > -- run gvim, find by role, don't float -- > NS "notes" "gvim --role notes ~/notes.txt" (role =? "notes") nonFloating -- > ] where role = stringProperty "WM_WINDOW_ROLE" -- -- Add keybindings: -- -- > , ((modm .|. controlMask .|. shiftMask, xK_t), namedScratchpadAction scratchpads "htop") -- > , ((modm .|. controlMask .|. shiftMask, xK_s), namedScratchpadAction scratchpads "stardict") -- > , ((modm .|. controlMask .|. shiftMask, xK_n), namedScratchpadAction scratchpads "notes") -- -- ... and a manage hook: -- -- > , manageHook = namedScratchpadManageHook scratchpads -- -- For detailed instruction on editing the key binding see -- "XMonad.Doc.Extending#Editing_key_bindings" -- -- | Single named scratchpad configuration data NamedScratchpad = NS { name :: String -- ^ Scratchpad name , cmd :: String -- ^ Command used to run application , query :: Query Bool -- ^ Query to find already running application , hook :: ManageHook -- ^ Manage hook called for application window, use it to define the placement. See @nonFloating@, @defaultFloating@ and @customFloating@ } -- | Manage hook that makes the window non-floating nonFloating :: ManageHook nonFloating = idHook -- | Manage hook that makes the window floating with the default placement defaultFloating :: ManageHook defaultFloating = doFloat -- | Manage hook that makes the window floating with custom placement customFloating :: W.RationalRect -> ManageHook customFloating = doRectFloat -- | Named scratchpads configuration type NamedScratchpads = [NamedScratchpad] -- | Finds named scratchpad configuration by name findByName :: NamedScratchpads -> String -> Maybe NamedScratchpad findByName c s = listToMaybe $ filter ((s==) . name) c -- | Runs application which should appear in specified scratchpad runApplication :: NamedScratchpad -> X () runApplication = spawn . cmd -- | Action to pop up specified named scratchpad namedScratchpadAction :: NamedScratchpads -- ^ Named scratchpads configuration -> String -- ^ Scratchpad name -> X () namedScratchpadAction = someNamedScratchpadAction (\f ws -> f $ head ws) allNamedScratchpadAction :: NamedScratchpads -> String -> X () allNamedScratchpadAction = someNamedScratchpadAction mapM_ someNamedScratchpadAction :: ((Window -> X ()) -> [Window] -> X ()) -> NamedScratchpads -> String -> X () someNamedScratchpadAction f confs n | Just conf <- findByName confs n = withWindowSet $ \s -> do filterCurrent <- filterM (runQuery (query conf)) ((maybe [] W.integrate . W.stack . W.workspace . W.current) s) filterAll <- filterM (runQuery (query conf)) (W.allWindows s) case filterCurrent of [] -> do case filterAll of [] -> runApplication conf _ -> f (windows . W.shiftWin (W.currentTag s)) filterAll _ -> do if null (filter ((== scratchpadWorkspaceTag) . W.tag) (W.workspaces s)) then addHiddenWorkspace scratchpadWorkspaceTag else return () f (windows . W.shiftWin scratchpadWorkspaceTag) filterAll | otherwise = return () -- tag of the scratchpad workspace scratchpadWorkspaceTag :: String scratchpadWorkspaceTag = "NSP" -- | Manage hook to use with named scratchpads namedScratchpadManageHook :: NamedScratchpads -- ^ Named scratchpads configuration -> ManageHook namedScratchpadManageHook = composeAll . fmap (\c -> query c --> hook c) -- | Transforms a workspace list containing the NSP workspace into one that -- doesn't contain it. Intended for use with logHooks. namedScratchpadFilterOutWorkspace :: [WindowSpace] -> [WindowSpace] namedScratchpadFilterOutWorkspace = filter (\(W.Workspace tag _ _) -> tag /= scratchpadWorkspaceTag) -- | Transforms a pretty-printer into one not displaying the NSP workspace. -- -- A simple use could be: -- -- > logHook = dynamicLogWithPP . namedScratchpadFilterOutWorkspace $ defaultPP -- -- Here is another example, when using "XMonad.Layout.IndependentScreens". -- If you have handles @hLeft@ and @hRight@ for bars on the left and right screens, respectively, and @pp@ is a pretty-printer function that takes a handle, you could write -- -- > logHook = let log screen handle = dynamicLogWithPP . namedScratchpadFilterOutWorkspacePP . marshallPP screen . pp $ handle -- > in log 0 hLeft >> log 1 hRight namedScratchpadFilterOutWorkspacePP :: PP -> PP namedScratchpadFilterOutWorkspacePP pp = pp { ppSort = fmap (. namedScratchpadFilterOutWorkspace) (ppSort pp) } -- vim:ts=4:shiftwidth=4:softtabstop=4:expandtab:foldlevel=20:
markus1189/xmonad-contrib-710
XMonad/Util/NamedScratchpad.hs
Haskell
bsd-3-clause
7,541
{-# LANGUAGE DataKinds, ExistentialQuantification, GADTs, PolyKinds, TypeOperators #-} {-# LANGUAGE TypeInType, TypeFamilies #-} {- # LANGUAGE UndecidableInstances #-} module T15552 where import Data.Kind data Elem :: k -> [k] -> Type where Here :: Elem x (x : xs) There :: Elem x xs -> Elem x (y : xs) data EntryOfVal (v :: Type) (kvs :: [Type]) where EntryOfVal :: forall (v :: Type) (kvs :: [Type]) (k :: Type). Elem (k, v) kvs -> EntryOfVal v kvs type family EntryOfValKey (eov :: EntryOfVal v kvs) :: Type where EntryOfValKey ('EntryOfVal (_ :: Elem (k, v) kvs)) = k type family GetEntryOfVal (eov :: EntryOfVal v kvs) :: Elem (EntryOfValKey eov, v) kvs where GetEntryOfVal ('EntryOfVal e) = e type family FirstEntryOfVal (v :: Type) (kvs :: [Type]) :: EntryOfVal v kvs where FirstEntryOfVal v (_ : kvs) = 'EntryOfVal (There (GetEntryOfVal (FirstEntryOfVal v kvs))) --type instance FirstEntryOfVal v (_ : kvs) -- = 'EntryOfVal ('There (GetEntryOfVal (FirstEntryOfVal v kvs)))
sdiehl/ghc
testsuite/tests/typecheck/should_fail/T15552a.hs
Haskell
bsd-3-clause
1,051
module AddOneParameter.D1 where {-add parameter 'f' to function 'sq' . This refactoring affects module 'D1', 'C1' and 'A1'-} sumSquares (x:xs) = sq x + sumSquares xs sumSquares [] = 0 sq x = x ^ pow pow =2
RefactoringTools/HaRe
test/testdata/AddOneParameter/D1.hs
Haskell
bsd-3-clause
215
{-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Machine.Wye -- Copyright : (C) 2012 Edward Kmett, Rúnar Bjarnason, Paul Chiusano -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : provisional -- Portability : Rank-2 Types, GADTs -- ---------------------------------------------------------------------------- module Data.Machine.Wye ( -- * Wyes Wye, WyeT , Y(..) , wye , addX, addY , capX, capY ) where import Control.Category import Data.Machine.Process import Data.Machine.Type import Data.Machine.Is import Data.Machine.Source import Prelude hiding ((.),id) ------------------------------------------------------------------------------- -- Wyes ------------------------------------------------------------------------------- -- | The input descriptor for a 'Wye' or 'WyeT' data Y a b c where X :: Y a b a -- block waiting on the left input Y :: Y a b b -- block waiting on the right input Z :: Y a b (Either a b) -- block waiting on either input -- | A 'Machine' that can read from two input stream in a non-deterministic manner. type Wye a b c = Machine (Y a b) c -- | A 'Machine' that can read from two input stream in a non-deterministic manner with monadic side-effects. type WyeT m a b c = MachineT m (Y a b) c -- | Compose a pair of pipes onto the front of a 'Wye'. -- | Precompose a 'Process' onto each input of a 'Wye' (or 'WyeT'). -- -- This is left biased in that it tries to draw values from the 'X' input whenever they are -- available, and only draws from the 'Y' input when 'X' would block. wye :: Monad m => ProcessT m a a' -> ProcessT m b b' -> WyeT m a' b' c -> WyeT m a b c wye ma mb m = MachineT $ runMachineT m >>= \v -> case v of Yield o k -> return $ Yield o (wye ma mb k) Stop -> return Stop Await f X ff -> runMachineT ma >>= \u -> case u of Yield a k -> runMachineT . wye k mb $ f a Stop -> runMachineT $ wye stopped mb ff Await g Refl fg -> return . Await (\a -> wye (g a) mb $ encased v) X . wye fg mb $ encased v Await f Y ff -> runMachineT mb >>= \u -> case u of Yield b k -> runMachineT . wye ma k $ f b Stop -> runMachineT $ wye ma stopped ff Await g Refl fg -> return . Await (\b -> wye ma (g b) $ encased v) Y . wye ma fg $ encased v Await f Z ff -> runMachineT ma >>= \u -> case u of Yield a k -> runMachineT . wye k mb . f $ Left a Stop -> runMachineT mb >>= \w -> case w of Yield b k -> runMachineT . wye stopped k . f $ Right b Stop -> runMachineT $ wye stopped stopped ff Await g Refl fg -> return . Await (\b -> wye stopped (g b) $ encased v) Y . wye stopped fg $ encased v Await g Refl fg -> runMachineT mb >>= \w -> case w of Yield b k -> runMachineT . wye (encased u) k . f $ Right b Stop -> return . Await (\a -> wye (g a) stopped $ encased v) X . wye fg stopped $ encased v Await h Refl fh -> return . Await (\c -> case c of Left a -> wye (g a) (encased w) $ encased v Right b -> wye (encased u) (h b) $ encased v) Z . wye fg fh $ encased v -- | Precompose a pipe onto the left input of a wye. addX :: Monad m => ProcessT m a b -> WyeT m b c d -> WyeT m a c d addX p = wye p echo {-# INLINE addX #-} -- | Precompose a pipe onto the right input of a tee. addY :: Monad m => ProcessT m b c -> WyeT m a c d -> WyeT m a b d addY = wye echo {-# INLINE addY #-} -- | Tie off one input of a tee by connecting it to a known source. capX :: Monad m => SourceT m a -> WyeT m a b c -> ProcessT m b c capX s t = process (capped Right) (addX s t) {-# INLINE capX #-} -- | Tie off one input of a tee by connecting it to a known source. capY :: Monad m => SourceT m b -> WyeT m a b c -> ProcessT m a c capY s t = process (capped Left) (addY s t) {-# INLINE capY #-} -- | Natural transformation used by 'capX' and 'capY' capped :: (a -> Either a a) -> Y a a b -> a -> b capped _ X = id capped _ Y = id capped f Z = f {-# INLINE capped #-}
YoEight/machines
src/Data/Machine/Wye.hs
Haskell
bsd-3-clause
4,564
module SubPatternIn3 where -- takes into account general type variables -- within type implementation. -- here T has its arguments instantiated within g -- selecting 'b' should instantiate list patterns -- selecting 'c' should give an error. -- data T a b = C1 a b | C2 b g :: Int -> T Int [Int] -> Int g z (C1 b c) = b g z (C2 x@[]) = hd x g z (C2 x@(b_1 : b_2)) = hd x g z (C2 x) = hd x f :: [Int] -> Int f x@[] = hd x + hd (tl x) f x@(y:ys) = hd x + hd (tl x) hd x = head x tl x = tail x
kmate/HaRe
old/testing/subIntroPattern/SubPatternIn3_TokOut.hs
Haskell
bsd-3-clause
500
{-# LANGUAGE BangPatterns #-} {-# OPTIONS -fvia-C -optc-O3 -fexcess-precision -optc-msse3 #-} import Control.Monad.ST import Data.Array.ST import Data.Array.Base main = print $ runST (do arr <- newArray (1,2000000) 137.0 :: ST s (STUArray s Int Double) go arr 2000000 0.0 ) go :: STUArray s Int Double -> Int -> Double -> ST s Double go !a i !acc | i < 1 = return acc | otherwise = do b <- unsafeRead a i unsafeWrite a i (b+3.0) c <- unsafeRead a i go a (i-1) (c+acc)
urbanslug/ghc
testsuite/tests/perf/should_run/T3586.hs
Haskell
bsd-3-clause
544
{-# LANGUAGE TypeApplications #-} {-# LANGUAGE TemplateHaskell #-} module SuperUserSpark.CompilerSpec where import TestImport hiding ((<.>)) import Data.Either (isLeft, isRight) import Data.List (isPrefixOf) import System.FilePath.Posix ((<.>)) import SuperUserSpark.Compiler import SuperUserSpark.Compiler.Gen () import SuperUserSpark.Compiler.Internal import SuperUserSpark.Compiler.TestUtils import SuperUserSpark.Compiler.Types import SuperUserSpark.Compiler.Utils import SuperUserSpark.CoreTypes import SuperUserSpark.Language.Gen () import SuperUserSpark.Language.Types import SuperUserSpark.OptParse.Gen () import SuperUserSpark.PreCompiler import SuperUserSpark.Utils import TestUtils spec :: Spec spec = do parallel $ do instanceSpec singleCompileDecSpec precompileSpec compileUnitSpec utilsSpec hopTests exactTests compilerBlackBoxTests precompileSpec :: Spec precompileSpec = describe "pre-compilation" $ do cleanContentSpec cleanContentSpec :: Spec cleanContentSpec = do let validFp = genValid `suchThat` cleanBy cleanFilePath describe "cleanCard" $ do it "doesn't report any card with valid content and a valid name" $ do forAll (genValid `suchThat` cleanBy cleanCardName) $ \cn -> forAll (genValid `suchThat` cleanBy cleanDeclaration) $ \cc -> Card cn cc `shouldSatisfy` cleanBy cleanCard describe "cleanCardName" $ do pend it "doesn't report an emty card name" $ do "" `shouldSatisfy` cleanBy cleanCardName it "reports card names with newlines" $ do forAll (sequenceA [genValid, pure '\n', genValid]) $ \s -> s `shouldNotSatisfy` cleanBy cleanCardName describe "cleanDeclaration" $ do describe "Deploy" $ do it "doesn't report Deploy declarations with valid filepaths" $ do forAll validFp $ \src -> forAll validFp $ \dst -> forAll genValid $ \kind -> Deploy src dst kind `shouldSatisfy` cleanBy cleanDeclaration it "reports Deploy declarations with an invalid source" $ do forAll (genValid `suchThat` (not . cleanBy cleanFilePath)) $ \src -> forAll validFp $ \dst -> forAll genValid $ \kind -> Deploy src dst kind `shouldNotSatisfy` cleanBy cleanDeclaration it "reports Deploy declarations with an invalid destination" $ do forAll validFp $ \src -> forAll (genValid `suchThat` (not . cleanBy cleanFilePath)) $ \dst -> forAll genValid $ \kind -> Deploy src dst kind `shouldNotSatisfy` cleanBy cleanDeclaration pend describe "SparkOff" $ do it "reports SparkOff declarations with an invalid card reference" $ do forAll (genValid `suchThat` (not . cleanBy cleanCardReference)) $ \cr -> SparkOff cr `shouldNotSatisfy` cleanBy cleanDeclaration it "doesn't report SparkOff declarations with a valid card reference" $ do forAll (genValid `suchThat` cleanBy cleanCardReference) $ \cr -> SparkOff cr `shouldSatisfy` cleanBy cleanDeclaration pend describe "IntoDir" $ do it "reports IntoDir declarations with an invalid filepath" $ do forAll (genValid `suchThat` (not . cleanBy cleanFilePath)) $ \fp -> IntoDir fp `shouldNotSatisfy` cleanBy cleanDeclaration it "doesn't report IntoDir declarations with a valid filepath" $ do forAll (genValid `suchThat` cleanBy cleanFilePath) $ \fp -> IntoDir fp `shouldSatisfy` cleanBy cleanDeclaration pend describe "OutofDir" $ do it "reports OutofDir declarations with an invalid filepath" $ do forAll (genValid `suchThat` (not . cleanBy cleanFilePath)) $ \fp -> OutofDir fp `shouldNotSatisfy` cleanBy cleanDeclaration it "doesn't report OutofDir declarations with a valid filepath" $ do forAll (genValid `suchThat` cleanBy cleanFilePath) $ \fp -> OutofDir fp `shouldSatisfy` cleanBy cleanDeclaration pend describe "DeployKindOverride" $ do it "doesn't report any deployment kind override declarations" $ do forAll genValid $ \kind -> DeployKindOverride kind `shouldSatisfy` cleanBy cleanDeclaration pend describe "Alternatives" $ do it "reports alternatives declarations with as much as a single invalid filepath" $ do forAll (genValid `suchThat` (any $ not . cleanBy cleanFilePath)) $ \fs -> Alternatives fs `shouldNotSatisfy` cleanBy cleanDeclaration it "doesn't report alternatives declarations with valid filepaths" $ do forAll (genValid `suchThat` (all $ cleanBy cleanFilePath)) $ \fs -> Alternatives fs `shouldSatisfy` cleanBy cleanDeclaration pend describe "Block" $ do it "reports block declarations with as much as a single invalid declaration inside" $ do forAll (genValid `suchThat` (any $ not . cleanBy cleanDeclaration)) $ \ds -> Block ds `shouldNotSatisfy` cleanBy cleanDeclaration it "doesn't report any block declarations with valid declarations inside" $ do forAll (genValid `suchThat` (all $ cleanBy cleanDeclaration)) $ \ds -> Block ds `shouldSatisfy` cleanBy cleanDeclaration pend describe "cleanCardReference" $ do it "works the same as cleanCardName separately" $ do forAll genValid $ \cnr -> cleanBy cleanCardNameReference cnr === cleanBy cleanCardReference (CardName cnr) it "works the same as cleanCardFile separately" $ do forAll genValid $ \cfr -> cleanBy cleanCardFileReference cfr === cleanBy cleanCardReference (CardFile cfr) pend describe "cleanCardNameReference" $ do it "reports card name references with an invalid card name" $ do forAll (genValid `suchThat` (not . cleanBy cleanCardName)) $ \cn -> CardNameReference cn `shouldNotSatisfy` cleanBy cleanCardNameReference it "doesn't report card name references with a valid card name" $ do forAll (genValid `suchThat` cleanBy cleanCardName) $ \cn -> CardNameReference cn `shouldSatisfy` cleanBy cleanCardNameReference pend describe "cleanCardFileReference" $ do it "reports card file references with an invalid filepath" $ do forAll (genValid `suchThat` (not . cleanBy cleanFilePath)) $ \fp -> forAll genValid $ \cn -> CardFileReference fp cn `shouldNotSatisfy` cleanBy cleanCardFileReference it "reports card file references with an invalid card name" $ do forAll genValid $ \fp -> forAll (genValid `suchThat` (not . cleanBy cleanCardNameReference)) $ \cn -> CardFileReference fp (Just cn) `shouldNotSatisfy` cleanBy cleanCardFileReference it "doesn't report card file references with a valid card name reference and valid filepath" $ do forAll (genValid `suchThat` cleanBy cleanFilePath) $ \fp -> forAll (genValid `suchThat` cleanBy cleanCardNameReference) $ \cn -> CardFileReference fp (Just cn) `shouldSatisfy` cleanBy cleanCardFileReference pend describe "cleanFilePath" $ do it "reports empty an filepath" $ do filePathDirty [] let nonNull = genValid `suchThat` (not . null) it "reports filepaths with newlines" $ do forAll (nonNull `suchThat` containsNewlineCharacter) filePathDirty let withoutNewlines = nonNull `suchThat` (not . containsNewlineCharacter) it "reports filepaths with multiple consequtive slashes" $ do once $ forAll (withoutNewlines `suchThat` containsMultipleConsequtiveSlashes) filePathDirty let c = filePathClean it "doesn't report these valid filepaths" $ do c "noextension" c ".bashrc" c "file.txt" c "Some file with spaces.doc" c "some/relative/filepath.file" -- TODO(syd) Use the default config to generate this! defaultCompilerState :: CompilerState defaultCompilerState = CompilerState { stateDeploymentKindLocalOverride = Nothing , stateInto = "" , stateOutofPrefix = [] } instanceSpec :: Spec instanceSpec = parallel $ do eqSpec @CompileAssignment genValidSpec @CompileAssignment eqSpec @CompileSettings genValidSpec @CompileSettings eqSpec @(Deployment FilePath) genValidSpec @(Deployment FilePath) jsonSpecOnValid @(Deployment FilePath) functorSpec @Deployment eqSpec @(DeploymentDirections FilePath) genValidSpec @(DeploymentDirections FilePath) jsonSpecOnValid @(DeploymentDirections FilePath) functorSpec @DeploymentDirections eqSpec @PrefixPart genValidSpec @PrefixPart eqSpec @CompilerState genValidSpec @CompilerState singleCompileDecSpec :: Spec singleCompileDecSpec = describe "compileDec" $ do let s = defaultCompilerState let c = defaultCompileSettings let sc = singleShouldCompileTo c s let nonNull = genValid `suchThat` (not . null) let validFilePath = nonNull `suchThat` (not . containsNewlineCharacter) let easyFilePath = validFilePath `suchThat` (not . isPrefixOf ".") let validFp = genValid `suchThat` cleanBy cleanFilePath describe "Deploy" $ do it "uses the exact right text in source and destination when given valid filepaths without a leading dot" $ do forAll easyFilePath $ \from -> forAll easyFilePath $ \to -> sc (Deploy from to Nothing) (Deployment (Directions [from] to) LinkDeployment) it "handles filepaths with a leading dot correctly" $ do pending it "figures out the correct paths in these cases with default config and initial state" $ do let d = (Deploy "from" "to" $ Just LinkDeployment) sc d (Deployment (Directions ["from"] "to") LinkDeployment) it "uses the alternates correctly" $ do pending it "uses the into's correctly" $ do pending it "uses the outof's correctly" $ do pending pend describe "SparkOff" $ do it "adds a single card file reference to the list of cards to spark later" $ do forAll validFilePath $ \f -> let cr = CardFile $ CardFileReference f Nothing d = SparkOff cr in compileSingleDec d s c `shouldBe` Right (s, ([], [cr])) it "adds any card reference to the list" $ do pending pend let shouldState = shouldResultInState c s describe "IntoDir" $ do it "adds the given directory to the into state" $ do forAll validFp $ \fp -> shouldState (IntoDir fp) $ s {stateInto = fp} it "compounds with the input state" $ do pendingWith "Change the input state to an explicit list first" pend describe "OutofDir" $ do it "adds the given directory to the outof state" $ do forAll validFp $ \fp -> shouldState (OutofDir fp) $ s {stateOutofPrefix = [Literal fp]} pend describe "DeployKindOverride" $ do it "modifies the internal deployment kind override" $ do forAll genValid $ \kind -> shouldState (DeployKindOverride kind) $ s {stateDeploymentKindLocalOverride = Just kind} pend describe "Block" $ do it "uses a separate scope for its sub-compilation" $ do forAll genValid $ \ds -> shouldState (Block ds) s pend describe "Alternatives" $ do it "adds an alternatives prefix to the outof prefix in the compiler state" $ do forAll (listOf validFilePath) $ \fps -> shouldState (Alternatives fps) $ s {stateOutofPrefix = [Alts fps]} pend runDefaultImpureCompiler :: ImpureCompiler a -> IO (Either CompileError a) runDefaultImpureCompiler = flip runReaderT defaultCompileSettings . runExceptT compileUnitSpec :: Spec compileUnitSpec = describe "compileUnit" $ do it "Only ever produces valid results" $ forAll genValid $ \sets -> validIfSucceeds (runIdentity . flip runReaderT sets . runExceptT . compileUnit) utilsSpec :: Spec utilsSpec = parallel $ do describe "initialState" $ it "is valid" $ isValid initialState describe "sources" $ it "only produces valid prefix parts" $ producesValid sources describe "resolvePrefix" $ it "only produces valid paths" $ producesValid resolvePrefix hopTests :: Spec hopTests = do describe "hop test" $ do dir <- runIO $ resolveDir' "test_resources/hop_test" let root = dir </> $(mkRelFile "root.sus") let hop1 = dir </> $(mkRelDir "hop1dir") </> $(mkRelFile "hop1.sus") let hop2 = dir </> $(mkRelDir "hop1dir") </> $(mkRelDir "hop2dir") </> $(mkRelFile "hop2.sus") let hop3 = dir </> $(mkRelDir "hop1dir") </> $(mkRelDir "hop2dir") </> $(mkRelDir "hop3dir") </> $(mkRelFile "hop3.sus") it "compiles hop3 correctly" $ do r <- runDefaultImpureCompiler $ compileJob $ StrongCardFileReference hop3 Nothing r `shouldBe` Right [ Deployment (Directions ["z/delta"] "d/three") LinkDeployment ] it "compiles hop2 correctly" $ do r <- runDefaultImpureCompiler $ compileJob $ StrongCardFileReference hop2 Nothing r `shouldBe` Right [ Deployment (Directions ["y/gamma"] "c/two") LinkDeployment , Deployment (Directions ["hop3dir/z/delta"] "d/three") LinkDeployment ] it "compiles hop1 correctly" $ do r <- runDefaultImpureCompiler $ compileJob $ StrongCardFileReference hop1 Nothing r `shouldBe` Right [ Deployment (Directions ["x/beta"] "b/one") LinkDeployment , Deployment (Directions ["hop2dir/y/gamma"] "c/two") LinkDeployment , Deployment (Directions ["hop2dir/hop3dir/z/delta"] "d/three") LinkDeployment ] it "compiles root correctly" $ do r <- runDefaultImpureCompiler $ compileJob $ StrongCardFileReference root Nothing r `shouldBe` Right [ Deployment (Directions ["u/alpha"] "a/zero") LinkDeployment , Deployment (Directions ["hop1dir/x/beta"] "b/one") LinkDeployment , Deployment (Directions ["hop1dir/hop2dir/y/gamma"] "c/two") LinkDeployment , Deployment (Directions ["hop1dir/hop2dir/hop3dir/z/delta"] "d/three") LinkDeployment ] exactTests :: Spec exactTests = do describe "exact tests" $ do dir <- runIO $ resolveDir' "test_resources/exact_compile_test_src" forFileInDirss [dir] $ \fp -> do if fileExtension fp == Just ".res" then return () else do it (toFilePath fp) $ do let orig = fp result <- parseAbsFile $ toFilePath fp <.> "res" ads <- runDefaultImpureCompiler $ compileJob $ StrongCardFileReference orig Nothing eds <- runDefaultImpureCompiler $ inputCompiled result ads `shouldBe` eds hopTestDir :: Path Rel Dir hopTestDir = $(mkRelDir "hop_test") compilerBlackBoxTests :: Spec compilerBlackBoxTests = do tr <- runIO $ resolveDir' "test_resources" describe "Succesful compile examples" $ do let dirs = map (tr </>) [shouldCompileDir, hopTestDir] forFileInDirss dirs $ \f -> do it (toFilePath f) $ do r <- runDefaultImpureCompiler $ compileJob $ StrongCardFileReference f Nothing r `shouldSatisfy` isRight describe "Unsuccesfull compile examples" $ do let dirs = map (tr </>) [shouldNotParseDir, shouldNotCompileDir] forFileInDirss dirs $ \f -> do it (toFilePath f) $ do r <- runDefaultImpureCompiler $ compileJob $ StrongCardFileReference f Nothing r `shouldSatisfy` isLeft
NorfairKing/super-user-spark
test/SuperUserSpark/CompilerSpec.hs
Haskell
mit
18,597
module REPL.Parser where import Letter.Core import Letter.Parser import Control.Monad (void) data Command = Eval Line | Describe Line | Import String | Quit deriving Show commandToken long short = choice' $ map (symbol . (':':)) [long, short] importCmd = Import <$> (commandToken "import" "i" >> filename) describe = commandToken "describe" "d" >> (Describe <$> line) commandExp = ((\_ -> Quit) <$> commandToken "quit" "q") <||> importCmd <||> describe <||> (Eval <$> line) command = commandExp <* space
harlanhaskins/Letter
Haskell/app/REPL/Parser.hs
Haskell
mit
587
{-# LANGUAGE OverloadedStrings #-} module Idle.Screens.Home where import Data.IORef import Data.List.NonEmpty import Data.Maybe import Data.Monoid import qualified Data.Text as T import Idle.Ore import Graphics.Vty hiding (string) import Graphics.Vty.Widgets.All import System.Exit import System.IO.Unsafe import Text.Printf data Zipper a = Zipper { left :: [a] , zFocus :: a , right :: [a] } enter :: NonEmpty a -> Zipper a enter (m :| ms) = Zipper [] m ms next :: Zipper a -> Maybe (Zipper a) next (Zipper ls f (r:rs)) = Just $ Zipper (f:ls) r rs next _ = Nothing previous :: Zipper a -> Maybe (Zipper a) previous (Zipper (l:ls) f rs) = Just $ Zipper ls l (f:rs) previous _ = Nothing num :: IORef (Zipper Ore) num = unsafePerformIO $ ores >>= newIORef . enter drawDisplay :: Widget FormattedText -> Widget FormattedText -> Widget FormattedText -> IO () drawDisplay disp l r = do (Zipper ls f rs) <- readIORef num setText l $ if null ls then " " else "◀ " setText r $ if null rs then " " else " ▶" setTextWithAttrs disp $ display f where showB m | m >= 10000000000 = T.pack $ printf "%.2fB" (fromIntegral (m `div` 10000000) / 100 :: Double) showB m = T.pack $ show m plain t = (T.cons '\n' $ T.center 16 ' ' t, def_attr) line = ("\n", def_attr) display (Ore n h d v i) = i ++ [ line, plain n , plain $ "HP: " <> showB h , plain $ "D: " <> showB d , plain $ "$" <> showB v] home :: IO (Widget (Box Table FormattedText), Widget FocusGroup) home = do legend <- plainText "[q]uit [u]pgrade [s]ave" oreDisplay <- plainText "nothing" leftArrow <- plainText "nothing" rightArrow <- plainText "nothing" oreTable <- newTable [ ColumnSpec (ColFixed 2) (Just AlignLeft) Nothing , ColumnSpec (ColFixed 20) (Just AlignCenter) Nothing , ColumnSpec (ColFixed 2) (Just AlignRight) Nothing ] BorderNone addRow oreTable [leftArrow, oreDisplay, rightArrow] homeScreen <- vBox oreTable legend f <- newFocusGroup _ <- addToFocusGroup f homeScreen drawDisplay oreDisplay leftArrow rightArrow homeScreen `onKeyPressed` \this k _ms -> case k of KEsc -> exitSuccess KASCII 'q' -> exitSuccess KASCII ']' -> do atomicModifyIORef' num (\z -> (fromMaybe z (next z), ())) drawDisplay oreDisplay leftArrow rightArrow return True KASCII '[' -> do atomicModifyIORef' num (\z -> (fromMaybe z (previous z), ())) drawDisplay oreDisplay leftArrow rightArrow return True KASCII 't' -> do vis <- getVisible this setVisible this (not vis) >> return True _ -> return False return (homeScreen, f)
pikajude/idle
src/Idle/Screens/Home.hs
Haskell
mit
2,879
-- BNF Converter: Error Monad -- Copyright (C) 2004 Author: Aarne Ranta -- This file comes with NO WARRANTY and may be used FOR ANY PURPOSE. module ComponentModel.Parsers.ErrM where -- the Error monad: like Maybe type with error msgs import Control.Monad (MonadPlus(..), liftM) data Err a = Ok a | Bad String deriving (Read, Show, Eq, Ord) instance Monad Err where return = Ok fail = Bad Ok a >>= f = f a Bad s >>= f = Bad s instance Functor Err where fmap = liftM instance MonadPlus Err where mzero = Bad "Err.mzero" mplus (Bad _) y = y mplus x _ = x
hephaestus-pl/hephaestus
willian/hephaestus-integrated/asset-base/component-model/src/ComponentModel/Parsers/ErrM.hs
Haskell
mit
598
module Config.AppConfig ( AppConfig (..) , getAppConfig ) where import Auth0.Config as Auth0 import Config.Environment (Environment (..)) import Control.Monad (liftM) import Data.Maybe (fromJust) import Data.Text as T import LoadEnv import qualified Network.Wai.Middleware.RequestLogger.LogEntries as LE import System.Directory (getAppUserDataDirectory) import qualified System.Environment as Env import System.FilePath.Posix ((</>), (<.>)) import qualified Users.Api as UsersApi type AppName = Text data AppConfig = AppConfig { getAppName :: AppName , getPort :: Int , getBasePath :: Text , getEnv :: Environment , getLogEntriesConfig :: LE.Config , getAuthConfig :: Auth0.Config , getUsersApiConfig :: UsersApi.Config , getMarketingSiteUrl :: Text } deriving (Show) getAppConfig :: AppName -> Environment -> IO AppConfig getAppConfig appName env = do loadEnvVars appName env port <- Env.lookupEnv "PORT" basePath <- T.pack <$> Env.getEnv "BASEPATH" leConfig <- logEntriesConfig authConfig <- auth0Config usersConfig <- usersApiConfig marketingSiteUrl <- T.pack <$> Env.getEnv "APP_MARKETING_BASE_PATH" let webServerPort = maybe 8080 id (liftM read port) return $ AppConfig { getAppName = appName , getPort = webServerPort , getBasePath = basePath , getEnv = env , getLogEntriesConfig = leConfig , getAuthConfig = authConfig , getUsersApiConfig = usersConfig , getMarketingSiteUrl = marketingSiteUrl } usersApiConfig :: IO UsersApi.Config usersApiConfig = do basePath <- T.pack <$> Env.getEnv "APP_USERS_API_BASE_PATH" return $ UsersApi.Config basePath auth0Config :: IO Auth0.Config auth0Config = do clientID <- T.pack <$> Env.getEnv "APP_AUTH_ZERO_CLIENT_ID" clientSecret <- T.pack <$> Env.getEnv "APP_AUTH_ZERO_CLIENT_SECRET" redirectURI <- T.pack <$> Env.getEnv "APP_AUTH_ZERO_REDIRECT_URI" grantType <- T.pack <$> Env.getEnv "APP_AUTH_ZERO_GRANT_TYPE" basePath <- T.pack <$> Env.getEnv "APP_AUTH_ZERO_BASE_PATH" apiToken <- T.pack <$> Env.getEnv "APP_AUTH_ZERO_API_TOKEN" return $ Auth0.Config clientID clientSecret redirectURI grantType basePath apiToken -- The unsafe call to :fromJust is acceptable here -- since we are bootstrapping the application. -- If required configuration is not present and parsible, -- then we should fail to start the app logEntriesConfig :: IO LE.Config logEntriesConfig = do hostname <- Env.getEnv "APP_LOGENTRIES_DATA_DOMAIN" port <- read <$> Env.getEnv "APP_LOGENTRIES_DATA_PORT" token <- (fromJust . LE.fromString) <$> Env.getEnv "APP_LOGENTRIES_LOG_KEY" return $ LE.Config hostname port token -- laodEnvVars will look for configuration files matching the lowercase -- environment name in the user's data directory -- Ex. if the app name is 'cool-app' and the environment is Production, -- the env vars will be loaded from ~/.cool-app/production.env -- loadEnvVars will NOT raise an exception if the environment file is not found loadEnvVars :: AppName -> Environment -> IO () loadEnvVars appName env = dataDirectory appName >>= \dataDir -> do let filePath = dataDir </> envName env <.> "env" loadEnvFrom $ filePath where envName :: Environment -> FilePath envName = T.unpack . toLower . T.pack . show dataDirectory :: AppName -> IO FilePath dataDirectory = getAppUserDataDirectory . T.unpack
gust/feature-creature
auth-service/src/Config/AppConfig.hs
Haskell
mit
3,553
module Main where import qualified Dropbox as DB import System.Exit (exitFailure) import System.Environment (getArgs) import System.IO (hGetLine, hPutStrLn, stderr, stdout, stdin) import qualified Data.ByteString.Char8 as C8 import Control.Monad.IO.Class (liftIO) hostsDev = DB.Hosts "meta.dbdev.corp.dropbox.com" "api.dbdev.corp.dropbox.com" "api-content.dbdev.corp.dropbox.com" main :: IO () main = do args <- getArgs case args of [appKey, appSecret] -> mainProd appKey appSecret _ -> do hPutStrLn stderr "Usage: COMMAND app-key app-secret" exitFailure mainProd = main_ DB.hostsDefault mainDev = main_ hostsDev mkConfig hosts appKey appSecret = do base <- DB.mkConfig DB.localeEn appKey appSecret DB.AccessTypeDropbox return $ base { DB.configHosts = hosts } auth mgr config = liftIO $ do -- OAuth (requestToken, authUrl) <- DB.authStart mgr config Nothing `dieOnFailure` "Couldn't get request token" hPutStrLn stdout $ "Request Token: " ++ show requestToken hPutStrLn stdout $ "Auth URL: " ++ authUrl hGetLine stdin (accessToken, userId) <- DB.authFinish mgr config requestToken `dieOnFailure` "Couldn't get access token" hPutStrLn stdout $ "Access Token: " ++ show accessToken return accessToken accountInfo mgr session = liftIO $ do hPutStrLn stdout $ "---- Account Info ----" accountInfo <- DB.getAccountInfo mgr session `dieOnFailure` "Couldn't get account info" hPutStrLn stdout $ show accountInfo rootMetadata mgr session = liftIO $ do hPutStrLn stdout $ "---- Root Folder ----" (DB.Meta meta extra, mContents) <- DB.getMetadataWithChildren mgr session "/" Nothing `dieOnFailure` "Couldn't get root folder listing" (hash, children) <- case mContents of Just (DB.FolderContents hash children) -> return (hash, children) _ -> die "Root is not a folder? What the poop?" mapM_ ((hPutStrLn stdout).show) children hPutStrLn stdout $ "---- Root Folder (Again) ----" secondTime <- DB.getMetadataWithChildrenIfChanged mgr session "/" Nothing hash `dieOnFailure` "Couldn't get root folder listing again" hPutStrLn stdout (show secondTime) -- Will almost always print "Nothing" (i.e. "nothing has changed") addFile mgr session = liftIO $ do hPutStrLn stdout $ "---- Add File ----" meta <- DB.putFile mgr session "/Facts.txt" DB.WriteModeAdd (DB.bsRequestBody $ C8.pack "Rian hates types.\n") `dieOnFailure` "Couldn't add Facts.txt" hPutStrLn stdout $ show meta getFileContents mgr session = liftIO $ do hPutStrLn stdout $ "---- Get File ----" (meta, contents) <- DB.getFileBs mgr session "/Facts.txt" Nothing `dieOnFailure` "Couldn't read Facts.txt" hPutStrLn stdout $ show meta C8.hPutStrLn stdout contents main_ :: DB.Hosts -> String -> String -> IO () main_ hosts appKey appSecret = do config <- mkConfig hosts appKey appSecret DB.withManager $ \mgr -> do accessToken <- auth mgr config let session = DB.Session config accessToken accountInfo mgr session rootMetadata mgr session addFile mgr session getFileContents mgr session return () dieOnFailure :: IO (Either String v) -> String -> IO v dieOnFailure action errorPrefix = do ev <- action case ev of Left err -> die (errorPrefix ++ ": " ++ err) Right result -> return result die message = do hPutStrLn stderr message exitFailure
cakoose/dropbox-sdk-haskell
Examples/Simple.hs
Haskell
mit
3,524
{-# LANGUAGE PackageImports #-} {- Instead of generating C code directly, the STG compiler will instead build *abstract* C, a data structure representing the subset of C to which we want to compile. Abstract C supports nested definitions of functions and static arrays. These are floated to the top level when transformed into C source code. -} module AbstractC where import Control.Applicative import Control.Monad import "mtl" Control.Monad.State import Data.List import Data.Maybe import Text.Printf data Def = StaticArray { arrayName :: String, arrayType :: String, arrayElems :: [String] } | Function { functionName :: String, functionCode :: [Statement] } deriving (Show, Eq) -- | Generate a C declaration for a Def. genDecl :: Def -> String genDecl (StaticArray name ty elems) = printf "static %s %s[%d];\n" ty name (length elems) genDecl def@(Function name code) = unlines (nested ++ [top]) where top = printf "StgFunPtr %s();" name nested = map genDecl $ getNested def -- | Generate C code for a Def. genDef :: Def -> String genDef (StaticArray name ty elems) = printf "static %s %s[] = {%s};\n" ty name (intercalate ", " $ map genElem elems) where genElem e = printf "(%s)%s" ty e genDef def@(Function name code) = unlines (nested ++ [top]) where top = printf "StgFunPtr %s() {\n%s}" name (concat $ catMaybes $ map genStatement code) nested = map genDef $ getNested def -- | Represents a statement in a function body. data Statement = NestedDef Def | Return String | Switch String [(String, [Statement])] (Maybe [Statement]) | Code String deriving (Show, Eq) -- | Generate C code for a function statement. genStatement :: Statement -> Maybe String genStatement (NestedDef _) = Nothing genStatement (Return expr) = Just $ printf " return %s;\n" expr genStatement (Switch base cases def) = Just $ printf " switch (%s) {\n%s }\n" base body where mkCase (value, code) = printf " case %s:\n%s break;\n" value $ concat $ catMaybes $ map genStatement code defaultCase Nothing = "" defaultCase (Just code) = printf " default:\n%s" $ concat $ catMaybes $ map genStatement code body = concat (map mkCase cases ++ [defaultCase def]) genStatement (Code x) = Just (' ':x ++ ";\n") data GetNestedState = GNS [Def] -- | Add a Def to the accumulator state. addNested :: Def -> State GetNestedState () addNested def = do (GNS defs) <- get put (GNS (def:defs)) -- | Get a list of inner Defs. getNested :: Def -> [Def] getNested fun = let (GNS defs) = execState (mapM_ exNested $ functionCode fun) (GNS []) in defs -- | Possibly extract a nested Def from s atatement. exNested :: Statement -> State GetNestedState () exNested (NestedDef def) = addNested def exNested _ = return ()
tcsavage/lazy-compiler
src/AbstractC.hs
Haskell
mit
2,860
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables, RecordWildCards #-} module Text.Blaze.Html.Bootstrap where import Text.Blaze import qualified Text.Blaze.Html5 as H import qualified Text.Blaze.Html5.Attributes as A hiding (form, label) import Text.Blaze.Html5 import Text.Blaze.Html5.Attributes hiding (form, label) import Text.Blaze.Internal import qualified Data.Text as T import Data.Monoid import Control.Monad import Text.Blaze.Html.Utils formControl = A.class_ "form-control" glyphicon :: T.Text -> H.Html glyphicon s = H.span !. ("glyphicon glyphicon-"<>s) $ "" dataToggle :: T.Text -> Attribute dataToggle k = H.customAttribute "data-toggle" $ preEscapedToValue $ k dataTarget :: T.Text -> Attribute dataTarget k = H.customAttribute "data-target" $ preEscapedToValue $ k dataDismiss :: T.Text -> Attribute dataDismiss k = H.customAttribute "data-dismiss" $ preEscapedToValue $ k type NavTree = [NavItem] data NavItem = Header H.Html | Divider | Link H.Html | ActiveLink H.Html | SubTree H.Html NavTree -- example brand : H.a !. "navbar-brand" ! A.href "#" $ "Project name" data NavBar = NavBar { navBarBrand :: H.Html, navBarLeft :: NavTree, navBarRight :: NavTree } instance Monoid NavBar where mempty = NavBar mempty [] [] (NavBar b1 l1 r1) `mappend` (NavBar b2 l2 r2) = NavBar (b1<>b2) (l1++l2) (r1++r2) instance ToMarkup NavBar where toMarkup NavBar{..} = H.div !. "navbar navbar-default" ! role "navigation" $ do H.div !. "container" $ do H.div !. "navbar-header" $ do H.button ! A.type_ "button" !. "navbar-toggle" ! dataToggle "collapse" ! dataTarget "navbar-collapse" $ do H.span !. "sr-only" $ "Toggle navigation" H.span !. "icon-bar" $ "" H.span !. "icon-bar" $ "" H.span !. "icon-bar" $ "" navBarBrand H.div !. "navbar-collapse collapse" $ do H.ul !. "nav navbar-nav" $ do mapM_ navBarItem navBarLeft H.ul !. "nav navbar-nav navbar-right" $ do mapM_ navBarItem navBarRight staticNavBar :: NavBar -> H.Html staticNavBar nb = (H.toHtml nb) !. "navbar-static-top" fixedNavBar :: NavBar -> H.Html fixedNavBar nb = (H.toHtml nb) !. "navbar-fixed-top" navBarItem (Header h) = H.li h navBarItem (Link h) = H.li h navBarItem (ActiveLink h) = H.li !. "active" $ h navBarItem (Divider) = mempty navBarItem (SubTree hdr items) = H.li !. "dropdown" $ do H.a ! A.href "#" !. "dropdown-toggle" ! dataToggle "dropdown" $ do hdr H.b !. "caret" $ "" H.ul !. "dropdown-menu" $ do mapM_ dropdownItem items dropdownItem (Header h) = H.li !. "dropdown-header" $ h dropdownItem (Divider) = H.li !. "divider" $ "" dropdownItem (Link h) = H.li h dropdownItem (ActiveLink h) = H.li !. "active" $ h -- TODO http://stackoverflow.com/questions/18023493/bootstrap-3-dropdown-sub-menu-missing dropdownItem (SubTree hdr items) = error "dropdown submenus not yet implemented" data LoginRegister = LoginRegister { loginFormTitle :: Maybe T.Text, nameLabel :: T.Text, loginAction :: T.Text, registerAction:: T.Text, registerQuestions :: [(T.Text, T.Text)] } --generated by blaze-from-html from http://bootsnipp.com/snippets/featured/loginregister-in-tabbed-interface login_register_form :: LoginRegister -> Html login_register_form LoginRegister{..} = do H.div ! class_ "container" $ H.div ! class_ "row" $ H.div ! class_ "span12" $ H.div ! class_ "" ! A.id "loginModal" $ do case loginFormTitle of Nothing -> "" Just title -> H.div ! class_ "modal-header" $ do button ! type_ "button" ! class_ "close" ! dataAttribute "dismiss" "modal" $ mempty h3 $ toHtml title H.div ! class_ "modal-body" $ H.div ! class_ "well" $ do ul ! class_ "nav nav-tabs" $ do li ! class_ "active" $ a ! href "#login" ! dataAttribute "toggle" "tab" $ "Login" li $ a ! href "#create" ! dataAttribute "toggle" "tab" $ "Create Account" H.div ! A.id "myTabContent" ! class_ "tab-content" $ do H.div ! class_ "tab-pane active" ! A.id "login" $ do H.form ! class_ "form-horizontal" ! action (toValue loginAction) ! method "POST" $ fieldset $ do H.div ! A.id "legend" $ legend ! class_ "" $ "Login" H.div ! class_ "control-group" $ do -- Username H.label ! class_ "control-label" ! for (toName nameLabel) $ (toHtml nameLabel) H.div ! class_ "controls" $ input ! type_ "text" ! A.id (toValue nameLabel) ! name (toName nameLabel) ! placeholder "" ! class_ "input-xlarge" H.div ! class_ "control-group" $ do -- Password H.label ! class_ "control-label" ! for "password" $ "Password" H.div ! class_ "controls" $ input ! type_ "password" ! A.id "password" ! name "password" ! placeholder "" ! class_ "input-xlarge" H.div ! class_ "control-group" $ do -- Button H.div ! class_ "controls" $ button ! class_ "btn btn-success" $ "Login" H.div ! class_ "tab-pane" ! A.id "create" $ do H.form ! class_ "form-horizontal" ! action (toValue registerAction) ! method "POST" $ fieldset $ do H.div ! A.id "legend" $ legend ! class_ "" $ "Register" H.div ! class_ "control-group" $ do H.label ! class_ "control-label" $ (toHtml nameLabel) H.div ! class_ "controls" $ input ! type_ "text" ! value "" ! name (toName nameLabel) ! class_ "input-xlarge" H.div ! class_ "control-group" $ do -- Password H.label ! class_ "control-label" ! for "password" $ "Password" H.div ! class_ "controls" $ input ! type_ "password" ! A.id "password" ! name "password" ! placeholder "" ! class_ "input-xlarge" forM_ registerQuestions $ \(lbl, nm) -> do H.div ! class_ "control-group" $ do H.label ! class_ "control-label" $ (toHtml lbl) H.div ! class_ "controls" $ input ! type_ "text" ! value "" ! name (toValue nm) ! class_ "input-xlarge" H.div $ button ! class_ "btn btn-primary" $ "Create Account" toName txt = toValue $ T.toLower $ T.filter (/=' ') txt modal elemid mtitle mbody mfooter = H.div !. "modal fade" ! A.id elemid ! A.tabindex "-1" ! role "dialog" $ do H.div !. "modal-dialog" $ do H.div !. "modal-content" $ do H.div !. "modal-header" $ do H.button ! A.type_ "button" !. "close" ! dataDismiss "modal" $ do H.span (preEscapedToHtml ("&times;"::T.Text)) H.span !. "sr-only" $ "Close" H.h4 !. "modal-title" ! A.id "myModalLabel" $ mtitle H.div !. "modal-body" $ mbody H.div !. "modal-footer" $ mfooter progressBar = H.div !. "progress" $ do H.div !. "progress-bar" ! role "progressbar" ! A.style "width: 0%;" $ "" postButton :: T.Text -> T.Text -> H.Html -> H.Html postButton url btnClass label = H.form ! A.action (H.toValue $ url) ! A.method "post" $ do H.button !. ("btn " <> btnClass) ! A.type_ "submit" $ label row x = H.div ! class_ "row" $ x
glutamate/blaze-bootstrap
Text/Blaze/Html/Bootstrap.hs
Haskell
mit
7,552
{-# LANGUAGE OverloadedStrings #-} module Landing.Markdown (parseMarkdown) where import Text.Pandoc import Text.Pandoc.Options import Data.Set (Set, fromList) import Network.URI (isAbsoluteURI) import Landing.Repo (Repo, joinPath) import qualified Data.ByteString.Lazy.Char8 as C parseMarkdown :: Repo -> C.ByteString -> C.ByteString parseMarkdown repo = C.pack . writeHtmlString writeOptions . changeURIs repo . readMarkdown readOptions . C.unpack changeURIs :: Repo -> Pandoc -> Pandoc changeURIs repo = bottomUp (map $ convertURIs repo) convertURIs :: Repo -> Inline -> Inline convertURIs repo (Image a (b, c)) | isAbsoluteURI b = Image a (b, c) | otherwise = Image a (generateGitHubURI repo b, c) convertURIs _ x = x generateGitHubURI :: Repo -> String -> String generateGitHubURI repo path = concat [ "https://raw.githubusercontent.com/", joinPath repo, "/", path ] writeOptions = def { writerExtensions = extensions , writerReferenceLinks = True , writerSectionDivs = True , writerHighlight = True } readOptions = def { readerExtensions = extensions } extensions :: Set Extension extensions = fromList [ Ext_pipe_tables , Ext_raw_html , Ext_tex_math_single_backslash , Ext_fenced_code_blocks , Ext_fenced_code_attributes , Ext_auto_identifiers , Ext_ascii_identifiers , Ext_backtick_code_blocks , Ext_autolink_bare_uris , Ext_intraword_underscores , Ext_strikeout , Ext_lists_without_preceding_blankline ]
dennis84/landing-haskell
Landing/Markdown.hs
Haskell
mit
1,552
{-# LANGUAGE CPP #-} module Cabal ( getPackageGhcOpts , findCabalFile, findFile ) where import Stack import Control.Exception (IOException, catch) import Control.Monad (when) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.State (execStateT, modify) import Data.Char (isSpace) import Data.List (foldl', nub, sort, find, isPrefixOf, isSuffixOf) import Data.Maybe (isJust) #if __GLASGOW_HASKELL__ < 709 import Control.Applicative ((<$>)) import Data.Monoid (Monoid(..)) #endif #if __GLASGOW_HASKELL__ < 802 import Distribution.Package (PackageIdentifier(..), PackageName) #endif import Distribution.PackageDescription (PackageDescription(..), Executable(..), TestSuite(..), Benchmark(..), emptyHookedBuildInfo, buildable, libBuildInfo) import qualified Distribution.PackageDescription as Distribution #if MIN_VERSION_Cabal(2, 2, 0) import qualified Distribution.PackageDescription.Parsec as Distribution #else import qualified Distribution.PackageDescription.Parse as Distribution #endif import Distribution.Simple.Configure (configure) import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..), Component(..), componentName, getComponentLocalBuildInfo, componentBuildInfo) import Distribution.Simple.Compiler (PackageDB(..)) import Distribution.Simple.Command (CommandParse(..), commandParseArgs) import Distribution.Simple.GHC (componentGhcOptions) import Distribution.Simple.Program (defaultProgramConfiguration) import Distribution.Simple.Program.Db (lookupProgram) import Distribution.Simple.Program.Types (ConfiguredProgram(programVersion), simpleProgram) import Distribution.Simple.Program.GHC (GhcOptions(..), renderGhcOptions) import Distribution.Simple.Setup (ConfigFlags(..), defaultConfigFlags, configureCommand, toFlag, flagToMaybe) #if MIN_VERSION_Cabal(1,21,1) import Distribution.Utils.NubList #endif import qualified Distribution.Simple.GHC as GHC(configure) import Distribution.Verbosity (silent) import qualified Distribution.Verbosity as Distribution import Distribution.Version import System.IO.Error (ioeGetErrorString) import System.Directory (doesFileExist, doesDirectoryExist, getDirectoryContents) import System.FilePath (takeDirectory, splitFileName, (</>)) readGenericPackageDescription :: Distribution.Verbosity -> FilePath -> IO Distribution.GenericPackageDescription #if MIN_VERSION_Cabal(2, 0, 0) readGenericPackageDescription = Distribution.readGenericPackageDescription #else readGenericPackageDescription = Distribution.readPackageDescription #endif -- TODO: Fix callsites so we don't need `allComponentsBy`. It was taken from -- http://hackage.haskell.org/package/Cabal-1.16.0.3/docs/src/Distribution-Simple-LocalBuildInfo.html#allComponentsBy -- since it doesn't exist in Cabal 1.18.* -- -- | Obtains all components (libs, exes, or test suites), transformed by the -- given function. Useful for gathering dependencies with component context. allComponentsBy :: PackageDescription -> (Component -> a) -> [a] allComponentsBy pkg_descr f = [ f (CLib lib) | Just lib <- [library pkg_descr] , buildable (libBuildInfo lib) ] ++ [ f (CExe exe) | exe <- executables pkg_descr , buildable (buildInfo exe) ] ++ [ f (CTest tst) | tst <- testSuites pkg_descr , buildable (testBuildInfo tst)] ++ [ f (CBench bm) | bm <- benchmarks pkg_descr , buildable (benchmarkBuildInfo bm)] stackifyFlags :: ConfigFlags -> Maybe StackConfig -> ConfigFlags stackifyFlags cfg Nothing = cfg stackifyFlags cfg (Just si) = cfg { configHcPath = toFlag ghc , configHcPkg = toFlag ghcPkg , configDistPref = toFlag dist , configPackageDBs = pdbs } where pdbs = [Nothing, Just GlobalPackageDB] ++ pdbs' pdbs' = Just . SpecificPackageDB <$> stackDbs si dist = stackDist si ghc = stackGhcBinDir si </> "ghc" ghcPkg = stackGhcBinDir si </> "ghc-pkg" -- via: https://groups.google.com/d/msg/haskell-stack/8HJ6DHAinU0/J68U6AXTsasJ -- cabal configure --package-db=clear --package-db=global --package-db=$(stack path --snapshot-pkg-db) --package-db=$(stack path --local-pkg-db) getPackageGhcOpts :: FilePath -> Maybe StackConfig -> [String] -> IO (Either String [String]) getPackageGhcOpts path mbStack opts = getPackageGhcOpts' `catch` (\e -> return $ Left $ "Cabal error: " ++ ioeGetErrorString (e :: IOException)) where getPackageGhcOpts' :: IO (Either String [String]) getPackageGhcOpts' = do genPkgDescr <- readGenericPackageDescription silent path distDir <- getDistDir -- TODO(SN): defaultProgramConfiguration is deprecated let programCfg = defaultProgramConfiguration let initCfgFlags = (defaultConfigFlags programCfg) { configDistPref = toFlag distDir -- TODO: figure out how to find out this flag , configUserInstall = toFlag True -- configure with --enable-tests to include test dependencies/modules , configTests = toFlag True -- configure with --enable-benchmarks to include benchmark dependencies/modules , configBenchmarks = toFlag True } let initCfgFlags' = stackifyFlags initCfgFlags mbStack cfgFlags <- flip execStateT initCfgFlags' $ do let sandboxConfig = takeDirectory path </> "cabal.sandbox.config" exists <- lift $ doesFileExist sandboxConfig when exists $ do sandboxPackageDb <- lift $ getSandboxPackageDB sandboxConfig modify $ \x -> x { configPackageDBs = [Just sandboxPackageDb] } let cmdUI = configureCommand programCfg case commandParseArgs cmdUI True opts of CommandReadyToGo (modFlags, _) -> modify modFlags CommandErrors (e:_) -> error e _ -> return () localBuildInfo <- configure (genPkgDescr, emptyHookedBuildInfo) cfgFlags let baseDir = fst . splitFileName $ path case getGhcVersion localBuildInfo of Nothing -> return $ Left "GHC is not configured" Just ghcVersion -> do #if __GLASGOW_HASKELL__ < 802 let pkgDescr = localPkgDescr localBuildInfo let mbLibName = pkgLibName pkgDescr #endif let ghcOpts' = foldl' mappend mempty . map (getComponentGhcOptions localBuildInfo) . flip allComponentsBy id . localPkgDescr $ localBuildInfo -- FIX bug in GhcOptions' `mappend` #if MIN_VERSION_Cabal(2,4,0) -- API Change, just for the glory of Satan: -- Distribution.Simple.Program.GHC.GhcOptions no longer uses NubListR's ghcOpts = ghcOpts' { ghcOptExtra = filter (/= "-Werror") $ ghcOptExtra ghcOpts' #elif MIN_VERSION_Cabal(1,21,1) -- API Change: -- Distribution.Simple.Program.GHC.GhcOptions now uses NubListR's -- GhcOptions { .. ghcOptPackages :: NubListR (InstalledPackageId, PackageId, ModuleRemaining) .. } ghcOpts = ghcOpts' { ghcOptExtra = overNubListR (filter (/= "-Werror")) $ ghcOptExtra ghcOpts' #endif #if MIN_VERSION_Cabal(1,21,1) #if __GLASGOW_HASKELL__ >= 709 , ghcOptPackageDBs = sort $ nub (ghcOptPackageDBs ghcOpts') #endif #if __GLASGOW_HASKELL__ < 802 , ghcOptPackages = overNubListR (filter (\(_, pkgId, _) -> Just (pkgName pkgId) /= mbLibName)) $ (ghcOptPackages ghcOpts') #endif , ghcOptSourcePath = overNubListR (map (baseDir </>)) (ghcOptSourcePath ghcOpts') } #else -- GhcOptions { .. ghcOptPackages :: [(InstalledPackageId, PackageId)] .. } let ghcOpts = ghcOpts' { ghcOptExtra = filter (/= "-Werror") $ nub $ ghcOptExtra ghcOpts' , ghcOptPackages = filter (\(_, pkgId) -> Just (pkgName pkgId) /= mbLibName) $ nub (ghcOptPackages ghcOpts') , ghcOptSourcePath = map (baseDir </>) (ghcOptSourcePath ghcOpts') } #endif let hcPath = flagToMaybe . configHcPath $ configFlags localBuildInfo let pkgPath = flagToMaybe . configHcPkg $ configFlags localBuildInfo -- TODO(SN): defaultProgramConfiguration is deprecated (ghcInfo, mbPlatform, _) <- GHC.configure silent hcPath pkgPath defaultProgramConfiguration putStrLn $ "Configured GHC " ++ show ghcVersion ++ " " ++ show mbPlatform #if MIN_VERSION_Cabal(1,23,2) -- API Change: -- Distribution.Simple.Program.GHC.renderGhcOptions now takes Platform argument -- renderGhcOptions :: Compiler -> Platform -> GhcOptions -> [String] return $ case mbPlatform of Just platform -> Right $ renderGhcOptions ghcInfo platform ghcOpts Nothing -> Left "GHC.configure did not return platform" #else #if MIN_VERSION_Cabal(1,20,0) -- renderGhcOptions :: Compiler -> GhcOptions -> [String] return $ Right $ renderGhcOptions ghcInfo ghcOpts #else -- renderGhcOptions :: Version -> GhcOptions -> [String] return $ Right $ renderGhcOptions ghcVersion ghcOpts #endif #endif -- returns the right 'dist' directory in the case of a sandbox getDistDir = do let dir = takeDirectory path </> "dist" exists <- doesDirectoryExist dir if not exists then return dir else do contents <- getDirectoryContents dir return . maybe dir (dir </>) $ find ("dist-sandbox-" `isPrefixOf`) contents #if __GLASGOW_HASKELL__ < 802 pkgLibName :: PackageDescription -> Maybe PackageName pkgLibName pkgDescr = if hasLibrary pkgDescr then Just $ pkgName . package $ pkgDescr else Nothing #endif hasLibrary :: PackageDescription -> Bool hasLibrary = isJust . library getComponentGhcOptions :: LocalBuildInfo -> Component -> GhcOptions getComponentGhcOptions lbi comp = componentGhcOptions silent lbi bi clbi (buildDir lbi) where bi = componentBuildInfo comp -- TODO(SN): getComponentLocalBuildInfo is deprecated as of Cabal-2.0.0.2 clbi = getComponentLocalBuildInfo lbi (componentName comp) getGhcVersion :: LocalBuildInfo -> Maybe Version getGhcVersion lbi = let db = withPrograms lbi in do ghc <- lookupProgram (simpleProgram "ghc") db programVersion ghc getSandboxPackageDB :: FilePath -> IO PackageDB getSandboxPackageDB sandboxPath = do contents <- readFile sandboxPath return $ SpecificPackageDB $ extractValue . parse $ contents where pkgDbKey = "package-db:" parse = head . filter (pkgDbKey `isPrefixOf`) . lines extractValue = takeWhile (`notElem` "\n\r") . dropWhile isSpace . drop (length pkgDbKey) -- | looks for file matching a predicate starting from dir and going up until root findFile :: (FilePath -> Bool) -> FilePath -> IO (Maybe FilePath) findFile p dir = do allFiles <- getDirectoryContents dir case find p allFiles of Just cabalFile -> return $ Just $ dir </> cabalFile Nothing -> let parentDir = takeDirectory dir in if parentDir == dir then return Nothing else findFile p parentDir findCabalFile :: FilePath -> IO (Maybe FilePath) findCabalFile = findFile isCabalFile where isCabalFile :: FilePath -> Bool isCabalFile path = ".cabal" `isSuffixOf` path && length path > length ".cabal"
hdevtools/hdevtools
src/Cabal.hs
Haskell
mit
11,960
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE UnicodeSyntax #-} module Unison.FileParsers where import Unison.Prelude import Control.Lens (view, _3) import qualified Unison.Parser as Parser import Control.Monad.State (evalStateT) import Control.Monad.Writer (tell) import Data.Bifunctor ( first ) import qualified Data.Foldable as Foldable import qualified Data.Map as Map import Data.List (partition) import qualified Data.Set as Set import qualified Data.Sequence as Seq import Data.Text (unpack) import qualified Unison.ABT as ABT import qualified Unison.Blank as Blank import qualified Unison.Name as Name import qualified Unison.Names3 as Names import Unison.Parser (Ann) import qualified Unison.Parsers as Parsers import qualified Unison.Referent as Referent import Unison.Reference (Reference) import Unison.Result (Note (..), Result, pattern Result, ResultT, CompilerBug(..)) import qualified Unison.Result as Result import qualified Unison.Term as Term import qualified Unison.Type as Type import qualified Unison.Typechecker as Typechecker import qualified Unison.Typechecker.TypeLookup as TL import qualified Unison.Typechecker.Context as Context import qualified Unison.UnisonFile as UF import qualified Unison.Util.List as List import qualified Unison.Util.Relation as Rel import Unison.Var (Var) import qualified Unison.Var as Var import Unison.Names3 (Names0) type Term v = Term.Term v Ann type Type v = Type.Type v Ann type UnisonFile v = UF.UnisonFile v Ann type Result' v = Result (Seq (Note v Ann)) debug :: Bool debug = False convertNotes :: Ord v => Typechecker.Notes v ann -> Seq (Note v ann) convertNotes (Typechecker.Notes bugs es is) = (CompilerBug . TypecheckerBug <$> bugs) <> (TypeError <$> es) <> (TypeInfo <$> Seq.fromList is') where is' = snd <$> List.uniqueBy' f ([(1::Word)..] `zip` Foldable.toList is) f (_, Context.TopLevelComponent cs) = Right [ v | (v,_,_) <- cs ] f (i, _) = Left i -- each round of TDNR emits its own TopLevelComponent notes, so we remove -- duplicates (based on var name and location), preferring the later note as -- that will have the latest typechecking info parseAndSynthesizeFile :: (Var v, Monad m) => [Type v] -> (Set Reference -> m (TL.TypeLookup v Ann)) -> Parser.ParsingEnv -> FilePath -> Text -> ResultT (Seq (Note v Ann)) m (Either Names0 (UF.TypecheckedUnisonFile v Ann)) parseAndSynthesizeFile ambient typeLookupf env filePath src = do when debug $ traceM "parseAndSynthesizeFile" uf <- Result.fromParsing $ Parsers.parseFile filePath (unpack src) env let names0 = Names.currentNames (Parser.names env) (tm, tdnrMap, typeLookup) <- resolveNames typeLookupf names0 uf let (Result notes' r) = synthesizeFile ambient typeLookup tdnrMap uf tm tell notes' $> maybe (Left (UF.toNames uf )) Right r type TDNRMap v = Map Typechecker.Name [Typechecker.NamedReference v Ann] resolveNames :: (Var v, Monad m) => (Set Reference -> m (TL.TypeLookup v Ann)) -> Names.Names0 -> UnisonFile v -> ResultT (Seq (Note v Ann)) m (Term v, TDNRMap v, TL.TypeLookup v Ann) resolveNames typeLookupf preexistingNames uf = do let tm = UF.typecheckingTerm uf deps = Term.dependencies tm possibleDeps = [ (Name.toText name, Var.name v, r) | (name, r) <- Rel.toList (Names.terms0 preexistingNames), v <- Set.toList (Term.freeVars tm), name `Name.endsWithSegments` Name.fromVar v ] possibleRefs = Referent.toReference . view _3 <$> possibleDeps tl <- lift . lift . fmap (UF.declsToTypeLookup uf <>) $ typeLookupf (deps <> Set.fromList possibleRefs) -- For populating the TDNR environment, we pick definitions -- from the namespace and from the local file whose full name -- has a suffix that equals one of the free variables in the file. -- Example, the namespace has [foo.bar.baz, qux.quaffle] and -- the file has definitons [utils.zonk, utils.blah] and -- the file has free variables [bar.baz, zonk]. -- -- In this case, [foo.bar.baz, utils.zonk] are used to create -- the TDNR environment. let fqnsByShortName = List.multimap $ -- external TDNR possibilities [ (shortname, nr) | (name, shortname, r) <- possibleDeps, typ <- toList $ TL.typeOfReferent tl r, let nr = Typechecker.NamedReference name typ (Right r) ] <> -- local file TDNR possibilities [ (Var.name v, nr) | (name, r) <- Rel.toList (Names.terms0 $ UF.toNames uf), v <- Set.toList (Term.freeVars tm), name `Name.endsWithSegments` Name.fromVar v, typ <- toList $ TL.typeOfReferent tl r, let nr = Typechecker.NamedReference (Name.toText name) typ (Right r) ] pure (tm, fqnsByShortName, tl) synthesizeFile' :: forall v . Var v => [Type v] -> TL.TypeLookup v Ann -> UnisonFile v -> Result (Seq (Note v Ann)) (UF.TypecheckedUnisonFile v Ann) synthesizeFile' ambient tl uf = synthesizeFile ambient tl mempty uf $ UF.typecheckingTerm uf synthesizeFile :: forall v . Var v => [Type v] -> TL.TypeLookup v Ann -> TDNRMap v -> UnisonFile v -> Term v -> Result (Seq (Note v Ann)) (UF.TypecheckedUnisonFile v Ann) synthesizeFile ambient tl fqnsByShortName uf term = do let -- substitute Blanks for any remaining free vars in UF body tdnrTerm = Term.prepareTDNR term env0 = Typechecker.Env ambient tl fqnsByShortName Result notes mayType = evalStateT (Typechecker.synthesizeAndResolve env0) tdnrTerm -- If typechecking succeeded, reapply the TDNR decisions to user's term: Result (convertNotes notes) mayType >>= \_typ -> do let infos = Foldable.toList $ Typechecker.infos notes (topLevelComponents :: [[(v, Term v, Type v)]]) <- let topLevelBindings :: Map v (Term v) topLevelBindings = Map.mapKeys Var.reset $ extractTopLevelBindings tdnrTerm extractTopLevelBindings (Term.LetRecNamedAnnotatedTop' True _ bs body) = Map.fromList (first snd <$> bs) <> extractTopLevelBindings body extractTopLevelBindings _ = Map.empty tlcsFromTypechecker = List.uniqueBy' (fmap vars) [ t | Context.TopLevelComponent t <- infos ] where vars (v, _, _) = v strippedTopLevelBinding (v, typ, redundant) = do tm <- case Map.lookup v topLevelBindings of Nothing -> Result.compilerBug $ Result.TopLevelComponentNotFound v term Just (Term.Ann' x _) | redundant -> pure x Just x -> pure x -- The Var.reset removes any freshening added during typechecking pure (Var.reset v, tm, typ) in -- use tlcsFromTypechecker to inform annotation-stripping decisions traverse (traverse strippedTopLevelBinding) tlcsFromTypechecker let doTdnr = applyTdnrDecisions infos doTdnrInComponent (v, t, tp) = (\t -> (v, t, tp)) <$> doTdnr t _ <- doTdnr tdnrTerm tdnredTlcs <- (traverse . traverse) doTdnrInComponent topLevelComponents let (watches', terms') = partition isWatch tdnredTlcs isWatch = all (\(v,_,_) -> Set.member v watchedVars) watchedVars = Set.fromList [ v | (v, _) <- UF.allWatches uf ] tlcKind [] = error "empty TLC, should never occur" tlcKind tlc@((v,_,_):_) = let hasE k = elem v . fmap fst $ Map.findWithDefault [] k (UF.watches uf) in case Foldable.find hasE (Map.keys $ UF.watches uf) of Nothing -> error "wat" Just kind -> (kind, tlc) pure $ UF.typecheckedUnisonFile (UF.dataDeclarationsId uf) (UF.effectDeclarationsId uf) terms' (map tlcKind watches') where applyTdnrDecisions :: [Context.InfoNote v Ann] -> Term v -> Result' v (Term v) applyTdnrDecisions infos tdnrTerm = foldM go tdnrTerm decisions where -- UF data/effect ctors + builtins + TLC Term.vars go term _decision@(shortv, loc, replacement) = ABT.visit (resolve shortv loc replacement) term decisions = [ (v, loc, replacement) | Context.Decision v loc replacement <- infos ] -- resolve (v,loc) in a matching Blank to whatever `fqn` maps to in `names` resolve shortv loc replacement t = case t of Term.Blank' (Blank.Recorded (Blank.Resolve loc' name)) | loc' == loc && Var.nameStr shortv == name -> -- loc of replacement already chosen correctly by whatever made the -- Decision pure . pure $ replacement _ -> Nothing
unisonweb/platform
parser-typechecker/src/Unison/FileParsers.hs
Haskell
mit
9,073
module Language.TaPL.TypedArith.Parser (parseString, parseFile) where import qualified Text.Parsec.Token as Token import Text.Parsec.Language (emptyDef) import Text.Parsec.Prim (parse) import Text.Parsec.String (Parser) import Control.Applicative ((<|>)) import Control.Monad (liftM) import Language.TaPL.TypedArith.Syntax (Term(..), integerToTerm) -- This module is adapted from: http://www.haskell.org/haskellwiki/Parsing_a_simple_imperative_language booleanDef = emptyDef { Token.reservedNames = [ "if" , "then" , "else" , "true" , "false" , "zero" , "succ" , "pred" , "iszero" ] } lexer = Token.makeTokenParser booleanDef reserved = Token.reserved lexer -- parses a reserved name parens = Token.parens lexer -- parses surrounding parenthesis: -- parens p -- takes care of the parenthesis and -- uses p to parse what's inside them whiteSpace = Token.whiteSpace lexer -- parses whitespace integer = Token.integer lexer -- parses an integer booleanParser :: Parser Term booleanParser = whiteSpace >> expr expr :: Parser Term expr = parens expr <|> ifExpr <|> (reserved "true" >> return TmTrue) <|> (reserved "false" >> return TmFalse) <|> arithExpr ifExpr :: Parser Term ifExpr = do reserved "if" t1 <- expr reserved "then" t2 <- expr reserved "else" t3 <- expr return $ TmIf t1 t2 t3 arithExpr :: Parser Term arithExpr = (reserved "zero" >> return TmZero) <|> predExpr <|> succExpr <|> iszeroExpr <|> liftM integerToTerm integer predExpr :: Parser Term predExpr = oneArgExprHelper TmPred "pred" succExpr :: Parser Term succExpr = oneArgExprHelper TmSucc "succ" iszeroExpr :: Parser Term iszeroExpr = oneArgExprHelper TmIsZero "iszero" oneArgExprHelper :: (Term -> Term) -> String -> Parser Term oneArgExprHelper constructor word = do reserved word t <- expr return $ constructor t parseString :: String -> Term parseString str = case parse booleanParser "" str of Left e -> error $ show e Right t -> t parseFile :: String -> IO Term parseFile file = do program <- readFile file case parse booleanParser "" program of Left e -> print e >> fail "parse error" Right t -> return t
zeckalpha/TaPL
src/Language/TaPL/TypedArith/Parser.hs
Haskell
mit
2,844
module Game where import Linear import Time import Input import Transform data GameState a = GameState { worms :: [Worm a] } data Worm a = Worm type Position = V2 -- nextState :: State -> DTime -> [InputEvent] -> State -- nextState s dt is = s -- TODO
epeld/zatacka
old/Game.hs
Haskell
apache-2.0
257
{-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE ScopedTypeVariables #-} module Network.GRPC.HighLevel.Client ( ClientError(..) , ClientRegisterable(..) , ClientRequest(..) , ClientResult(..) , GRPCMethodType(..) , MetadataMap(..) , RegisteredMethod , ServiceClient , StatusCode(..) , StatusDetails(..) , StreamRecv , StreamSend , TimeoutSeconds , WritesDone , LL.Client , LL.ClientConfig(..) , LL.ClientSSLConfig(..) , LL.ClientSSLKeyCertPair(..) , LL.Host(..) , LL.Port(..) , clientRequest -- * Client utility functions , acquireClient , simplifyServerStreaming , simplifyUnary ) where import Control.Monad.Managed (Managed, liftIO, managed) import qualified Data.ByteString.Lazy as BL import Network.GRPC.HighLevel.Server (convertRecv, convertSend) import Network.GRPC.LowLevel (GRPCIOError (..), GRPCMethodType (..), MetadataMap (..), StatusCode (..), StatusDetails (..), StreamRecv, StreamSend) import qualified Network.GRPC.LowLevel as LL import Network.GRPC.LowLevel.CompletionQueue (TimeoutSeconds) import Network.GRPC.LowLevel.Op (WritesDone) import Proto3.Suite (Message, fromByteString, toLazyByteString) import Proto3.Wire.Decode (ParseError) newtype RegisteredMethod (mt :: GRPCMethodType) request response = RegisteredMethod (LL.RegisteredMethod mt) deriving Show type ServiceClient service = service ClientRequest ClientResult data ClientError = ClientErrorNoParse ParseError | ClientIOError GRPCIOError deriving (Show, Eq) data ClientRequest (streamType :: GRPCMethodType) request response where ClientNormalRequest :: request -> TimeoutSeconds -> MetadataMap -> ClientRequest 'Normal request response ClientWriterRequest :: TimeoutSeconds -> MetadataMap -> (StreamSend request -> IO ()) -> ClientRequest 'ClientStreaming request response -- | The final field will be invoked once, and it should repeatedly -- invoke its final argument (of type @(StreamRecv response)@) -- in order to obtain the streaming response incrementally. ClientReaderRequest :: request -> TimeoutSeconds -> MetadataMap -> (LL.ClientCall -> MetadataMap -> StreamRecv response -> IO ()) -> ClientRequest 'ServerStreaming request response ClientBiDiRequest :: TimeoutSeconds -> MetadataMap -> (LL.ClientCall -> MetadataMap -> StreamRecv response -> StreamSend request -> WritesDone -> IO ()) -> ClientRequest 'BiDiStreaming request response data ClientResult (streamType :: GRPCMethodType) response where ClientNormalResponse :: response -> MetadataMap -> MetadataMap -> StatusCode -> StatusDetails -> ClientResult 'Normal response ClientWriterResponse :: Maybe response -> MetadataMap -> MetadataMap -> StatusCode -> StatusDetails -> ClientResult 'ClientStreaming response ClientReaderResponse :: MetadataMap -> StatusCode -> StatusDetails -> ClientResult 'ServerStreaming response ClientBiDiResponse :: MetadataMap -> StatusCode -> StatusDetails -> ClientResult 'BiDiStreaming response ClientErrorResponse :: ClientError -> ClientResult streamType response class ClientRegisterable (methodType :: GRPCMethodType) where clientRegisterMethod :: LL.Client -> LL.MethodName -> IO (RegisteredMethod methodType request response) instance ClientRegisterable 'Normal where clientRegisterMethod client methodName = RegisteredMethod <$> LL.clientRegisterMethodNormal client methodName instance ClientRegisterable 'ClientStreaming where clientRegisterMethod client methodName = RegisteredMethod <$> LL.clientRegisterMethodClientStreaming client methodName instance ClientRegisterable 'ServerStreaming where clientRegisterMethod client methodName = RegisteredMethod <$> LL.clientRegisterMethodServerStreaming client methodName instance ClientRegisterable 'BiDiStreaming where clientRegisterMethod client methodName = RegisteredMethod <$> LL.clientRegisterMethodBiDiStreaming client methodName clientRequest :: (Message request, Message response) => LL.Client -> RegisteredMethod streamType request response -> ClientRequest streamType request response -> IO (ClientResult streamType response) clientRequest client (RegisteredMethod method) (ClientNormalRequest req timeout meta) = mkResponse <$> LL.clientRequest client method timeout (BL.toStrict (toLazyByteString req)) meta where mkResponse (Left ioError_) = ClientErrorResponse (ClientIOError ioError_) mkResponse (Right rsp) = case fromByteString (LL.rspBody rsp) of Left err -> ClientErrorResponse (ClientErrorNoParse err) Right parsedRsp -> ClientNormalResponse parsedRsp (LL.initMD rsp) (LL.trailMD rsp) (LL.rspCode rsp) (LL.details rsp) clientRequest client (RegisteredMethod method) (ClientWriterRequest timeout meta handler) = mkResponse <$> LL.clientWriter client method timeout meta (handler . convertSend) where mkResponse (Left ioError_) = ClientErrorResponse (ClientIOError ioError_) mkResponse (Right (rsp_, initMD_, trailMD_, rspCode_, details_)) = case maybe (Right Nothing) (fmap Just . fromByteString) rsp_ of Left err -> ClientErrorResponse (ClientErrorNoParse err) Right parsedRsp -> ClientWriterResponse parsedRsp initMD_ trailMD_ rspCode_ details_ clientRequest client (RegisteredMethod method) (ClientReaderRequest req timeout meta handler) = mkResponse <$> LL.clientReader client method timeout (BL.toStrict (toLazyByteString req)) meta (\cc m recv -> handler cc m (convertRecv recv)) where mkResponse (Left ioError_) = ClientErrorResponse (ClientIOError ioError_) mkResponse (Right (meta_, rspCode_, details_)) = ClientReaderResponse meta_ rspCode_ details_ clientRequest client (RegisteredMethod method) (ClientBiDiRequest timeout meta handler) = mkResponse <$> LL.clientRW client method timeout meta (\cc _m recv send writesDone -> handler cc meta (convertRecv recv) (convertSend send) writesDone) where mkResponse (Left ioError_) = ClientErrorResponse (ClientIOError ioError_) mkResponse (Right (meta_, rspCode_, details_)) = ClientBiDiResponse meta_ rspCode_ details_ acquireClient :: LL.ClientConfig -- ^ The client configuration (host, port, SSL settings, etc) -> (LL.Client -> IO (ServiceClient service)) -- ^ The client implementation (typically generated) -> Managed (ServiceClient service) acquireClient cfg impl = do g <- managed LL.withGRPC c <- managed (LL.withClient g cfg) liftIO (impl c) -- | A utility for simplifying server-streaming gRPC client requests; you can -- use this to avoid 'ClientRequest' and 'ClientResult' pattern-matching -- boilerplate at call sites. simplifyServerStreaming :: TimeoutSeconds -- ^ RPC call timeout, in seconds -> MetadataMap -- ^ RPC call metadata -> (ClientError -> IO StatusDetails) -- ^ Handler for client errors -> (StatusCode -> StatusDetails -> IO StatusDetails) -- ^ Handler for non-StatusOk response -> (ClientRequest 'ServerStreaming request response -> IO (ClientResult 'ServerStreaming response)) -- ^ Endpoint implementation (typically generated by grpc-haskell) -> request -- ^ Request payload -> (LL.ClientCall -> MetadataMap -> StreamRecv response -> IO ()) -- ^ Stream handler; note that the 'StreamRecv' -- action must be called repeatedly in order to -- consume the stream -> IO StatusDetails simplifyServerStreaming timeout meta clientError nonStatusOkError f x handler = do let request = ClientReaderRequest x timeout meta handler response <- f request case response of ClientReaderResponse _ StatusOk details -> pure details ClientReaderResponse _ statusCode details -> nonStatusOkError statusCode details ClientErrorResponse err -> clientError err -- | A utility for simplifying unary gRPC client requests; you can use this to -- avoid 'ClientRequest' and 'ClientResult' pattern-matching boilerplate at -- call sites. simplifyUnary :: TimeoutSeconds -- ^ RPC call timeout, in seconds -> MetadataMap -- ^ RPC call metadata -> (ClientError -> IO (response, StatusDetails)) -- ^ Handler for client errors -> (response -> StatusCode -> StatusDetails -> IO (response, StatusDetails)) -- ^ Handler for non-StatusOK responses -> (ClientRequest 'Normal request response -> IO (ClientResult 'Normal response)) -- ^ Endpoint implementation (typically generated by grpc-haskell) -> (request -> IO (response, StatusDetails)) -- ^ The simplified happy-path (StatusOk) unary call action simplifyUnary timeout meta clientError nonStatusOkError f x = do let request = ClientNormalRequest x timeout meta response <- f request case response of ClientNormalResponse y _ _ StatusOk details -> pure (y, details) ClientNormalResponse y _ _ code details -> nonStatusOkError y code details ClientErrorResponse err -> clientError err
awakenetworks/gRPC-haskell
src/Network/GRPC/HighLevel/Client.hs
Haskell
apache-2.0
10,256
{-# LANGUAGE FlexibleContexts, TypeOperators, Rank2Types, TypeFamilies #-} module Data.HMin where import Data.MemoTrie import Data.AdditiveGroup import Data.VectorSpace import Data.Maclaurin import Data.Basis import Data.LinearMap import Control.Arrow -- convenience type and eq operator type Equation a b = (a -> b) -> b -> a -> b infixl 5 ~= (~=) :: Num b => (a -> b) -> b -> a -> b f ~= c = \x -> f x - c eqAnd :: Num c => (a -> c) -> (b -> c) -> (a, b) -> c eqAnd f1 f2 (x, y) = sqr (f1 x) + sqr (f2 y) eqAnd' :: Num c => (a -> c) -> (a -> c) -> a -> c eqAnd' f1 f2 x = (f1 `eqAnd` f2) (dup x) where dup v = (v, v) sqr :: Num b => b -> b sqr x = x*x sqrD :: (Num b, VectorSpace b, b ~ Scalar b, b ~ (Scalar a), HasBasis a, HasTrie (Basis a)) => (a :> b) -> (a :> b) sqrD = sqr solve :: (Show a, Num b, Ord b, AdditiveGroup a) => (a :~> b) -> ((a :> b) -> Bool) -> ((a :> b) -> a) -> a -> a solve eq stopfunc stepfunc start = let delta = eq start in if stopfunc delta then start else solve eq stopfunc stepfunc (start ^+^ stepfunc delta) -- TODO -- need this -- https://en.wikipedia.org/wiki/Pushforward_(differential) gradStepFunc :: (HasBasis a, HasTrie (Basis a), VectorSpace b, Num b, Scalar a ~ b, Scalar b ~ b) => a -> (a :> b) -> a gradStepFunc gammas delta = negateV $ dV gammas (sqrD delta) -- TODO double check this please -- the derivative in the V direction with "f," a function to get us -- from a :> b to a... dV :: (Scalar a ~ b, Scalar b ~ b, HasBasis a, HasTrie (Basis a), VectorSpace b) => a -> (a :> b) -> a dV dv dfx = recompose . map (\(v, s) -> (v, (^* s) . powVal $ derivAtBasis dfx v)) $ decompose dv equ' :: ((Double, Double) :~> Double) equ' = sqr fstD + sqr sndD ~= 4 equ'' :: ((Double, Double) :~> Double) equ'' = fstD + 2*sndD ~= 2 -- this seems to requre the list of basis values... {- instance (VectorSpace b, HasBasis a, HasTrie (Basis a), Scalar a ~ Scalar b) => HasBasis (a -> b) where type Basis (a -> b) = (Basis a) -> b -- TODO -- do we really need Scalar a ~ Scalar b? -- lapply requires it, so seems possible. -- move to linear maps... basisValue f = sumV . map (\(b, s) -> s *^ f b) . decompose -- TODO -- I think I need the list of basis vectors (possibly infinite) here... -- Data.VectorSpace.project??? decompose f = map (first (f . basisValue)) -} -- https://stackoverflow.com/questions/9313994/derivative-towers-and-how-to-use-the-vector-space-package-haskell diff :: (Double :~> (Double,Double,Double) ) -> (Double :~> (Double,Double,Double)) diff g = \x -> (atBasis (derivative (g x)) ()) diff' :: Either () () -> ((Double, Double) :~> Double) -> ((Double, Double) :~> Double) diff' b g = \(x,y) -> derivAtBasis (g (x,y)) b eval :: (a :~> b) -> a -> b eval g x = powVal (g x) f :: Double :~> (Double,Double,Double) f x = tripleD (pureD 0, pureD 1, (2*idD) x) f' :: (Double, Double) :~> Double f' xy = fstD xy + (sndD*2) xy
cspollard/hminimize
src/Data/HMin.hs
Haskell
apache-2.0
3,062
module OAuthToken ( AccessToken , RequestToken , OAuthToken ) where import Prelude import Yesod import qualified Data.Text as T import Database.Persist.Store ( SqlType (SqlString) , PersistValue (PersistText) ) class (Read a, Show a, PathPiece a, PersistField a) => OAuthToken a where mkToken :: String -> Maybe a getToken :: a -> T.Text newtype AccessToken = AccessToken T.Text deriving (Eq) newtype RequestToken = RequestToken T.Text deriving (Eq) instance Show AccessToken where show (AccessToken t) = T.unpack t instance Show RequestToken where show (RequestToken t) = T.unpack t instance OAuthToken RequestToken where mkToken = mkOAuthToken RequestToken "R-" getToken (RequestToken t) = t instance OAuthToken AccessToken where mkToken = mkOAuthToken AccessToken "A-" getToken (AccessToken t) = t simpleReadsPrec :: (OAuthToken t) => Int -> ReadS t simpleReadsPrec _ s = case mkToken s of Just tok -> [(tok, "")] Nothing -> [] instance Read AccessToken where readsPrec = simpleReadsPrec instance Read RequestToken where readsPrec = simpleReadsPrec mkOAuthToken :: (OAuthToken a) => (T.Text -> a) -> String -> String -> Maybe a mkOAuthToken constructor pre text = if correctLength && validChars text && prefixMatches then Just $ constructor $ T.pack text else Nothing where length_without_prefix = 16 correctLength = length text == length_without_prefix + length pre validChars = foldr ((&&) . base64Char) True prefixMatches = take (length pre) text == pre base64Char x = or [ x `elem` ['A' .. 'Z'] , x `elem` ['a' .. 'z'] , x `elem` ['0' .. '9'] , x `elem` "+/=" , x `elem` pre] generalFromPathPiece :: OAuthToken a => T.Text -> Maybe a generalFromPathPiece s = case reads $ T.unpack s of [(a, "")] -> Just a _ -> Nothing instance PathPiece RequestToken where fromPathPiece = generalFromPathPiece toPathPiece = T.pack . show instance PathPiece AccessToken where fromPathPiece = generalFromPathPiece toPathPiece = T.pack . show instance PersistField RequestToken where sqlType _ = SqlString toPersistValue = PersistText . getToken fromPersistValue (PersistText val) = case mkToken $ T.unpack val of Just tok -> Right tok Nothing -> Left "no token" fromPersistValue _ = Left "unsupported value" instance PersistField AccessToken where sqlType _ = SqlString toPersistValue = PersistText . getToken fromPersistValue (PersistText val) = case mkToken $ T.unpack val of Just tok -> Right tok Nothing -> Left "no token" fromPersistValue _ = Left "unsupported value"
JanAhrens/yesod-oauth-demo
OAuthToken.hs
Haskell
bsd-2-clause
2,945
-- Usage: xmacrorec2 | ConvertClicks > clicks.txt module Main (main) where import Control.Monad (void) import Data.Char (isDigit) import Data.List (isPrefixOf) import System.Environment (getArgs) main :: IO () main = do args <- getArgs let printFunc = toClick $ if "--haskell" `elem` args then printTuple else printCommand void $ mainLoop printFunc ("", "") where xOffset = id yOffset = flip (-) 38 printTuple x y = print (xOffset x, yOffset y) printCommand x y = putStrLn $ "click " ++ show (xOffset x) ++ " " ++ show (yOffset y) mainLoop :: PrintFunc -> (String, String) -> IO (String, String) mainLoop prt window = getLine >>= updateWindow >>= prt >>= mainLoop prt where move (_, a) b = (a, b) updateWindow = return . move window -- |Output click with coordinates if applicable. -- >>> toClick (\x y -> print (x, y)) ("MotionNotify 1500 550","ButtonPress 1") -- (1500,550) -- ("MotionNotify 1500 550","ButtonPress 1") -- >>> toClick (\x y -> print (x, y)) ("ButtonPress 1","MotionNotify 1500 550") -- ("ButtonPress 1","MotionNotify 1500 550") toClick :: (Int -> Int -> IO ()) -> (String, String) -> IO (String, String) toClick prt window@(a, b) | isClick b = print' (toXY a) >> return window | otherwise = return window where isClick = (==) "ButtonPress 1" print' Nothing = return () print' (Just (x, y)) = prt x y -- |Return the XY coordinates from the string. -- >>> toXY "MotionNotify 123 456" -- Just (123,456) -- >>> toXY "Bla 123 456" -- Nothing toXY :: String -> Maybe (Int, Int) toXY a | "MotionNotify " `isPrefixOf` a = Just (x, y) | otherwise = Nothing where xy = dropWhile (not . isDigit) a x = read $ takeWhile isDigit xy y = read $ dropWhile isDigit xy type PrintFunc = (String, String) -> IO (String, String)
KaiHa/GuiTest
src/ConvertClicks.hs
Haskell
bsd-3-clause
1,984
-- | Simple prettified log module Emulator.Log ( prettify , state , core , registers , ram ) where import Control.Applicative ((<$>)) import Control.Monad (forM) import Data.List (intercalate) import Emulator import Emulator.Monad import Instruction import Memory (Address (..)) import Util prettify :: MonadEmulator m => m String prettify = unlines <$> sequence [core , registers , return "" , return "RAM:" , return "" , ram] state :: MonadEmulator m => Instruction Operand -> Instruction Value -> m String state instr instr' = unlines <$> sequence [ return $ "Execute: " ++ show instr ++ " -> " ++ show instr' , core , registers ] core :: MonadEmulator m => m String core = do pc <- load Pc sp <- load Sp o <- load O cycles <- load Cycles return $ intercalate ", " $ [ "PC: " ++ prettifyWord16 pc , "SP: " ++ prettifyWord16 sp , "O: " ++ prettifyWord16 o , "CYCLES: " ++ prettifyWord16 cycles ] registers :: MonadEmulator m => m String registers = do rs <- forM [minBound .. maxBound] $ \name -> do val <- load (Register name) return (name, val) return $ intercalate ", " $ [show name ++ ": " ++ prettifyWord16 val | (name, val) <- rs] ram :: MonadEmulator m => m String ram = unlines <$> mapM line [(x * 8, x * 8 + 7) | x <- [0 .. 0xffff `div` 8]] where line (lo, up) = do vs <- mapM (load . Ram) [lo .. up] return $ prettifyWord16 lo ++ ": " ++ unwords (map prettifyWord16 vs)
jaspervdj/dcpu16-hs
src/Emulator/Log.hs
Haskell
bsd-3-clause
1,573
{-# LANGUAGE TemplateHaskell #-} module Cloud.AWS.EC2.Types.RouteTable ( PropagatingVgw , Route(..) , RouteOrigin(..) , RouteState(..) , RouteTable(..) , RouteTableAssociation(..) ) where import Cloud.AWS.EC2.Types.Common (ResourceTag) import Cloud.AWS.Lib.FromText (deriveFromText) import Data.Text (Text) type PropagatingVgw = Text data Route = Route { routeDestinationCidrBlock :: Text , routeGatewayId :: Maybe Text , routeInstanceId :: Maybe Text , routeInstanceOwnerId :: Maybe Text , routeNetworkInterfaceId :: Maybe Text , routeState :: RouteState , routeOrigin :: Maybe RouteOrigin } deriving (Show, Read, Eq) data RouteOrigin = RouteOriginCreateRouteTable | RouteOriginCreateRoute | RouteOriginTableEnableVgwRoutePropagation deriving (Show, Read, Eq) data RouteState = RouteStateActive | RouteStateBlackhole deriving (Show, Read, Eq) data RouteTable = RouteTable { routeTableId :: Text , routeTableVpcId :: Text , routeTableRouteSet :: [Route] , routeTableAssociationSet :: [RouteTableAssociation] , routeTablePropagatingVgw :: Maybe PropagatingVgw , routeTableTagSet :: [ResourceTag] } deriving (Show, Read, Eq) data RouteTableAssociation = RouteTableAssociation { routeTableAssociationId :: Text , routeTableAssociationRouteTableId :: Text , routeTableAssociationSubnetId :: Maybe Text , routeTableAssociationMain :: Maybe Bool } deriving (Show, Read, Eq) deriveFromText "RouteOrigin" [ "CreateRouteTable" , "CreateRoute" , "EnableVgwRoutePropagation" ] deriveFromText "RouteState" ["active", "blackhole"]
worksap-ate/aws-sdk
Cloud/AWS/EC2/Types/RouteTable.hs
Haskell
bsd-3-clause
1,682
{-# OPTIONS -fglasgow-exts #-} ---------------------------------------------------------------------- -- | -- Module : Interface.TV.Misc -- Copyright : (c) Conal Elliott 2006 -- License : LGPL -- -- Maintainer : conal@conal.net -- Stability : experimental -- Portability : portable -- -- Miscellaneous helpers ---------------------------------------------------------------------- module Interface.TV.Misc ( -- readD {-, Cofunctor(..), ToIO(..), wrapF -} ) where -- | Read with default value. If the input doesn't parse as a value of -- the expected type, or it's ambiguous, yield the default value. readD :: Read a => a -> String -> a readD dflt str | [(a,"")] <- reads str = a | otherwise = dflt -- Cofunctor is in TypeCompose -- -- | Often useful for \"acceptors\" of values. -- class Cofunctor acceptor where -- cofmap :: (a -> b) -> (acceptor b -> acceptor a) -- -- | Arrows that convert to IO actions. -- class Arrow (~>) => ToIO (~>) where -- -- Result type is restricted to () to allow arr types that yield more -- -- (or fewer) than one value. -- toIO :: () ~> () -> IO () -- | Handy wrapping pattern. For instance, @wrapF show read@ turns a -- string function into value function. -- wrapF :: (c->d) -> (a->b) -> ((b->c) -> (a->d)) -- wrapF after before f = after . f . before
conal/TV
src/Interface/TV/Misc.hs
Haskell
bsd-3-clause
1,361
{-# LANGUAGE NamedFieldPuns #-} module Main where import Control.Monad.Except import Data.Foldable import System.Environment import System.IO import Language.Scheme.Pretty import Language.Scheme.Reader data FormatError = FormatError deriving (Eq, Show) type FormatM = ExceptT FormatError IO -- FIXME: Don't ignore blank lines formatString :: String -> FormatM String formatString s = do case readExprList s of Left _ -> throwError FormatError Right exprs -> pure $ prettyPrint exprs -- FIXME: Add IO exception handling formatFile :: FilePath -> IO () formatFile path = do contents <- readFile path res <- runExceptT (formatString contents) case res of Left e -> print e Right newContents -> writeFile path newContents usage :: String usage = "Usage: schemefmt [path ...]" main :: IO () main = do args <- getArgs if null args then putStrLn usage else traverse_ formatFile args
alldne/scheme
schemefmt/Main.hs
Haskell
bsd-3-clause
923
-- -- | Values with a @public@ boolean accessor. module Data.Geo.OSM.Lens.PublicL where import Control.Lens.Lens class PublicL a where publicL :: Lens' a Bool
tonymorris/geo-osm
src/Data/Geo/OSM/Lens/PublicL.hs
Haskell
bsd-3-clause
168
module Parser ( dimacs, CNF, Clause, Lit, Var, ) where import Control.Applicative import Control.Monad import Text.Trifecta type CNF = [Clause] type Clause = [Lit] type Lit = Int type Var = Int dimacs :: Parser CNF dimacs = do skipMany $ char 'c' >> manyTill anyChar newline (_nvar, nclause) <- (,) <$ symbol "p" <* symbol "cnf" <*> integral <*> integral replicateM nclause $ manyTill integral $ (try $ integral >>= guard . (==0)) where integral = fmap fromIntegral (spaces >> integer)
tanakh/necosat
src/Parser.hs
Haskell
bsd-3-clause
537
{-# LANGUAGE ViewPatterns, TupleSections, RecordWildCards, ScopedTypeVariables, PatternGuards, DeriveDataTypeable #-} module Output.Items(writeItems, lookupItem) where import Language.Haskell.Exts import System.IO.Extra import Data.List.Extra import System.FilePath import Control.Monad.Extra import Data.Maybe import Data.IORef import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy.Char8 as LBS import qualified Data.ByteString.Lazy.UTF8 as UTF8 import Input.Type import General.Util import General.Store outputItem :: (Id, ItemEx) -> [String] outputItem (i, ItemEx{..}) = [show i ++ " " ++ showItem itemItem ,if null itemURL then "." else itemURL ,maybe "." (joinPair " ") itemPackage ,maybe "." (joinPair " ") itemModule] ++ replace [""] ["."] (lines itemDocs) inputItem :: [String] -> (Id, ItemEx) inputItem ((word1 -> (i,name)):url:pkg:modu:docs) = (,) (read i) $ ItemEx (fromMaybe (error $ "Failed to reparse: " ++ name) $ readItem name) (if url == "." then "" else url) (f pkg) (f modu) (unlines docs) where f "." = Nothing f x = Just (word1 x) data Items = Items deriving Typeable -- write all the URLs, docs and enough info to pretty print it to a result -- and replace each with an identifier (index in the space) - big reduction in memory writeItems :: StoreOut -> FilePath -> [Either String ItemEx] -> IO [(Maybe Id, Item)] writeItems store file xs = do warns <- newIORef 0 pos <- newIORef 0 res <- writeStoreType store Items $ writeStoreParts store $ do withBinaryFile (file <.> "warn") WriteMode $ \herr -> do hSetEncoding herr utf8 flip mapMaybeM xs $ \x -> case x of Right item@ItemEx{..} | f itemItem -> do i <- readIORef pos let bs = BS.concat $ LBS.toChunks $ UTF8.fromString $ unlines $ outputItem (Id i, item) writeStoreBS store $ intToBS $ BS.length bs writeStoreBS store bs writeIORef pos $ i + fromIntegral (intSize + BS.length bs) return $ Just (Just $ Id i, itemItem) Right ItemEx{..} -> return $ Just (Nothing, itemItem) Left err -> do modifyIORef warns (+1); hPutStrLn herr err; return Nothing warns <- readIORef warns unless (warns == 0) $ putStrLn $ "Failed to parse " ++ show warns ++ " definitions, see " ++ file <.> "warn" return res where f :: Item -> Bool f (IDecl i@InstDecl{}) = False f x = True lookupItem :: StoreIn -> IO (Id -> IO ItemEx) lookupItem store = do let x = readStoreBS $ readStoreType Items store return $ \(Id i) -> do let i2 = fromIntegral i let n = intFromBS $ BS.take intSize $ BS.drop i2 x return $ snd $ inputItem $ lines $ UTF8.toString $ LBS.fromChunks $ return $ BS.take n $ BS.drop (i2 + intSize) x
ndmitchell/hogle-dead
src/Output/Items.hs
Haskell
bsd-3-clause
2,938
-- | This module exports functionality for generating a call graph of -- an Futhark program. module Futhark.Analysis.CallGraph ( CallGraph , buildCallGraph , FunctionTable , buildFunctionTable ) where import Control.Monad.Reader import qualified Data.HashMap.Lazy as HM import Futhark.Representation.SOACS type FunctionTable = HM.HashMap Name FunDef buildFunctionTable :: Prog -> FunctionTable buildFunctionTable = foldl expand HM.empty . progFunctions where expand ftab f = HM.insert (funDefName f) f ftab -- | The symbol table for functions data CGEnv = CGEnv { envFtable :: FunctionTable } type CGM = Reader CGEnv -- | Building the call grah runs in this monad. There is no -- mutable state. runCGM :: CGM a -> CGEnv -> a runCGM = runReader -- | The call graph is just a mapping from a function name, i.e., the -- caller, to a list of the names of functions called by the function. -- The order of this list is not significant. type CallGraph = HM.HashMap Name [Name] -- | @buildCallGraph prog@ build the program's Call Graph. The representation -- is a hashtable that maps function names to a list of callee names. buildCallGraph :: Prog -> CallGraph buildCallGraph prog = do let ftable = buildFunctionTable prog runCGM (foldM buildCGfun HM.empty entry_points) $ CGEnv ftable where entry_points = map funDefName $ filter funDefEntryPoint $ progFunctions prog -- | @buildCallGraph cg f@ updates Call Graph @cg@ with the contributions of function -- @fname@, and recursively, with the contributions of the callees of @fname@. buildCGfun :: CallGraph -> Name -> CGM CallGraph buildCGfun cg fname = do bnd <- asks $ HM.lookup fname . envFtable case bnd of Nothing -> return cg -- Must be builtin or similar. Just f -> case HM.lookup fname cg of Just _ -> return cg Nothing -> do let callees = buildCGbody [] $ funDefBody f let cg' = HM.insert fname callees cg -- recursively build the callees foldM buildCGfun cg' callees buildCGbody :: [Name] -> Body -> [Name] buildCGbody callees = foldl (\x -> buildCGexp x . bindingExp) callees . bodyBindings buildCGexp :: [Name] -> Exp -> [Name] buildCGexp callees (Apply fname _ _) | fname `elem` callees = callees | otherwise = fname:callees buildCGexp callees (Op op) = case op of Map _ _ lam _ -> buildCGbody callees $ lambdaBody lam Reduce _ _ _ lam _ -> buildCGbody callees $ lambdaBody lam Scan _ _ lam _ -> buildCGbody callees $ lambdaBody lam Redomap _ _ _ lam0 lam1 _ _ -> buildCGbody (buildCGbody callees $ lambdaBody lam0) (lambdaBody lam1) Scanomap _ _ lam0 lam1 _ _ -> buildCGbody (buildCGbody callees $ lambdaBody lam0) (lambdaBody lam1) Stream _ _ (RedLike _ _ lam0 _) lam _ -> buildCGbody (buildCGbody callees $ lambdaBody lam0) (extLambdaBody lam) Stream _ _ _ lam _ -> buildCGbody callees (extLambdaBody lam) Write {} -> callees buildCGexp callees e = foldExp folder callees e where folder = identityFolder { foldOnBody = \x body -> return $ buildCGbody x body }
mrakgr/futhark
src/Futhark/Analysis/CallGraph.hs
Haskell
bsd-3-clause
3,338
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types, GeneralizedNewtypeDeriving, TemplateHaskell, FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, UndecidableInstances #-} {-# OPTIONS_HADDOCK hide #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.AD.Internal.Types -- Copyright : (c) Edward Kmett 2010 -- License : BSD3 -- Maintainer : ekmett@gmail.com -- Stability : experimental -- Portability : GHC only -- ----------------------------------------------------------------------------- module Numeric.AD.Internal.Types ( AD(..) ) where #ifndef MIN_VERSION_base #define MIN_VERSION_base (x,y,z) 1 #endif import Data.Data (Data(..), mkDataType, DataType, mkConstr, Constr, constrIndex, Fixity(..)) #if MIN_VERSION_base(4,4,0) import Data.Typeable (Typeable1(..), Typeable(..), TyCon, mkTyCon3, mkTyConApp, gcast1) #else import Data.Typeable (Typeable1(..), Typeable(..), TyCon, mkTyCon, mkTyConApp, gcast1) #endif import Language.Haskell.TH import Numeric.AD.Internal.Classes -- | 'AD' serves as a common wrapper for different 'Mode' instances, exposing a traditional -- numerical tower. Universal quantification is used to limit the actions in user code to -- machinery that will return the same answers under all AD modes, allowing us to use modes -- interchangeably as both the type level \"brand\" and dictionary, providing a common API. newtype AD f a = AD { runAD :: f a } deriving (Iso (f a), Lifted, Mode, Primal) -- > instance (Lifted f, Num a) => Num (AD f a) -- etc. let f = varT (mkName "f") in deriveNumeric (classP ''Lifted [f]:) (conT ''AD `appT` f) instance Typeable1 f => Typeable1 (AD f) where typeOf1 tfa = mkTyConApp adTyCon [typeOf1 (undefined `asArgsType` tfa)] where asArgsType :: f a -> t f a -> f a asArgsType = const adTyCon :: TyCon #if MIN_VERSION_base(4,4,0) adTyCon = mkTyCon3 "ad" "Numeric.AD.Internal.Types" "AD" #else adTyCon = mkTyCon "Numeric.AD.Internal.Types.AD" #endif {-# NOINLINE adTyCon #-} adConstr :: Constr adConstr = mkConstr adDataType "AD" [] Prefix {-# NOINLINE adConstr #-} adDataType :: DataType adDataType = mkDataType "Numeric.AD.Internal.Types.AD" [adConstr] {-# NOINLINE adDataType #-} instance (Typeable1 f, Typeable a, Data (f a), Data a) => Data (AD f a) where gfoldl f z (AD a) = z AD `f` a toConstr _ = adConstr gunfold k z c = case constrIndex c of 1 -> k (z AD) _ -> error "gunfold" dataTypeOf _ = adDataType dataCast1 f = gcast1 f
yairchu/ad
src/Numeric/AD/Internal/Types.hs
Haskell
bsd-3-clause
2,573
module Serv.Server ( bootstrap ) where import Control.Concurrent.Async import Serv.Server.Core.Runtime import Serv.Server.Features.Runtime import Serv.Server.ServerEnv bootstrap :: IO () bootstrap = do serverEnv <- setupServerEnv concurrently_ (runCore serverEnv) (runFeatures serverEnv)
orangefiredragon/bear
src/Serv/Server.hs
Haskell
bsd-3-clause
353
module Text.Liquid.Generators where import Control.Monad (join) import Data.List.NonEmpty import Data.Monoid import Data.Scientific import Data.Text import Prelude hiding (null) import Test.QuickCheck import Text.Liquid.Types -- | Any allowed char in a variable == a-z, _- newtype VariableChars = VariableChars { varChars :: Text } deriving (Eq, Show) instance Arbitrary VariableChars where arbitrary = VariableChars . pack <$> (listOf1 $ elements (['a'..'z'] <> ['A'..'Z'] <> ['_','-'])) -- | Any alpha char newtype AlphaChars = AlphaChars { alphaChars :: Text } deriving (Eq, Show) instance Arbitrary AlphaChars where arbitrary = AlphaChars . pack <$> (listOf1 $ elements (['a'..'z'] <> ['A'..'Z'])) -- | Any allowed char type newtype AnyChar = AnyChar { anyChars :: Text } deriving (Eq, Show) instance Arbitrary AnyChar where arbitrary = AnyChar . pack <$> arbitrary -- | Test helper for scientific values sc :: Double -> Scientific sc d = fromFloatDigits d genJsonAddress :: Gen (JsonVarPath) genJsonAddress = do h <- hd b <- bd return $ fromList (h:b) where hd = ObjectIndex . varChars <$> arbitrary bd = resize 3 $ listOf $ oneof [ ObjectIndex . varChars <$> arbitrary , ArrayIndex <$> suchThat arbitrary ((<) 0) ] genRawText :: Gen Expr genRawText = RawText . alphaChars <$> suchThat arbitrary (not . null . alphaChars) genNum :: Gen Expr genNum = Num . sc <$> arbitrary genVariable :: Gen Expr genVariable = Variable <$> genJsonAddress genQuoteString :: Gen Expr genQuoteString = QuoteString . alphaChars <$> arbitrary genCompare :: Gen Expr genCompare = elements [ Equal , NotEqual , GtEqual , LtEqual , Gt , Lt ] <*> anyVal <*> anyVal where anyVal = oneof [ genNum , genVariable , genQuoteString , pure Null , pure Nil , pure Trueth , pure Falseth ] genBooleanLogic :: Gen Expr genBooleanLogic = oneof [ cp, or, ad, cn, trth ] where cp = genCompare or = Or <$> genCompare <*> genCompare ad = And <$> genCompare <*> genCompare cn = Contains <$> genVariable <*> oneof [ genNum, genQuoteString ] trth = oneof [ Truthy <$> genNum , Truthy <$> genQuoteString , Truthy <$> genVariable , pure Trueth , pure Falseth , pure Nil , pure Null ] genIfClause :: Gen Expr genIfClause = IfClause <$> genBooleanLogic genIfKeyClause :: Gen Expr genIfKeyClause = IfKeyClause <$> genVariable genElsIfClause :: Gen Expr genElsIfClause = ElsIfClause <$> genBooleanLogic genElse :: Gen Expr genElse = pure Else genFilterCell :: Gen Expr genFilterCell = oneof [ pure $ FilterCell "toUpper" [] , pure $ FilterCell "toLower" [] , pure $ FilterCell "toTitle" [] , FilterCell "replace" <$> sequence [ genQuoteString, genQuoteString ] , pure $ FilterCell "first" [] , pure $ FilterCell "last" [] , FilterCell "firstOrDefault" <$> oneof [ pure <$> genQuoteString, pure <$> genNum ] , FilterCell "lastOrDefault" <$> oneof [ pure <$> genQuoteString, pure <$> genNum ] , FilterCell "renderWithSeparator" <$> sequence [ genQuoteString ] , FilterCell "toSentenceWithSeparator" <$> sequence [ genQuoteString, genQuoteString ] , pure $ FilterCell "countElements" [] ] genFilter :: Gen Expr genFilter = Filter <$> oneof [ genQuoteString, genVariable ] <*> resize 2 (listOf1 genFilterCell) genOutput :: Gen Expr genOutput = Output <$> oneof [ genFilter , genVariable , genQuoteString ] genTrueStatements :: Gen Expr genTrueStatements = TrueStatements <$> arrangements where arrangements = oneof [ sequence [ genRawText ] , sequence [ genOutput ] , sequence [ genRawText, genOutput ] , sequence [ genOutput, genRawText ] , sequence [ genRawText, genOutput, genRawText ] , sequence [ genOutput, genRawText, genOutput ] ] genIfLogic :: Gen Expr genIfLogic = oneof [ styleA , styleB , styleC , styleD ] where styleA = IfLogic <$> oneof[genIfClause, genIfKeyClause] <*> genTrueStatements styleB = IfLogic <$> (IfLogic <$> oneof[genIfClause, genIfKeyClause] <*> genTrueStatements) <*> (IfLogic <$> genElse <*> genTrueStatements) styleC = IfLogic <$> (IfLogic <$> oneof[genIfClause, genIfKeyClause] <*> genTrueStatements) <*> (IfLogic <$> genElsIfClause <*> genTrueStatements) styleD = IfLogic <$> (IfLogic <$> oneof[genIfClause, genIfKeyClause] <*> genTrueStatements) <*> (IfLogic <$> (IfLogic <$> genElsIfClause <*> genTrueStatements) <*> (IfLogic <$> genElse <*> genTrueStatements)) genCaseLogic :: Gen Expr genCaseLogic = CaseLogic <$> genVariable <*> ((resize 2 $ listOf1 tup) >>= \l -> ((<>) l <$> oneof [ pure <$> ((,) <$> genElse <*> genTrueStatements) , pure [] ])) where tup = (,) <$> oneof [genQuoteString, genNum] <*> genTrueStatements genExpr :: Gen Expr genExpr = oneof [ genRawText , genIfLogic , genOutput , genCaseLogic ] genTemplateExpr :: Gen [Expr] genTemplateExpr = concatAdj <$> listOf1 genExpr -- | Concatenate adjacent RawText expressions in a list -- This isn't a valid outcome from parsing and as such is illegal concatAdj :: [Expr] -> [Expr] concatAdj [] = [] concatAdj (x:[]) = [x] concatAdj ((RawText x):(RawText y):[]) = [RawText $ x <> y] concatAdj (x:y:[]) = [x, y] concatAdj ((RawText x):(RawText y):xs) = concatAdj ((RawText $ x <> y):xs) concatAdj (x:y:xs) = x:concatAdj (y:xs)
projectorhq/haskell-liquid
test/Text/Liquid/Generators.hs
Haskell
bsd-3-clause
6,564
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE IncoherentInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Control.Exception.Enclosed.Either ( eTry , eExIO , eIoTry , eIOExIO , eTextTry , eTxIO , eIOExTxIO ) where import Data.Text as T import Data.Maybe import Data.Monoid import Data.Either.Combinators import Control.DeepSeq import Control.Monad.Trans.Control import Control.Exception.Enclosed import Control.Exception.Lifted import Control.Monad.Trans.Either fromIOException' :: SomeException -> IOException fromIOException' e = fromMaybe (throw . AssertionFailed $ "Not an IOException:" <> show e) $ fromException e -- | Runs provided @IO@ action, captures synchronous exceptions as @Left@ values, -- re-throws asynchronous exceptions. -- -- /Note:/ value @a@ if fully evaluated, and as such it should be a member of the -- @NFData@ typeclass eTry , eExIO :: (MonadBaseControl IO (EitherT e IO), NFData a) => IO a -> EitherT SomeException IO a eTry = EitherT . tryAnyDeep eExIO = EitherT . tryAnyDeep -- | Runs provided @IO@ action, captures synchronous @IOException@ as @Left@ -- values, re-throws asynchronous exceptions (and synchronous non-IOExceptions). -- -- /note:/ value @a@ if fully evaluated, and as such it should be a member of the -- @nfdata@ typeclass eIoTry, eIOExIO :: (MonadBaseControl IO (EitherT e IO), NFData a) => IO a -> EitherT IOException IO a eIoTry = EitherT . fmap (mapLeft fromIOException') . tryAnyDeep eIOExIO = EitherT . fmap (mapLeft fromIOException') . tryAnyDeep -- | Runs provided @IO@ action, captures synchronous @IOException@ as left @Text@ -- values, re-throws asynchronous exceptions (and synchronous non-IOExceptions). -- -- /note:/ value @a@ if fully evaluated, and as such it should be a member of the -- @nfdata@ typeclass eTextTry, eTxIO, eIOExTxIO :: (MonadBaseControl IO (EitherT e IO), NFData a) => IO a -> EitherT Text IO a eTextTry = bimapEitherT (T.pack . show) id . eIOExIO eTxIO = eTextTry eIOExTxIO= eTextTry
jcristovao/enclosed-exceptions-either
src/Control/Exception/Enclosed/Either.hs
Haskell
bsd-3-clause
2,114
module T271 where import Data.Kind (Type) import Data.Singletons.Base.TH $(singletons [d| newtype Constant (a :: Type) (b :: Type) = Constant a deriving (Eq, Ord) data Identity :: Type -> Type where Identity :: a -> Identity a deriving (Eq, Ord) |])
goldfirere/singletons
singletons-base/tests/compile-and-dump/Singletons/T271.hs
Haskell
bsd-3-clause
301
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -Wno-unused-top-binds #-} module Nix.String ( NixString , principledGetContext , principledMakeNixString , principledMempty , StringContext(..) , ContextFlavor(..) , NixLikeContext(..) , NixLikeContextValue(..) , toNixLikeContext , fromNixLikeContext , stringHasContext , principledIntercalateNixString , hackyGetStringNoContext , principledGetStringNoContext , principledStringIgnoreContext , hackyStringIgnoreContext , hackyMakeNixStringWithoutContext , principledMakeNixStringWithoutContext , principledMakeNixStringWithSingletonContext , principledModifyNixContents , principledStringMappend , principledStringMempty , principledStringMConcat , WithStringContext , WithStringContextT(..) , extractNixString , addStringContext , addSingletonStringContext , runWithStringContextT , runWithStringContext ) where import Control.Monad.Writer import Data.Functor.Identity import qualified Data.HashMap.Lazy as M import qualified Data.HashSet as S import Data.Hashable import Data.Text ( Text ) import qualified Data.Text as Text import GHC.Generics -- {-# WARNING hackyGetStringNoContext, hackyStringIgnoreContext, hackyMakeNixStringWithoutContext "This NixString function needs to be replaced" #-} -- | A 'ContextFlavor' describes the sum of possible derivations for string contexts data ContextFlavor = DirectPath | AllOutputs | DerivationOutput !Text deriving (Show, Eq, Ord, Generic) instance Hashable ContextFlavor -- | A 'StringContext' ... data StringContext = StringContext { scPath :: !Text , scFlavor :: !ContextFlavor } deriving (Eq, Ord, Show, Generic) instance Hashable StringContext data NixString = NixString { nsContents :: !Text , nsContext :: !(S.HashSet StringContext) } deriving (Eq, Ord, Show, Generic) instance Hashable NixString newtype NixLikeContext = NixLikeContext { getNixLikeContext :: M.HashMap Text NixLikeContextValue } deriving (Eq, Ord, Show, Generic) data NixLikeContextValue = NixLikeContextValue { nlcvPath :: !Bool , nlcvAllOutputs :: !Bool , nlcvOutputs :: ![Text] } deriving (Show, Eq, Ord, Generic) instance Semigroup NixLikeContextValue where a <> b = NixLikeContextValue { nlcvPath = nlcvPath a || nlcvPath b , nlcvAllOutputs = nlcvAllOutputs a || nlcvAllOutputs b , nlcvOutputs = nlcvOutputs a <> nlcvOutputs b } instance Monoid NixLikeContextValue where mempty = NixLikeContextValue False False [] toStringContexts :: (Text, NixLikeContextValue) -> [StringContext] toStringContexts (path, nlcv) = case nlcv of NixLikeContextValue True _ _ -> StringContext path DirectPath : toStringContexts (path, nlcv { nlcvPath = False }) NixLikeContextValue _ True _ -> StringContext path AllOutputs : toStringContexts (path, nlcv { nlcvAllOutputs = False }) NixLikeContextValue _ _ ls | not (null ls) -> map (StringContext path . DerivationOutput) ls _ -> [] toNixLikeContextValue :: StringContext -> (Text, NixLikeContextValue) toNixLikeContextValue sc = (,) (scPath sc) $ case scFlavor sc of DirectPath -> NixLikeContextValue True False [] AllOutputs -> NixLikeContextValue False True [] DerivationOutput t -> NixLikeContextValue False False [t] toNixLikeContext :: S.HashSet StringContext -> NixLikeContext toNixLikeContext stringContext = NixLikeContext $ S.foldr go mempty stringContext where go sc hm = let (t, nlcv) = toNixLikeContextValue sc in M.insertWith (<>) t nlcv hm fromNixLikeContext :: NixLikeContext -> S.HashSet StringContext fromNixLikeContext = S.fromList . join . map toStringContexts . M.toList . getNixLikeContext principledGetContext :: NixString -> S.HashSet StringContext principledGetContext = nsContext -- | Combine two NixStrings using mappend principledMempty :: NixString principledMempty = NixString "" mempty -- | Combine two NixStrings using mappend principledStringMappend :: NixString -> NixString -> NixString principledStringMappend (NixString s1 t1) (NixString s2 t2) = NixString (s1 <> s2) (t1 <> t2) -- | Combine two NixStrings using mappend hackyStringMappend :: NixString -> NixString -> NixString hackyStringMappend (NixString s1 t1) (NixString s2 t2) = NixString (s1 <> s2) (t1 <> t2) -- | Combine NixStrings with a separator principledIntercalateNixString :: NixString -> [NixString] -> NixString principledIntercalateNixString _ [] = principledMempty principledIntercalateNixString _ [ns] = ns principledIntercalateNixString sep nss = NixString contents ctx where contents = Text.intercalate (nsContents sep) (map nsContents nss) ctx = S.unions (nsContext sep : map nsContext nss) -- | Combine NixStrings using mconcat hackyStringMConcat :: [NixString] -> NixString hackyStringMConcat = foldr hackyStringMappend (NixString mempty mempty) -- | Empty string with empty context. principledStringMempty :: NixString principledStringMempty = NixString mempty mempty -- | Combine NixStrings using mconcat principledStringMConcat :: [NixString] -> NixString principledStringMConcat = foldr principledStringMappend (NixString mempty mempty) --instance Semigroup NixString where --NixString s1 t1 <> NixString s2 t2 = NixString (s1 <> s2) (t1 <> t2) --instance Monoid NixString where -- mempty = NixString mempty mempty -- mappend = (<>) -- | Extract the string contents from a NixString that has no context hackyGetStringNoContext :: NixString -> Maybe Text hackyGetStringNoContext (NixString s c) | null c = Just s | otherwise = Nothing -- | Extract the string contents from a NixString that has no context principledGetStringNoContext :: NixString -> Maybe Text principledGetStringNoContext (NixString s c) | null c = Just s | otherwise = Nothing -- | Extract the string contents from a NixString even if the NixString has an associated context principledStringIgnoreContext :: NixString -> Text principledStringIgnoreContext (NixString s _) = s -- | Extract the string contents from a NixString even if the NixString has an associated context hackyStringIgnoreContext :: NixString -> Text hackyStringIgnoreContext (NixString s _) = s -- | Returns True if the NixString has an associated context stringHasContext :: NixString -> Bool stringHasContext (NixString _ c) = not (null c) -- | Constructs a NixString without a context hackyMakeNixStringWithoutContext :: Text -> NixString hackyMakeNixStringWithoutContext = flip NixString mempty -- | Constructs a NixString without a context principledMakeNixStringWithoutContext :: Text -> NixString principledMakeNixStringWithoutContext = flip NixString mempty -- | Modify the string part of the NixString, leaving the context unchanged principledModifyNixContents :: (Text -> Text) -> NixString -> NixString principledModifyNixContents f (NixString s c) = NixString (f s) c -- | Create a NixString using a singleton context principledMakeNixStringWithSingletonContext :: Text -> StringContext -> NixString principledMakeNixStringWithSingletonContext s c = NixString s (S.singleton c) -- | Create a NixString from a Text and context principledMakeNixString :: Text -> S.HashSet StringContext -> NixString principledMakeNixString s c = NixString s c -- | A monad for accumulating string context while producing a result string. newtype WithStringContextT m a = WithStringContextT (WriterT (S.HashSet StringContext) m a) deriving (Functor, Applicative, Monad, MonadTrans, MonadWriter (S.HashSet StringContext)) type WithStringContext = WithStringContextT Identity -- | Add 'StringContext's into the resulting set. addStringContext :: Monad m => S.HashSet StringContext -> WithStringContextT m () addStringContext = WithStringContextT . tell -- | Add a 'StringContext' into the resulting set. addSingletonStringContext :: Monad m => StringContext -> WithStringContextT m () addSingletonStringContext = WithStringContextT . tell . S.singleton -- | Get the contents of a 'NixString' and write its context into the resulting set. extractNixString :: Monad m => NixString -> WithStringContextT m Text extractNixString (NixString s c) = WithStringContextT $ tell c >> return s -- | Run an action producing a string with a context and put those into a 'NixString'. runWithStringContextT :: Monad m => WithStringContextT m Text -> m NixString runWithStringContextT (WithStringContextT m) = uncurry NixString <$> runWriterT m -- | Run an action producing a string with a context and put those into a 'NixString'. runWithStringContext :: WithStringContextT Identity Text -> NixString runWithStringContext = runIdentity . runWithStringContextT
jwiegley/hnix
src/Nix/String.hs
Haskell
bsd-3-clause
8,970
import Control.Concurrent import GHCJS.Marshal.Pure import GHCJS.Require helloWorld = putStrLn "[haskell] Hello World" launchTheMissiles = do threadDelay (1000 * 1000 * 5) putStrLn "[haskell] OMG what did I do?!" return $ Just $ pToJSVal (10 :: Double) main = do export0 "helloWorld" helloWorld export "launchTheMissiles" launchTheMissiles defaultMain
beijaflor-io/ghcjs-commonjs
old-examples/ghcjs-loader-test/Main.hs
Haskell
mit
409
{-# LANGUAGE DeriveGeneric #-} module Pos.DB.Epoch.Index ( writeEpochIndex , getEpochBlundOffset , SlotIndexOffset (..) ) where import Universum import Data.Binary (Binary, decode, encode) import qualified Data.ByteString.Builder as Builder import qualified Data.ByteString.Lazy as LBS import Formatting (build, sformat, (%)) import System.IO (IOMode (..), SeekMode (..), hSeek, withBinaryFile) import Pos.Core (LocalSlotIndex (..), SlotCount, localSlotIndices) -- When we store all blocks for an epoch in a "epoch" file we need a fast and -- simple way of extracting any single block from the epoch file without decoding -- the whole file. -- -- We do this by keeping a separate index file that for each slot, can give the -- offset in the file where that block occurs. There are 21600 slots/blocks per -- epoch (10 * blkSecurityParam) and in the first 62 epochs, the smallest number -- of blocks in an epoch was 21562. The means the most disk storage efficient -- and quickest to access way to store the slot index to file offset mapping in -- file is as a dense vector of 64 bit file offsets indexed by the slot index, -- even if that means that the file has to have sentinel values inserted at empty -- slot indices. -- -- We use 'maxBound' as the sentinel value. On read, if we get a value of -- 'maxBound' we return 'Nothing', otherwise the offset is returned wrapped -- in a 'Just'. header :: LBS.ByteString header = "Epoch Index v1\n\n" headerLength :: Num a => a headerLength = fromIntegral $ LBS.length header hCheckHeader :: FilePath -> Handle -> IO () hCheckHeader fpath h = do hSeek h AbsoluteSeek 0 headerBytes <- LBS.hGet h headerLength when (headerBytes /= header) $ error $ sformat ("Invalid header in epoch index file " % build) fpath data SlotIndexOffset = SlotIndexOffset { sioSlotIndex :: !Word16 , sioOffset :: !Word64 } deriving (Eq, Generic, Show) instance Binary SlotIndexOffset -- | Write a list of @SlotIndexOffset@s to a dense @Binary@ representation -- -- To make it dense we pad the list with @maxBound :: Word64@ whenever we see -- a missing @LocalSlotIndex@ writeEpochIndex :: SlotCount -> FilePath -> [SlotIndexOffset] -> IO () writeEpochIndex epochSlots path = withBinaryFile path WriteMode . flip Builder.hPutBuilder . (Builder.lazyByteString header <>) . foldMap (Builder.lazyByteString . encode . sioOffset) . padIndex epochSlots -- | Pad a list of @SlotIndexOffset@s ordered by @LocalSlotIndex@ padIndex :: SlotCount -> [SlotIndexOffset] -> [SlotIndexOffset] padIndex epochSlots = go ( flip SlotIndexOffset maxBound . getSlotIndex <$> localSlotIndices epochSlots ) where go [] _ = [] go xs [] = xs go (x : xs) (y : ys) | sioSlotIndex x == sioSlotIndex y = y : go xs ys | otherwise = x : go xs (y : ys) getSlotIndexOffsetN :: FilePath -> LocalSlotIndex -> IO Word64 getSlotIndexOffsetN fpath (UnsafeLocalSlotIndex i) = withBinaryFile fpath ReadMode $ \h -> do hCheckHeader fpath h hSeek h AbsoluteSeek (headerLength + fromIntegral i * 8) decode <$> LBS.hGet h 8 getEpochBlundOffset :: FilePath -> LocalSlotIndex -> IO (Maybe Word64) getEpochBlundOffset fpath lsi = do off <- getSlotIndexOffsetN fpath lsi -- 'maxBound' is the sentinel value which means there is no block -- in the epoch file for the specified 'LocalSlotIndex'. pure $ if off == maxBound then Nothing else Just off
input-output-hk/pos-haskell-prototype
db/src/Pos/DB/Epoch/Index.hs
Haskell
mit
3,622
{-# LANGUAGE QuasiQuotes #-} module CUDA (cudaTests) where import Test.Framework import Test.Framework.Providers.HUnit import Test.HUnit (Assertion, (@?=)) import Language.C.Quote.CUDA import Language.C.Syntax import Data.Loc (noLoc) mkDeclarator params mutability = LambdaDeclarator (Params params False noLoc) mutability Nothing noLoc mkIntroducer :: [CaptureListEntry] -> LambdaIntroducer mkIntroducer mode = (LambdaIntroducer mode noLoc) emptyLambda = lambdaByCapture [] lambdaByCapture captureMode = Lambda (mkIntroducer captureMode) Nothing [] noLoc lambdaByCaptureBody captureMode statements = Lambda (mkIntroducer captureMode) Nothing statements noLoc lambdaByCaptureParams captureMode params = Lambda (mkIntroducer captureMode) (Just $ mkDeclarator params False) [] noLoc lambdaByParams params = Lambda (mkIntroducer []) (Just $ mkDeclarator params False) [] noLoc mutableLambdaByParams params = Lambda (mkIntroducer []) (Just $ mkDeclarator params True) [] noLoc cudaTests :: Test cudaTests = testGroup "CUDA" $ map (testCase "lambda-expressions parsing") lambdas where lambdas :: [Assertion] lambdas = [ [cexp|[=] {}|] @?= lambdaByCapture [DefaultByValue] , [cexp|[&] {}|] @?= lambdaByCapture[DefaultByReference] , [cexp|[] {}|] @?= lambdaByCapture [] , [cexp|[] {}|] @?= emptyLambda , [cexp|[] () {}|] @?= lambdaByParams [] , [cexp|[] (int i) {}|] @?= lambdaByParams [param_int_i] , [cexp|[] (int i, double j) {}|] @?= lambdaByParams [param_int_i, param_double_h] , [cexp|[] ($param:param_int_i) {}|] @?= lambdaByParams [param_int_i] , [cexp|[] (int i) mutable {}|] @?= mutableLambdaByParams [param_int_i] , [cexp|[&] (int i) {}|] @?= lambdaByCaptureParams [DefaultByReference] [param_int_i] , [cexp|[&] { $item:item_return_7 } |] @?= lambdaCapturingByRefAndReturning7 , [cexp|[&] { return $exp:exp_7; } |] @?= lambdaCapturingByRefAndReturning7 , [cexp|[]{}()|] @?= FnCall emptyLambda [] noLoc , [cexp|[](){}()|] @?= FnCall (lambdaByParams []) [] noLoc ] lambdaCapturingByRefAndReturning7 = lambdaByCaptureBody [DefaultByReference] [item_return_7] exp_7 = [cexp|7|] item_return_7 = [citem|return 7;|] param_int_i = [cparam|int i|] param_double_h = [cparam|double j|]
flowbox-public/language-c-quote
tests/unit/CUDA.hs
Haskell
bsd-3-clause
2,423
module T3132 where import Data.Array.Unboxed step :: UArray Int Double -> [Double] step y = [y!1 + y!0]
mpickering/ghc-exactprint
tests/examples/ghc710/T3132.hs
Haskell
bsd-3-clause
106
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Pattern-matching bindings (HsBinds and MonoBinds) Handles @HsBinds@; those at the top level require different handling, in that the @Rec@/@NonRec@/etc structure is thrown away (whereas at lower levels it is preserved with @let@/@letrec@s). -} {-# LANGUAGE CPP #-} module DsBinds ( dsTopLHsBinds, dsLHsBinds, decomposeRuleLhs, dsSpec, dsHsWrapper, dsTcEvBinds, dsTcEvBinds_s, dsEvBinds ) where #include "HsVersions.h" import {-# SOURCE #-} DsExpr( dsLExpr ) import {-# SOURCE #-} Match( matchWrapper ) import DsMonad import DsGRHSs import DsUtils import HsSyn -- lots of things import CoreSyn -- lots of things import Literal ( Literal(MachStr) ) import CoreSubst import OccurAnal ( occurAnalyseExpr ) import MkCore import CoreUtils import CoreArity ( etaExpand ) import CoreUnfold import CoreFVs import UniqSupply import Digraph import PrelNames import TysPrim ( mkProxyPrimTy ) import TyCon import TcEvidence import TcType import Type import Kind (returnsConstraintKind) import Coercion hiding (substCo) import TysWiredIn ( eqBoxDataCon, coercibleDataCon, mkListTy , mkBoxedTupleTy, charTy, typeNatKind, typeSymbolKind ) import Id import MkId(proxyHashId) import Class import DataCon ( dataConTyCon ) import Name import IdInfo ( IdDetails(..) ) import Var import VarSet import Rules import VarEnv import Outputable import Module import SrcLoc import Maybes import OrdList import Bag import BasicTypes hiding ( TopLevel ) import DynFlags import FastString import Util import MonadUtils import Control.Monad(liftM) import Fingerprint(Fingerprint(..), fingerprintString) {- ************************************************************************ * * \subsection[dsMonoBinds]{Desugaring a @MonoBinds@} * * ************************************************************************ -} dsTopLHsBinds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) dsTopLHsBinds binds = ds_lhs_binds binds dsLHsBinds :: LHsBinds Id -> DsM [(Id,CoreExpr)] dsLHsBinds binds = do { binds' <- ds_lhs_binds binds ; return (fromOL binds') } ------------------------ ds_lhs_binds :: LHsBinds Id -> DsM (OrdList (Id,CoreExpr)) ds_lhs_binds binds = do { ds_bs <- mapBagM dsLHsBind binds ; return (foldBag appOL id nilOL ds_bs) } dsLHsBind :: LHsBind Id -> DsM (OrdList (Id,CoreExpr)) dsLHsBind (L loc bind) = putSrcSpanDs loc $ dsHsBind bind dsHsBind :: HsBind Id -> DsM (OrdList (Id,CoreExpr)) dsHsBind (VarBind { var_id = var, var_rhs = expr, var_inline = inline_regardless }) = do { dflags <- getDynFlags ; core_expr <- dsLExpr expr -- Dictionary bindings are always VarBinds, -- so we only need do this here ; let var' | inline_regardless = var `setIdUnfolding` mkCompulsoryUnfolding core_expr | otherwise = var ; return (unitOL (makeCorePair dflags var' False 0 core_expr)) } dsHsBind (FunBind { fun_id = L _ fun, fun_matches = matches , fun_co_fn = co_fn, fun_tick = tick , fun_infix = inf }) = do { dflags <- getDynFlags ; (args, body) <- matchWrapper (FunRhs (idName fun) inf) matches ; let body' = mkOptTickBox tick body ; rhs <- dsHsWrapper co_fn (mkLams args body') ; {- pprTrace "dsHsBind" (ppr fun <+> ppr (idInlinePragma fun)) $ -} return (unitOL (makeCorePair dflags fun False 0 rhs)) } dsHsBind (PatBind { pat_lhs = pat, pat_rhs = grhss, pat_rhs_ty = ty , pat_ticks = (rhs_tick, var_ticks) }) = do { body_expr <- dsGuarded grhss ty ; let body' = mkOptTickBox rhs_tick body_expr ; sel_binds <- mkSelectorBinds var_ticks pat body' -- We silently ignore inline pragmas; no makeCorePair -- Not so cool, but really doesn't matter ; return (toOL sel_binds) } -- A common case: one exported variable -- Non-recursive bindings come through this way -- So do self-recursive bindings, and recursive bindings -- that have been chopped up with type signatures dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = [export] , abs_ev_binds = ev_binds, abs_binds = binds }) | ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = prags } <- export = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec (fromOL bind_prs) ; ds_binds <- dsTcEvBinds_s ev_binds ; rhs <- dsHsWrapper wrap $ -- Usually the identity mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ Var local ; (spec_binds, rules) <- dsSpecs rhs prags ; let global' = addIdSpecialisations global rules main_bind = makeCorePair dflags global' (isDefaultMethod prags) (dictArity dicts) rhs ; return (main_bind `consOL` spec_binds) } dsHsBind (AbsBinds { abs_tvs = tyvars, abs_ev_vars = dicts , abs_exports = exports, abs_ev_binds = ev_binds , abs_binds = binds }) -- See Note [Desugaring AbsBinds] = do { dflags <- getDynFlags ; bind_prs <- ds_lhs_binds binds ; let core_bind = Rec [ makeCorePair dflags (add_inline lcl_id) False 0 rhs | (lcl_id, rhs) <- fromOL bind_prs ] -- Monomorphic recursion possible, hence Rec locals = map abe_mono exports tup_expr = mkBigCoreVarTup locals tup_ty = exprType tup_expr ; ds_binds <- dsTcEvBinds_s ev_binds ; let poly_tup_rhs = mkLams tyvars $ mkLams dicts $ mkCoreLets ds_binds $ Let core_bind $ tup_expr ; poly_tup_id <- newSysLocalDs (exprType poly_tup_rhs) ; let mk_bind (ABE { abe_wrap = wrap, abe_poly = global , abe_mono = local, abe_prags = spec_prags }) = do { tup_id <- newSysLocalDs tup_ty ; rhs <- dsHsWrapper wrap $ mkLams tyvars $ mkLams dicts $ mkTupleSelector locals local tup_id $ mkVarApps (Var poly_tup_id) (tyvars ++ dicts) ; let rhs_for_spec = Let (NonRec poly_tup_id poly_tup_rhs) rhs ; (spec_binds, rules) <- dsSpecs rhs_for_spec spec_prags ; let global' = (global `setInlinePragma` defaultInlinePragma) `addIdSpecialisations` rules -- Kill the INLINE pragma because it applies to -- the user written (local) function. The global -- Id is just the selector. Hmm. ; return ((global', rhs) `consOL` spec_binds) } ; export_binds_s <- mapM mk_bind exports ; return ((poly_tup_id, poly_tup_rhs) `consOL` concatOL export_binds_s) } where inline_env :: IdEnv Id -- Maps a monomorphic local Id to one with -- the inline pragma from the source -- The type checker put the inline pragma -- on the *global* Id, so we need to transfer it inline_env = mkVarEnv [ (lcl_id, setInlinePragma lcl_id prag) | ABE { abe_mono = lcl_id, abe_poly = gbl_id } <- exports , let prag = idInlinePragma gbl_id ] add_inline :: Id -> Id -- tran add_inline lcl_id = lookupVarEnv inline_env lcl_id `orElse` lcl_id dsHsBind (PatSynBind{}) = panic "dsHsBind: PatSynBind" ------------------------ makeCorePair :: DynFlags -> Id -> Bool -> Arity -> CoreExpr -> (Id, CoreExpr) makeCorePair dflags gbl_id is_default_method dict_arity rhs | is_default_method -- Default methods are *always* inlined = (gbl_id `setIdUnfolding` mkCompulsoryUnfolding rhs, rhs) | DFunId is_newtype <- idDetails gbl_id = (mk_dfun_w_stuff is_newtype, rhs) | otherwise = case inlinePragmaSpec inline_prag of EmptyInlineSpec -> (gbl_id, rhs) NoInline -> (gbl_id, rhs) Inlinable -> (gbl_id `setIdUnfolding` inlinable_unf, rhs) Inline -> inline_pair where inline_prag = idInlinePragma gbl_id inlinable_unf = mkInlinableUnfolding dflags rhs inline_pair | Just arity <- inlinePragmaSat inline_prag -- Add an Unfolding for an INLINE (but not for NOINLINE) -- And eta-expand the RHS; see Note [Eta-expanding INLINE things] , let real_arity = dict_arity + arity -- NB: The arity in the InlineRule takes account of the dictionaries = ( gbl_id `setIdUnfolding` mkInlineUnfolding (Just real_arity) rhs , etaExpand real_arity rhs) | otherwise = pprTrace "makeCorePair: arity missing" (ppr gbl_id) $ (gbl_id `setIdUnfolding` mkInlineUnfolding Nothing rhs, rhs) -- See Note [ClassOp/DFun selection] in TcInstDcls -- See Note [Single-method classes] in TcInstDcls mk_dfun_w_stuff is_newtype | is_newtype = gbl_id `setIdUnfolding` mkInlineUnfolding (Just 0) rhs `setInlinePragma` alwaysInlinePragma { inl_sat = Just 0 } | otherwise = gbl_id `setIdUnfolding` mkDFunUnfolding dfun_bndrs dfun_constr dfun_args `setInlinePragma` dfunInlinePragma (dfun_bndrs, dfun_body) = collectBinders (simpleOptExpr rhs) (dfun_con, dfun_args) = collectArgs dfun_body dfun_constr | Var id <- dfun_con , DataConWorkId con <- idDetails id = con | otherwise = pprPanic "makeCorePair: dfun" (ppr rhs) dictArity :: [Var] -> Arity -- Don't count coercion variables in arity dictArity dicts = count isId dicts {- [Desugaring AbsBinds] ~~~~~~~~~~~~~~~~~~~~~ In the general AbsBinds case we desugar the binding to this: tup a (d:Num a) = let fm = ...gm... gm = ...fm... in (fm,gm) f a d = case tup a d of { (fm,gm) -> fm } g a d = case tup a d of { (fm,gm) -> fm } Note [Rules and inlining] ~~~~~~~~~~~~~~~~~~~~~~~~~ Common special case: no type or dictionary abstraction This is a bit less trivial than you might suppose The naive way woudl be to desguar to something like f_lcl = ...f_lcl... -- The "binds" from AbsBinds M.f = f_lcl -- Generated from "exports" But we don't want that, because if M.f isn't exported, it'll be inlined unconditionally at every call site (its rhs is trivial). That would be ok unless it has RULES, which would thereby be completely lost. Bad, bad, bad. Instead we want to generate M.f = ...f_lcl... f_lcl = M.f Now all is cool. The RULES are attached to M.f (by SimplCore), and f_lcl is rapidly inlined away. This does not happen in the same way to polymorphic binds, because they desugar to M.f = /\a. let f_lcl = ...f_lcl... in f_lcl Although I'm a bit worried about whether full laziness might float the f_lcl binding out and then inline M.f at its call site Note [Specialising in no-dict case] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Even if there are no tyvars or dicts, we may have specialisation pragmas. Class methods can generate AbsBinds [] [] [( ... spec-prag] { AbsBinds [tvs] [dicts] ...blah } So the overloading is in the nested AbsBinds. A good example is in GHC.Float: class (Real a, Fractional a) => RealFrac a where round :: (Integral b) => a -> b instance RealFrac Float where {-# SPECIALIZE round :: Float -> Int #-} The top-level AbsBinds for $cround has no tyvars or dicts (because the instance does not). But the method is locally overloaded! Note [Abstracting over tyvars only] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When abstracting over type variable only (not dictionaries), we don't really need to built a tuple and select from it, as we do in the general case. Instead we can take AbsBinds [a,b] [ ([a,b], fg, fl, _), ([b], gg, gl, _) ] { fl = e1 gl = e2 h = e3 } and desugar it to fg = /\ab. let B in e1 gg = /\b. let a = () in let B in S(e2) h = /\ab. let B in e3 where B is the *non-recursive* binding fl = fg a b gl = gg b h = h a b -- See (b); note shadowing! Notice (a) g has a different number of type variables to f, so we must use the mkArbitraryType thing to fill in the gaps. We use a type-let to do that. (b) The local variable h isn't in the exports, and rather than clone a fresh copy we simply replace h by (h a b), where the two h's have different types! Shadowing happens here, which looks confusing but works fine. (c) The result is *still* quadratic-sized if there are a lot of small bindings. So if there are more than some small number (10), we filter the binding set B by the free variables of the particular RHS. Tiresome. Why got to this trouble? It's a common case, and it removes the quadratic-sized tuple desugaring. Less clutter, hopefully faster compilation, especially in a case where there are a *lot* of bindings. Note [Eta-expanding INLINE things] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider foo :: Eq a => a -> a {-# INLINE foo #-} foo x = ... If (foo d) ever gets floated out as a common sub-expression (which can happen as a result of method sharing), there's a danger that we never get to do the inlining, which is a Terribly Bad thing given that the user said "inline"! To avoid this we pre-emptively eta-expand the definition, so that foo has the arity with which it is declared in the source code. In this example it has arity 2 (one for the Eq and one for x). Doing this should mean that (foo d) is a PAP and we don't share it. Note [Nested arities] ~~~~~~~~~~~~~~~~~~~~~ For reasons that are not entirely clear, method bindings come out looking like this: AbsBinds [] [] [$cfromT <= [] fromT] $cfromT [InlPrag=INLINE] :: T Bool -> Bool { AbsBinds [] [] [fromT <= [] fromT_1] fromT :: T Bool -> Bool { fromT_1 ((TBool b)) = not b } } } Note the nested AbsBind. The arity for the InlineRule on $cfromT should be gotten from the binding for fromT_1. It might be better to have just one level of AbsBinds, but that requires more thought! -} ------------------------ dsSpecs :: CoreExpr -- Its rhs -> TcSpecPrags -> DsM ( OrdList (Id,CoreExpr) -- Binding for specialised Ids , [CoreRule] ) -- Rules for the Global Ids -- See Note [Handling SPECIALISE pragmas] in TcBinds dsSpecs _ IsDefaultMethod = return (nilOL, []) dsSpecs poly_rhs (SpecPrags sps) = do { pairs <- mapMaybeM (dsSpec (Just poly_rhs)) sps ; let (spec_binds_s, rules) = unzip pairs ; return (concatOL spec_binds_s, rules) } dsSpec :: Maybe CoreExpr -- Just rhs => RULE is for a local binding -- Nothing => RULE is for an imported Id -- rhs is in the Id's unfolding -> Located TcSpecPrag -> DsM (Maybe (OrdList (Id,CoreExpr), CoreRule)) dsSpec mb_poly_rhs (L loc (SpecPrag poly_id spec_co spec_inl)) | isJust (isClassOpId_maybe poly_id) = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for class method selector") <+> quotes (ppr poly_id)) ; return Nothing } -- There is no point in trying to specialise a class op -- Moreover, classops don't (currently) have an inl_sat arity set -- (it would be Just 0) and that in turn makes makeCorePair bleat | no_act_spec && isNeverActive rule_act = putSrcSpanDs loc $ do { warnDs (ptext (sLit "Ignoring useless SPECIALISE pragma for NOINLINE function:") <+> quotes (ppr poly_id)) ; return Nothing } -- Function is NOINLINE, and the specialiation inherits that -- See Note [Activation pragmas for SPECIALISE] | otherwise = putSrcSpanDs loc $ do { uniq <- newUnique ; let poly_name = idName poly_id spec_occ = mkSpecOcc (getOccName poly_name) spec_name = mkInternalName uniq spec_occ (getSrcSpan poly_name) ; (bndrs, ds_lhs) <- liftM collectBinders (dsHsWrapper spec_co (Var poly_id)) ; let spec_ty = mkPiTypes bndrs (exprType ds_lhs) ; -- pprTrace "dsRule" (vcat [ ptext (sLit "Id:") <+> ppr poly_id -- , ptext (sLit "spec_co:") <+> ppr spec_co -- , ptext (sLit "ds_rhs:") <+> ppr ds_lhs ]) $ case decomposeRuleLhs bndrs ds_lhs of { Left msg -> do { warnDs msg; return Nothing } ; Right (rule_bndrs, _fn, args) -> do { dflags <- getDynFlags ; this_mod <- getModule ; let fn_unf = realIdUnfolding poly_id unf_fvs = stableUnfoldingVars fn_unf `orElse` emptyVarSet in_scope = mkInScopeSet (unf_fvs `unionVarSet` exprsFreeVars args) spec_unf = specUnfolding dflags (mkEmptySubst in_scope) bndrs args fn_unf spec_id = mkLocalId spec_name spec_ty `setInlinePragma` inl_prag `setIdUnfolding` spec_unf rule = mkRule this_mod False {- Not auto -} is_local_id (mkFastString ("SPEC " ++ showPpr dflags poly_name)) rule_act poly_name rule_bndrs args (mkVarApps (Var spec_id) bndrs) ; spec_rhs <- dsHsWrapper spec_co poly_rhs -- Commented out: see Note [SPECIALISE on INLINE functions] -- ; when (isInlinePragma id_inl) -- (warnDs $ ptext (sLit "SPECIALISE pragma on INLINE function probably won't fire:") -- <+> quotes (ppr poly_name)) ; return (Just (unitOL (spec_id, spec_rhs), rule)) -- NB: do *not* use makeCorePair on (spec_id,spec_rhs), because -- makeCorePair overwrites the unfolding, which we have -- just created using specUnfolding } } } where is_local_id = isJust mb_poly_rhs poly_rhs | Just rhs <- mb_poly_rhs = rhs -- Local Id; this is its rhs | Just unfolding <- maybeUnfoldingTemplate (realIdUnfolding poly_id) = unfolding -- Imported Id; this is its unfolding -- Use realIdUnfolding so we get the unfolding -- even when it is a loop breaker. -- We want to specialise recursive functions! | otherwise = pprPanic "dsImpSpecs" (ppr poly_id) -- The type checker has checked that it *has* an unfolding id_inl = idInlinePragma poly_id -- See Note [Activation pragmas for SPECIALISE] inl_prag | not (isDefaultInlinePragma spec_inl) = spec_inl | not is_local_id -- See Note [Specialising imported functions] -- in OccurAnal , isStrongLoopBreaker (idOccInfo poly_id) = neverInlinePragma | otherwise = id_inl -- Get the INLINE pragma from SPECIALISE declaration, or, -- failing that, from the original Id spec_prag_act = inlinePragmaActivation spec_inl -- See Note [Activation pragmas for SPECIALISE] -- no_act_spec is True if the user didn't write an explicit -- phase specification in the SPECIALISE pragma no_act_spec = case inlinePragmaSpec spec_inl of NoInline -> isNeverActive spec_prag_act _ -> isAlwaysActive spec_prag_act rule_act | no_act_spec = inlinePragmaActivation id_inl -- Inherit | otherwise = spec_prag_act -- Specified by user {- Note [SPECIALISE on INLINE functions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We used to warn that using SPECIALISE for a function marked INLINE would be a no-op; but it isn't! Especially with worker/wrapper split we might have {-# INLINE f #-} f :: Ord a => Int -> a -> ... f d x y = case x of I# x' -> $wf d x' y We might want to specialise 'f' so that we in turn specialise '$wf'. We can't even /name/ '$wf' in the source code, so we can't specialise it even if we wanted to. Trac #10721 is a case in point. Note [Activation pragmas for SPECIALISE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ From a user SPECIALISE pragma for f, we generate a) A top-level binding spec_fn = rhs b) A RULE f dOrd = spec_fn We need two pragma-like things: * spec_fn's inline pragma: inherited from f's inline pragma (ignoring activation on SPEC), unless overriden by SPEC INLINE * Activation of RULE: from SPECIALISE pragma (if activation given) otherwise from f's inline pragma This is not obvious (see Trac #5237)! Examples Rule activation Inline prag on spec'd fn --------------------------------------------------------------------- SPEC [n] f :: ty [n] Always, or NOINLINE [n] copy f's prag NOINLINE f SPEC [n] f :: ty [n] NOINLINE copy f's prag NOINLINE [k] f SPEC [n] f :: ty [n] NOINLINE [k] copy f's prag INLINE [k] f SPEC [n] f :: ty [n] INLINE [k] copy f's prag SPEC INLINE [n] f :: ty [n] INLINE [n] (ignore INLINE prag on f, same activation for rule and spec'd fn) NOINLINE [k] f SPEC f :: ty [n] INLINE [k] ************************************************************************ * * \subsection{Adding inline pragmas} * * ************************************************************************ -} decomposeRuleLhs :: [Var] -> CoreExpr -> Either SDoc ([Var], Id, [CoreExpr]) -- (decomposeRuleLhs bndrs lhs) takes apart the LHS of a RULE, -- The 'bndrs' are the quantified binders of the rules, but decomposeRuleLhs -- may add some extra dictionary binders (see Note [Free dictionaries]) -- -- Returns Nothing if the LHS isn't of the expected shape -- Note [Decomposing the left-hand side of a RULE] decomposeRuleLhs orig_bndrs orig_lhs | not (null unbound) -- Check for things unbound on LHS -- See Note [Unused spec binders] = Left (vcat (map dead_msg unbound)) | Just (fn_id, args) <- decompose fun2 args2 , let extra_dict_bndrs = mk_extra_dict_bndrs fn_id args = -- pprTrace "decmposeRuleLhs" (vcat [ ptext (sLit "orig_bndrs:") <+> ppr orig_bndrs -- , ptext (sLit "orig_lhs:") <+> ppr orig_lhs -- , ptext (sLit "lhs1:") <+> ppr lhs1 -- , ptext (sLit "extra_dict_bndrs:") <+> ppr extra_dict_bndrs -- , ptext (sLit "fn_id:") <+> ppr fn_id -- , ptext (sLit "args:") <+> ppr args]) $ Right (orig_bndrs ++ extra_dict_bndrs, fn_id, args) | otherwise = Left bad_shape_msg where lhs1 = drop_dicts orig_lhs lhs2 = simpleOptExpr lhs1 -- See Note [Simplify rule LHS] (fun2,args2) = collectArgs lhs2 lhs_fvs = exprFreeVars lhs2 unbound = filterOut (`elemVarSet` lhs_fvs) orig_bndrs orig_bndr_set = mkVarSet orig_bndrs -- Add extra dict binders: Note [Free dictionaries] mk_extra_dict_bndrs fn_id args = [ mkLocalId (localiseName (idName d)) (idType d) | d <- varSetElems (exprsFreeVars args `delVarSetList` (fn_id : orig_bndrs)) -- fn_id: do not quantify over the function itself, which may -- itself be a dictionary (in pathological cases, Trac #10251) , isDictId d ] decompose (Var fn_id) args | not (fn_id `elemVarSet` orig_bndr_set) = Just (fn_id, args) decompose _ _ = Nothing bad_shape_msg = hang (ptext (sLit "RULE left-hand side too complicated to desugar")) 2 (vcat [ text "Optimised lhs:" <+> ppr lhs2 , text "Orig lhs:" <+> ppr orig_lhs]) dead_msg bndr = hang (sep [ ptext (sLit "Forall'd") <+> pp_bndr bndr , ptext (sLit "is not bound in RULE lhs")]) 2 (vcat [ text "Orig bndrs:" <+> ppr orig_bndrs , text "Orig lhs:" <+> ppr orig_lhs , text "optimised lhs:" <+> ppr lhs2 ]) pp_bndr bndr | isTyVar bndr = ptext (sLit "type variable") <+> quotes (ppr bndr) | Just pred <- evVarPred_maybe bndr = ptext (sLit "constraint") <+> quotes (ppr pred) | otherwise = ptext (sLit "variable") <+> quotes (ppr bndr) drop_dicts :: CoreExpr -> CoreExpr drop_dicts e = wrap_lets needed bnds body where needed = orig_bndr_set `minusVarSet` exprFreeVars body (bnds, body) = split_lets (occurAnalyseExpr e) -- The occurAnalyseExpr drops dead bindings which is -- crucial to ensure that every binding is used later; -- which in turn makes wrap_lets work right split_lets :: CoreExpr -> ([(DictId,CoreExpr)], CoreExpr) split_lets e | Let (NonRec d r) body <- e , isDictId d , (bs, body') <- split_lets body = ((d,r):bs, body') | otherwise = ([], e) wrap_lets :: VarSet -> [(DictId,CoreExpr)] -> CoreExpr -> CoreExpr wrap_lets _ [] body = body wrap_lets needed ((d, r) : bs) body | rhs_fvs `intersectsVarSet` needed = Let (NonRec d r) (wrap_lets needed' bs body) | otherwise = wrap_lets needed bs body where rhs_fvs = exprFreeVars r needed' = (needed `minusVarSet` rhs_fvs) `extendVarSet` d {- Note [Decomposing the left-hand side of a RULE] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There are several things going on here. * drop_dicts: see Note [Drop dictionary bindings on rule LHS] * simpleOptExpr: see Note [Simplify rule LHS] * extra_dict_bndrs: see Note [Free dictionaries] Note [Drop dictionary bindings on rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ drop_dicts drops dictionary bindings on the LHS where possible. E.g. let d:Eq [Int] = $fEqList $fEqInt in f d --> f d Reasoning here is that there is only one d:Eq [Int], and so we can quantify over it. That makes 'd' free in the LHS, but that is later picked up by extra_dict_bndrs (Note [Dead spec binders]). NB 1: We can only drop the binding if the RHS doesn't bind one of the orig_bndrs, which we assume occur on RHS. Example f :: (Eq a) => b -> a -> a {-# SPECIALISE f :: Eq a => b -> [a] -> [a] #-} Here we want to end up with RULE forall d:Eq a. f ($dfEqList d) = f_spec d Of course, the ($dfEqlist d) in the pattern makes it less likely to match, but there is no other way to get d:Eq a NB 2: We do drop_dicts *before* simplOptEpxr, so that we expect all the evidence bindings to be wrapped around the outside of the LHS. (After simplOptExpr they'll usually have been inlined.) dsHsWrapper does dependency analysis, so that civilised ones will be simple NonRec bindings. We don't handle recursive dictionaries! NB3: In the common case of a non-overloaded, but perhaps-polymorphic specialisation, we don't need to bind *any* dictionaries for use in the RHS. For example (Trac #8331) {-# SPECIALIZE INLINE useAbstractMonad :: ReaderST s Int #-} useAbstractMonad :: MonadAbstractIOST m => m Int Here, deriving (MonadAbstractIOST (ReaderST s)) is a lot of code but the RHS uses no dictionaries, so we want to end up with RULE forall s (d :: MonadAbstractIOST (ReaderT s)). useAbstractMonad (ReaderT s) d = $suseAbstractMonad s Trac #8848 is a good example of where there are some intersting dictionary bindings to discard. The drop_dicts algorithm is based on these observations: * Given (let d = rhs in e) where d is a DictId, matching 'e' will bind e's free variables. * So we want to keep the binding if one of the needed variables (for which we need a binding) is in fv(rhs) but not already in fv(e). * The "needed variables" are simply the orig_bndrs. Consider f :: (Eq a, Show b) => a -> b -> String ... SPECIALISE f :: (Show b) => Int -> b -> String ... Then orig_bndrs includes the *quantified* dictionaries of the type namely (dsb::Show b), but not the one for Eq Int So we work inside out, applying the above criterion at each step. Note [Simplify rule LHS] ~~~~~~~~~~~~~~~~~~~~~~~~ simplOptExpr occurrence-analyses and simplifies the LHS: (a) Inline any remaining dictionary bindings (which hopefully occur just once) (b) Substitute trivial lets so that they don't get in the way Note that we substitute the function too; we might have this as a LHS: let f71 = M.f Int in f71 (c) Do eta reduction. To see why, consider the fold/build rule, which without simplification looked like: fold k z (build (/\a. g a)) ==> ... This doesn't match unless you do eta reduction on the build argument. Similarly for a LHS like augment g (build h) we do not want to get augment (\a. g a) (build h) otherwise we don't match when given an argument like augment (\a. h a a) (build h) Note [Matching seqId] ~~~~~~~~~~~~~~~~~~~ The desugarer turns (seq e r) into (case e of _ -> r), via a special-case hack and this code turns it back into an application of seq! See Note [Rules for seq] in MkId for the details. Note [Unused spec binders] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: a -> a ... SPECIALISE f :: Eq a => a -> a ... It's true that this *is* a more specialised type, but the rule we get is something like this: f_spec d = f RULE: f = f_spec d Note that the rule is bogus, because it mentions a 'd' that is not bound on the LHS! But it's a silly specialisation anyway, because the constraint is unused. We could bind 'd' to (error "unused") but it seems better to reject the program because it's almost certainly a mistake. That's what the isDeadBinder call detects. Note [Free dictionaries] ~~~~~~~~~~~~~~~~~~~~~~~~ When the LHS of a specialisation rule, (/\as\ds. f es) has a free dict, which is presumably in scope at the function definition site, we can quantify over it too. *Any* dict with that type will do. So for example when you have f :: Eq a => a -> a f = <rhs> ... SPECIALISE f :: Int -> Int ... Then we get the SpecPrag SpecPrag (f Int dInt) And from that we want the rule RULE forall dInt. f Int dInt = f_spec f_spec = let f = <rhs> in f Int dInt But be careful! That dInt might be GHC.Base.$fOrdInt, which is an External Name, and you can't bind them in a lambda or forall without getting things confused. Likewise it might have an InlineRule or something, which would be utterly bogus. So we really make a fresh Id, with the same unique and type as the old one, but with an Internal name and no IdInfo. ************************************************************************ * * Desugaring evidence * * ************************************************************************ -} dsHsWrapper :: HsWrapper -> CoreExpr -> DsM CoreExpr dsHsWrapper WpHole e = return e dsHsWrapper (WpTyApp ty) e = return $ App e (Type ty) dsHsWrapper (WpLet ev_binds) e = do bs <- dsTcEvBinds ev_binds return (mkCoreLets bs e) dsHsWrapper (WpCompose c1 c2) e = do { e1 <- dsHsWrapper c2 e ; dsHsWrapper c1 e1 } dsHsWrapper (WpFun c1 c2 t1 _) e = do { x <- newSysLocalDs t1 ; e1 <- dsHsWrapper c1 (Var x) ; e2 <- dsHsWrapper c2 (e `mkCoreAppDs` e1) ; return (Lam x e2) } dsHsWrapper (WpCast co) e = ASSERT(tcCoercionRole co == Representational) dsTcCoercion co (mkCastDs e) dsHsWrapper (WpEvLam ev) e = return $ Lam ev e dsHsWrapper (WpTyLam tv) e = return $ Lam tv e dsHsWrapper (WpEvApp tm) e = liftM (App e) (dsEvTerm tm) -------------------------------------- dsTcEvBinds_s :: [TcEvBinds] -> DsM [CoreBind] dsTcEvBinds_s [] = return [] dsTcEvBinds_s (b:rest) = ASSERT( null rest ) -- Zonker ensures null dsTcEvBinds b dsTcEvBinds :: TcEvBinds -> DsM [CoreBind] dsTcEvBinds (TcEvBinds {}) = panic "dsEvBinds" -- Zonker has got rid of this dsTcEvBinds (EvBinds bs) = dsEvBinds bs dsEvBinds :: Bag EvBind -> DsM [CoreBind] dsEvBinds bs = mapM ds_scc (sccEvBinds bs) where ds_scc (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = r })) = liftM (NonRec v) (dsEvTerm r) ds_scc (CyclicSCC bs) = liftM Rec (mapM ds_pair bs) ds_pair (EvBind { eb_lhs = v, eb_rhs = r }) = liftM ((,) v) (dsEvTerm r) sccEvBinds :: Bag EvBind -> [SCC EvBind] sccEvBinds bs = stronglyConnCompFromEdgedVertices edges where edges :: [(EvBind, EvVar, [EvVar])] edges = foldrBag ((:) . mk_node) [] bs mk_node :: EvBind -> (EvBind, EvVar, [EvVar]) mk_node b@(EvBind { eb_lhs = var, eb_rhs = term }) = (b, var, varSetElems (evVarsOfTerm term)) --------------------------------------- dsEvTerm :: EvTerm -> DsM CoreExpr dsEvTerm (EvId v) = return (Var v) dsEvTerm (EvCast tm co) = do { tm' <- dsEvTerm tm ; dsTcCoercion co $ mkCastDs tm' } -- 'v' is always a lifted evidence variable so it is -- unnecessary to call varToCoreExpr v here. dsEvTerm (EvDFunApp df tys tms) = return (Var df `mkTyApps` tys `mkApps` (map Var tms)) dsEvTerm (EvCoercion (TcCoVarCo v)) = return (Var v) -- See Note [Simple coercions] dsEvTerm (EvCoercion co) = dsTcCoercion co mkEqBox dsEvTerm (EvSuperClass d n) = do { d' <- dsEvTerm d ; let (cls, tys) = getClassPredTys (exprType d') sc_sel_id = classSCSelId cls n -- Zero-indexed ; return $ Var sc_sel_id `mkTyApps` tys `App` d' } dsEvTerm (EvDelayedError ty msg) = return $ Var errorId `mkTyApps` [ty] `mkApps` [litMsg] where errorId = tYPE_ERROR_ID litMsg = Lit (MachStr (fastStringToByteString msg)) dsEvTerm (EvLit l) = case l of EvNum n -> mkIntegerExpr n EvStr s -> mkStringExprFS s dsEvTerm (EvCallStack cs) = dsEvCallStack cs dsEvTerm (EvTypeable ev) = dsEvTypeable ev dsEvTypeable :: EvTypeable -> DsM CoreExpr dsEvTypeable ev = do tyCl <- dsLookupTyCon typeableClassName typeRepTc <- dsLookupTyCon typeRepTyConName let tyRepType = mkTyConApp typeRepTc [] (ty, rep) <- case ev of EvTypeableTyCon tc ks -> do ctr <- dsLookupGlobalId mkPolyTyConAppName mkTyCon <- dsLookupGlobalId mkTyConName dflags <- getDynFlags let mkRep cRep kReps tReps = mkApps (Var ctr) [ cRep, mkListExpr tyRepType kReps , mkListExpr tyRepType tReps ] let kindRep k = case splitTyConApp_maybe k of Nothing -> panic "dsEvTypeable: not a kind constructor" Just (kc,ks) -> do kcRep <- tyConRep dflags mkTyCon kc reps <- mapM kindRep ks return (mkRep kcRep [] reps) tcRep <- tyConRep dflags mkTyCon tc kReps <- mapM kindRep ks return ( mkTyConApp tc ks , mkRep tcRep kReps [] ) EvTypeableTyApp t1 t2 -> do e1 <- getRep tyCl t1 e2 <- getRep tyCl t2 ctr <- dsLookupGlobalId mkAppTyName return ( mkAppTy (snd t1) (snd t2) , mkApps (Var ctr) [ e1, e2 ] ) EvTypeableTyLit t -> do e <- tyLitRep t return (snd t, e) -- TyRep -> Typeable t -- see also: Note [Memoising typeOf] repName <- newSysLocalDs tyRepType let proxyT = mkProxyPrimTy (typeKind ty) ty method = bindNonRec repName rep $ mkLams [mkWildValBinder proxyT] (Var repName) -- package up the method as `Typeable` dictionary return $ mkCastDs method $ mkSymCo $ getTypeableCo tyCl ty where -- co: method -> Typeable k t getTypeableCo tc t = case instNewTyCon_maybe tc [typeKind t, t] of Just (_,co) -> co _ -> panic "Class `Typeable` is not a `newtype`." -- Typeable t -> TyRep getRep tc (ev,t) = do typeableExpr <- dsEvTerm ev let co = getTypeableCo tc t method = mkCastDs typeableExpr co proxy = mkTyApps (Var proxyHashId) [typeKind t, t] return (mkApps method [proxy]) -- KnownNat t -> TyRep (also used for KnownSymbol) tyLitRep (ev,t) = do dict <- dsEvTerm ev fun <- dsLookupGlobalId $ case typeKind t of k | eqType k typeNatKind -> typeNatTypeRepName | eqType k typeSymbolKind -> typeSymbolTypeRepName | otherwise -> panic "dsEvTypeable: unknown type lit kind" let finst = mkTyApps (Var fun) [t] proxy = mkTyApps (Var proxyHashId) [typeKind t, t] return (mkApps finst [ dict, proxy ]) -- This part could be cached tyConRep dflags mkTyCon tc = do pkgStr <- mkStringExprFS pkg_fs modStr <- mkStringExprFS modl_fs nameStr <- mkStringExprFS name_fs return (mkApps (Var mkTyCon) [ int64 high, int64 low , pkgStr, modStr, nameStr ]) where tycon_name = tyConName tc modl = nameModule tycon_name pkg = modulePackageKey modl modl_fs = moduleNameFS (moduleName modl) pkg_fs = packageKeyFS pkg name_fs = occNameFS (nameOccName tycon_name) hash_name_fs | isPromotedTyCon tc = appendFS (mkFastString "$k") name_fs | isPromotedDataCon tc = appendFS (mkFastString "$c") name_fs | isTupleTyCon tc && returnsConstraintKind (tyConKind tc) = appendFS (mkFastString "$p") name_fs | otherwise = name_fs hashThis = unwords $ map unpackFS [pkg_fs, modl_fs, hash_name_fs] Fingerprint high low = fingerprintString hashThis int64 | wORD_SIZE dflags == 4 = mkWord64LitWord64 | otherwise = mkWordLit dflags . fromIntegral {- Note [Memoising typeOf] ~~~~~~~~~~~~~~~~~~~~~~~~~~ See #3245, #9203 IMPORTANT: we don't want to recalculate the TypeRep once per call with the proxy argument. This is what went wrong in #3245 and #9203. So we help GHC by manually keeping the 'rep' *outside* the lambda. -} dsEvCallStack :: EvCallStack -> DsM CoreExpr -- See Note [Overview of implicit CallStacks] in TcEvidence.hs dsEvCallStack cs = do df <- getDynFlags m <- getModule srcLocDataCon <- dsLookupDataCon srcLocDataConName let srcLocTyCon = dataConTyCon srcLocDataCon let srcLocTy = mkTyConTy srcLocTyCon let mkSrcLoc l = liftM (mkCoreConApps srcLocDataCon) (sequence [ mkStringExpr (showPpr df $ modulePackageKey m) , mkStringExprFS (moduleNameFS $ moduleName m) , mkStringExprFS (srcSpanFile l) , return $ mkIntExprInt df (srcSpanStartLine l) , return $ mkIntExprInt df (srcSpanStartCol l) , return $ mkIntExprInt df (srcSpanEndLine l) , return $ mkIntExprInt df (srcSpanEndCol l) ]) -- Be careful to use [Char] instead of String here to avoid -- unnecessary dependencies on GHC.Base, particularly when -- building GHC.Err.absentError let callSiteTy = mkBoxedTupleTy [mkListTy charTy, srcLocTy] matchId <- newSysLocalDs $ mkListTy callSiteTy callStackDataCon <- dsLookupDataCon callStackDataConName let callStackTyCon = dataConTyCon callStackDataCon let callStackTy = mkTyConTy callStackTyCon let emptyCS = mkCoreConApps callStackDataCon [mkNilExpr callSiteTy] let pushCS name loc rest = mkWildCase rest callStackTy callStackTy [( DataAlt callStackDataCon , [matchId] , mkCoreConApps callStackDataCon [mkConsExpr callSiteTy (mkCoreTup [name, loc]) (Var matchId)] )] let mkPush name loc tm = do nameExpr <- mkStringExprFS name locExpr <- mkSrcLoc loc case tm of EvCallStack EvCsEmpty -> return (pushCS nameExpr locExpr emptyCS) _ -> do tmExpr <- dsEvTerm tm -- at this point tmExpr :: IP sym CallStack -- but we need the actual CallStack to pass to pushCS, -- so we use unwrapIP to strip the dictionary wrapper -- See Note [Overview of implicit CallStacks] let ip_co = unwrapIP (exprType tmExpr) return (pushCS nameExpr locExpr (mkCastDs tmExpr ip_co)) case cs of EvCsTop name loc tm -> mkPush name loc tm EvCsPushCall name loc tm -> mkPush (occNameFS $ getOccName name) loc tm EvCsEmpty -> panic "Cannot have an empty CallStack" --------------------------------------- dsTcCoercion :: TcCoercion -> (Coercion -> CoreExpr) -> DsM CoreExpr -- This is the crucial function that moves -- from TcCoercions to Coercions; see Note [TcCoercions] in Coercion -- e.g. dsTcCoercion (trans g1 g2) k -- = case g1 of EqBox g1# -> -- case g2 of EqBox g2# -> -- k (trans g1# g2#) -- thing_inside will get a coercion at the role requested dsTcCoercion co thing_inside = do { us <- newUniqueSupply ; let eqvs_covs :: [(EqVar,CoVar)] eqvs_covs = zipWith mk_co_var (varSetElems (coVarsOfTcCo co)) (uniqsFromSupply us) subst = mkCvSubst emptyInScopeSet [(eqv, mkCoVarCo cov) | (eqv, cov) <- eqvs_covs] result_expr = thing_inside (ds_tc_coercion subst co) result_ty = exprType result_expr ; return (foldr (wrap_in_case result_ty) result_expr eqvs_covs) } where mk_co_var :: Id -> Unique -> (Id, Id) mk_co_var eqv uniq = (eqv, mkUserLocal occ uniq ty loc) where eq_nm = idName eqv occ = nameOccName eq_nm loc = nameSrcSpan eq_nm ty = mkCoercionType (getEqPredRole (evVarPred eqv)) ty1 ty2 (ty1, ty2) = getEqPredTys (evVarPred eqv) wrap_in_case result_ty (eqv, cov) body = case getEqPredRole (evVarPred eqv) of Nominal -> Case (Var eqv) eqv result_ty [(DataAlt eqBoxDataCon, [cov], body)] Representational -> Case (Var eqv) eqv result_ty [(DataAlt coercibleDataCon, [cov], body)] Phantom -> panic "wrap_in_case/phantom" ds_tc_coercion :: CvSubst -> TcCoercion -> Coercion -- If the incoming TcCoercion if of type (a ~ b) (resp. Coercible a b) -- the result is of type (a ~# b) (reps. a ~# b) -- The VarEnv maps EqVars of type (a ~ b) to Coercions of type (a ~# b) (resp. and so on) -- No need for InScope set etc because the ds_tc_coercion subst tc_co = go tc_co where go (TcRefl r ty) = Refl r (Coercion.substTy subst ty) go (TcTyConAppCo r tc cos) = mkTyConAppCo r tc (map go cos) go (TcAppCo co1 co2) = mkAppCo (go co1) (go co2) go (TcForAllCo tv co) = mkForAllCo tv' (ds_tc_coercion subst' co) where (subst', tv') = Coercion.substTyVarBndr subst tv go (TcAxiomInstCo ax ind cos) = AxiomInstCo ax ind (map go cos) go (TcPhantomCo ty1 ty2) = UnivCo (fsLit "ds_tc_coercion") Phantom ty1 ty2 go (TcSymCo co) = mkSymCo (go co) go (TcTransCo co1 co2) = mkTransCo (go co1) (go co2) go (TcNthCo n co) = mkNthCo n (go co) go (TcLRCo lr co) = mkLRCo lr (go co) go (TcSubCo co) = mkSubCo (go co) go (TcLetCo bs co) = ds_tc_coercion (ds_co_binds bs) co go (TcCastCo co1 co2) = mkCoCast (go co1) (go co2) go (TcCoVarCo v) = ds_ev_id subst v go (TcAxiomRuleCo co ts cs) = AxiomRuleCo co (map (Coercion.substTy subst) ts) (map go cs) go (TcCoercion co) = co ds_co_binds :: TcEvBinds -> CvSubst ds_co_binds (EvBinds bs) = foldl ds_scc subst (sccEvBinds bs) ds_co_binds eb@(TcEvBinds {}) = pprPanic "ds_co_binds" (ppr eb) ds_scc :: CvSubst -> SCC EvBind -> CvSubst ds_scc subst (AcyclicSCC (EvBind { eb_lhs = v, eb_rhs = ev_term })) = extendCvSubstAndInScope subst v (ds_co_term subst ev_term) ds_scc _ (CyclicSCC other) = pprPanic "ds_scc:cyclic" (ppr other $$ ppr tc_co) ds_co_term :: CvSubst -> EvTerm -> Coercion ds_co_term subst (EvCoercion tc_co) = ds_tc_coercion subst tc_co ds_co_term subst (EvId v) = ds_ev_id subst v ds_co_term subst (EvCast tm co) = mkCoCast (ds_co_term subst tm) (ds_tc_coercion subst co) ds_co_term _ other = pprPanic "ds_co_term" (ppr other $$ ppr tc_co) ds_ev_id :: CvSubst -> EqVar -> Coercion ds_ev_id subst v | Just co <- Coercion.lookupCoVar subst v = co | otherwise = pprPanic "ds_tc_coercion" (ppr v $$ ppr tc_co) {- Note [Simple coercions] ~~~~~~~~~~~~~~~~~~~~~~~ We have a special case for coercions that are simple variables. Suppose cv :: a ~ b is in scope Lacking the special case, if we see f a b cv we'd desguar to f a b (case cv of EqBox (cv# :: a ~# b) -> EqBox cv#) which is a bit stupid. The special case does the obvious thing. This turns out to be important when desugaring the LHS of a RULE (see Trac #7837). Suppose we have normalise :: (a ~ Scalar a) => a -> a normalise_Double :: Double -> Double {-# RULES "normalise" normalise = normalise_Double #-} Then the RULE we want looks like forall a, (cv:a~Scalar a). normalise a cv = normalise_Double But without the special case we generate the redundant box/unbox, which simpleOpt (currently) doesn't remove. So the rule never matches. Maybe simpleOpt should be smarter. But it seems like a good plan to simply never generate the redundant box/unbox in the first place. -}
ml9951/ghc
compiler/deSugar/DsBinds.hs
Haskell
bsd-3-clause
48,481
-- | Devel web server. module DevelMain where import HL.Dispatch () import HL.Foundation import Control.Concurrent import Data.IORef import Foreign.Store import Network.Wai.Handler.Warp import System.Environment (getEnvironment) import Yesod import Yesod.Static -- | Start the web server. main :: IO (Store (IORef Application)) main = do s <- static "static" c <- newChan app <- toWaiApp (App s c) ref <- newIORef app env <- getEnvironment let port = maybe 1990 read $ lookup "PORT" env tid <- forkIO (runSettings (setPort port defaultSettings) (\req -> do handler <- readIORef ref handler req)) _ <- newStore tid ref' <- newStore ref _ <- newStore c return ref' -- | Update the server, start it if not running. update :: IO (Store (IORef Application)) update = do m <- lookupStore 1 case m of Nothing -> main Just store -> do ref <- readStore store c <- readStore (Store 2) writeChan c () s <- static "static" app <- toWaiApp (App s c) writeIORef ref app return store
mietek/hl
src/DevelMain.hs
Haskell
bsd-3-clause
1,219
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE OverloadedStrings #-} {- Copyright (C) - 2017 Róman Joost <roman@bromeco.de> This file is part of gtfsschedule. gtfsschedule is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. gtfsschedule is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with gtfsschedule. If not, see <http://www.gnu.org/licenses/>. -} module CSV.Import.Route where import CSV.Import.Util (maybeToPersist) import Data.Csv (DefaultOrdered, FromNamedRecord) import GHC.Generics import qualified Data.Text as T import Database.Persist (PersistValue (..)) data Route = Route { route_id :: !T.Text , route_short_name :: !T.Text , route_long_name :: !T.Text , route_desc :: Maybe T.Text , route_type :: !T.Text , route_url :: Maybe T.Text , route_color :: Maybe T.Text , route_text_color :: Maybe T.Text } deriving (Eq, Generic, Show) instance FromNamedRecord Route instance DefaultOrdered Route prepareSQL :: T.Text prepareSQL = "insert into route (route_id, short_name, long_name, desc, type, url, color, text_color)\ \ values (?, ?, ?, ?, ?, ?, ?, ?);" convertToValues :: Route -> [PersistValue] convertToValues r = [ PersistText $ route_id r , PersistText $ route_short_name r , PersistText $ route_long_name r , maybeToPersist PersistText $ route_desc r , PersistText $ route_type r , maybeToPersist PersistText $ route_url r , maybeToPersist PersistText $ route_color r , maybeToPersist PersistText $ route_text_color r ]
romanofski/gtfsbrisbane
src/CSV/Import/Route.hs
Haskell
bsd-3-clause
2,302
-- | -- Module : Basement.These -- License : BSD-style -- Maintainer : Nicolas Di Prima <nicolas@primetype.co.uk> -- Stability : stable -- Portability : portable -- -- @These a b@, sum type to represent either @a@ or @b@ or both. -- module Basement.These ( These(..) ) where import Basement.Compat.Base import Basement.NormalForm import Basement.Compat.Bifunctor -- | Either a or b or both. data These a b = This a | That b | These a b deriving (Eq, Ord, Show, Typeable) instance (NormalForm a, NormalForm b) => NormalForm (These a b) where toNormalForm (This a) = toNormalForm a toNormalForm (That b) = toNormalForm b toNormalForm (These a b) = toNormalForm a `seq` toNormalForm b instance Bifunctor These where bimap fa _ (This a) = This (fa a) bimap _ fb (That b) = That (fb b) bimap fa fb (These a b) = These (fa a) (fb b) instance Functor (These a) where fmap = second
vincenthz/hs-foundation
basement/Basement/These.hs
Haskell
bsd-3-clause
951
{- Copyright 2015 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} {-# LANGUAGE PackageImports #-} {-# LANGUAGE NoImplicitPrelude #-} module GHC.TypeLits (module M) where import "base" GHC.TypeLits as M
xwysp/codeworld
codeworld-base/src/GHC/TypeLits.hs
Haskell
apache-2.0
739
{-# LANGUAGE CPP , GADTs , KindSignatures , DataKinds , Rank2Types , ScopedTypeVariables , MultiParamTypeClasses , FlexibleContexts , FlexibleInstances #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2016.05.24 -- | -- Module : Language.Hakaru.Evaluation.EvalMonad -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : wren@community.haskell.org -- Stability : experimental -- Portability : GHC-only -- -- ---------------------------------------------------------------- module Language.Hakaru.Evaluation.EvalMonad ( runPureEvaluate , pureEvaluate -- * The pure-evaluation monad -- ** List-based version , ListContext(..), PureAns, Eval(..), runEval , residualizePureListContext -- ** TODO: IntMap-based version ) where import Prelude hiding (id, (.)) import Control.Category (Category(..)) #if __GLASGOW_HASKELL__ < 710 import Data.Functor ((<$>)) import Control.Applicative (Applicative(..)) #endif import qualified Data.Foldable as F import Language.Hakaru.Syntax.IClasses (Some2(..)) import Language.Hakaru.Syntax.Variable (memberVarSet) import Language.Hakaru.Syntax.ABT (ABT(..), subst, maxNextFree) import Language.Hakaru.Syntax.DatumABT import Language.Hakaru.Syntax.AST import Language.Hakaru.Evaluation.Types import Language.Hakaru.Evaluation.Lazy (evaluate) import Language.Hakaru.Evaluation.PEvalMonad (ListContext(..)) -- The rest of these are just for the emit code, which isn't currently exported. import Data.Text (Text) import qualified Data.Text as Text import qualified Data.Traversable as T import Language.Hakaru.Syntax.IClasses (Functor11(..)) import Language.Hakaru.Syntax.Variable (Variable(), toAssocs1) import Language.Hakaru.Syntax.ABT (caseVarSyn, caseBinds, substs) import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing (Sing, sUnPair) import Language.Hakaru.Syntax.TypeOf (typeOf) import Language.Hakaru.Syntax.Datum import Language.Hakaru.Evaluation.Lazy (reifyPair) #ifdef __TRACE_DISINTEGRATE__ import Debug.Trace (trace) #endif ---------------------------------------------------------------- ---------------------------------------------------------------- -- | Call 'evaluate' on a term. This variant returns an @abt@ expression itself so you needn't worry about the 'Eval' monad. For the monadic-version, see 'pureEvaluate'. -- -- BUG: now that we've indexed 'ListContext' by a 'Purity', does exposing the implementation details still enable clients to break our invariants? runPureEvaluate :: (ABT Term abt) => abt '[] a -> abt '[] a runPureEvaluate e = runEval (fromWhnf <$> pureEvaluate e) [Some2 e] -- 'evaluate' itself can never @lub@ or @bot@, as captured by the -- fact that it's type doesn't include 'Alternative' nor 'MonadPlus' -- constraints. So non-singularity of results could only come from -- calling @perform@. However, we will never call perform because: (a) the initial heap must be 'Pure' so we will never call @perform@ for a statement on the initial heap, and (b) 'evaluate' itself will never push impure statements so we will never call @perform@ for the statements we push either. -- -- | Call 'evaluate' on a term. This variant returns something in the 'Eval' monad so you can string multiple evaluation calls together. For the non-monadic version, see 'runPureEvaluate'. pureEvaluate :: (ABT Term abt) => TermEvaluator abt (Eval abt) pureEvaluate = evaluate (brokenInvariant "perform") ---------------------------------------------------------------- type PureAns abt a = ListContext abt 'Pure -> abt '[] a newtype Eval abt x = Eval { unEval :: forall a. (x -> PureAns abt a) -> PureAns abt a } brokenInvariant :: String -> a brokenInvariant loc = error (loc ++ ": Eval's invariant broken") -- | Run a computation in the 'Eval' monad, residualizing out all the -- statements in the final evaluation context. The second argument -- should include all the terms altered by the 'Eval' expression; this -- is necessary to ensure proper hygiene; for example(s): -- -- > runEval (pureEvaluate e) [Some2 e] -- -- We use 'Some2' on the inputs because it doesn't matter what their -- type or locally-bound variables are, so we want to allow @f@ to -- contain terms with different indices. runEval :: (ABT Term abt, F.Foldable f) => Eval abt (abt '[] a) -> f (Some2 abt) -> abt '[] a runEval (Eval m) es = m residualizePureListContext (ListContext (maxNextFree es) []) residualizePureListContext :: forall abt a . (ABT Term abt) => abt '[] a -> ListContext abt 'Pure -> abt '[] a residualizePureListContext e0 = foldl step e0 . statements where -- TODO: make paremetric in the purity, so we can combine 'residualizeListContext' with this function. step :: abt '[] a -> Statement abt Location 'Pure -> abt '[] a step e s = case s of SLet (Location x) body _ | not (x `memberVarSet` freeVars e) -> e -- TODO: if used exactly once in @e@, then inline. | otherwise -> case getLazyVariable body of Just y -> subst x (var y) e Nothing -> case getLazyLiteral body of Just v -> subst x (syn $ Literal_ v) e Nothing -> syn (Let_ :$ fromLazy body :* bind x e :* End) ---------------------------------------------------------------- instance Functor (Eval abt) where fmap f (Eval m) = Eval $ \c -> m (c . f) instance Applicative (Eval abt) where pure x = Eval $ \c -> c x Eval mf <*> Eval mx = Eval $ \c -> mf $ \f -> mx $ \x -> c (f x) instance Monad (Eval abt) where return = pure Eval m >>= k = Eval $ \c -> m $ \x -> unEval (k x) c instance (ABT Term abt) => EvaluationMonad abt (Eval abt) 'Pure where freshNat = Eval $ \c (ListContext i ss) -> c i (ListContext (i+1) ss) unsafePush s = Eval $ \c (ListContext i ss) -> c () (ListContext i (s:ss)) -- N.B., the use of 'reverse' is necessary so that the order -- of pushing matches that of 'pushes' unsafePushes ss = Eval $ \c (ListContext i ss') -> c () (ListContext i (reverse ss ++ ss')) select x p = loop [] where -- TODO: use a DList to avoid reversing inside 'unsafePushes' loop ss = do ms <- unsafePop case ms of Nothing -> do unsafePushes ss return Nothing Just s -> -- Alas, @p@ will have to recheck 'isBoundBy' -- in order to grab the 'Refl' proof we erased; -- but there's nothing to be done for it. case x `isBoundBy` s >> p s of Nothing -> loop (s:ss) Just mr -> do r <- mr unsafePushes ss return (Just r) -- TODO: make parametric in the purity -- | Not exported because we only need it for defining 'select' on 'Eval'. unsafePop :: Eval abt (Maybe (Statement abt Location 'Pure)) unsafePop = Eval $ \c h@(ListContext i ss) -> case ss of [] -> c Nothing h s:ss' -> c (Just s) (ListContext i ss') ---------------------------------------------------------------- ---------------------------------------------------------------- -- | Emit some code that binds a variable, and return the variable -- thus bound. The function says what to wrap the result of the -- continuation with; i.e., what we're actually emitting. emit :: (ABT Term abt) => Text -> Sing a -> (forall r. abt '[a] r -> abt '[] r) -> Eval abt (Variable a) emit hint typ f = do x <- freshVar hint typ Eval $ \c h -> (f . bind x) $ c x h -- | A smart constructor for emitting let-bindings. If the input -- is already a variable then we just return it; otherwise we emit -- the let-binding. N.B., this function provides the invariant that -- the result is in fact a variable; whereas 'emitLet'' does not. emitLet :: (ABT Term abt) => abt '[] a -> Eval abt (Variable a) emitLet e = caseVarSyn e return $ \_ -> emit Text.empty (typeOf e) $ \f -> syn (Let_ :$ e :* f :* End) -- | A smart constructor for emitting let-bindings. If the input -- is already a variable or a literal constant, then we just return -- it; otherwise we emit the let-binding. N.B., this function -- provides weaker guarantees on the type of the result; if you -- require the result to always be a variable, then see 'emitLet' -- instead. emitLet' :: (ABT Term abt) => abt '[] a -> Eval abt (abt '[] a) emitLet' e = caseVarSyn e (const $ return e) $ \t -> case t of Literal_ _ -> return e _ -> do x <- emit Text.empty (typeOf e) $ \f -> syn (Let_ :$ e :* f :* End) return (var x) -- | A smart constructor for emitting \"unpair\". If the input -- argument is actually a constructor then we project out the two -- components; otherwise we emit the case-binding and return the -- two variables. emitUnpair :: (ABT Term abt) => Whnf abt (HPair a b) -> Eval abt (abt '[] a, abt '[] b) emitUnpair (Head_ w) = return $ reifyPair w emitUnpair (Neutral e) = do let (a,b) = sUnPair (typeOf e) x <- freshVar Text.empty a y <- freshVar Text.empty b emitUnpair_ x y e emitUnpair_ :: forall abt a b . (ABT Term abt) => Variable a -> Variable b -> abt '[] (HPair a b) -> Eval abt (abt '[] a, abt '[] b) emitUnpair_ x y = loop where done :: abt '[] (HPair a b) -> Eval abt (abt '[] a, abt '[] b) done e = #ifdef __TRACE_DISINTEGRATE__ trace "-- emitUnpair: done (term is not Datum_ nor Case_)" $ #endif Eval $ \c h -> ( syn . Case_ e . (:[]) . Branch (pPair PVar PVar) . bind x . bind y ) $ c (var x, var y) h loop :: abt '[] (HPair a b) -> Eval abt (abt '[] a, abt '[] b) loop e0 = caseVarSyn e0 (done . var) $ \t -> case t of Datum_ d -> do #ifdef __TRACE_DISINTEGRATE__ trace "-- emitUnpair: found Datum_" $ return () #endif return $ reifyPair (WDatum d) Case_ e bs -> do #ifdef __TRACE_DISINTEGRATE__ trace "-- emitUnpair: going under Case_" $ return () #endif -- TODO: we want this to duplicate the current -- continuation for (the evaluation of @loop@ in) -- all branches. So far our traces all end up -- returning @bot@ on the first branch, and hence -- @bot@ for the whole case-expression, so we can't -- quite tell whether it does what is intended. -- -- N.B., the only 'Eval'-effects in 'applyBranch' -- are to freshen variables; thus this use of -- 'traverse' is perfectly sound. emitCaseWith loop e bs _ -> done e0 -- TODO: emitUneither -- | Run each of the elements of the traversable using the same -- heap and continuation for each one, then pass the results to a -- function for emitting code. emitFork_ :: (ABT Term abt, T.Traversable t) => (forall r. t (abt '[] r) -> abt '[] r) -> t (Eval abt a) -> Eval abt a emitFork_ f ms = Eval $ \c h -> f $ fmap (\m -> unEval m c h) ms emitCaseWith :: (ABT Term abt) => (abt '[] b -> Eval abt r) -> abt '[] a -> [Branch a abt b] -> Eval abt r emitCaseWith f e bs = do gms <- T.for bs $ \(Branch pat body) -> let (vars, body') = caseBinds body in (\vars' -> let rho = toAssocs1 vars (fmap11 var vars') in GBranch pat vars' (f $ substs rho body') ) <$> freshenVars vars Eval $ \c h -> syn (Case_ e (map (fromGBranch . fmap (\m -> unEval m c h)) gms)) {-# INLINE emitCaseWith #-} ---------------------------------------------------------------- ----------------------------------------------------------- fin.
zaxtax/hakaru
haskell/Language/Hakaru/Evaluation/EvalMonad.hs
Haskell
bsd-3-clause
12,638
foo f = (\ g x -> f (g x))
bitemyapp/tandoori
input/lambda.hs
Haskell
bsd-3-clause
27
{-# LANGUAGE NoImplicitPrelude #-} {-| Module : Stack.Sig Description : GPG Signatures for Stack Copyright : (c) 2015-2018, Stack contributors License : BSD3 Maintainer : Tim Dysinger <tim@fpcomplete.com> Stability : experimental Portability : POSIX -} module Stack.Sig (module Sig) where import Stack.Sig.GPG as Sig import Stack.Sig.Sign as Sig
anton-dessiatov/stack
src/Stack/Sig.hs
Haskell
bsd-3-clause
362
{-# LANGUAGE DeriveGeneric, ScopedTypeVariables #-} module GCoArbitraryExample where import GHC.Generics (Generic) import Test.QuickCheck import Test.QuickCheck.Function data D a = C1 a | C2 deriving (Eq, Show, Read, Generic) instance Arbitrary a => Arbitrary (D a) instance CoArbitrary a => CoArbitrary (D a) instance (Show a, Read a) => Function (D a) where function = functionShow main :: IO () main = quickCheck $ \(Fun _ f) -> f (C1 (2::Int)) `elem` [0, 1 :: Int]
srhb/quickcheck
tests/GCoArbitraryExample.hs
Haskell
bsd-3-clause
480
{-# LANGUAGE Rank2Types, ScopedTypeVariables #-} -- Test the handling of conditionals in rank-n stuff -- Should fail, regardless of branch ordering module ShouldFail where -- These two are ok f1 = (\ (x :: forall a. a->a) -> x) f2 = (\ (x :: forall a. a->a) -> x) id 'c' -- These fail f3 v = (if v then (\ (x :: forall a. a->a) -> x) else (\ x -> x) ) id 'c' f4 v = (if v then (\ x -> x) else (\ (x :: forall a. a->a) -> x) ) id 'c'
hvr/jhc
regress/tests/1_typecheck/4_fail/ghc/tcfail104.hs
Haskell
mit
470
{-# LANGUAGE BangPatterns, CPP, Rank2Types #-} -- | -- Module : Data.Text.Internal.Encoding.Fusion -- Copyright : (c) Tom Harper 2008-2009, -- (c) Bryan O'Sullivan 2009, -- (c) Duncan Coutts 2009 -- -- License : BSD-style -- Maintainer : bos@serpentine.com -- Stability : experimental -- Portability : portable -- -- /Warning/: this is an internal module, and does not have a stable -- API or name. Functions in this module may not check or enforce -- preconditions expected by public modules. Use at your own risk! -- -- Fusible 'Stream'-oriented functions for converting between 'Text' -- and several common encodings. module Data.Text.Internal.Encoding.Fusion ( -- * Streaming streamASCII , streamUtf8 , streamUtf16LE , streamUtf16BE , streamUtf32LE , streamUtf32BE -- * Unstreaming , unstream , module Data.Text.Internal.Encoding.Fusion.Common ) where #if defined(ASSERTS) import Control.Exception (assert) #endif import Data.ByteString.Internal (ByteString(..), mallocByteString, memcpy) import Data.Text.Internal.Fusion (Step(..), Stream(..)) import Data.Text.Internal.Fusion.Size import Data.Text.Encoding.Error import Data.Text.Internal.Encoding.Fusion.Common import Data.Text.Internal.Unsafe.Char (unsafeChr, unsafeChr8, unsafeChr32) import Data.Text.Internal.Unsafe.Shift (shiftL, shiftR) import Data.Word (Word8, Word16, Word32) import Foreign.ForeignPtr (withForeignPtr, ForeignPtr) import Foreign.Storable (pokeByteOff) import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as B import qualified Data.Text.Internal.Encoding.Utf8 as U8 import qualified Data.Text.Internal.Encoding.Utf16 as U16 import qualified Data.Text.Internal.Encoding.Utf32 as U32 import Data.Text.Unsafe (unsafeDupablePerformIO) streamASCII :: ByteString -> Stream Char streamASCII bs = Stream next 0 (maxSize l) where l = B.length bs {-# INLINE next #-} next i | i >= l = Done | otherwise = Yield (unsafeChr8 x1) (i+1) where x1 = B.unsafeIndex bs i {-# DEPRECATED streamASCII "Do not use this function" #-} {-# INLINE [0] streamASCII #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using UTF-8 -- encoding. streamUtf8 :: OnDecodeError -> ByteString -> Stream Char streamUtf8 onErr bs = Stream next 0 (maxSize l) where l = B.length bs next i | i >= l = Done | U8.validate1 x1 = Yield (unsafeChr8 x1) (i+1) | i+1 < l && U8.validate2 x1 x2 = Yield (U8.chr2 x1 x2) (i+2) | i+2 < l && U8.validate3 x1 x2 x3 = Yield (U8.chr3 x1 x2 x3) (i+3) | i+3 < l && U8.validate4 x1 x2 x3 x4 = Yield (U8.chr4 x1 x2 x3 x4) (i+4) | otherwise = decodeError "streamUtf8" "UTF-8" onErr (Just x1) (i+1) where x1 = idx i x2 = idx (i + 1) x3 = idx (i + 2) x4 = idx (i + 3) idx = B.unsafeIndex bs {-# INLINE [0] streamUtf8 #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using little -- endian UTF-16 encoding. streamUtf16LE :: OnDecodeError -> ByteString -> Stream Char streamUtf16LE onErr bs = Stream next 0 (maxSize (l `shiftR` 1)) where l = B.length bs {-# INLINE next #-} next i | i >= l = Done | i+1 < l && U16.validate1 x1 = Yield (unsafeChr x1) (i+2) | i+3 < l && U16.validate2 x1 x2 = Yield (U16.chr2 x1 x2) (i+4) | otherwise = decodeError "streamUtf16LE" "UTF-16LE" onErr Nothing (i+1) where x1 = idx i + (idx (i + 1) `shiftL` 8) x2 = idx (i + 2) + (idx (i + 3) `shiftL` 8) idx = fromIntegral . B.unsafeIndex bs :: Int -> Word16 {-# INLINE [0] streamUtf16LE #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using big -- endian UTF-16 encoding. streamUtf16BE :: OnDecodeError -> ByteString -> Stream Char streamUtf16BE onErr bs = Stream next 0 (maxSize (l `shiftR` 1)) where l = B.length bs {-# INLINE next #-} next i | i >= l = Done | i+1 < l && U16.validate1 x1 = Yield (unsafeChr x1) (i+2) | i+3 < l && U16.validate2 x1 x2 = Yield (U16.chr2 x1 x2) (i+4) | otherwise = decodeError "streamUtf16BE" "UTF-16BE" onErr Nothing (i+1) where x1 = (idx i `shiftL` 8) + idx (i + 1) x2 = (idx (i + 2) `shiftL` 8) + idx (i + 3) idx = fromIntegral . B.unsafeIndex bs :: Int -> Word16 {-# INLINE [0] streamUtf16BE #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using big -- endian UTF-32 encoding. streamUtf32BE :: OnDecodeError -> ByteString -> Stream Char streamUtf32BE onErr bs = Stream next 0 (maxSize (l `shiftR` 2)) where l = B.length bs {-# INLINE next #-} next i | i >= l = Done | i+3 < l && U32.validate x = Yield (unsafeChr32 x) (i+4) | otherwise = decodeError "streamUtf32BE" "UTF-32BE" onErr Nothing (i+1) where x = shiftL x1 24 + shiftL x2 16 + shiftL x3 8 + x4 x1 = idx i x2 = idx (i+1) x3 = idx (i+2) x4 = idx (i+3) idx = fromIntegral . B.unsafeIndex bs :: Int -> Word32 {-# INLINE [0] streamUtf32BE #-} -- | /O(n)/ Convert a 'ByteString' into a 'Stream Char', using little -- endian UTF-32 encoding. streamUtf32LE :: OnDecodeError -> ByteString -> Stream Char streamUtf32LE onErr bs = Stream next 0 (maxSize (l `shiftR` 2)) where l = B.length bs {-# INLINE next #-} next i | i >= l = Done | i+3 < l && U32.validate x = Yield (unsafeChr32 x) (i+4) | otherwise = decodeError "streamUtf32LE" "UTF-32LE" onErr Nothing (i+1) where x = shiftL x4 24 + shiftL x3 16 + shiftL x2 8 + x1 x1 = idx i x2 = idx $ i+1 x3 = idx $ i+2 x4 = idx $ i+3 idx = fromIntegral . B.unsafeIndex bs :: Int -> Word32 {-# INLINE [0] streamUtf32LE #-} -- | /O(n)/ Convert a 'Stream' 'Word8' to a 'ByteString'. unstream :: Stream Word8 -> ByteString unstream (Stream next s0 len) = unsafeDupablePerformIO $ do let mlen = upperBound 4 len mallocByteString mlen >>= loop mlen 0 s0 where loop !n !off !s fp = case next s of Done -> trimUp fp n off Skip s' -> loop n off s' fp Yield x s' | off == n -> realloc fp n off s' x | otherwise -> do withForeignPtr fp $ \p -> pokeByteOff p off x loop n (off+1) s' fp {-# NOINLINE realloc #-} realloc fp n off s x = do let n' = n+n fp' <- copy0 fp n n' withForeignPtr fp' $ \p -> pokeByteOff p off x loop n' (off+1) s fp' {-# NOINLINE trimUp #-} trimUp fp _ off = return $! PS fp 0 off copy0 :: ForeignPtr Word8 -> Int -> Int -> IO (ForeignPtr Word8) copy0 !src !srcLen !destLen = #if defined(ASSERTS) assert (srcLen <= destLen) $ #endif do dest <- mallocByteString destLen withForeignPtr src $ \src' -> withForeignPtr dest $ \dest' -> memcpy dest' src' (fromIntegral srcLen) return dest decodeError :: forall s. String -> String -> OnDecodeError -> Maybe Word8 -> s -> Step s Char decodeError func kind onErr mb i = case onErr desc mb of Nothing -> Skip i Just c -> Yield c i where desc = "Data.Text.Internal.Encoding.Fusion." ++ func ++ ": Invalid " ++ kind ++ " stream"
beni55/text
Data/Text/Internal/Encoding/Fusion.hs
Haskell
bsd-2-clause
7,772
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Utility functions on @Core@ syntax -} {-# LANGUAGE CPP #-} module CoreSubst ( -- * Main data types Subst(..), -- Implementation exported for supercompiler's Renaming.hs only TvSubstEnv, IdSubstEnv, InScopeSet, -- ** Substituting into expressions and related types deShadowBinds, substSpec, substRulesForImportedIds, substTy, substCo, substExpr, substExprSC, substBind, substBindSC, substUnfolding, substUnfoldingSC, lookupIdSubst, lookupTvSubst, lookupCvSubst, substIdOcc, substTickish, substVarSet, -- ** Operations on substitutions emptySubst, mkEmptySubst, mkSubst, mkOpenSubst, substInScope, isEmptySubst, extendIdSubst, extendIdSubstList, extendTvSubst, extendTvSubstList, extendCvSubst, extendCvSubstList, extendSubst, extendSubstList, extendSubstWithVar, zapSubstEnv, addInScopeSet, extendInScope, extendInScopeList, extendInScopeIds, isInScope, setInScope, delBndr, delBndrs, -- ** Substituting and cloning binders substBndr, substBndrs, substRecBndrs, cloneBndr, cloneBndrs, cloneIdBndr, cloneIdBndrs, cloneRecIdBndrs, -- ** Simple expression optimiser simpleOptPgm, simpleOptExpr, simpleOptExprWith, exprIsConApp_maybe, exprIsLiteral_maybe, exprIsLambda_maybe, ) where #include "HsVersions.h" import CoreSyn import CoreFVs import CoreSeq import CoreUtils import Literal ( Literal(MachStr) ) import qualified Data.ByteString as BS import OccurAnal( occurAnalyseExpr, occurAnalysePgm ) import qualified Type import qualified Coercion -- We are defining local versions import Type hiding ( substTy, extendTvSubst, extendTvSubstList , isInScope, substTyVarBndr, cloneTyVarBndr ) import Coercion hiding ( substTy, substCo, extendTvSubst, substTyVarBndr, substCoVarBndr ) import TyCon ( tyConArity ) import DataCon import PrelNames ( eqBoxDataConKey, coercibleDataConKey, unpackCStringIdKey , unpackCStringUtf8IdKey ) import OptCoercion ( optCoercion ) import PprCore ( pprCoreBindings, pprRules ) import Module ( Module ) import VarSet import VarEnv import Id import Name ( Name ) import Var import IdInfo import Unique import UniqSupply import Maybes import ErrUtils import DynFlags import BasicTypes ( isAlwaysActive ) import Util import Pair import Outputable import PprCore () -- Instances import FastString import Data.List import TysWiredIn {- ************************************************************************ * * \subsection{Substitutions} * * ************************************************************************ -} -- | A substitution environment, containing both 'Id' and 'TyVar' substitutions. -- -- Some invariants apply to how you use the substitution: -- -- 1. #in_scope_invariant# The in-scope set contains at least those 'Id's and 'TyVar's that will be in scope /after/ -- applying the substitution to a term. Precisely, the in-scope set must be a superset of the free vars of the -- substitution range that might possibly clash with locally-bound variables in the thing being substituted in. -- -- 2. #apply_once# You may apply the substitution only /once/ -- -- There are various ways of setting up the in-scope set such that the first of these invariants hold: -- -- * Arrange that the in-scope set really is all the things in scope -- -- * Arrange that it's the free vars of the range of the substitution -- -- * Make it empty, if you know that all the free vars of the substitution are fresh, and hence can't possibly clash data Subst = Subst InScopeSet -- Variables in in scope (both Ids and TyVars) /after/ -- applying the substitution IdSubstEnv -- Substitution for Ids TvSubstEnv -- Substitution from TyVars to Types CvSubstEnv -- Substitution from CoVars to Coercions -- INVARIANT 1: See #in_scope_invariant# -- This is what lets us deal with name capture properly -- It's a hard invariant to check... -- -- INVARIANT 2: The substitution is apply-once; see Note [Apply once] with -- Types.TvSubstEnv -- -- INVARIANT 3: See Note [Extending the Subst] {- Note [Extending the Subst] ~~~~~~~~~~~~~~~~~~~~~~~~~~ For a core Subst, which binds Ids as well, we make a different choice for Ids than we do for TyVars. For TyVars, see Note [Extending the TvSubst] with Type.TvSubstEnv For Ids, we have a different invariant The IdSubstEnv is extended *only* when the Unique on an Id changes Otherwise, we just extend the InScopeSet In consequence: * If the TvSubstEnv and IdSubstEnv are both empty, substExpr would be a no-op, so substExprSC ("short cut") does nothing. However, substExpr still goes ahead and substitutes. Reason: we may want to replace existing Ids with new ones from the in-scope set, to avoid space leaks. * In substIdBndr, we extend the IdSubstEnv only when the unique changes * If the CvSubstEnv, TvSubstEnv and IdSubstEnv are all empty, substExpr does nothing (Note that the above rule for substIdBndr maintains this property. If the incoming envts are both empty, then substituting the type and IdInfo can't change anything.) * In lookupIdSubst, we *must* look up the Id in the in-scope set, because it may contain non-trivial changes. Example: (/\a. \x:a. ...x...) Int We extend the TvSubstEnv with [a |-> Int]; but x's unique does not change so we only extend the in-scope set. Then we must look up in the in-scope set when we find the occurrence of x. * The requirement to look up the Id in the in-scope set means that we must NOT take no-op short cut when the IdSubst is empty. We must still look up every Id in the in-scope set. * (However, we don't need to do so for expressions found in the IdSubst itself, whose range is assumed to be correct wrt the in-scope set.) Why do we make a different choice for the IdSubstEnv than the TvSubstEnv and CvSubstEnv? * For Ids, we change the IdInfo all the time (e.g. deleting the unfolding), and adding it back later, so using the TyVar convention would entail extending the substitution almost all the time * The simplifier wants to look up in the in-scope set anyway, in case it can see a better unfolding from an enclosing case expression * For TyVars, only coercion variables can possibly change, and they are easy to spot -} -- | An environment for substituting for 'Id's type IdSubstEnv = IdEnv CoreExpr ---------------------------- isEmptySubst :: Subst -> Bool isEmptySubst (Subst _ id_env tv_env cv_env) = isEmptyVarEnv id_env && isEmptyVarEnv tv_env && isEmptyVarEnv cv_env emptySubst :: Subst emptySubst = Subst emptyInScopeSet emptyVarEnv emptyVarEnv emptyVarEnv mkEmptySubst :: InScopeSet -> Subst mkEmptySubst in_scope = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv mkSubst :: InScopeSet -> TvSubstEnv -> CvSubstEnv -> IdSubstEnv -> Subst mkSubst in_scope tvs cvs ids = Subst in_scope ids tvs cvs -- | Find the in-scope set: see "CoreSubst#in_scope_invariant" substInScope :: Subst -> InScopeSet substInScope (Subst in_scope _ _ _) = in_scope -- | Remove all substitutions for 'Id's and 'Var's that might have been built up -- while preserving the in-scope set zapSubstEnv :: Subst -> Subst zapSubstEnv (Subst in_scope _ _ _) = Subst in_scope emptyVarEnv emptyVarEnv emptyVarEnv -- | Add a substitution for an 'Id' to the 'Subst': you must ensure that the in-scope set is -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this extendIdSubst :: Subst -> Id -> CoreExpr -> Subst -- ToDo: add an ASSERT that fvs(subst-result) is already in the in-scope set extendIdSubst (Subst in_scope ids tvs cvs) v r = Subst in_scope (extendVarEnv ids v r) tvs cvs -- | Adds multiple 'Id' substitutions to the 'Subst': see also 'extendIdSubst' extendIdSubstList :: Subst -> [(Id, CoreExpr)] -> Subst extendIdSubstList (Subst in_scope ids tvs cvs) prs = Subst in_scope (extendVarEnvList ids prs) tvs cvs -- | Add a substitution for a 'TyVar' to the 'Subst': you must ensure that the in-scope set is -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this extendTvSubst :: Subst -> TyVar -> Type -> Subst extendTvSubst (Subst in_scope ids tvs cvs) v r = Subst in_scope ids (extendVarEnv tvs v r) cvs -- | Adds multiple 'TyVar' substitutions to the 'Subst': see also 'extendTvSubst' extendTvSubstList :: Subst -> [(TyVar,Type)] -> Subst extendTvSubstList (Subst in_scope ids tvs cvs) prs = Subst in_scope ids (extendVarEnvList tvs prs) cvs -- | Add a substitution from a 'CoVar' to a 'Coercion' to the 'Subst': you must ensure that the in-scope set is -- such that the "CoreSubst#in_scope_invariant" is true after extending the substitution like this extendCvSubst :: Subst -> CoVar -> Coercion -> Subst extendCvSubst (Subst in_scope ids tvs cvs) v r = Subst in_scope ids tvs (extendVarEnv cvs v r) -- | Adds multiple 'CoVar' -> 'Coercion' substitutions to the -- 'Subst': see also 'extendCvSubst' extendCvSubstList :: Subst -> [(CoVar,Coercion)] -> Subst extendCvSubstList (Subst in_scope ids tvs cvs) prs = Subst in_scope ids tvs (extendVarEnvList cvs prs) -- | Add a substitution appropriate to the thing being substituted -- (whether an expression, type, or coercion). See also -- 'extendIdSubst', 'extendTvSubst', and 'extendCvSubst'. extendSubst :: Subst -> Var -> CoreArg -> Subst extendSubst subst var arg = case arg of Type ty -> ASSERT( isTyVar var ) extendTvSubst subst var ty Coercion co -> ASSERT( isCoVar var ) extendCvSubst subst var co _ -> ASSERT( isId var ) extendIdSubst subst var arg extendSubstWithVar :: Subst -> Var -> Var -> Subst extendSubstWithVar subst v1 v2 | isTyVar v1 = ASSERT( isTyVar v2 ) extendTvSubst subst v1 (mkTyVarTy v2) | isCoVar v1 = ASSERT( isCoVar v2 ) extendCvSubst subst v1 (mkCoVarCo v2) | otherwise = ASSERT( isId v2 ) extendIdSubst subst v1 (Var v2) -- | Add a substitution as appropriate to each of the terms being -- substituted (whether expressions, types, or coercions). See also -- 'extendSubst'. extendSubstList :: Subst -> [(Var,CoreArg)] -> Subst extendSubstList subst [] = subst extendSubstList subst ((var,rhs):prs) = extendSubstList (extendSubst subst var rhs) prs -- | Find the substitution for an 'Id' in the 'Subst' lookupIdSubst :: SDoc -> Subst -> Id -> CoreExpr lookupIdSubst doc (Subst in_scope ids _ _) v | not (isLocalId v) = Var v | Just e <- lookupVarEnv ids v = e | Just v' <- lookupInScope in_scope v = Var v' -- Vital! See Note [Extending the Subst] | otherwise = WARN( True, ptext (sLit "CoreSubst.lookupIdSubst") <+> doc <+> ppr v $$ ppr in_scope) Var v -- | Find the substitution for a 'TyVar' in the 'Subst' lookupTvSubst :: Subst -> TyVar -> Type lookupTvSubst (Subst _ _ tvs _) v = ASSERT( isTyVar v) lookupVarEnv tvs v `orElse` Type.mkTyVarTy v -- | Find the coercion substitution for a 'CoVar' in the 'Subst' lookupCvSubst :: Subst -> CoVar -> Coercion lookupCvSubst (Subst _ _ _ cvs) v = ASSERT( isCoVar v ) lookupVarEnv cvs v `orElse` mkCoVarCo v delBndr :: Subst -> Var -> Subst delBndr (Subst in_scope ids tvs cvs) v | isCoVar v = Subst in_scope ids tvs (delVarEnv cvs v) | isTyVar v = Subst in_scope ids (delVarEnv tvs v) cvs | otherwise = Subst in_scope (delVarEnv ids v) tvs cvs delBndrs :: Subst -> [Var] -> Subst delBndrs (Subst in_scope ids tvs cvs) vs = Subst in_scope (delVarEnvList ids vs) (delVarEnvList tvs vs) (delVarEnvList cvs vs) -- Easiest thing is just delete all from all! -- | Simultaneously substitute for a bunch of variables -- No left-right shadowing -- ie the substitution for (\x \y. e) a1 a2 -- so neither x nor y scope over a1 a2 mkOpenSubst :: InScopeSet -> [(Var,CoreArg)] -> Subst mkOpenSubst in_scope pairs = Subst in_scope (mkVarEnv [(id,e) | (id, e) <- pairs, isId id]) (mkVarEnv [(tv,ty) | (tv, Type ty) <- pairs]) (mkVarEnv [(v,co) | (v, Coercion co) <- pairs]) ------------------------------ isInScope :: Var -> Subst -> Bool isInScope v (Subst in_scope _ _ _) = v `elemInScopeSet` in_scope -- | Add the 'Var' to the in-scope set, but do not remove -- any existing substitutions for it addInScopeSet :: Subst -> VarSet -> Subst addInScopeSet (Subst in_scope ids tvs cvs) vs = Subst (in_scope `extendInScopeSetSet` vs) ids tvs cvs -- | Add the 'Var' to the in-scope set: as a side effect, -- and remove any existing substitutions for it extendInScope :: Subst -> Var -> Subst extendInScope (Subst in_scope ids tvs cvs) v = Subst (in_scope `extendInScopeSet` v) (ids `delVarEnv` v) (tvs `delVarEnv` v) (cvs `delVarEnv` v) -- | Add the 'Var's to the in-scope set: see also 'extendInScope' extendInScopeList :: Subst -> [Var] -> Subst extendInScopeList (Subst in_scope ids tvs cvs) vs = Subst (in_scope `extendInScopeSetList` vs) (ids `delVarEnvList` vs) (tvs `delVarEnvList` vs) (cvs `delVarEnvList` vs) -- | Optimized version of 'extendInScopeList' that can be used if you are certain -- all the things being added are 'Id's and hence none are 'TyVar's or 'CoVar's extendInScopeIds :: Subst -> [Id] -> Subst extendInScopeIds (Subst in_scope ids tvs cvs) vs = Subst (in_scope `extendInScopeSetList` vs) (ids `delVarEnvList` vs) tvs cvs setInScope :: Subst -> InScopeSet -> Subst setInScope (Subst _ ids tvs cvs) in_scope = Subst in_scope ids tvs cvs -- Pretty printing, for debugging only instance Outputable Subst where ppr (Subst in_scope ids tvs cvs) = ptext (sLit "<InScope =") <+> braces (fsep (map ppr (varEnvElts (getInScopeVars in_scope)))) $$ ptext (sLit " IdSubst =") <+> ppr ids $$ ptext (sLit " TvSubst =") <+> ppr tvs $$ ptext (sLit " CvSubst =") <+> ppr cvs <> char '>' {- ************************************************************************ * * Substituting expressions * * ************************************************************************ -} -- | Apply a substitution to an entire 'CoreExpr'. Remember, you may only -- apply the substitution /once/: see "CoreSubst#apply_once" -- -- Do *not* attempt to short-cut in the case of an empty substitution! -- See Note [Extending the Subst] substExprSC :: SDoc -> Subst -> CoreExpr -> CoreExpr substExprSC _doc subst orig_expr | isEmptySubst subst = orig_expr | otherwise = -- pprTrace "enter subst-expr" (doc $$ ppr orig_expr) $ subst_expr subst orig_expr substExpr :: SDoc -> Subst -> CoreExpr -> CoreExpr substExpr _doc subst orig_expr = subst_expr subst orig_expr subst_expr :: Subst -> CoreExpr -> CoreExpr subst_expr subst expr = go expr where go (Var v) = lookupIdSubst (text "subst_expr") subst v go (Type ty) = Type (substTy subst ty) go (Coercion co) = Coercion (substCo subst co) go (Lit lit) = Lit lit go (App fun arg) = App (go fun) (go arg) go (Tick tickish e) = mkTick (substTickish subst tickish) (go e) go (Cast e co) = Cast (go e) (substCo subst co) -- Do not optimise even identity coercions -- Reason: substitution applies to the LHS of RULES, and -- if you "optimise" an identity coercion, you may -- lose a binder. We optimise the LHS of rules at -- construction time go (Lam bndr body) = Lam bndr' (subst_expr subst' body) where (subst', bndr') = substBndr subst bndr go (Let bind body) = Let bind' (subst_expr subst' body) where (subst', bind') = substBind subst bind go (Case scrut bndr ty alts) = Case (go scrut) bndr' (substTy subst ty) (map (go_alt subst') alts) where (subst', bndr') = substBndr subst bndr go_alt subst (con, bndrs, rhs) = (con, bndrs', subst_expr subst' rhs) where (subst', bndrs') = substBndrs subst bndrs -- | Apply a substitution to an entire 'CoreBind', additionally returning an updated 'Subst' -- that should be used by subsequent substitutions. substBind, substBindSC :: Subst -> CoreBind -> (Subst, CoreBind) substBindSC subst bind -- Short-cut if the substitution is empty | not (isEmptySubst subst) = substBind subst bind | otherwise = case bind of NonRec bndr rhs -> (subst', NonRec bndr' rhs) where (subst', bndr') = substBndr subst bndr Rec pairs -> (subst', Rec (bndrs' `zip` rhss')) where (bndrs, rhss) = unzip pairs (subst', bndrs') = substRecBndrs subst bndrs rhss' | isEmptySubst subst' = rhss | otherwise = map (subst_expr subst') rhss substBind subst (NonRec bndr rhs) = (subst', NonRec bndr' (subst_expr subst rhs)) where (subst', bndr') = substBndr subst bndr substBind subst (Rec pairs) = (subst', Rec (bndrs' `zip` rhss')) where (bndrs, rhss) = unzip pairs (subst', bndrs') = substRecBndrs subst bndrs rhss' = map (subst_expr subst') rhss -- | De-shadowing the program is sometimes a useful pre-pass. It can be done simply -- by running over the bindings with an empty substitution, because substitution -- returns a result that has no-shadowing guaranteed. -- -- (Actually, within a single /type/ there might still be shadowing, because -- 'substTy' is a no-op for the empty substitution, but that's probably OK.) -- -- [Aug 09] This function is not used in GHC at the moment, but seems so -- short and simple that I'm going to leave it here deShadowBinds :: CoreProgram -> CoreProgram deShadowBinds binds = snd (mapAccumL substBind emptySubst binds) {- ************************************************************************ * * Substituting binders * * ************************************************************************ Remember that substBndr and friends are used when doing expression substitution only. Their only business is substitution, so they preserve all IdInfo (suitably substituted). For example, we *want* to preserve occ info in rules. -} -- | Substitutes a 'Var' for another one according to the 'Subst' given, returning -- the result and an updated 'Subst' that should be used by subsequent substitutions. -- 'IdInfo' is preserved by this process, although it is substituted into appropriately. substBndr :: Subst -> Var -> (Subst, Var) substBndr subst bndr | isTyVar bndr = substTyVarBndr subst bndr | isCoVar bndr = substCoVarBndr subst bndr | otherwise = substIdBndr (text "var-bndr") subst subst bndr -- | Applies 'substBndr' to a number of 'Var's, accumulating a new 'Subst' left-to-right substBndrs :: Subst -> [Var] -> (Subst, [Var]) substBndrs subst bndrs = mapAccumL substBndr subst bndrs -- | Substitute in a mutually recursive group of 'Id's substRecBndrs :: Subst -> [Id] -> (Subst, [Id]) substRecBndrs subst bndrs = (new_subst, new_bndrs) where -- Here's the reason we need to pass rec_subst to subst_id (new_subst, new_bndrs) = mapAccumL (substIdBndr (text "rec-bndr") new_subst) subst bndrs substIdBndr :: SDoc -> Subst -- ^ Substitution to use for the IdInfo -> Subst -> Id -- ^ Substitution and Id to transform -> (Subst, Id) -- ^ Transformed pair -- NB: unfolding may be zapped substIdBndr _doc rec_subst subst@(Subst in_scope env tvs cvs) old_id = -- pprTrace "substIdBndr" (doc $$ ppr old_id $$ ppr in_scope) $ (Subst (in_scope `extendInScopeSet` new_id) new_env tvs cvs, new_id) where id1 = uniqAway in_scope old_id -- id1 is cloned if necessary id2 | no_type_change = id1 | otherwise = setIdType id1 (substTy subst old_ty) old_ty = idType old_id no_type_change = isEmptyVarEnv tvs || isEmptyVarSet (Type.tyVarsOfType old_ty) -- new_id has the right IdInfo -- The lazy-set is because we're in a loop here, with -- rec_subst, when dealing with a mutually-recursive group new_id = maybeModifyIdInfo mb_new_info id2 mb_new_info = substIdInfo rec_subst id2 (idInfo id2) -- NB: unfolding info may be zapped -- Extend the substitution if the unique has changed -- See the notes with substTyVarBndr for the delVarEnv new_env | no_change = delVarEnv env old_id | otherwise = extendVarEnv env old_id (Var new_id) no_change = id1 == old_id -- See Note [Extending the Subst] -- it's /not/ necessary to check mb_new_info and no_type_change {- Now a variant that unconditionally allocates a new unique. It also unconditionally zaps the OccInfo. -} -- | Very similar to 'substBndr', but it always allocates a new 'Unique' for -- each variable in its output. It substitutes the IdInfo though. cloneIdBndr :: Subst -> UniqSupply -> Id -> (Subst, Id) cloneIdBndr subst us old_id = clone_id subst subst (old_id, uniqFromSupply us) -- | Applies 'cloneIdBndr' to a number of 'Id's, accumulating a final -- substitution from left to right cloneIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id]) cloneIdBndrs subst us ids = mapAccumL (clone_id subst) subst (ids `zip` uniqsFromSupply us) cloneBndrs :: Subst -> UniqSupply -> [Var] -> (Subst, [Var]) -- Works for all kinds of variables (typically case binders) -- not just Ids cloneBndrs subst us vs = mapAccumL (\subst (v, u) -> cloneBndr subst u v) subst (vs `zip` uniqsFromSupply us) cloneBndr :: Subst -> Unique -> Var -> (Subst, Var) cloneBndr subst uniq v | isTyVar v = cloneTyVarBndr subst v uniq | otherwise = clone_id subst subst (v,uniq) -- Works for coercion variables too -- | Clone a mutually recursive group of 'Id's cloneRecIdBndrs :: Subst -> UniqSupply -> [Id] -> (Subst, [Id]) cloneRecIdBndrs subst us ids = (subst', ids') where (subst', ids') = mapAccumL (clone_id subst') subst (ids `zip` uniqsFromSupply us) -- Just like substIdBndr, except that it always makes a new unique -- It is given the unique to use clone_id :: Subst -- Substitution for the IdInfo -> Subst -> (Id, Unique) -- Substitution and Id to transform -> (Subst, Id) -- Transformed pair clone_id rec_subst subst@(Subst in_scope idvs tvs cvs) (old_id, uniq) = (Subst (in_scope `extendInScopeSet` new_id) new_idvs tvs new_cvs, new_id) where id1 = setVarUnique old_id uniq id2 = substIdType subst id1 new_id = maybeModifyIdInfo (substIdInfo rec_subst id2 (idInfo old_id)) id2 (new_idvs, new_cvs) | isCoVar old_id = (idvs, extendVarEnv cvs old_id (mkCoVarCo new_id)) | otherwise = (extendVarEnv idvs old_id (Var new_id), cvs) {- ************************************************************************ * * Types and Coercions * * ************************************************************************ For types and coercions we just call the corresponding functions in Type and Coercion, but we have to repackage the substitution, from a Subst to a TvSubst. -} substTyVarBndr :: Subst -> TyVar -> (Subst, TyVar) substTyVarBndr (Subst in_scope id_env tv_env cv_env) tv = case Type.substTyVarBndr (TvSubst in_scope tv_env) tv of (TvSubst in_scope' tv_env', tv') -> (Subst in_scope' id_env tv_env' cv_env, tv') cloneTyVarBndr :: Subst -> TyVar -> Unique -> (Subst, TyVar) cloneTyVarBndr (Subst in_scope id_env tv_env cv_env) tv uniq = case Type.cloneTyVarBndr (TvSubst in_scope tv_env) tv uniq of (TvSubst in_scope' tv_env', tv') -> (Subst in_scope' id_env tv_env' cv_env, tv') substCoVarBndr :: Subst -> TyVar -> (Subst, TyVar) substCoVarBndr (Subst in_scope id_env tv_env cv_env) cv = case Coercion.substCoVarBndr (CvSubst in_scope tv_env cv_env) cv of (CvSubst in_scope' tv_env' cv_env', cv') -> (Subst in_scope' id_env tv_env' cv_env', cv') -- | See 'Type.substTy' substTy :: Subst -> Type -> Type substTy subst ty = Type.substTy (getTvSubst subst) ty getTvSubst :: Subst -> TvSubst getTvSubst (Subst in_scope _ tenv _) = TvSubst in_scope tenv getCvSubst :: Subst -> CvSubst getCvSubst (Subst in_scope _ tenv cenv) = CvSubst in_scope tenv cenv -- | See 'Coercion.substCo' substCo :: Subst -> Coercion -> Coercion substCo subst co = Coercion.substCo (getCvSubst subst) co {- ************************************************************************ * * \section{IdInfo substitution} * * ************************************************************************ -} substIdType :: Subst -> Id -> Id substIdType subst@(Subst _ _ tv_env cv_env) id | (isEmptyVarEnv tv_env && isEmptyVarEnv cv_env) || isEmptyVarSet (Type.tyVarsOfType old_ty) = id | otherwise = setIdType id (substTy subst old_ty) -- The tyVarsOfType is cheaper than it looks -- because we cache the free tyvars of the type -- in a Note in the id's type itself where old_ty = idType id ------------------ -- | Substitute into some 'IdInfo' with regard to the supplied new 'Id'. substIdInfo :: Subst -> Id -> IdInfo -> Maybe IdInfo substIdInfo subst new_id info | nothing_to_do = Nothing | otherwise = Just (info `setSpecInfo` substSpec subst new_id old_rules `setUnfoldingInfo` substUnfolding subst old_unf) where old_rules = specInfo info old_unf = unfoldingInfo info nothing_to_do = isEmptySpecInfo old_rules && isClosedUnfolding old_unf ------------------ -- | Substitutes for the 'Id's within an unfolding substUnfolding, substUnfoldingSC :: Subst -> Unfolding -> Unfolding -- Seq'ing on the returned Unfolding is enough to cause -- all the substitutions to happen completely substUnfoldingSC subst unf -- Short-cut version | isEmptySubst subst = unf | otherwise = substUnfolding subst unf substUnfolding subst df@(DFunUnfolding { df_bndrs = bndrs, df_args = args }) = df { df_bndrs = bndrs', df_args = args' } where (subst',bndrs') = substBndrs subst bndrs args' = map (substExpr (text "subst-unf:dfun") subst') args substUnfolding subst unf@(CoreUnfolding { uf_tmpl = tmpl, uf_src = src }) -- Retain an InlineRule! | not (isStableSource src) -- Zap an unstable unfolding, to save substitution work = NoUnfolding | otherwise -- But keep a stable one! = seqExpr new_tmpl `seq` unf { uf_tmpl = new_tmpl } where new_tmpl = substExpr (text "subst-unf") subst tmpl substUnfolding _ unf = unf -- NoUnfolding, OtherCon ------------------ substIdOcc :: Subst -> Id -> Id -- These Ids should not be substituted to non-Ids substIdOcc subst v = case lookupIdSubst (text "substIdOcc") subst v of Var v' -> v' other -> pprPanic "substIdOcc" (vcat [ppr v <+> ppr other, ppr subst]) ------------------ -- | Substitutes for the 'Id's within the 'WorkerInfo' given the new function 'Id' substSpec :: Subst -> Id -> SpecInfo -> SpecInfo substSpec subst new_id (SpecInfo rules rhs_fvs) = seqSpecInfo new_spec `seq` new_spec where subst_ru_fn = const (idName new_id) new_spec = SpecInfo (map (substRule subst subst_ru_fn) rules) (substVarSet subst rhs_fvs) ------------------ substRulesForImportedIds :: Subst -> [CoreRule] -> [CoreRule] substRulesForImportedIds subst rules = map (substRule subst not_needed) rules where not_needed name = pprPanic "substRulesForImportedIds" (ppr name) ------------------ substRule :: Subst -> (Name -> Name) -> CoreRule -> CoreRule -- The subst_ru_fn argument is applied to substitute the ru_fn field -- of the rule: -- - Rules for *imported* Ids never change ru_fn -- - Rules for *local* Ids are in the IdInfo for that Id, -- and the ru_fn field is simply replaced by the new name -- of the Id substRule _ _ rule@(BuiltinRule {}) = rule substRule subst subst_ru_fn rule@(Rule { ru_bndrs = bndrs, ru_args = args , ru_fn = fn_name, ru_rhs = rhs , ru_local = is_local }) = rule { ru_bndrs = bndrs' , ru_fn = if is_local then subst_ru_fn fn_name else fn_name , ru_args = map (substExpr doc subst') args , ru_rhs = substExpr (text "foo") subst' rhs } -- Do NOT optimise the RHS (previously we did simplOptExpr here) -- See Note [Substitute lazily] where doc = ptext (sLit "subst-rule") <+> ppr fn_name (subst', bndrs') = substBndrs subst bndrs ------------------ substVects :: Subst -> [CoreVect] -> [CoreVect] substVects subst = map (substVect subst) ------------------ substVect :: Subst -> CoreVect -> CoreVect substVect subst (Vect v rhs) = Vect v (simpleOptExprWith subst rhs) substVect _subst vd@(NoVect _) = vd substVect _subst vd@(VectType _ _ _) = vd substVect _subst vd@(VectClass _) = vd substVect _subst vd@(VectInst _) = vd ------------------ substVarSet :: Subst -> VarSet -> VarSet substVarSet subst fvs = foldVarSet (unionVarSet . subst_fv subst) emptyVarSet fvs where subst_fv subst fv | isId fv = exprFreeVars (lookupIdSubst (text "substVarSet") subst fv) | otherwise = Type.tyVarsOfType (lookupTvSubst subst fv) ------------------ substTickish :: Subst -> Tickish Id -> Tickish Id substTickish subst (Breakpoint n ids) = Breakpoint n (map do_one ids) where do_one = getIdFromTrivialExpr . lookupIdSubst (text "subst_tickish") subst substTickish _subst other = other {- Note [Substitute lazily] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The functions that substitute over IdInfo must be pretty lazy, becuause they are knot-tied by substRecBndrs. One case in point was Trac #10627 in which a rule for a function 'f' referred to 'f' (at a differnet type) on the RHS. But instead of just substituting in the rhs of the rule, we were calling simpleOptExpr, which looked at the idInfo for 'f'; result <<loop>>. In any case we don't need to optimise the RHS of rules, or unfoldings, because the simplifier will do that. Note [substTickish] ~~~~~~~~~~~~~~~~~~~~~~ A Breakpoint contains a list of Ids. What happens if we ever want to substitute an expression for one of these Ids? First, we ensure that we only ever substitute trivial expressions for these Ids, by marking them as NoOccInfo in the occurrence analyser. Then, when substituting for the Id, we unwrap any type applications and abstractions to get back to an Id, with getIdFromTrivialExpr. Second, we have to ensure that we never try to substitute a literal for an Id in a breakpoint. We ensure this by never storing an Id with an unlifted type in a Breakpoint - see Coverage.mkTickish. Breakpoints can't handle free variables with unlifted types anyway. -} {- Note [Worker inlining] ~~~~~~~~~~~~~~~~~~~~~~ A worker can get sustituted away entirely. - it might be trivial - it might simply be very small We do not treat an InlWrapper as an 'occurrence' in the occurrence analyser, so it's possible that the worker is not even in scope any more. In all all these cases we simply drop the special case, returning to InlVanilla. The WARN is just so I can see if it happens a lot. ************************************************************************ * * The Very Simple Optimiser * * ************************************************************************ Note [Optimise coercion boxes aggressively] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The simple expression optimiser needs to deal with Eq# boxes as follows: 1. If the result of optimising the RHS of a non-recursive binding is an Eq# box, that box is substituted rather than turned into a let, just as if it were trivial. let eqv = Eq# co in e ==> e[Eq# co/eqv] 2. If the result of optimising a case scrutinee is a Eq# box and the case deconstructs it in a trivial way, we evaluate the case then and there. case Eq# co of Eq# cov -> e ==> e[co/cov] We do this for two reasons: 1. Bindings/case scrutinisation of this form is often created by the evidence-binding mechanism and we need them to be inlined to be able desugar RULE LHSes that involve equalities (see e.g. T2291) 2. The test T4356 fails Lint because it creates a coercion between types of kind (* -> * -> *) and (?? -> ? -> *), which differ. If we do this inlining aggressively we can collapse away the intermediate coercion between these two types and hence pass Lint again. (This is a sort of a hack.) In fact, our implementation uses slightly liberalised versions of the second rule rule so that the optimisations are a bit more generally applicable. Precisely: 2a. We reduce any situation where we can spot a case-of-known-constructor As a result, the only time we should get residual coercion boxes in the code is when the type checker generates something like: \eqv -> let eqv' = Eq# (case eqv of Eq# cov -> ... cov ...) However, the case of lambda-bound equality evidence is fairly rare, so these two rules should suffice for solving the rule LHS problem for now. Annoyingly, we cannot use this modified rule 1a instead of 1: 1a. If we come across a let-bound constructor application with trivial arguments, add an appropriate unfolding to the let binder. We spot constructor applications by using exprIsConApp_maybe, so this would actually let rule 2a reduce more. The reason is that we REALLY NEED coercion boxes to be substituted away. With rule 1a we wouldn't simplify this expression at all: let eqv = Eq# co in foo eqv (bar eqv) The rule LHS desugarer can't deal with Let at all, so we need to push that box into the use sites. -} simpleOptExpr :: CoreExpr -> CoreExpr -- Do simple optimisation on an expression -- The optimisation is very straightforward: just -- inline non-recursive bindings that are used only once, -- or where the RHS is trivial -- -- We also inline bindings that bind a Eq# box: see -- See Note [Optimise coercion boxes aggressively]. -- -- The result is NOT guaranteed occurrence-analysed, because -- in (let x = y in ....) we substitute for x; so y's occ-info -- may change radically simpleOptExpr expr = -- pprTrace "simpleOptExpr" (ppr init_subst $$ ppr expr) simpleOptExprWith init_subst expr where init_subst = mkEmptySubst (mkInScopeSet (exprFreeVars expr)) -- It's potentially important to make a proper in-scope set -- Consider let x = ..y.. in \y. ...x... -- Then we should remember to clone y before substituting -- for x. It's very unlikely to occur, because we probably -- won't *be* substituting for x if it occurs inside a -- lambda. -- -- It's a bit painful to call exprFreeVars, because it makes -- three passes instead of two (occ-anal, and go) simpleOptExprWith :: Subst -> InExpr -> OutExpr simpleOptExprWith subst expr = simple_opt_expr subst (occurAnalyseExpr expr) ---------------------- simpleOptPgm :: DynFlags -> Module -> CoreProgram -> [CoreRule] -> [CoreVect] -> IO (CoreProgram, [CoreRule], [CoreVect]) simpleOptPgm dflags this_mod binds rules vects = do { dumpIfSet_dyn dflags Opt_D_dump_occur_anal "Occurrence analysis" (pprCoreBindings occ_anald_binds $$ pprRules rules ); ; return (reverse binds', substRulesForImportedIds subst' rules, substVects subst' vects) } where occ_anald_binds = occurAnalysePgm this_mod (\_ -> False) {- No rules active -} rules vects emptyVarEnv binds (subst', binds') = foldl do_one (emptySubst, []) occ_anald_binds do_one (subst, binds') bind = case simple_opt_bind subst bind of (subst', Nothing) -> (subst', binds') (subst', Just bind') -> (subst', bind':binds') ---------------------- type InVar = Var type OutVar = Var type InId = Id type OutId = Id type InExpr = CoreExpr type OutExpr = CoreExpr -- In these functions the substitution maps InVar -> OutExpr ---------------------- simple_opt_expr :: Subst -> InExpr -> OutExpr simple_opt_expr subst expr = go expr where in_scope_env = (substInScope subst, simpleUnfoldingFun) go (Var v) = lookupIdSubst (text "simpleOptExpr") subst v go (App e1 e2) = simple_app subst e1 [go e2] go (Type ty) = Type (substTy subst ty) go (Coercion co) = Coercion (optCoercion (getCvSubst subst) co) go (Lit lit) = Lit lit go (Tick tickish e) = mkTick (substTickish subst tickish) (go e) go (Cast e co) | isReflCo co' = go e | otherwise = Cast (go e) co' where co' = optCoercion (getCvSubst subst) co go (Let bind body) = case simple_opt_bind subst bind of (subst', Nothing) -> simple_opt_expr subst' body (subst', Just bind) -> Let bind (simple_opt_expr subst' body) go lam@(Lam {}) = go_lam [] subst lam go (Case e b ty as) -- See Note [Optimise coercion boxes aggressively] | isDeadBinder b , Just (con, _tys, es) <- exprIsConApp_maybe in_scope_env e' , Just (altcon, bs, rhs) <- findAlt (DataAlt con) as = case altcon of DEFAULT -> go rhs _ -> mkLets (catMaybes mb_binds) $ simple_opt_expr subst' rhs where (subst', mb_binds) = mapAccumL simple_opt_out_bind subst (zipEqual "simpleOptExpr" bs es) | otherwise = Case e' b' (substTy subst ty) (map (go_alt subst') as) where e' = go e (subst', b') = subst_opt_bndr subst b ---------------------- go_alt subst (con, bndrs, rhs) = (con, bndrs', simple_opt_expr subst' rhs) where (subst', bndrs') = subst_opt_bndrs subst bndrs ---------------------- -- go_lam tries eta reduction go_lam bs' subst (Lam b e) = go_lam (b':bs') subst' e where (subst', b') = subst_opt_bndr subst b go_lam bs' subst e | Just etad_e <- tryEtaReduce bs e' = etad_e | otherwise = mkLams bs e' where bs = reverse bs' e' = simple_opt_expr subst e ---------------------- -- simple_app collects arguments for beta reduction simple_app :: Subst -> InExpr -> [OutExpr] -> CoreExpr simple_app subst (App e1 e2) as = simple_app subst e1 (simple_opt_expr subst e2 : as) simple_app subst (Lam b e) (a:as) = case maybe_substitute subst b a of Just ext_subst -> simple_app ext_subst e as Nothing -> Let (NonRec b2 a) (simple_app subst' e as) where (subst', b') = subst_opt_bndr subst b b2 = add_info subst' b b' simple_app subst (Var v) as | isCompulsoryUnfolding (idUnfolding v) , isAlwaysActive (idInlineActivation v) -- See Note [Unfold compulsory unfoldings in LHSs] = simple_app subst (unfoldingTemplate (idUnfolding v)) as simple_app subst (Tick t e) as -- Okay to do "(Tick t e) x ==> Tick t (e x)"? | t `tickishScopesLike` SoftScope = mkTick t $ simple_app subst e as simple_app subst e as = foldl App (simple_opt_expr subst e) as ---------------------- simple_opt_bind,simple_opt_bind' :: Subst -> CoreBind -> (Subst, Maybe CoreBind) simple_opt_bind s b -- Can add trace stuff here = simple_opt_bind' s b simple_opt_bind' subst (Rec prs) = (subst'', res_bind) where res_bind = Just (Rec (reverse rev_prs')) (subst', bndrs') = subst_opt_bndrs subst (map fst prs) (subst'', rev_prs') = foldl do_pr (subst', []) (prs `zip` bndrs') do_pr (subst, prs) ((b,r), b') = case maybe_substitute subst b r2 of Just subst' -> (subst', prs) Nothing -> (subst, (b2,r2):prs) where b2 = add_info subst b b' r2 = simple_opt_expr subst r simple_opt_bind' subst (NonRec b r) = simple_opt_out_bind subst (b, simple_opt_expr subst r) ---------------------- simple_opt_out_bind :: Subst -> (InVar, OutExpr) -> (Subst, Maybe CoreBind) simple_opt_out_bind subst (b, r') | Just ext_subst <- maybe_substitute subst b r' = (ext_subst, Nothing) | otherwise = (subst', Just (NonRec b2 r')) where (subst', b') = subst_opt_bndr subst b b2 = add_info subst' b b' ---------------------- maybe_substitute :: Subst -> InVar -> OutExpr -> Maybe Subst -- (maybe_substitute subst in_var out_rhs) -- either extends subst with (in_var -> out_rhs) -- or returns Nothing maybe_substitute subst b r | Type ty <- r -- let a::* = TYPE ty in <body> = ASSERT( isTyVar b ) Just (extendTvSubst subst b ty) | Coercion co <- r = ASSERT( isCoVar b ) Just (extendCvSubst subst b co) | isId b -- let x = e in <body> , not (isCoVar b) -- See Note [Do not inline CoVars unconditionally] -- in SimplUtils , safe_to_inline (idOccInfo b) , isAlwaysActive (idInlineActivation b) -- Note [Inline prag in simplOpt] , not (isStableUnfolding (idUnfolding b)) , not (isExportedId b) , not (isUnLiftedType (idType b)) || exprOkForSpeculation r = Just (extendIdSubst subst b r) | otherwise = Nothing where -- Unconditionally safe to inline safe_to_inline :: OccInfo -> Bool safe_to_inline (IAmALoopBreaker {}) = False safe_to_inline IAmDead = True safe_to_inline (OneOcc in_lam one_br _) = (not in_lam && one_br) || trivial safe_to_inline NoOccInfo = trivial trivial | exprIsTrivial r = True | (Var fun, args) <- collectArgs r , Just dc <- isDataConWorkId_maybe fun , dc `hasKey` eqBoxDataConKey || dc `hasKey` coercibleDataConKey , all exprIsTrivial args = True -- See Note [Optimise coercion boxes aggressively] | otherwise = False ---------------------- subst_opt_bndr :: Subst -> InVar -> (Subst, OutVar) subst_opt_bndr subst bndr | isTyVar bndr = substTyVarBndr subst bndr | isCoVar bndr = substCoVarBndr subst bndr | otherwise = subst_opt_id_bndr subst bndr subst_opt_id_bndr :: Subst -> InId -> (Subst, OutId) -- Nuke all fragile IdInfo, unfolding, and RULES; -- it gets added back later by add_info -- Rather like SimplEnv.substIdBndr -- -- It's important to zap fragile OccInfo (which CoreSubst.substIdBndr -- carefully does not do) because simplOptExpr invalidates it subst_opt_id_bndr subst@(Subst in_scope id_subst tv_subst cv_subst) old_id = (Subst new_in_scope new_id_subst tv_subst cv_subst, new_id) where id1 = uniqAway in_scope old_id id2 = setIdType id1 (substTy subst (idType old_id)) new_id = zapFragileIdInfo id2 -- Zaps rules, worker-info, unfolding -- and fragile OccInfo new_in_scope = in_scope `extendInScopeSet` new_id -- Extend the substitution if the unique has changed, -- or there's some useful occurrence information -- See the notes with substTyVarBndr for the delSubstEnv new_id_subst | new_id /= old_id = extendVarEnv id_subst old_id (Var new_id) | otherwise = delVarEnv id_subst old_id ---------------------- subst_opt_bndrs :: Subst -> [InVar] -> (Subst, [OutVar]) subst_opt_bndrs subst bndrs = mapAccumL subst_opt_bndr subst bndrs ---------------------- add_info :: Subst -> InVar -> OutVar -> OutVar add_info subst old_bndr new_bndr | isTyVar old_bndr = new_bndr | otherwise = maybeModifyIdInfo mb_new_info new_bndr where mb_new_info = substIdInfo subst new_bndr (idInfo old_bndr) simpleUnfoldingFun :: IdUnfoldingFun simpleUnfoldingFun id | isAlwaysActive (idInlineActivation id) = idUnfolding id | otherwise = noUnfolding {- Note [Inline prag in simplOpt] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If there's an INLINE/NOINLINE pragma that restricts the phase in which the binder can be inlined, we don't inline here; after all, we don't know what phase we're in. Here's an example foo :: Int -> Int -> Int {-# INLINE foo #-} foo m n = inner m where {-# INLINE [1] inner #-} inner m = m+n bar :: Int -> Int bar n = foo n 1 When inlining 'foo' in 'bar' we want the let-binding for 'inner' to remain visible until Phase 1 Note [Unfold compulsory unfoldings in LHSs] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When the user writes `RULES map coerce = coerce` as a rule, the rule will only ever match if simpleOptExpr replaces coerce by its unfolding on the LHS, because that is the core that the rule matching engine will find. So do that for everything that has a compulsory unfolding. Also see Note [Desugaring coerce as cast] in Desugar. However, we don't want to inline 'seq', which happens to also have a compulsory unfolding, so we only do this unfolding only for things that are always-active. See Note [User-defined RULES for seq] in MkId. ************************************************************************ * * exprIsConApp_maybe * * ************************************************************************ Note [exprIsConApp_maybe] ~~~~~~~~~~~~~~~~~~~~~~~~~ exprIsConApp_maybe is a very important function. There are two principal uses: * case e of { .... } * cls_op e, where cls_op is a class operation In both cases you want to know if e is of form (C e1..en) where C is a data constructor. However e might not *look* as if Note [exprIsConApp_maybe on literal strings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ See #9400. Conceptually, a string literal "abc" is just ('a':'b':'c':[]), but in Core they are represented as unpackCString# "abc"# by MkCore.mkStringExprFS, or unpackCStringUtf8# when the literal contains multi-byte UTF8 characters. For optimizations we want to be able to treat it as a list, so they can be decomposed when used in a case-statement. exprIsConApp_maybe detects those calls to unpackCString# and returns: Just (':', [Char], ['a', unpackCString# "bc"]). We need to be careful about UTF8 strings here. ""# contains a ByteString, so we must parse it back into a FastString to split off the first character. That way we can treat unpackCString# and unpackCStringUtf8# in the same way. -} data ConCont = CC [CoreExpr] Coercion -- Substitution already applied -- | Returns @Just (dc, [t1..tk], [x1..xn])@ if the argument expression is -- a *saturated* constructor application of the form @dc t1..tk x1 .. xn@, -- where t1..tk are the *universally-qantified* type args of 'dc' exprIsConApp_maybe :: InScopeEnv -> CoreExpr -> Maybe (DataCon, [Type], [CoreExpr]) exprIsConApp_maybe (in_scope, id_unf) expr = go (Left in_scope) expr (CC [] (mkReflCo Representational (exprType expr))) where go :: Either InScopeSet Subst -> CoreExpr -> ConCont -> Maybe (DataCon, [Type], [CoreExpr]) go subst (Tick t expr) cont | not (tickishIsCode t) = go subst expr cont go subst (Cast expr co1) (CC [] co2) = go subst expr (CC [] (subst_co subst co1 `mkTransCo` co2)) go subst (App fun arg) (CC args co) = go subst fun (CC (subst_arg subst arg : args) co) go subst (Lam var body) (CC (arg:args) co) | exprIsTrivial arg -- Don't duplicate stuff! = go (extend subst var arg) body (CC args co) go (Right sub) (Var v) cont = go (Left (substInScope sub)) (lookupIdSubst (text "exprIsConApp" <+> ppr expr) sub v) cont go (Left in_scope) (Var fun) cont@(CC args co) | Just con <- isDataConWorkId_maybe fun , count isValArg args == idArity fun = dealWithCoercion co con args -- Look through dictionary functions; see Note [Unfolding DFuns] | DFunUnfolding { df_bndrs = bndrs, df_con = con, df_args = dfun_args } <- unfolding , bndrs `equalLength` args -- See Note [DFun arity check] , let subst = mkOpenSubst in_scope (bndrs `zip` args) = dealWithCoercion co con (map (substExpr (text "exprIsConApp1") subst) dfun_args) -- Look through unfoldings, but only arity-zero one; -- if arity > 0 we are effectively inlining a function call, -- and that is the business of callSiteInline. -- In practice, without this test, most of the "hits" were -- CPR'd workers getting inlined back into their wrappers, | idArity fun == 0 , Just rhs <- expandUnfolding_maybe unfolding , let in_scope' = extendInScopeSetSet in_scope (exprFreeVars rhs) = go (Left in_scope') rhs cont | (fun `hasKey` unpackCStringIdKey) || (fun `hasKey` unpackCStringUtf8IdKey) , [Lit (MachStr str)] <- args = dealWithStringLiteral fun str co where unfolding = id_unf fun go _ _ _ = Nothing ---------------------------- -- Operations on the (Either InScopeSet CoreSubst) -- The Left case is wildly dominant subst_co (Left {}) co = co subst_co (Right s) co = CoreSubst.substCo s co subst_arg (Left {}) e = e subst_arg (Right s) e = substExpr (text "exprIsConApp2") s e extend (Left in_scope) v e = Right (extendSubst (mkEmptySubst in_scope) v e) extend (Right s) v e = Right (extendSubst s v e) -- See Note [exprIsConApp_maybe on literal strings] dealWithStringLiteral :: Var -> BS.ByteString -> Coercion -> Maybe (DataCon, [Type], [CoreExpr]) -- This is not possible with user-supplied empty literals, MkCore.mkStringExprFS -- turns those into [] automatically, but just in case something else in GHC -- generates a string literal directly. dealWithStringLiteral _ str co | BS.null str = dealWithCoercion co nilDataCon [Type charTy] dealWithStringLiteral fun str co = let strFS = mkFastStringByteString str char = mkConApp charDataCon [mkCharLit (headFS strFS)] charTail = fastStringToByteString (tailFS strFS) -- In singleton strings, just add [] instead of unpackCstring# ""#. rest = if BS.null charTail then mkConApp nilDataCon [Type charTy] else App (Var fun) (Lit (MachStr charTail)) in dealWithCoercion co consDataCon [Type charTy, char, rest] dealWithCoercion :: Coercion -> DataCon -> [CoreExpr] -> Maybe (DataCon, [Type], [CoreExpr]) dealWithCoercion co dc dc_args | isReflCo co , let (univ_ty_args, rest_args) = splitAtList (dataConUnivTyVars dc) dc_args = Just (dc, stripTypeArgs univ_ty_args, rest_args) | Pair _from_ty to_ty <- coercionKind co , Just (to_tc, to_tc_arg_tys) <- splitTyConApp_maybe to_ty , to_tc == dataConTyCon dc -- These two tests can fail; we might see -- (C x y) `cast` (g :: T a ~ S [a]), -- where S is a type function. In fact, exprIsConApp -- will probably not be called in such circumstances, -- but there't nothing wrong with it = -- Here we do the KPush reduction rule as described in the FC paper -- The transformation applies iff we have -- (C e1 ... en) `cast` co -- where co :: (T t1 .. tn) ~ to_ty -- The left-hand one must be a T, because exprIsConApp returned True -- but the right-hand one might not be. (Though it usually will.) let tc_arity = tyConArity to_tc dc_univ_tyvars = dataConUnivTyVars dc dc_ex_tyvars = dataConExTyVars dc arg_tys = dataConRepArgTys dc non_univ_args = dropList dc_univ_tyvars dc_args (ex_args, val_args) = splitAtList dc_ex_tyvars non_univ_args -- Make the "theta" from Fig 3 of the paper gammas = decomposeCo tc_arity co theta_subst = liftCoSubstWith Representational (dc_univ_tyvars ++ dc_ex_tyvars) -- existentials are at role N (gammas ++ map (mkReflCo Nominal) (stripTypeArgs ex_args)) -- Cast the value arguments (which include dictionaries) new_val_args = zipWith cast_arg arg_tys val_args cast_arg arg_ty arg = mkCast arg (theta_subst arg_ty) dump_doc = vcat [ppr dc, ppr dc_univ_tyvars, ppr dc_ex_tyvars, ppr arg_tys, ppr dc_args, ppr ex_args, ppr val_args, ppr co, ppr _from_ty, ppr to_ty, ppr to_tc ] in ASSERT2( eqType _from_ty (mkTyConApp to_tc (stripTypeArgs $ takeList dc_univ_tyvars dc_args)) , dump_doc ) ASSERT2( all isTypeArg ex_args, dump_doc ) ASSERT2( equalLength val_args arg_tys, dump_doc ) Just (dc, to_tc_arg_tys, ex_args ++ new_val_args) | otherwise = Nothing stripTypeArgs :: [CoreExpr] -> [Type] stripTypeArgs args = ASSERT2( all isTypeArg args, ppr args ) [ty | Type ty <- args] -- We really do want isTypeArg here, not isTyCoArg! {- Note [Unfolding DFuns] ~~~~~~~~~~~~~~~~~~~~~~ DFuns look like df :: forall a b. (Eq a, Eq b) -> Eq (a,b) df a b d_a d_b = MkEqD (a,b) ($c1 a b d_a d_b) ($c2 a b d_a d_b) So to split it up we just need to apply the ops $c1, $c2 etc to the very same args as the dfun. It takes a little more work to compute the type arguments to the dictionary constructor. Note [DFun arity check] ~~~~~~~~~~~~~~~~~~~~~~~ Here we check that the total number of supplied arguments (inclding type args) matches what the dfun is expecting. This may be *less* than the ordinary arity of the dfun: see Note [DFun unfoldings] in CoreSyn -} exprIsLiteral_maybe :: InScopeEnv -> CoreExpr -> Maybe Literal -- Same deal as exprIsConApp_maybe, but much simpler -- Nevertheless we do need to look through unfoldings for -- Integer literals, which are vigorously hoisted to top level -- and not subsequently inlined exprIsLiteral_maybe env@(_, id_unf) e = case e of Lit l -> Just l Tick _ e' -> exprIsLiteral_maybe env e' -- dubious? Var v | Just rhs <- expandUnfolding_maybe (id_unf v) -> exprIsLiteral_maybe env rhs _ -> Nothing {- Note [exprIsLambda_maybe] ~~~~~~~~~~~~~~~~~~~~~~~~~~ exprIsLambda_maybe will, given an expression `e`, try to turn it into the form `Lam v e'` (returned as `Just (v,e')`). Besides using lambdas, it looks through casts (using the Push rule), and it unfolds function calls if the unfolding has a greater arity than arguments are present. Currently, it is used in Rules.match, and is required to make "map coerce = coerce" match. -} exprIsLambda_maybe :: InScopeEnv -> CoreExpr -> Maybe (Var, CoreExpr,[Tickish Id]) -- See Note [exprIsLambda_maybe] -- The simple case: It is a lambda already exprIsLambda_maybe _ (Lam x e) = Just (x, e, []) -- Still straightforward: Ticks that we can float out of the way exprIsLambda_maybe (in_scope_set, id_unf) (Tick t e) | tickishFloatable t , Just (x, e, ts) <- exprIsLambda_maybe (in_scope_set, id_unf) e = Just (x, e, t:ts) -- Also possible: A casted lambda. Push the coercion inside exprIsLambda_maybe (in_scope_set, id_unf) (Cast casted_e co) | Just (x, e,ts) <- exprIsLambda_maybe (in_scope_set, id_unf) casted_e -- Only do value lambdas. -- this implies that x is not in scope in gamma (makes this code simpler) , not (isTyVar x) && not (isCoVar x) , ASSERT( not $ x `elemVarSet` tyCoVarsOfCo co) True , Just (x',e') <- pushCoercionIntoLambda in_scope_set x e co , let res = Just (x',e',ts) = --pprTrace "exprIsLambda_maybe:Cast" (vcat [ppr casted_e,ppr co,ppr res)]) res -- Another attempt: See if we find a partial unfolding exprIsLambda_maybe (in_scope_set, id_unf) e | (Var f, as, ts) <- collectArgsTicks tickishFloatable e , idArity f > length (filter isValArg as) -- Make sure there is hope to get a lambda , Just rhs <- expandUnfolding_maybe (id_unf f) -- Optimize, for beta-reduction , let e' = simpleOptExprWith (mkEmptySubst in_scope_set) (rhs `mkApps` as) -- Recurse, because of possible casts , Just (x', e'', ts') <- exprIsLambda_maybe (in_scope_set, id_unf) e' , let res = Just (x', e'', ts++ts') = -- pprTrace "exprIsLambda_maybe:Unfold" (vcat [ppr e, ppr (x',e'')]) res exprIsLambda_maybe _ _e = -- pprTrace "exprIsLambda_maybe:Fail" (vcat [ppr _e]) Nothing pushCoercionIntoLambda :: InScopeSet -> Var -> CoreExpr -> Coercion -> Maybe (Var, CoreExpr) pushCoercionIntoLambda in_scope x e co -- This implements the Push rule from the paper on coercions -- Compare with simplCast in Simplify | ASSERT(not (isTyVar x) && not (isCoVar x)) True , Pair s1s2 t1t2 <- coercionKind co , Just (_s1,_s2) <- splitFunTy_maybe s1s2 , Just (t1,_t2) <- splitFunTy_maybe t1t2 = let [co1, co2] = decomposeCo 2 co -- Should we optimize the coercions here? -- Otherwise they might not match too well x' = x `setIdType` t1 in_scope' = in_scope `extendInScopeSet` x' subst = extendIdSubst (mkEmptySubst in_scope') x (mkCast (Var x') co1) in Just (x', subst_expr subst e `mkCast` co2) | otherwise = pprTrace "exprIsLambda_maybe: Unexpected lambda in case" (ppr (Lam x e)) Nothing
acowley/ghc
compiler/coreSyn/CoreSubst.hs
Haskell
bsd-3-clause
59,475
module Parser where import Ast import Text.Trifecta import Text.Trifecta.Delta
Agrosis/haxpr
src/Parser.hs
Haskell
mit
81
{-# htermination filterM :: Monad m => (a -> m Bool) -> [a] -> m [a] #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_filterM_2.hs
Haskell
mit
86
{-# LANGUAGE OverloadedStrings #-} module Web.Scotty.Blaze ( blaze , builder ) where import Network.Wai import Web.Scotty (ActionM, header) import qualified Control.Monad.State as MS import Text.Blaze.Html (Html) import Blaze.ByteString.Builder (Builder) import Text.Blaze.Html.Renderer.Utf8 (renderHtmlBuilder) -- | Render some Blaze Html -- blaze :: Html -> ActionM () blaze h = do header "Content-Type" "text/html" builder $ renderHtmlBuilder h -- | Render a generic builder -- builder :: Builder -> ActionM () builder = MS.modify . setContent setContent :: Builder -> Response -> Response setContent b (ResponseBuilder s h _) = ResponseBuilder s h b setContent b (ResponseFile s h _ _) = ResponseBuilder s h b setContent b (ResponseSource s h _) = ResponseBuilder s h b
jb55/scotty-blaze
src/Web/Scotty/Blaze.hs
Haskell
mit
837
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses, OverloadedStrings, TemplateHaskell, TypeSynonymInstances #-} module SpaceWeather.Regressor.Linear where import qualified Data.Aeson.TH as Aeson import SpaceWeather.Prediction data LinearOption = LinearOption deriving (Eq, Ord, Show, Read) Aeson.deriveJSON Aeson.defaultOptions ''LinearOption instance Predictor LinearOption where performPrediction = undefined
nushio3/UFCORIN
src/SpaceWeather/Regressor/Linear.hs
Haskell
mit
440
{-# htermination liftM2 :: Monad m => (a -> b -> c) -> (m a -> m b -> m c) #-} import Monad
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/Monad_liftM2_1.hs
Haskell
mit
92
----------------------------------------------------------------------------- -- -- Module : SGC.Object -- Copyright : -- License : MIT -- -- Maintainer : -- Stability : -- Portability : -- -- | -- {-# LANGUAGE FunctionalDependencies #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE Rank2Types #-} module SGC.Object where import PhyQ import Data.Typeable (Typeable) import GHC.Exts (Constraint) ----------------------------------------------------------------------------- class AnyObject obj where objId :: obj -> String data SomeObject = forall obj . (Typeable obj, AnyObject obj) => SomeObject obj data SomeObject' (c :: * -> Constraint) = forall obj . (Typeable obj, AnyObject obj, c obj) => SomeObject' obj fromSomeObject' :: (forall obj . (Typeable obj, AnyObject obj, c obj) => obj -> x) -> SomeObject' c -> x fromSomeObject' f (SomeObject' obj) = f obj ----------------------------------------------------------------------------- type Measure a v q = a -> Measurable q v class HasMass v a where objMass :: Measure a v Mass class HasPosition sys vec a where objPosition :: sys -> Measure a vec Position objSpeed :: sys -> Measure a vec Speed objDistance :: (HasPosition sys vec a, Ord vec, Num vec) => sys -> a -> a -> Measurable Position vec objDistance sys x y = let px = objPosition sys x py = objPosition sys y in py $- px ----------------------------------------------------------------------------- class (HasPosition sys vec a, HasMass v a) => MaterialPoint' sys vec v a | vec -> v type MaterialPoint sys vec v = SomeObject' (MaterialPoint' sys vec v) instance HasPosition sys vec (MaterialPoint sys vec v) where objPosition sys = fromSomeObject' $ objPosition sys objSpeed sys = fromSomeObject' $ objSpeed sys instance HasMass v (MaterialPoint sys vec v) where objMass = fromSomeObject' objMass ----------------------------------------------------------------------------- -- class HasPosition sys vec a where -- objPosition :: sys -> Measure a vec Position -- objSpeed :: sys -> Measure a vec Speed -----------------------------------------------------------------------------
fehu/hsgc
SGC/Object_OLD.hs
Haskell
mit
2,381
newtype DiffList a = DiffList {getDiffList :: [a] -> [a]} toDiffList :: [a] -> DiffList a toDiffList xs = DiffList (xs++) fromDiffList :: DiffList a -> [a] fromDiffList (DiffList f) = f [] instance Monoid (DiffList a) where mempty = DiffList (\xs -> [] ++ xs) (DiffList f) `mappend` (DiffList g) = DiffList (\xs -> f (g xs))
RAFIRAF/HASKELL
For a Few Monads More/difflist.hs
Haskell
mit
353
-- necessary for `ToParamSchema Core.EpochIndex` {-# OPTIONS_GHC -fno-warn-orphans #-} module Cardano.Node.API.Swagger where import Universum import Control.Lens (at, (?~)) import Data.Swagger import Servant import Servant.Swagger import Servant.Swagger.UI (SwaggerSchemaUI) import Pos.Chain.Txp (TxIn, TxOut, TxOutAux) import Pos.Chain.Update (SoftwareVersion) import Pos.Util.Swagger (swaggerSchemaUIServer) import Pos.Web (CConfirmedProposalState, serveDocImpl) import Pos.Web.Types (TlsParams) forkDocServer :: HasSwagger a => Proxy a -> SoftwareVersion -> String -> Word16 -> Maybe TlsParams -> IO () forkDocServer prxy swVersion ip port' tlsParams = serveDocImpl (pure app) ip port' tlsParams Nothing Nothing where app = serve (Proxy @("docs" :> "v1" :> SwaggerSchemaUI "index" "swagger.json")) (swaggerSchemaUIServer (documentationApi swVersion prxy)) documentationApi :: HasSwagger a => SoftwareVersion -> Proxy a -> Swagger documentationApi curSoftwareVersion prxy = toSwagger prxy & info.title .~ "Cardano Node API" & info.version .~ fromString (show curSoftwareVersion) & host ?~ "127.0.0.1:8083" & info.license ?~ ("MIT" & url ?~ URL "https://raw.githubusercontent.com/input-output-hk/cardano-sl/develop/lib/LICENSE") instance ToParamSchema TxIn where toParamSchema _ = mempty & type_ .~ SwaggerString instance ToSchema TxIn where declareNamedSchema = pure . paramSchemaToNamedSchema defaultSchemaOptions instance ToSchema TxOut where declareNamedSchema _ = pure $ NamedSchema (Just "TxOut") $ mempty & type_ .~ SwaggerObject & required .~ ["coin", "address"] & properties .~ (mempty & at "coin" ?~ (Inline $ mempty & type_ .~ SwaggerNumber ) & at "address" ?~ (Inline $ mempty & type_ .~ SwaggerString ) ) instance ToSchema TxOutAux instance ToSchema CConfirmedProposalState
input-output-hk/pos-haskell-prototype
node/src/Cardano/Node/API/Swagger.hs
Haskell
mit
2,254
{{hs_copyright}} module {{module_name}}App.Types ( Milliseconds (..) ) where newtype Milliseconds = Milliseconds Int
rcook/ptool-templates
elm-haskell/app_Types.hs
Haskell
mit
126
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-| Module : Ogma.Api.Definition Copyright : (c) Ogma Project, 2016 License : MIT Stability : experimental -} module Ogma.Api.Definition where import Data.Aeson import Data.Aeson.Types import Data.Aeson.TH import Data.Proxy import Data.Text (Text) import Data.Time import GHC.Generics import GHC.Int import Servant.API import Data.Char (toLower) data AccountNewPost = AccountNewPost { accountNewEmail :: Text , accountNewLogin :: Text } deriving (Generic) deriveJSON (defaultOptions { fieldLabelModifier = map toLower . drop 10 }) ''AccountNewPost data GetTokenPost = GetTokenPost { getTokenLogin :: Text } deriving (Generic) deriveJSON (defaultOptions { fieldLabelModifier = map toLower . drop 8 }) ''GetTokenPost data GetTokenResponse = GetTokenResponse { getTokenAccess :: Text , getTokenRefresh :: Text , getTokenExpire :: UTCTime } deriving (Generic) deriveJSON (defaultOptions { fieldLabelModifier = map toLower . drop 8 }) ''GetTokenResponse data DocumentPost = DocumentPost { postDocumentTitle :: Text , postDocumentContent :: Text } deriving (Generic) deriveJSON (defaultOptions { fieldLabelModifier = map toLower . drop 12 }) ''DocumentPost data GetDocument = GetDocument { getDocumentTitle :: Text , getDocumentContent :: Text , getDocumentModifiedOn :: UTCTime , getDocumentCreatedOn :: UTCTime , getDocumentPerm :: Text } deriving (Generic) deriveJSON (defaultOptions { fieldLabelModifier = map toLower . drop 11 }) ''GetDocument type OgmaAPI = "account" :> "new" :> ReqBody '[JSON] AccountNewPost :> PostCreated '[JSON] (Headers '[Header "resource-id" Int64] NoContent) :<|> "get_token" :> ReqBody '[JSON] GetTokenPost :> Post '[JSON] GetTokenResponse :<|> AuthProtect "ogma-identity" :> ("document" :> "new" :> ReqBody '[JSON] DocumentPost :> PostCreated '[JSON] (Headers '[Header "resource-id" Int64] NoContent) :<|> "document" :> Capture "id" Int64 :> ReqBody '[JSON] DocumentPost :> Put '[JSON] NoContent :<|> "document" :> Capture "id" Int64 :> Get '[JSON] GetDocument) ogmaAPI :: Proxy OgmaAPI ogmaAPI = Proxy
lgeorget/ogma
api/src/Ogma/Api/Definition.hs
Haskell
mit
2,891
module MHMC.Error ( --TODO: EVERYTHING ) where
killmous/MHMC
src/MHMC/Error.hs
Haskell
mit
47
module Graphics.CG.Primitives.Triangle(Triangle, makeTriangle, sortTrianglePoints) where import Data.List (sort) import Graphics.Gloss.Data.Point type Triangle = (Point, Point, Point) makeTriangle :: Point -> Point -> Point -> Triangle makeTriangle a b c = (a, b, c) sortTrianglePoints :: Triangle -> Triangle sortTrianglePoints (a, b, c) = (\[a, b, c] -> (a, b, c)) $ sort [a, b, c]
jagajaga/CG-Haskell
Graphics/CG/Primitives/Triangle.hs
Haskell
mit
425
module AlecAirport.A281511Spec (main, spec) where import Test.Hspec import AlecAirport.A281511 (a281511) main :: IO () main = hspec spec spec :: Spec spec = describe "A281511" $ it "correctly computes the first 20 elements" $ take 20 (map a281511 [1..]) `shouldBe` expectedValue where expectedValue = [1,1,2,1,2,2,3,1,3,2,4,3,1,4,4,2,5,3,3,4]
peterokagey/haskellOEIS
test/AlecAirport/A281511Spec.hs
Haskell
apache-2.0
357
{-# LANGUAGE ForeignFunctionInterface, CPP #-} module Format where import Foreign import Foreign.C import Foreign.Marshal.Alloc import qualified Data.ByteString as B import qualified Data.ByteString.Unsafe as BU import Data.Monoid import System.Posix.Files data Format = F { formatName :: String, formatEntry :: Int, formatHeaderSize :: Int, formatHeaderCons :: Int -> IO (Ptr CChar) } instance Show Format where show = formatName writeFormat fmt name dat = do hp <- formatHeaderCons fmt (B.length dat) h <- BU.unsafePackCStringLen (hp,formatHeaderSize fmt) B.writeFile name (h <> dat) stat <- getFileStatus name let (+) = unionFileModes setFileMode name (ownerExecuteMode + groupExecuteMode + otherExecuteMode + fileMode stat) #define IMPORT_FUN(fun,t) foreign import ccall #fun fun :: t #define IMPORT_FORMAT(fmt) IMPORT_FUN(fmt##_entry,Int) ; IMPORT_FUN(fmt##_headerSize,Int) ; IMPORT_FUN(fmt##_headerCons,Int -> IO (Ptr CChar)) ; fmt = F #fmt fmt##_entry fmt##_headerSize fmt##_headerCons raw entry = F ("raw:"++show entry) entry 0 (const $ return nullPtr) IMPORT_FORMAT(elf64) ; IMPORT_FORMAT(elf32) ; IMPORT_FORMAT(exe) formats = [elf64,elf32,exe] #if x86_64_HOST_ARCH defaultFormat = elf64 #else defaultFormat = raw 0 #endif
lih/Alpha
src/Format.hs
Haskell
bsd-2-clause
1,277
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QDial_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:25 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QDial_h ( QsetNotchesVisible_h(..) ,QsetWrapping_h(..) ) where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Enums.Gui.QAbstractSlider import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QDial ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QDial_unSetUserMethod" qtc_QDial_unSetUserMethod :: Ptr (TQDial a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QDialSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QDial ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QDialSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QDial ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QDialSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDial_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QDial ()) (QDial x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDial setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDial_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDial_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDial x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setUserMethod" qtc_QDial_setUserMethod :: Ptr (TQDial a) -> CInt -> Ptr (Ptr (TQDial x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QDial :: (Ptr (TQDial x0) -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QDial_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDialSc a) (QDial x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDial setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDial_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDial_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDial x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QDial ()) (QDial x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDial setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDial_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDial_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setUserMethodVariant" qtc_QDial_setUserMethodVariant :: Ptr (TQDial a) -> CInt -> Ptr (Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QDial :: (Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QDial_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDialSc a) (QDial x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDial setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDial_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDial_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QDial ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDial_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QDial_unSetHandler" qtc_QDial_unSetHandler :: Ptr (TQDial a) -> CWString -> IO (CBool) instance QunSetHandler (QDialSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDial_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QDial ()) (QDial x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler1" qtc_QDial_setHandler1 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial1 :: (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDial1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QDial ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_event cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_event" qtc_QDial_event :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QDialSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_event cobj_x0 cobj_x1 instance QsetHandler (QDial ()) (QDial x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qDialFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler2" qtc_QDial_setHandler2 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial2 :: (Ptr (TQDial x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQDial x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QDial2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qDialFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqminimumSizeHint_h (QDial ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint cobj_x0 foreign import ccall "qtc_QDial_minimumSizeHint" qtc_QDial_minimumSizeHint :: Ptr (TQDial a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QDialSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QDial ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDial_minimumSizeHint_qth" qtc_QDial_minimumSizeHint_qth :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QDialSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QDial ()) (QDial x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler3" qtc_QDial_setHandler3 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial3 :: (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDial3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QmouseMoveEvent_h (QDial ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mouseMoveEvent" qtc_QDial_mouseMoveEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QDialSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QDial ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mousePressEvent" qtc_QDial_mousePressEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QDialSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QDial ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mouseReleaseEvent" qtc_QDial_mouseReleaseEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QDialSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseReleaseEvent cobj_x0 cobj_x1 instance QpaintEvent_h (QDial ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_paintEvent" qtc_QDial_paintEvent :: Ptr (TQDial a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QDialSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_paintEvent cobj_x0 cobj_x1 instance QresizeEvent_h (QDial ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_resizeEvent" qtc_QDial_resizeEvent :: Ptr (TQDial a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QDialSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_resizeEvent cobj_x0 cobj_x1 instance QsetHandler (QDial ()) (QDial x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler4" qtc_QDial_setHandler4 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial4 :: (Ptr (TQDial x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDial4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () class QsetNotchesVisible_h x0 x1 where setNotchesVisible_h :: x0 -> x1 -> IO () instance QsetNotchesVisible_h (QDial ()) ((Bool)) where setNotchesVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setNotchesVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_setNotchesVisible" qtc_QDial_setNotchesVisible :: Ptr (TQDial a) -> CBool -> IO () instance QsetNotchesVisible_h (QDialSc a) ((Bool)) where setNotchesVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setNotchesVisible cobj_x0 (toCBool x1) class QsetWrapping_h x0 x1 where setWrapping_h :: x0 -> x1 -> IO () instance QsetWrapping_h (QDial ()) ((Bool)) where setWrapping_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setWrapping cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_setWrapping" qtc_QDial_setWrapping :: Ptr (TQDial a) -> CBool -> IO () instance QsetWrapping_h (QDialSc a) ((Bool)) where setWrapping_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setWrapping cobj_x0 (toCBool x1) instance QqsizeHint_h (QDial ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint cobj_x0 foreign import ccall "qtc_QDial_sizeHint" qtc_QDial_sizeHint :: Ptr (TQDial a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QDialSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint cobj_x0 instance QsizeHint_h (QDial ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDial_sizeHint_qth" qtc_QDial_sizeHint_qth :: Ptr (TQDial a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QDialSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QsetHandler (QDial ()) (QDial x0 -> SliderChange -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 if (objectIsNull x0obj) then return () else _handler x0obj x1enum setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler5" qtc_QDial_setHandler5 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CLong -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial5 :: (Ptr (TQDial x0) -> CLong -> IO ()) -> IO (FunPtr (Ptr (TQDial x0) -> CLong -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDial5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> SliderChange -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 if (objectIsNull x0obj) then return () else _handler x0obj x1enum setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsliderChange_h (QDial ()) ((SliderChange)) where sliderChange_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sliderChange cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDial_sliderChange" qtc_QDial_sliderChange :: Ptr (TQDial a) -> CLong -> IO () instance QsliderChange_h (QDialSc a) ((SliderChange)) where sliderChange_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_sliderChange cobj_x0 (toCLong $ qEnum_toInt x1) instance QchangeEvent_h (QDial ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_changeEvent" qtc_QDial_changeEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QDialSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_changeEvent cobj_x0 cobj_x1 instance QkeyPressEvent_h (QDial ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_keyPressEvent" qtc_QDial_keyPressEvent :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QDialSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyPressEvent cobj_x0 cobj_x1 instance QwheelEvent_h (QDial ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_wheelEvent" qtc_QDial_wheelEvent :: Ptr (TQDial a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QDialSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_wheelEvent cobj_x0 cobj_x1 instance QactionEvent_h (QDial ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_actionEvent" qtc_QDial_actionEvent :: Ptr (TQDial a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QDialSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_actionEvent cobj_x0 cobj_x1 instance QcloseEvent_h (QDial ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_closeEvent" qtc_QDial_closeEvent :: Ptr (TQDial a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QDialSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_closeEvent cobj_x0 cobj_x1 instance QcontextMenuEvent_h (QDial ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_contextMenuEvent" qtc_QDial_contextMenuEvent :: Ptr (TQDial a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QDialSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QDial ()) (QDial x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDialFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler6" qtc_QDial_setHandler6 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial6 :: (Ptr (TQDial x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQDial x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDial6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDialFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QdevType_h (QDial ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_devType cobj_x0 foreign import ccall "qtc_QDial_devType" qtc_QDial_devType :: Ptr (TQDial a) -> IO CInt instance QdevType_h (QDialSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_devType cobj_x0 instance QdragEnterEvent_h (QDial ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dragEnterEvent" qtc_QDial_dragEnterEvent :: Ptr (TQDial a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QDialSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QDial ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dragLeaveEvent" qtc_QDial_dragLeaveEvent :: Ptr (TQDial a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QDialSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QDial ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dragMoveEvent" qtc_QDial_dragMoveEvent :: Ptr (TQDial a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QDialSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QDial ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_dropEvent" qtc_QDial_dropEvent :: Ptr (TQDial a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QDialSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QDial ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_enterEvent" qtc_QDial_enterEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QDialSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_enterEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QDial ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_focusInEvent" qtc_QDial_focusInEvent :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QDialSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QDial ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_focusOutEvent" qtc_QDial_focusOutEvent :: Ptr (TQDial a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QDialSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_focusOutEvent cobj_x0 cobj_x1 instance QsetHandler (QDial ()) (QDial x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler7" qtc_QDial_setHandler7 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial7 :: (Ptr (TQDial x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQDial x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDial7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QDial ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QDial_heightForWidth" qtc_QDial_heightForWidth :: Ptr (TQDial a) -> CInt -> IO CInt instance QheightForWidth_h (QDialSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_heightForWidth cobj_x0 (toCInt x1) instance QhideEvent_h (QDial ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_hideEvent" qtc_QDial_hideEvent :: Ptr (TQDial a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QDialSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QDial ()) (QDial x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler8" qtc_QDial_setHandler8 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial8 :: (Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QDial8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDialFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QinputMethodQuery_h (QDial ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDial_inputMethodQuery" qtc_QDial_inputMethodQuery :: Ptr (TQDial a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QDialSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyReleaseEvent_h (QDial ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_keyReleaseEvent" qtc_QDial_keyReleaseEvent :: Ptr (TQDial a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QDialSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_keyReleaseEvent cobj_x0 cobj_x1 instance QleaveEvent_h (QDial ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_leaveEvent" qtc_QDial_leaveEvent :: Ptr (TQDial a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QDialSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_leaveEvent cobj_x0 cobj_x1 instance QmouseDoubleClickEvent_h (QDial ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_mouseDoubleClickEvent" qtc_QDial_mouseDoubleClickEvent :: Ptr (TQDial a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QDialSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QDial ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_moveEvent" qtc_QDial_moveEvent :: Ptr (TQDial a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QDialSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QDial ()) (QDial x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qDialFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler9" qtc_QDial_setHandler9 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial9 :: (Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QDial9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qDialFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QpaintEngine_h (QDial ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_paintEngine cobj_x0 foreign import ccall "qtc_QDial_paintEngine" qtc_QDial_paintEngine :: Ptr (TQDial a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QDialSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_paintEngine cobj_x0 instance QsetVisible_h (QDial ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QDial_setVisible" qtc_QDial_setVisible :: Ptr (TQDial a) -> CBool -> IO () instance QsetVisible_h (QDialSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDial_setVisible cobj_x0 (toCBool x1) instance QshowEvent_h (QDial ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_showEvent" qtc_QDial_showEvent :: Ptr (TQDial a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QDialSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_showEvent cobj_x0 cobj_x1 instance QtabletEvent_h (QDial ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDial_tabletEvent" qtc_QDial_tabletEvent :: Ptr (TQDial a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QDialSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDial_tabletEvent cobj_x0 cobj_x1 instance QsetHandler (QDial ()) (QDial x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDialFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDial_setHandler10" qtc_QDial_setHandler10 :: Ptr (TQDial a) -> CWString -> Ptr (Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDial10 :: (Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDial10_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialSc a) (QDial x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDial10 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDial10_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDial_setHandler10 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDial x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDialFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QDial ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDial_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDial_eventFilter" qtc_QDial_eventFilter :: Ptr (TQDial a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QDialSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDial_eventFilter cobj_x0 cobj_x1 cobj_x2
keera-studios/hsQt
Qtc/Gui/QDial_h.hs
Haskell
bsd-2-clause
58,905
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} -- Create a source distribution tarball module Stack.SDist ( getSDistTarball ) where import qualified Codec.Archive.Tar as Tar import qualified Codec.Archive.Tar.Entry as Tar import qualified Codec.Compression.GZip as GZip import Control.Applicative import Control.Concurrent.Execute (ActionContext(..)) import Control.Monad (when, void) import Control.Monad.Catch (MonadCatch, MonadMask) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control (liftBaseWith) import Control.Monad.Trans.Resource import qualified Data.ByteString.Lazy as L import Data.Either (partitionEithers) import Data.List import qualified Data.Map.Strict as Map import Data.Monoid ((<>)) import qualified Data.Set as Set import qualified Data.Text as T import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Prelude -- Fix redundant import warnings import Stack.Build (mkBaseConfigOpts) import Stack.Build.Execute import Stack.Build.Source (loadSourceMap, localFlags) import Stack.Build.Target import Stack.Constants import Stack.Package import Stack.Types import Stack.Types.Internal import qualified System.FilePath as FP import System.IO.Temp (withSystemTempDirectory) type M env m = (MonadIO m,MonadReader env m,HasHttpManager env,HasBuildConfig env,MonadLogger m,MonadBaseControl IO m,MonadCatch m,MonadMask m,HasLogLevel env,HasEnvConfig env,HasTerminal env) -- | Given the path to a local package, creates its source -- distribution tarball. -- -- While this yields a 'FilePath', the name of the tarball, this -- tarball is not written to the disk and instead yielded as a lazy -- bytestring. getSDistTarball :: M env m => Path Abs Dir -> m (FilePath, L.ByteString) getSDistTarball pkgDir = do let pkgFp = toFilePath pkgDir lp <- readLocalPackage pkgDir $logInfo $ "Getting file list for " <> T.pack pkgFp fileList <- getSDistFileList lp $logInfo $ "Building sdist tarball for " <> T.pack pkgFp files <- normalizeTarballPaths (lines fileList) liftIO $ do -- NOTE: Could make this use lazy I/O to only read files as needed -- for upload (both GZip.compress and Tar.write are lazy). -- However, it seems less error prone and more predictable to read -- everything in at once, so that's what we're doing for now: let packWith f isDir fp = f (pkgFp FP.</> fp) (either error id (Tar.toTarPath isDir (pkgId FP.</> fp))) tarName = pkgId FP.<.> "tar.gz" pkgId = packageIdentifierString (packageIdentifier (lpPackage lp)) dirEntries <- mapM (packWith Tar.packDirectoryEntry True) (dirsFromFiles files) fileEntries <- mapM (packWith Tar.packFileEntry False) files return (tarName, GZip.compress (Tar.write (dirEntries ++ fileEntries))) -- Read in a 'LocalPackage' config. This makes some default decisions -- about 'LocalPackage' fields that might not be appropriate for other -- usecases. -- -- TODO: Dedupe with similar code in "Stack.Build.Source". readLocalPackage :: M env m => Path Abs Dir -> m LocalPackage readLocalPackage pkgDir = do econfig <- asks getEnvConfig bconfig <- asks getBuildConfig cabalfp <- getCabalFileName pkgDir name <- parsePackageNameFromFilePath cabalfp let config = PackageConfig { packageConfigEnableTests = False , packageConfigEnableBenchmarks = False , packageConfigFlags = localFlags Map.empty bconfig name , packageConfigCompilerVersion = envConfigCompilerVersion econfig , packageConfigPlatform = configPlatform $ getConfig bconfig } package <- readPackage config cabalfp return LocalPackage { lpPackage = package , lpExeComponents = Nothing -- HACK: makes it so that sdist output goes to a log instead of a file. , lpDir = pkgDir , lpCabalFile = cabalfp -- NOTE: these aren't the 'correct values, but aren't used in -- the usage of this function in this module. , lpTestDeps = Map.empty , lpBenchDeps = Map.empty , lpTestBench = Nothing , lpDirtyFiles = True , lpNewBuildCache = Map.empty , lpFiles = Set.empty , lpComponents = Set.empty } getSDistFileList :: M env m => LocalPackage -> m String getSDistFileList lp = withSystemTempDirectory (stackProgName <> "-sdist") $ \tmpdir -> do menv <- getMinimalEnvOverride let bopts = defaultBuildOpts baseConfigOpts <- mkBaseConfigOpts bopts (_, _mbp, locals, _extraToBuild, sourceMap) <- loadSourceMap NeedTargets bopts runInBase <- liftBaseWith $ \run -> return (void . run) withExecuteEnv menv bopts baseConfigOpts locals sourceMap $ \ee -> do withSingleContext runInBase ac ee task Nothing (Just "sdist") $ \_package _cabalfp _pkgDir cabal _announce _console _mlogFile -> do let outFile = tmpdir FP.</> "source-files-list" cabal False ["sdist", "--list-sources", outFile] liftIO (readFile outFile) where package = lpPackage lp ac = ActionContext Set.empty task = Task { taskProvides = PackageIdentifier (packageName package) (packageVersion package) , taskType = TTLocal lp , taskConfigOpts = TaskConfigOpts { tcoMissing = Set.empty , tcoOpts = \_ -> ConfigureOpts [] [] } , taskPresent = Map.empty } normalizeTarballPaths :: M env m => [FilePath] -> m [FilePath] normalizeTarballPaths fps = do --TODO: consider whether erroring out is better - otherwise the --user might upload an incomplete tar? when (not (null outsideDir)) $ $logWarn $ T.concat [ "Warning: These files are outside of the package directory, and will be omitted from the tarball: " , T.pack (show outsideDir)] return files where (outsideDir, files) = partitionEithers (map pathToEither fps) pathToEither fp = maybe (Left fp) Right (normalizePath fp) normalizePath :: FilePath -> (Maybe FilePath) normalizePath = fmap FP.joinPath . go . FP.splitDirectories . FP.normalise where go [] = Just [] go ("..":_) = Nothing go (_:"..":xs) = go xs go (x:xs) = (x :) <$> go xs dirsFromFiles :: [FilePath] -> [FilePath] dirsFromFiles dirs = Set.toAscList (Set.delete "." results) where results = foldl' (\s -> go s . FP.takeDirectory) Set.empty dirs go s x | Set.member x s = s | otherwise = go (Set.insert x s) (FP.takeDirectory x)
bixuanzju/stack
src/Stack/SDist.hs
Haskell
bsd-3-clause
7,020
{-# LANGUAGE DeriveDataTypeable, CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Xmobar -- Copyright : (c) Andrea Rossato -- License : BSD-style (see LICENSE) -- -- Maintainer : Jose A. Ortega Ruiz <jao@gnu.org> -- Stability : unstable -- Portability : unportable -- -- A status bar for the Xmonad Window Manager -- ----------------------------------------------------------------------------- module Xmobar ( -- * Main Stuff -- $main X , XConf (..), runX , startLoop -- * Program Execution -- $command , startCommand -- * Window Management -- $window , createWin, updateWin -- * Printing -- $print , drawInWin, printStrings ) where import Prelude hiding (catch) import Graphics.X11.Xlib hiding (textExtents, textWidth) import Graphics.X11.Xlib.Extras import Graphics.X11.Xinerama import Graphics.X11.Xrandr import Control.Arrow ((&&&)) import Control.Monad.Reader import Control.Concurrent import Control.Concurrent.STM import Control.Exception (catch, SomeException(..)) import Data.Bits import Config import Parsers import Commands import Runnable import Signal import Window import XUtil #ifdef DBUS import IPC.DBus #endif -- $main -- -- The Xmobar data type and basic loops and functions. -- | The X type is a ReaderT type X = ReaderT XConf IO -- | The ReaderT inner component data XConf = XConf { display :: Display , rect :: Rectangle , window :: Window , fontS :: XFont , config :: Config } -- | Runs the ReaderT runX :: XConf -> X () -> IO () runX xc f = runReaderT f xc -- | Starts the main event loop and threads startLoop :: XConf -> TMVar SignalType -> [[(Maybe ThreadId, TVar String)]] -> IO () startLoop xcfg@(XConf _ _ w _ _) sig vs = do tv <- atomically $ newTVar [] _ <- forkIO (checker tv [] vs sig `catch` \(SomeException _) -> void (putStrLn "Thread checker failed")) #ifdef THREADED_RUNTIME _ <- forkOS (eventer sig `catch` #else _ <- forkIO (eventer sig `catch` #endif \(SomeException _) -> void (putStrLn "Thread eventer failed")) #ifdef DBUS runIPC sig #endif eventLoop tv xcfg sig where -- Reacts on events from X eventer signal = allocaXEvent $ \e -> do dpy <- openDisplay "" xrrSelectInput dpy (defaultRootWindow dpy) rrScreenChangeNotifyMask selectInput dpy w (exposureMask .|. structureNotifyMask) forever $ do #ifdef THREADED_RUNTIME nextEvent dpy e #else nextEvent' dpy e #endif ev <- getEvent e case ev of -- ConfigureEvent {} -> (atomically $ putTMVar signal Reposition) ExposeEvent {} -> atomically $ putTMVar signal Wakeup RRScreenChangeNotifyEvent {} -> atomically $ putTMVar signal Reposition _ -> return () -- | Send signal to eventLoop every time a var is updated checker :: TVar [String] -> [String] -> [[(Maybe ThreadId, TVar String)]] -> TMVar SignalType -> IO () checker tvar ov vs signal = do nval <- atomically $ do nv <- mapM concatV vs guard (nv /= ov) writeTVar tvar nv return nv atomically $ putTMVar signal Wakeup checker tvar nval vs signal where concatV = fmap concat . mapM (readTVar . snd) -- | Continuously wait for a signal from a thread or a interrupt handler eventLoop :: TVar [String] -> XConf -> TMVar SignalType -> IO () eventLoop tv xc@(XConf d r w fs cfg) signal = do typ <- atomically $ takeTMVar signal case typ of Wakeup -> do runX xc (updateWin tv) eventLoop tv xc signal Reposition -> reposWindow cfg ChangeScreen -> do ncfg <- updateConfigPosition cfg reposWindow ncfg Hide t -> hide (t*100*1000) Reveal t -> reveal (t*100*1000) Toggle t -> toggle t TogglePersistent -> eventLoop tv xc { config = cfg { persistent = not $ persistent cfg } } signal where isPersistent = not $ persistent cfg hide t | t == 0 = when isPersistent (hideWindow d w) >> eventLoop tv xc signal | otherwise = do void $ forkIO $ threadDelay t >> atomically (putTMVar signal $ Hide 0) eventLoop tv xc signal reveal t | t == 0 = do when isPersistent (showWindow r cfg d w) eventLoop tv xc signal | otherwise = do void $ forkIO $ threadDelay t >> atomically (putTMVar signal $ Reveal 0) eventLoop tv xc signal toggle t = do ismapped <- isMapped d w atomically (putTMVar signal $ if ismapped then Hide t else Reveal t) eventLoop tv xc signal reposWindow rcfg = do r' <- repositionWin d w fs rcfg eventLoop tv (XConf d r' w fs rcfg) signal updateConfigPosition ocfg = case position ocfg of OnScreen n o -> do srs <- getScreenInfo d if n == length srs then return (ocfg {position = OnScreen 1 o}) else return (ocfg {position = OnScreen (n+1) o}) o -> return (ocfg {position = OnScreen 1 o}) -- $command -- | Runs a command as an independent thread and returns its thread id -- and the TVar the command will be writing to. startCommand :: TMVar SignalType -> (Runnable,String,String) -> IO (Maybe ThreadId, TVar String) startCommand sig (com,s,ss) | alias com == "" = do var <- atomically $ newTVar is atomically $ writeTVar var (s ++ ss) return (Nothing,var) | otherwise = do var <- atomically $ newTVar is let cb str = atomically $ writeTVar var (s ++ str ++ ss) h <- forkIO $ start com cb _ <- forkIO $ trigger com $ maybe (return ()) (atomically . putTMVar sig) return (Just h,var) where is = s ++ "Updating..." ++ ss updateWin :: TVar [String] -> X () updateWin v = do xc <- ask s <- io $ atomically $ readTVar v let (conf,rec) = (config &&& rect) xc l:c:r:_ = s ++ repeat "" ps <- io $ mapM (parseString conf) [l, c, r] drawInWin rec ps -- $print -- | Draws in and updates the window drawInWin :: Rectangle -> [[(String, String)]] -> X () drawInWin (Rectangle _ _ wid ht) ~[left,center,right] = do r <- ask let (c,d ) = (config &&& display) r (w,fs) = (window &&& fontS ) r strLn = io . mapM (\(s,cl) -> textWidth d fs s >>= \tw -> return (s,cl,fi tw)) withColors d [bgColor c, borderColor c] $ \[bgcolor, bdcolor] -> do gc <- io $ createGC d w -- create a pixmap to write to and fill it with a rectangle p <- io $ createPixmap d w wid ht (defaultDepthOfScreen (defaultScreenOfDisplay d)) -- the fgcolor of the rectangle will be the bgcolor of the window io $ setForeground d gc bgcolor io $ fillRectangle d p gc 0 0 wid ht -- write to the pixmap the new string printStrings p gc fs 1 L =<< strLn left printStrings p gc fs 1 R =<< strLn right printStrings p gc fs 1 C =<< strLn center -- draw 1 pixel border if requested io $ drawBorder (border c) d p gc bdcolor wid ht -- copy the pixmap with the new string to the window io $ copyArea d p w gc 0 0 wid ht 0 0 -- free up everything (we do not want to leak memory!) io $ freeGC d gc io $ freePixmap d p -- resync io $ sync d True -- | An easy way to print the stuff we need to print printStrings :: Drawable -> GC -> XFont -> Position -> Align -> [(String, String, Position)] -> X () printStrings _ _ _ _ _ [] = return () printStrings dr gc fontst offs a sl@((s,c,l):xs) = do r <- ask (as,ds) <- io $ textExtents fontst s let (conf,d) = (config &&& display) r Rectangle _ _ wid ht = rect r totSLen = foldr (\(_,_,len) -> (+) len) 0 sl valign = (fi ht `div` 2) + (fi (as + ds) `div` 3) remWidth = fi wid - fi totSLen offset = case a of C -> (remWidth + offs) `div` 2 R -> remWidth L -> offs (fc,bc) = case break (==',') c of (f,',':b) -> (f, b ) (f, _) -> (f, bgColor conf) withColors d [bc] $ \[bc'] -> do io $ setForeground d gc bc' io $ fillRectangle d dr gc offset 0 (fi l) ht io $ printString d dr fontst gc fc bc offset valign s printStrings dr gc fontst (offs + l) a xs
raboof/xmobar
src/Xmobar.hs
Haskell
bsd-3-clause
9,113
{-# language CPP #-} -- | = Name -- -- VK_EXT_hdr_metadata - device extension -- -- == VK_EXT_hdr_metadata -- -- [__Name String__] -- @VK_EXT_hdr_metadata@ -- -- [__Extension Type__] -- Device extension -- -- [__Registered Extension Number__] -- 106 -- -- [__Revision__] -- 2 -- -- [__Extension and Version Dependencies__] -- -- - Requires Vulkan 1.0 -- -- - Requires @VK_KHR_swapchain@ -- -- [__Contact__] -- -- - Courtney Goeltzenleuchter -- <https://github.com/KhronosGroup/Vulkan-Docs/issues/new?body=[VK_EXT_hdr_metadata] @courtney-g%0A<<Here describe the issue or question you have about the VK_EXT_hdr_metadata extension>> > -- -- == Other Extension Metadata -- -- [__Last Modified Date__] -- 2018-12-19 -- -- [__IP Status__] -- No known IP claims. -- -- [__Contributors__] -- -- - Courtney Goeltzenleuchter, Google -- -- == Description -- -- This extension defines two new structures and a function to assign SMPTE -- (the Society of Motion Picture and Television Engineers) 2086 metadata -- and CTA (Consumer Technology Association) 861.3 metadata to a swapchain. -- The metadata includes the color primaries, white point, and luminance -- range of the reference monitor, which all together define the color -- volume containing all the possible colors the reference monitor can -- produce. The reference monitor is the display where creative work is -- done and creative intent is established. To preserve such creative -- intent as much as possible and achieve consistent color reproduction on -- different viewing displays, it is useful for the display pipeline to -- know the color volume of the original reference monitor where content -- was created or tuned. This avoids performing unnecessary mapping of -- colors that are not displayable on the original reference monitor. The -- metadata also includes the @maxContentLightLevel@ and -- @maxFrameAverageLightLevel@ as defined by CTA 861.3. -- -- While the general purpose of the metadata is to assist in the -- transformation between different color volumes of different displays and -- help achieve better color reproduction, it is not in the scope of this -- extension to define how exactly the metadata should be used in such a -- process. It is up to the implementation to determine how to make use of -- the metadata. -- -- == New Commands -- -- - 'setHdrMetadataEXT' -- -- == New Structures -- -- - 'HdrMetadataEXT' -- -- - 'XYColorEXT' -- -- == New Enum Constants -- -- - 'EXT_HDR_METADATA_EXTENSION_NAME' -- -- - 'EXT_HDR_METADATA_SPEC_VERSION' -- -- - Extending 'Vulkan.Core10.Enums.StructureType.StructureType': -- -- - 'Vulkan.Core10.Enums.StructureType.STRUCTURE_TYPE_HDR_METADATA_EXT' -- -- == Issues -- -- 1) Do we need a query function? -- -- __PROPOSED__: No, Vulkan does not provide queries for state that the -- application can track on its own. -- -- 2) Should we specify default if not specified by the application? -- -- __PROPOSED__: No, that leaves the default up to the display. -- -- == Version History -- -- - Revision 1, 2016-12-27 (Courtney Goeltzenleuchter) -- -- - Initial version -- -- - Revision 2, 2018-12-19 (Courtney Goeltzenleuchter) -- -- - Correct implicit validity for VkHdrMetadataEXT structure -- -- == See Also -- -- 'HdrMetadataEXT', 'XYColorEXT', 'setHdrMetadataEXT' -- -- == Document Notes -- -- For more information, see the -- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#VK_EXT_hdr_metadata Vulkan Specification> -- -- This page is a generated document. Fixes and changes should be made to -- the generator scripts, not directly. module Vulkan.Extensions.VK_EXT_hdr_metadata ( setHdrMetadataEXT , XYColorEXT(..) , HdrMetadataEXT(..) , EXT_HDR_METADATA_SPEC_VERSION , pattern EXT_HDR_METADATA_SPEC_VERSION , EXT_HDR_METADATA_EXTENSION_NAME , pattern EXT_HDR_METADATA_EXTENSION_NAME , SwapchainKHR(..) ) where import Vulkan.Internal.Utils (traceAroundEvent) import Control.Monad (unless) import Control.Monad.IO.Class (liftIO) import Foreign.Marshal.Alloc (allocaBytes) import GHC.IO (throwIO) import GHC.Ptr (nullFunPtr) import Foreign.Ptr (nullPtr) import Foreign.Ptr (plusPtr) import Data.Coerce (coerce) import Control.Monad.Trans.Class (lift) import Control.Monad.Trans.Cont (evalContT) import qualified Data.Vector (imapM_) import qualified Data.Vector (length) import Vulkan.CStruct (FromCStruct) import Vulkan.CStruct (FromCStruct(..)) import Vulkan.CStruct (ToCStruct) import Vulkan.CStruct (ToCStruct(..)) import Vulkan.Zero (Zero(..)) import Control.Monad.IO.Class (MonadIO) import Data.String (IsString) import Data.Typeable (Typeable) import Foreign.C.Types (CFloat) import Foreign.C.Types (CFloat(..)) import Foreign.C.Types (CFloat(CFloat)) import Foreign.Storable (Storable) import Foreign.Storable (Storable(peek)) import Foreign.Storable (Storable(poke)) import qualified Foreign.Storable (Storable(..)) import GHC.Generics (Generic) import GHC.IO.Exception (IOErrorType(..)) import GHC.IO.Exception (IOException(..)) import Foreign.Ptr (FunPtr) import Foreign.Ptr (Ptr) import Data.Word (Word32) import Data.Kind (Type) import Control.Monad.Trans.Cont (ContT(..)) import Data.Vector (Vector) import Vulkan.NamedType ((:::)) import Vulkan.Core10.Handles (Device) import Vulkan.Core10.Handles (Device(..)) import Vulkan.Core10.Handles (Device(Device)) import Vulkan.Dynamic (DeviceCmds(pVkSetHdrMetadataEXT)) import Vulkan.Core10.Handles (Device_T) import Vulkan.Core10.Enums.StructureType (StructureType) import Vulkan.Extensions.Handles (SwapchainKHR) import Vulkan.Extensions.Handles (SwapchainKHR(..)) import Vulkan.Core10.Enums.StructureType (StructureType(STRUCTURE_TYPE_HDR_METADATA_EXT)) import Vulkan.Extensions.Handles (SwapchainKHR(..)) foreign import ccall #if !defined(SAFE_FOREIGN_CALLS) unsafe #endif "dynamic" mkVkSetHdrMetadataEXT :: FunPtr (Ptr Device_T -> Word32 -> Ptr SwapchainKHR -> Ptr HdrMetadataEXT -> IO ()) -> Ptr Device_T -> Word32 -> Ptr SwapchainKHR -> Ptr HdrMetadataEXT -> IO () -- | vkSetHdrMetadataEXT - Set Hdr metadata -- -- = Description -- -- The metadata will be applied to the specified -- 'Vulkan.Extensions.Handles.SwapchainKHR' objects at the next -- 'Vulkan.Extensions.VK_KHR_swapchain.queuePresentKHR' call using that -- 'Vulkan.Extensions.Handles.SwapchainKHR' object. The metadata will -- persist until a subsequent 'setHdrMetadataEXT' changes it. -- -- == Valid Usage (Implicit) -- -- - #VUID-vkSetHdrMetadataEXT-device-parameter# @device@ /must/ be a -- valid 'Vulkan.Core10.Handles.Device' handle -- -- - #VUID-vkSetHdrMetadataEXT-pSwapchains-parameter# @pSwapchains@ -- /must/ be a valid pointer to an array of @swapchainCount@ valid -- 'Vulkan.Extensions.Handles.SwapchainKHR' handles -- -- - #VUID-vkSetHdrMetadataEXT-pMetadata-parameter# @pMetadata@ /must/ be -- a valid pointer to an array of @swapchainCount@ valid -- 'HdrMetadataEXT' structures -- -- - #VUID-vkSetHdrMetadataEXT-swapchainCount-arraylength# -- @swapchainCount@ /must/ be greater than @0@ -- -- - #VUID-vkSetHdrMetadataEXT-commonparent# Both of @device@, and the -- elements of @pSwapchains@ /must/ have been created, allocated, or -- retrieved from the same 'Vulkan.Core10.Handles.Instance' -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_hdr_metadata VK_EXT_hdr_metadata>, -- 'Vulkan.Core10.Handles.Device', 'HdrMetadataEXT', -- 'Vulkan.Extensions.Handles.SwapchainKHR' setHdrMetadataEXT :: forall io . (MonadIO io) => -- | @device@ is the logical device where the swapchain(s) were created. Device -> -- | @pSwapchains@ is a pointer to an array of @swapchainCount@ -- 'Vulkan.Extensions.Handles.SwapchainKHR' handles. ("swapchains" ::: Vector SwapchainKHR) -> -- | @pMetadata@ is a pointer to an array of @swapchainCount@ -- 'HdrMetadataEXT' structures. ("metadata" ::: Vector HdrMetadataEXT) -> io () setHdrMetadataEXT device swapchains metadata = liftIO . evalContT $ do let vkSetHdrMetadataEXTPtr = pVkSetHdrMetadataEXT (case device of Device{deviceCmds} -> deviceCmds) lift $ unless (vkSetHdrMetadataEXTPtr /= nullFunPtr) $ throwIO $ IOError Nothing InvalidArgument "" "The function pointer for vkSetHdrMetadataEXT is null" Nothing Nothing let vkSetHdrMetadataEXT' = mkVkSetHdrMetadataEXT vkSetHdrMetadataEXTPtr let pSwapchainsLength = Data.Vector.length $ (swapchains) lift $ unless ((Data.Vector.length $ (metadata)) == pSwapchainsLength) $ throwIO $ IOError Nothing InvalidArgument "" "pMetadata and pSwapchains must have the same length" Nothing Nothing pPSwapchains <- ContT $ allocaBytes @SwapchainKHR ((Data.Vector.length (swapchains)) * 8) lift $ Data.Vector.imapM_ (\i e -> poke (pPSwapchains `plusPtr` (8 * (i)) :: Ptr SwapchainKHR) (e)) (swapchains) pPMetadata <- ContT $ allocaBytes @HdrMetadataEXT ((Data.Vector.length (metadata)) * 64) lift $ Data.Vector.imapM_ (\i e -> poke (pPMetadata `plusPtr` (64 * (i)) :: Ptr HdrMetadataEXT) (e)) (metadata) lift $ traceAroundEvent "vkSetHdrMetadataEXT" (vkSetHdrMetadataEXT' (deviceHandle (device)) ((fromIntegral pSwapchainsLength :: Word32)) (pPSwapchains) (pPMetadata)) pure $ () -- | VkXYColorEXT - Specify X,Y chromaticity coordinates -- -- = Description -- -- Chromaticity coordinates are as specified in CIE 15:2004 “Calculation of -- chromaticity coordinates” (Section 7.3) and are limited to between 0 and -- 1 for real colors for the reference monitor. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_hdr_metadata VK_EXT_hdr_metadata>, -- 'HdrMetadataEXT' data XYColorEXT = XYColorEXT { -- | @x@ is the x chromaticity coordinate. x :: Float , -- | @y@ is the y chromaticity coordinate. y :: Float } deriving (Typeable, Eq) #if defined(GENERIC_INSTANCES) deriving instance Generic (XYColorEXT) #endif deriving instance Show XYColorEXT instance ToCStruct XYColorEXT where withCStruct x f = allocaBytes 8 $ \p -> pokeCStruct p x (f p) pokeCStruct p XYColorEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (x)) poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (y)) f cStructSize = 8 cStructAlignment = 4 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr CFloat)) (CFloat (zero)) poke ((p `plusPtr` 4 :: Ptr CFloat)) (CFloat (zero)) f instance FromCStruct XYColorEXT where peekCStruct p = do x <- peek @CFloat ((p `plusPtr` 0 :: Ptr CFloat)) y <- peek @CFloat ((p `plusPtr` 4 :: Ptr CFloat)) pure $ XYColorEXT (coerce @CFloat @Float x) (coerce @CFloat @Float y) instance Storable XYColorEXT where sizeOf ~_ = 8 alignment ~_ = 4 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero XYColorEXT where zero = XYColorEXT zero zero -- | VkHdrMetadataEXT - Specify Hdr metadata -- -- == Valid Usage (Implicit) -- -- Note -- -- The validity and use of this data is outside the scope of Vulkan. -- -- = See Also -- -- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_EXT_hdr_metadata VK_EXT_hdr_metadata>, -- 'Vulkan.Core10.Enums.StructureType.StructureType', 'XYColorEXT', -- 'setHdrMetadataEXT' data HdrMetadataEXT = HdrMetadataEXT { -- | @displayPrimaryRed@ is a 'XYColorEXT' structure specifying the reference -- monitor’s red primary in chromaticity coordinates displayPrimaryRed :: XYColorEXT , -- | @displayPrimaryGreen@ is a 'XYColorEXT' structure specifying the -- reference monitor’s green primary in chromaticity coordinates displayPrimaryGreen :: XYColorEXT , -- | @displayPrimaryBlue@ is a 'XYColorEXT' structure specifying the -- reference monitor’s blue primary in chromaticity coordinates displayPrimaryBlue :: XYColorEXT , -- | @whitePoint@ is a 'XYColorEXT' structure specifying the reference -- monitor’s white-point in chromaticity coordinates whitePoint :: XYColorEXT , -- | @maxLuminance@ is the maximum luminance of the reference monitor in nits maxLuminance :: Float , -- | @minLuminance@ is the minimum luminance of the reference monitor in nits minLuminance :: Float , -- | @maxContentLightLevel@ is content’s maximum luminance in nits maxContentLightLevel :: Float , -- | @maxFrameAverageLightLevel@ is the maximum frame average light level in -- nits maxFrameAverageLightLevel :: Float } deriving (Typeable) #if defined(GENERIC_INSTANCES) deriving instance Generic (HdrMetadataEXT) #endif deriving instance Show HdrMetadataEXT instance ToCStruct HdrMetadataEXT where withCStruct x f = allocaBytes 64 $ \p -> pokeCStruct p x (f p) pokeCStruct p HdrMetadataEXT{..} f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_HDR_METADATA_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr XYColorEXT)) (displayPrimaryRed) poke ((p `plusPtr` 24 :: Ptr XYColorEXT)) (displayPrimaryGreen) poke ((p `plusPtr` 32 :: Ptr XYColorEXT)) (displayPrimaryBlue) poke ((p `plusPtr` 40 :: Ptr XYColorEXT)) (whitePoint) poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (maxLuminance)) poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (minLuminance)) poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (maxContentLightLevel)) poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (maxFrameAverageLightLevel)) f cStructSize = 64 cStructAlignment = 8 pokeZeroCStruct p f = do poke ((p `plusPtr` 0 :: Ptr StructureType)) (STRUCTURE_TYPE_HDR_METADATA_EXT) poke ((p `plusPtr` 8 :: Ptr (Ptr ()))) (nullPtr) poke ((p `plusPtr` 16 :: Ptr XYColorEXT)) (zero) poke ((p `plusPtr` 24 :: Ptr XYColorEXT)) (zero) poke ((p `plusPtr` 32 :: Ptr XYColorEXT)) (zero) poke ((p `plusPtr` 40 :: Ptr XYColorEXT)) (zero) poke ((p `plusPtr` 48 :: Ptr CFloat)) (CFloat (zero)) poke ((p `plusPtr` 52 :: Ptr CFloat)) (CFloat (zero)) poke ((p `plusPtr` 56 :: Ptr CFloat)) (CFloat (zero)) poke ((p `plusPtr` 60 :: Ptr CFloat)) (CFloat (zero)) f instance FromCStruct HdrMetadataEXT where peekCStruct p = do displayPrimaryRed <- peekCStruct @XYColorEXT ((p `plusPtr` 16 :: Ptr XYColorEXT)) displayPrimaryGreen <- peekCStruct @XYColorEXT ((p `plusPtr` 24 :: Ptr XYColorEXT)) displayPrimaryBlue <- peekCStruct @XYColorEXT ((p `plusPtr` 32 :: Ptr XYColorEXT)) whitePoint <- peekCStruct @XYColorEXT ((p `plusPtr` 40 :: Ptr XYColorEXT)) maxLuminance <- peek @CFloat ((p `plusPtr` 48 :: Ptr CFloat)) minLuminance <- peek @CFloat ((p `plusPtr` 52 :: Ptr CFloat)) maxContentLightLevel <- peek @CFloat ((p `plusPtr` 56 :: Ptr CFloat)) maxFrameAverageLightLevel <- peek @CFloat ((p `plusPtr` 60 :: Ptr CFloat)) pure $ HdrMetadataEXT displayPrimaryRed displayPrimaryGreen displayPrimaryBlue whitePoint (coerce @CFloat @Float maxLuminance) (coerce @CFloat @Float minLuminance) (coerce @CFloat @Float maxContentLightLevel) (coerce @CFloat @Float maxFrameAverageLightLevel) instance Storable HdrMetadataEXT where sizeOf ~_ = 64 alignment ~_ = 8 peek = peekCStruct poke ptr poked = pokeCStruct ptr poked (pure ()) instance Zero HdrMetadataEXT where zero = HdrMetadataEXT zero zero zero zero zero zero zero zero type EXT_HDR_METADATA_SPEC_VERSION = 2 -- No documentation found for TopLevel "VK_EXT_HDR_METADATA_SPEC_VERSION" pattern EXT_HDR_METADATA_SPEC_VERSION :: forall a . Integral a => a pattern EXT_HDR_METADATA_SPEC_VERSION = 2 type EXT_HDR_METADATA_EXTENSION_NAME = "VK_EXT_hdr_metadata" -- No documentation found for TopLevel "VK_EXT_HDR_METADATA_EXTENSION_NAME" pattern EXT_HDR_METADATA_EXTENSION_NAME :: forall a . (Eq a, IsString a) => a pattern EXT_HDR_METADATA_EXTENSION_NAME = "VK_EXT_hdr_metadata"
expipiplus1/vulkan
src/Vulkan/Extensions/VK_EXT_hdr_metadata.hs
Haskell
bsd-3-clause
16,530
{-# LANGUAGE ScopedTypeVariables, DeriveGeneric #-} import qualified Data.ByteString.Lazy as BL import Data.Csv import qualified Data.Vector as V import GHC.Generics data Person = Person String Int deriving Generic instance FromRecord Person instance ToRecord Person persons :: [Person] persons = [Person "John" 50000, Person "Jane" 60000] main :: IO () main = do BL.writeFile "salaries.csv" $ encode (V.fromList persons) csvData <- BL.readFile "salaries.csv" case decode NoHeader csvData of Left err -> putStrLn err Right v -> V.forM_ v $ \ (Person name salary) -> putStrLn $ name ++ " earns " ++ show salary ++ " dollars"
mikeizbicki/cassava
examples/IndexBasedGeneric.hs
Haskell
bsd-3-clause
669
-- |Basic types and interfaces module Data.Deciparsec.Parser ( -- * Types Parser, Result, ParserT, IResult(..), TokenSeq -- * Running Parsers -- ** Resupplyable parsers , runParserT, feedT, runParser, feed -- ** Non-resupplyable parsers , runParserT', evalParserT, execParserT, runParser', evalParser, execParser -- * User State , getUserState, putUserState, modifyUserState -- * Source Position , SourcePos, spName, spLine, spColumn, getSourcePos, putSourcePos, modifySourcePos ) where import Data.Monoid import Data.Functor.Identity import Data.Deciparsec.Internal import Data.Deciparsec.Internal.Types import Data.Deciparsec.TokenSeq (TokenSeq) -- |A Parser over the 'Identity' monad. type Parser s u r = ParserT s u Identity r -- |An 'IResult' in the 'Identity' monad. type Result s u r = IResult s u Identity r -- |The most general way to run a parser. A 'Partial' result can be resupplied with 'feedT'. runParserT :: (Monad m, TokenSeq s t) => ParserT s u m a -- ^The parser -> u -- ^The inital user state -> String -- ^The name of the source \"file\" -> s -- ^An inital token sequence. The rest can be supplied later -> m (IResult s u m a) runParserT p u src ts = runParserT_ p (ParserState (SourcePos src 1 1) u) (I ts) mempty Incomplete failK successK -- |Run a parser that cannot be resupplied. This will return either an error, or the result of the parse and the -- final user state. runParserT' :: (Monad m, TokenSeq s t) => ParserT s u m a -- ^The parser -> u -- ^The initial user state -> String -- ^The name of the source \"file\" -> s -- ^The entire token sequence to parse -> m (Either ParseError (a, u)) runParserT' p u src ts = do ir <- runParserT_ p (ParserState (SourcePos src 1 1) u) (I ts) mempty Complete failK successK case ir of Fail _ _ pe -> return $ Left pe Done _ u' r -> return $ Right (r, u') _ -> fail $ "runParserT': impossible error!" -- |Run a parser that cannot be resupplied, and return either an error or the result of the parser. The -- final user state will be discarded. evalParserT :: (Monad m, TokenSeq s t) => ParserT s u m a -- ^The parser -> u -- ^The initial user state -> String -- ^The name of the source \"file\" -> s -- ^The entire token sequence to parse -> m (Either ParseError a) evalParserT p u src ts = do res <- runParserT' p u src ts return $ either Left (Right . fst) res -- either Left (Right . fst) <$> runParserT' p u src ts -- This requires :: Functor m -- |Run a parser that cannot be resupplied, and return either an error or the final user state. The -- result of the parser will be discarded. execParserT :: (Monad m, TokenSeq s t) => ParserT s u m a -> u -> String -> s -> m (Either ParseError u) execParserT p u src ts = do res <- runParserT' p u src ts return $ either Left (Right . snd) res -- either Left (Right . snd) <$> runParserT' p u src ts -- This requires :: Functor m -- |Run a parser in the 'Identity' monad. A 'Partial' result can be resupplied with 'feed'. runParser :: TokenSeq s t => Parser s u a -- ^The parser -> u -- ^The initial user state -> String -- ^The name of the source \"file\" -> s -- ^An initial token sequence. The rest can be supplied later -> Result s u a runParser p u src ts = runIdentity $ runParserT p u src ts -- |Run a parser that cannot be resupplied in the 'Identity' monad. runParser' :: TokenSeq s t => Parser s u a -- ^The parser -> u -- ^The initial user state -> String -- ^The name of the source \"file\" -> s -- ^The entire token sequence to parse -> Either ParseError (a, u) runParser' p u src ts = runIdentity $ runParserT' p u src ts -- |Run a parser that cannot be resupplied in the 'Identity' monad, and return either an error or the result of -- the parser. The final user state will be discarded. evalParser :: TokenSeq s t => Parser s u a -> u -> String -> s -> Either ParseError a evalParser p u src ts = runIdentity $ evalParserT p u src ts -- |Run a parser that cannot be resupplied in the 'Identity' monad, and return either an error or the final user -- state. The result of the parser will be discarded. execParser :: TokenSeq s t => Parser s u a -> u -> String -> s -> Either ParseError u execParser p u src ts = runIdentity $ execParserT p u src ts -- |Provide additional input to a 'Partial' result from 'runParserT'. Provide an -- 'Data.Deciparsec.Internal.TokenSeq.empty' sequence to force the parser to \"finish\". feedT :: (Monad m, TokenSeq s t) => IResult s u m a -> s -> m (IResult s u m a) feedT f@(Fail {}) _ = return f feedT (Partial k) ts = k ts feedT (Done ts u r) ts' = return $ Done (ts <> ts') u r -- |Provide additional input to a 'Partial' result from 'runParser'. Provide an -- 'Data.Deciparsec.Internal.TokenSeq.empty' sequence to force the parser to \"finish\". feed :: TokenSeq s t => Result s u a -> s -> Result s u a feed = ((.).(.)) runIdentity feedT failK :: Monad m => Failure s u m a failK s0 i0 _a0 _m0 pe = return $ Fail (unI i0) (psState s0) pe successK :: Monad m => Success s u a m a successK s0 i0 _a0 _m0 a = return $ Done (unI i0) (psState s0) a
d3tucker/deciparsec
src/Data/Deciparsec/Parser.hs
Haskell
bsd-3-clause
5,712
{-# LANGUAGE PatternGuards #-} module Common.Draw (drawLineU, drawLineA) where -- Repa import Data.Array.Repa (Z (..), (:.) (..), U, DIM2, Array) import qualified Data.Array.Repa as R -- Acc import Data.Array.Accelerate.IO -- base import Control.Monad import Control.Monad.ST import qualified Data.STRef import qualified Data.Vector.Unboxed as UV import qualified Data.Vector.Generic.Mutable as MV import Common.World -- | Draw a line onto the Repa array drawLineU :: GlossCoord -> GlossCoord -> Cell -> Array U DIM2 Cell -> IO (Array U DIM2 Cell) drawLineU (xa, ya) (xb, yb) new array | sh@(Z :. _ :. width) <- R.extent array , (x0, y0, x1, y1) <- ( round xa + resWidth, round ya + resHeight , round xb + resWidth, round yb + resHeight ) , x0 < resX - 2, x1 < resX - 2, y0 < resY - 2, y1 < resY - 2, x0 > 2, y0 > 2, x1 > 2, y1 > 2 = do raw <- UV.unsafeThaw $ R.toUnboxed array stToIO $ bresenham raw (\(x,y)-> y * width + x) new (x0, y0) (x1, y1) raw' <- UV.unsafeFreeze raw return $ R.fromUnboxed sh raw' | otherwise = return array -- | Draw a line onto the Repa array backed by Accelerate drawLineA :: GlossCoord -> GlossCoord -> Cell -> Array A DIM2 Cell -> IO (Array A DIM2 Cell) drawLineA (xa, ya) (xb, yb) new array -- FIXME input check here as well, maybe faster = R.copyP array >>= drawLineU (xa, ya) (xb, yb) new >>= R.copyP -- Bresenham's line drawing, copypasted from -- http://rosettacode.org/wiki/Bitmap/Bresenham's_line_algorithm -- only destructively updating the array is fast enough bresenham vec ix val (xa, ya) (xb, yb) = do yV <- var y1 errorV <- var $ deltax `div` 2 forM_ [x1 .. x2] (\x -> do y <- get yV drawCirc $ if steep then (y, x) else (x, y) mutate errorV $ subtract deltay error <- get errorV when (error < 0) (do mutate yV (+ ystep) mutate errorV (+ deltax))) where steep = abs (yb - ya) > abs (xb - xa) (xa', ya', xb', yb') = if steep then (ya, xa, yb, xb) else (xa, ya, xb, yb) (x1, y1, x2, y2) = if xa' > xb' then (xb', yb', xa', ya') else (xa', ya', xb', yb') deltax = x2 - x1 deltay = abs $ y2 - y1 ystep = if y1 < y2 then 1 else -1 var = Data.STRef.newSTRef get = Data.STRef.readSTRef mutate = Data.STRef.modifySTRef drawCirc (x,y) = do MV.write vec (ix (x,y)) val -- me MV.write vec (ix (x,y+1)) val -- top MV.write vec (ix (x+1,y+1)) val -- top right MV.write vec (ix (x+1,y)) val -- right MV.write vec (ix (x+1,y-1)) val -- down right MV.write vec (ix (x,y-1)) val -- down MV.write vec (ix (x-1,y-1)) val -- down left MV.write vec (ix (x-1,y)) val -- left MV.write vec (ix (x-1,y+1)) val -- top left MV.write vec (ix (x,y+2)) val -- top top MV.write vec (ix (x+2,y)) val -- right right MV.write vec (ix (x-2,y)) val -- left left MV.write vec (ix (x,y-2)) val -- down down
tranma/falling-turnip
common/Draw.hs
Haskell
bsd-3-clause
3,473
module Notate.Actions ( runInstall , runNotebook , runKernel , runEval ) where import Control.Monad (unless, forM_) import Control.Monad.IO.Class (liftIO) import Control.Monad.State.Strict import qualified Data.Aeson as A import qualified Data.ByteString.Lazy as BL import Data.List (findIndex) import IHaskell.IPython.EasyKernel (easyKernel, KernelConfig(..)) import IHaskell.IPython.Types import qualified Language.Haskell.Interpreter as HI import Notate.Core import System.Directory import System.Environment (getEnv) import System.FilePath ((</>)) import System.IO import System.Process runInstall :: Kernel -> NotateM () runInstall kernel = do configDir <- gets nsConfigDir exists <- liftIO $ doesDirectoryExist configDir if exists then fail ("Already exists: " ++ configDir) else do liftIO $ createDirectory configDir let subConfigDir = configDir </> "config" dataDir = configDir </> "data" runtimeDir = configDir </> "runtime" liftIO $ createDirectory subConfigDir liftIO $ createDirectory dataDir liftIO $ createDirectory runtimeDir let kernelsDir = dataDir </> "kernels" liftIO $ createDirectory kernelsDir let thisKernelName = languageName (kernelLanguageInfo kernel) thisKernelDir = kernelsDir </> thisKernelName liftIO $ createDirectory thisKernelDir kernelSpec <- liftIO $ writeKernelspec kernel thisKernelDir let kernelFile = thisKernelDir </> "kernel.json" liftIO $ BL.writeFile kernelFile (A.encode (A.toJSON kernelSpec)) runNotebook :: NotateM () runNotebook = do configDir <- gets nsConfigDir home <- liftIO $ getEnv "HOME" let subConfigDir = configDir </> "config" dataDir = configDir </> "data" runtimeDir = configDir </> "runtime" procDef = CreateProcess { cmdspec = ShellCommand ("jupyter notebook") , cwd = Nothing , env = Just [ ("HOME", home) , ("JUPYTER_CONFIG_DIR", subConfigDir) , ("JUPYTER_PATH", dataDir) , ("JUPYTER_RUNTIME_DIR", runtimeDir) ] , std_in = Inherit , std_out = Inherit , std_err = Inherit , close_fds = False , create_group = False , delegate_ctlc = True , detach_console = False , create_new_console = False , new_session = False , child_group = Nothing , child_user = Nothing } (_, _, _, handle) <- liftIO $ createProcess procDef exitCode <- liftIO $ waitForProcess handle liftIO $ putStrLn ("jupyter exited with " ++ (show exitCode)) return () runKernel :: FilePath -> Kernel -> NotateM () runKernel profile kernel = do liftIO $ putStrLn "starting notate kernel" liftIO $ easyKernel profile kernel liftIO $ putStrLn "finished notate kernel" runEval :: NotateM () runEval = do return ()
ejconlon/notate
src/Notate/Actions.hs
Haskell
bsd-3-clause
2,885
{-# LANGUAGE CPP #-} {-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE DefaultSignatures #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE UndecidableInstances #-} #if __GLASGOW_HASKELL__ >= 800 {-# LANGUAGE UndecidableSuperClasses #-} #endif module WebApi.Internal where import Data.Text.Encoding (encodeUtf8Builder) import Control.Exception import Control.Monad.Catch (MonadCatch) import Control.Monad.IO.Class (MonadIO) import Control.Monad.Trans.Resource (runResourceT, withInternalState) import Data.ByteString (ByteString) import Data.ByteString.Builder (toLazyByteString, Builder) import Data.ByteString.Lazy as LBS (toStrict) import Data.List (find) #if !(MIN_VERSION_base(4,8,0)) import Data.Monoid ((<>)) #endif import Data.Maybe (fromMaybe) import Data.Proxy import qualified Data.Text as T (pack) import Data.Typeable (Typeable) import Network.HTTP.Media (MediaType, mapAcceptMedia, matchAccept, matchContent , mapAccept) import Network.HTTP.Media.RenderHeader (renderHeader) import Network.HTTP.Types hiding (Query) import qualified Network.Wai as Wai import qualified Network.Wai.Parse as Wai import Web.Cookie import WebApi.ContentTypes import WebApi.Contract import WebApi.Param import WebApi.Util import qualified Data.Text.Encoding as TE import GHC.TypeLits data RouteResult a = NotMatched | Matched a type RoutingApplication = Wai.Request -> (RouteResult Wai.Response -> IO Wai.ResponseReceived) -> IO Wai.ResponseReceived toApplication :: RoutingApplication -> Wai.Application toApplication app request respond = app request $ \routeResult -> case routeResult of Matched result -> respond result NotMatched -> respond (Wai.responseLBS notFound404 [] "") type FromWaiRequestCtx m r = ( FromParam 'QueryParam (QueryParam m r) , FromParam 'FormParam (FormParam m r) , FromParam 'FileParam (FileParam m r) , FromHeader (HeaderIn m r) , FromParam 'Cookie (CookieIn m r) , ToHListRecTuple (StripContents (RequestBody m r)) , PartDecodings (RequestBody m r) , SingMethod m , EncodingType m r (ContentTypes m r) ) fromWaiRequest :: forall m r. FromWaiRequestCtx m r => Wai.Request -> PathParam m r -> (Request m r -> IO (Response m r)) -> IO (Validation [ParamErr] (Response m r)) fromWaiRequest waiReq pathPar handlerFn = do let mContentTy = getContentType $ Wai.requestHeaders waiReq case hasFormData mContentTy of Just _ -> do runResourceT $ withInternalState $ \internalState -> do (formPar, filePar) <- Wai.parseRequestBody (Wai.tempFileBackEnd internalState) waiReq let request = Request <$> pure pathPar <*> (fromQueryParam $ Wai.queryString waiReq) <*> (fromFormParam formPar) <*> (fromFileParam (fmap fromWaiFile filePar)) <*> (fromHeader $ Wai.requestHeaders waiReq) <*> (fromCookie $ maybe [] parseCookies (getCookie waiReq)) <*> (fromBody []) handler' (acceptHeaderType accHdr <$> request) Nothing -> do bdy <- Wai.lazyRequestBody waiReq let rBody = [(fromMaybe (renderHeader $ contentType (Proxy :: Proxy OctetStream)) mContentTy, bdy)] let request = Request <$> pure pathPar <*> (fromQueryParam $ Wai.queryString waiReq) <*> (fromFormParam []) <*> (fromFileParam []) <*> (fromHeader $ Wai.requestHeaders waiReq) <*> (fromCookie $ maybe [] parseCookies (getCookie waiReq)) <*> (fromBody rBody) handler' (acceptHeaderType accHdr <$> request) where accHdr = getAcceptType (Wai.requestHeaders waiReq) handler' (Validation (Right req)) = handlerFn req >>= \resp -> return $ Validation (Right resp) handler' (Validation (Left parErr)) = return $ Validation (Left parErr) hasFormData x = matchContent [contentType (Proxy :: Proxy MultipartFormData), contentType (Proxy :: Proxy UrlEncoded)] =<< x acceptHeaderType :: Maybe ByteString -> Request m r -> Request m r acceptHeaderType (Just x) r = fromMaybe r $ (\(Encoding t _ _) -> setAcceptHeader t r) <$> matchAcceptHeaders x r acceptHeaderType Nothing r = r fromBody x = Validation $ either (\e -> Left [NotFound (bspack e)]) (Right . fromRecTuple (Proxy :: Proxy (StripContents (RequestBody m r)))) $ partDecodings (Proxy :: Proxy (RequestBody m r)) x bspack = TE.encodeUtf8 . T.pack fromWaiFile :: Wai.File FilePath -> (ByteString, FileInfo) fromWaiFile (fname, waiFileInfo) = (fname, FileInfo { fileName = Wai.fileName waiFileInfo , fileContentType = Wai.fileContentType waiFileInfo , fileContent = Wai.fileContent waiFileInfo }) toWaiResponse :: ( ToHeader (HeaderOut m r) , ToParam 'Cookie (CookieOut m r) , Encodings (ContentTypes m r) (ApiOut m r) , Encodings (ContentTypes m r) (ApiErr m r) ) => Wai.Request -> Response m r -> Wai.Response toWaiResponse wreq resp = case resp of Success status out hdrs cookies -> case encode' resp out of Just (ctype, o') -> let hds = (hContentType, renderHeader ctype) : handleHeaders' (toHeader hdrs) (toCookie cookies) in Wai.responseBuilder status hds o' Nothing -> Wai.responseBuilder notAcceptable406 [] "Matching content type not found" Failure (Left (ApiError status errs hdrs cookies)) -> case encode' resp errs of Just (ctype, errs') -> let hds = (hContentType, renderHeader ctype) : handleHeaders (toHeader <$> hdrs) (toCookie <$> cookies) in Wai.responseBuilder status hds errs' Nothing -> Wai.responseBuilder notAcceptable406 [] "Matching content type not found" Failure (Right (OtherError ex)) -> Wai.responseBuilder internalServerError500 [] (encodeUtf8Builder (T.pack (displayException ex))) where encode' :: ( Encodings (ContentTypes m r) a ) => apiRes m r -> a -> Maybe (MediaType, Builder) encode' r o = case getAccept wreq of Just acc -> let ecs = encodings (reproxy r) o in (,) <$> matchAccept (map fst ecs) acc <*> mapAcceptMedia ecs acc Nothing -> case encodings (reproxy r) o of (x : _) -> Just x _ -> Nothing reproxy :: apiRes m r -> Proxy (ContentTypes m r) reproxy = const Proxy handleHeaders :: Maybe [Header] -> Maybe [(ByteString, CookieInfo ByteString)] -> [Header] handleHeaders hds cks = handleHeaders' (maybe [] id hds) (maybe [] id cks) handleHeaders' :: [Header] -> [(ByteString, CookieInfo ByteString)] -> [Header] handleHeaders' hds cookies = let ckHs = map (\(ck, cv) -> (hSetCookie , renderSC ck cv)) cookies in hds <> ckHs renderSC k v = toStrict . toLazyByteString . renderSetCookie $ def { setCookieName = k , setCookieValue = cookieValue v , setCookiePath = cookiePath v , setCookieExpires = cookieExpires v , setCookieMaxAge = cookieMaxAge v , setCookieDomain = cookieDomain v , setCookieHttpOnly = fromMaybe False (cookieHttpOnly v) , setCookieSecure = fromMaybe False (cookieSecure v) } -- | Describes the implementation of a single API end point corresponding to @ApiContract (ApiInterface p) m r@ class (ApiContract (ApiInterface p) m r) => ApiHandler (p :: *) (m :: *) (r :: *) where -- | Handler for the API end point which returns a 'Response'. -- -- TODO : 'query' type parameter is an experimental one used for trying out dependently typed params. -- This parameter will let us refine the 'ApiOut' to the structure that is requested by the client. -- for eg : graph.facebook.com/bgolub?fields=id,name,picture -- -- This feature is not finalized and might get changed \/ removed. -- Currently the return type of handler is equivalent to `Response m r` -- handler :: (query ~ '[]) => Tagged query p -> Request m r -> HandlerM p (Query (Response m r) query) type family Query (t :: *) (query :: [*]) :: * where Query t '[] = t -- | Binds implementation to interface and provides a pluggable handler monad for the endpoint handler implementation. class ( MonadCatch (HandlerM p) , MonadIO (HandlerM p) , WebApi (ApiInterface p) ) => WebApiServer (p :: *) where -- | Type of the handler 'Monad'. It should implement 'MonadCatch' and 'MonadIO' classes. Defaults to 'IO'. type HandlerM p :: * -> * type ApiInterface p :: * -- provides common defaulting information for api handlers -- | Create a value of @IO a@ from @HandlerM p a@. toIO :: p -> WebApiRequest -> HandlerM p a -> IO a default toIO :: (HandlerM p ~ IO) => p -> WebApiRequest -> HandlerM p a -> IO a toIO _ _ = id type HandlerM p = IO -- | Type of settings of the server. data ServerSettings = ServerSettings -- | Default server settings. serverSettings :: ServerSettings serverSettings = ServerSettings newtype NestedApplication (apps :: [(Symbol, *)]) = NestedApplication [Wai.Application] unconsNesApp :: NestedApplication (app ': apps) -> (Wai.Application, NestedApplication apps) unconsNesApp (NestedApplication (app : apps)) = (app, NestedApplication apps) unconsNesApp (NestedApplication []) = error "Panic: cannot happen by construction" newtype ApiComponent c = ApiComponent Wai.Application nestedApi :: NestedApplication '[] nestedApi = NestedApplication [] data NestedR = NestedR -- | Type of Exception raised in a handler. data ApiException m r = ApiException { apiException :: ApiError m r } instance Show (ApiException m r) where show (ApiException _) = "ApiException" instance (Typeable m, Typeable r) => Exception (ApiException m r) where handleApiException :: (query ~ '[], Monad (HandlerM p)) => p -> ApiException m r -> (HandlerM p) (Query (Response m r) query) handleApiException _ = return . Failure . Left . apiException handleSomeException :: (query ~ '[], Monad (HandlerM p)) => p -> SomeException -> (HandlerM p) (Query (Response m r) query) handleSomeException _ = return . Failure . Right . OtherError getCookie :: Wai.Request -> Maybe ByteString getCookie = fmap snd . find ((== hCookie) . fst) . Wai.requestHeaders getAccept :: Wai.Request -> Maybe ByteString getAccept = fmap snd . find ((== hAccept) . fst) . Wai.requestHeaders hSetCookie :: HeaderName hSetCookie = "Set-Cookie" getContentType :: ResponseHeaders -> Maybe ByteString getContentType = fmap snd . find ((== hContentType) . fst) getAcceptType :: ResponseHeaders -> Maybe ByteString getAcceptType = fmap snd . find ((== hAccept) . fst) newtype Tagged (s :: [*]) b = Tagged { unTagged :: b } toTagged :: Proxy s -> b -> Tagged s b toTagged _ = Tagged class EncodingType m r (ctypes :: [*]) where getEncodingType :: Proxy ctypes -> [(MediaType, Encoding m r)] instance ( Accept ctype , Elem ctype (ContentTypes m r) , EncodingType m r ctypes ) => EncodingType m r (ctype ': ctypes) where getEncodingType _ = (contentType (Proxy :: Proxy ctype), Encoding (Proxy :: Proxy ctype) Proxy Proxy) : getEncodingType (Proxy :: Proxy ctypes) instance EncodingType m r '[] where getEncodingType _ = [] matchAcceptHeaders :: forall m r ctypes. ( EncodingType m r ctypes , ctypes ~ ContentTypes m r ) => ByteString -> Request m r -> Maybe (Encoding m r) matchAcceptHeaders b _ = mapAccept (getEncodingType (Proxy :: Proxy ctypes)) b data WebApiRequest = WebApiRequest { rawRequest :: Wai.Request }
byteally/webapi
webapi/src/WebApi/Internal.hs
Haskell
bsd-3-clause
13,144
#!/usr/bin/env runhaskell {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE OverlappingInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE NoMonomorphismRestriction #-} import Control.Monad import Data.Maybe import Narradar import Narradar.Types.ArgumentFiltering (AF_, simpleHeu, bestHeu, innermost) import Narradar.Types.Problem import Narradar.Types.Problem.Rewriting import Narradar.Types.Problem.NarrowingGen import Narradar.Processor.RPO import Narradar.Processor.FLOPS08 import Narradar.Processor.LOPSTR09 import Lattice import Narradar.Interface.Cli main = narradarMain listToMaybe -- Missing dispatcher cases instance (IsProblem typ, Pretty typ) => Dispatch (Problem typ trs) where dispatch p = error ("missing dispatcher for problem of type " ++ show (pPrint $ getFramework p)) instance Dispatch thing where dispatch _ = error "missing dispatcher" -- Prolog instance Dispatch PrologProblem where dispatch = apply SKTransform >=> dispatch -- Rewriting instance (Pretty (DPIdentifier a), Ord a, HasTrie a) => Dispatch (NProblem Rewriting (DPIdentifier a)) where dispatch = ev >=> (inn .|. (dg >=> rpoPlusTransforms >=> final)) instance (Pretty (DPIdentifier a), Ord a, HasTrie a) => Dispatch (NProblem IRewriting (DPIdentifier a)) where dispatch = sc >=> rpoPlusTransforms >=> final -- Narrowing Goal instance (id ~ DPIdentifier a, Ord a, Lattice (AF_ id), Pretty id, HasTrie a) => Dispatch (NProblem (InitialGoal (TermF (DPIdentifier a)) Narrowing) (DPIdentifier a)) where dispatch = apply (ComputeSafeAF bestHeu) >=> dg >=> apply (NarrowingGoalToRewriting bestHeu) >=> dispatch dg = apply DependencyGraphSCC{useInverse=True} sc = apply SubtermCriterion ev = apply ExtraVarsP inn = apply ToInnermost >=> dispatch rpoPlusTransforms = repeatSolver 5 ( (sc .|. lpo .|. rpos .|. graphTransform) >=> dg) where lpo = apply (RPOProc LPOAF Needed SMTFFI) lpos = apply (RPOProc LPOSAF Needed SMTFFI) rpos = apply (RPOProc RPOSAF Needed SMTFFI) graphTransform = apply NarrowingP .|. apply FInstantiation .|. apply Instantiation
pepeiborra/narradar
strategies/FLOPS08-search.hs
Haskell
bsd-3-clause
2,230
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses, DeriveDataTypeable, RecordWildCards#-} module CommandLine(withArgs,OutputFormat(..)) where import System.Console.CmdLib import qualified Math.Statistics.WCC as T data OutputFormat = PNG | RAW deriving (Eq,Data,Typeable,Show) data Opts = Opts { windowIncrement :: Int , windowSize :: Int -- , maxLag :: Int , lagSteps :: Int , lagIncrement :: Int , infile :: FilePath , outfile :: FilePath , outputFormat :: OutputFormat , debug :: Bool } deriving (Eq,Data,Typeable,Show) instance Attributes Opts where attributes _ = group "Options" [ windowIncrement %> [Help "Window increment", ArgHelp "INT"] , windowSize %> [Help "The window size", ArgHelp "SIZE"] -- , maxLag %> [Help "The maximum lag, should be divisible by lagIncrement"] , lagSteps %> [Help "Number of lag-steps"] , lagIncrement %> [Help "lag increment"] , outputFormat %> [Help "RAW will output the correlation matrix, PNG a png image", Default PNG, ArgHelp "RAW|PNG"] , infile %> [Help "The input filename. Two columns of numbers (lines starting with '#' is ignored)" ,ArgHelp "FILE"] , outfile %> [Help "The output filename", ArgHelp "FILE"] , debug %> [Help "Print debug information", Default False] ] readFlag _ = readCommon <+< (readOutputFormat) where readOutputFormat "PNG" = PNG readOutputFormat "RAW" = RAW readOutputFormat x = error $ "unknown output format: " ++ x instance RecordCommand Opts where mode_summary _ = "Compute the windowed cross correlation." run' _ = error "run' er undefined" -- add this to remove the warning about uninitialized fields. -- they isn't used though -- defaultOpts = Opts { windowIncrement = ns "windowIncrement" -- , windowSize = ns "windowSize" -- , maxLag = ns "maxLag" -- , lagIncrement = ns "lagIncrement" -- , infile = ns "input filename" -- , outfile = ns "output filename" -- , outputFormat = ns "output format" -- } -- where ns x = error $ "no " ++x++ " specified" --withArgs f = getArgs >>= executeR defaultOpts >>= return . parseOpts >>= \(i,o,out,p) -> f i o out p withArgs :: (FilePath -> FilePath -> Bool -> OutputFormat -> T.WCCParams -> IO ()) -> IO () withArgs f = getArgs >>= executeR Opts {} >>= return . parseOpts >>= \(i,o,debug,out,p) -> f i o debug out p --withArgs f = getArgs >>= dispatchR [] >>= f parseOpts :: Opts -> (FilePath,FilePath,Bool,OutputFormat,T.WCCParams) parseOpts (Opts {..}) | windowIncrement < 1 = bto "windowIncrement" | windowSize < 1 = bto "windowSize" -- | maxLag < 1 = bto "maxLag" | lagSteps < 1 = bto "lagSteps" | lagIncrement < 1 = bto "lagIncrement" -- | lagErr /= 0 = error $ "maxLag not divisible by lagIncrement" | infile == "" = nfg "in" | outfile == "" = nfg "out" | otherwise = (infile,outfile,debug,outputFormat,T.WCCParams {..}) where bto = error . (++" must be bigger than one.") nfg x = error $ "no " ++ x ++ "file given." -- (lagSteps,lagErr) = maxLag `divMod` lagIncrement
runebak/wcc
Source/CommandLine.hs
Haskell
bsd-3-clause
3,720
module Main (main) where import Control.Concurrent (forkIO) import Control.Concurrent.MVar (newEmptyMVar, MVar, takeMVar, putMVar) import Control.Concurrent.STM (TVar, atomically, writeTVar, newTChan, readTVar, newTVarIO) import Control.Monad (forever) import System.Environment (getArgs) import System.Exit (exitFailure, exitSuccess) import System.Posix.Signals (installHandler, sigHUP, sigTERM, sigINT, Handler(Catch)) import System.IO (hSetBuffering, hPutStrLn, BufferMode(LineBuffering), stdout, stderr) import qualified Data.Map as M import Angel.Log (logger) import Angel.Config (monitorConfig) import Angel.Data (GroupConfig(GroupConfig), spec) import Angel.Job (pollStale, syncSupervisors) import Angel.Files (startFileManager) -- |Signal handler: when a HUP is trapped, write to the wakeSig Tvar -- |to make the configuration monitor loop cycle/reload handleHup :: TVar (Maybe Int) -> IO () handleHup wakeSig = atomically $ writeTVar wakeSig $ Just 1 handleExit :: MVar Bool -> IO () handleExit mv = putMVar mv True main :: IO () main = handleArgs =<< getArgs handleArgs :: [String] -> IO () handleArgs ["--help"] = printHelp handleArgs ["-h"] = printHelp handleArgs [] = printHelp handleArgs [configPath] = runWithConfigPath configPath handleArgs _ = errorExit "expected a single config file. Run with --help for usasge." printHelp :: IO () printHelp = putStrLn "Usage: angel [--help] CONFIG_FILE" >> exitSuccess runWithConfigPath :: FilePath -> IO () runWithConfigPath configPath = do hSetBuffering stdout LineBuffering hSetBuffering stderr LineBuffering let logger' = logger "main" logger' "Angel started" logger' $ "Using config file: " ++ configPath -- Create the TVar that represents the "global state" of running applications -- and applications that _should_ be running fileReqChan <- atomically newTChan sharedGroupConfig <- newTVarIO $ GroupConfig M.empty M.empty fileReqChan -- The wake signal, set by the HUP handler to wake the monitor loop wakeSig <- newTVarIO Nothing installHandler sigHUP (Catch $ handleHup wakeSig) Nothing -- Handle dying bye <- newEmptyMVar installHandler sigTERM (Catch $ handleExit bye) Nothing installHandler sigINT (Catch $ handleExit bye) Nothing -- Fork off an ongoing state monitor to watch for inconsistent state forkIO $ pollStale sharedGroupConfig forkIO $ startFileManager fileReqChan -- Finally, run the config load/monitor thread forkIO $ forever $ monitorConfig configPath sharedGroupConfig wakeSig _ <- takeMVar bye logger' "INT | TERM received; initiating shutdown..." logger' " 1. Clearing config" atomically $ do cfg <- readTVar sharedGroupConfig writeTVar sharedGroupConfig cfg {spec = M.empty} logger' " 2. Forcing sync to kill running processes" syncSupervisors sharedGroupConfig logger' "That's all folks!" errorExit :: String -> IO () errorExit msg = hPutStrLn stderr msg >> exitFailure
zalora/Angel
src/Angel/Main.hs
Haskell
bsd-3-clause
3,527
module Rash.Runtime.Interpreter where import Control.Monad.IO.Class (liftIO) import qualified Control.Monad.Trans.State as State import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import qualified GHC.IO.Handle as Handle import qualified System.IO as IO import qualified System.Process as Proc import qualified Rash.Debug as Debug import Rash.IR.AST import Rash.Runtime.Builtins as Builtins import qualified Rash.Runtime.Process as Process import qualified Rash.Runtime.Runtime as RT import Rash.Runtime.Types import qualified Rash.Util as Util debug :: Show a => String -> a -> a debug a b = Debug.traceTmpl "exe" a b debugM :: (Show a, Monad f, Applicative f) => String -> a -> f () debugM a b = Debug.traceMTmpl "exe" a b die :: Show a => String -> a -> t die a b = Debug.die "exe" a b interpret :: Program -> [String] -> IO Value interpret (Program exprs) args = do let st = Map.insert "sys.argv" (VArray (map VString args)) Map.empty let ft = Builtins.builtins let hs = Handles IO.stdin IO.stdout IO.stderr let state = IState (Frame st hs) ft (val, final) <- State.runStateT (evalExprs exprs) state debugM "final state" final return val evalExprs :: [Expr] -> WithState Value evalExprs es = do debugM ("executing a list with " ++ (show (length es)) ++ " exprs") () evaled <- mapM evalExpr es return (last evaled) evalExpr :: Expr -> WithState Value evalExpr e = do _ <- debugM "executing" e v <- evalExpr' e _ <- debugM "returning" v _ <- debugM " <- " e return v evalExpr' :: Expr -> WithState Value evalExpr' Nop = return VNull evalExpr' (FunctionDefinition fd@(FuncDef name _ _)) = do RT.updateFuncTable $ Map.insert name (UserDefined fd) return VNull evalExpr' (If cond then' else') = do condVal <- evalExpr cond if Util.isTruthy condVal then evalExprs then' else evalExprs else' evalExpr' (Binop l Equals r) = do lval <- evalExpr l rval <- evalExpr r return $ VBool (lval == rval) evalExpr' (Binop l And r) = do lval <- evalExpr l res <- if (Util.isTruthy lval) then do rval <- evalExpr r return $ Util.isTruthy rval else return False return $ VBool res evalExpr' (Unop Not e) = do res <- evalExpr e return $ VBool $ not (Util.isTruthy res) evalExpr' (Concat exprs) = do vs <- mapM evalExpr exprs return $ VString $ foldl (\a b -> a ++ (Util.asString b)) "" vs evalExpr' (Variable name) = do st <- RT.getSymTable return $ fromMaybe VNull $ Map.lookup name st evalExpr' ss@(Subscript (Variable name) e) = do index <- evalExpr e st <- RT.getSymTable let var = Map.lookup name st return $ case (var, index) of (Just (VArray a), VInt i) -> Util.findWithDefault a i VNull (Just (VHash h), VString s) -> Map.findWithDefault VNull s h _ -> die "Can't do a subscript unless on array/int or hash/string" (ss, var, index) evalExpr' (Assignment (LVar name) e) = do result <- evalExpr e RT.updateSymTable $ Map.insert name result return result ------------------------------------------------ -- Function calls and pipes ------------------------------------------------ evalExpr' (Pipe (Stdin input) fns) = do inputStr <- eval2Str input (r,w) <- liftIO $ Proc.createPipe liftIO $ IO.hPutStr w inputStr result <- evalPipe fns r liftIO $ IO.hClose r return result evalExpr' (Pipe NoStdin fns) = do stdin <- RT.getStdin evalPipe fns stdin evalExpr' Null = return VNull evalExpr' (Integer i) = return $ VInt i evalExpr' (Str s) = return $ VString s evalExpr' (Array es) = do as <- mapM evalExpr es return $ VArray as evalExpr' e = do die "an unsupported expression was found" e eval2Str :: Expr -> WithState String eval2Str e = do expr <- evalExpr e let (VString str) = Util.toString expr return str evalPipe :: [FunctionCall] -> Handle.Handle -> WithState Value evalPipe fns stdin = do commands <- mapM evalArgs fns Process.evalPipe commands stdin evalExpr where evalArgs (Fn name args) = do args2 <- mapM evalExpr args return (name, args2) evalArgs e = die "how do we invoke non-FunctionInvocations" e
pbiggar/rash
src/Rash/Runtime/Interpreter.hs
Haskell
bsd-3-clause
4,274