code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 Typechecking class declarations -} {-# LANGUAGE CPP #-} module TcClassDcl ( tcClassSigs, tcClassDecl2, findMethodBind, instantiateMethod, tcClassMinimalDef, HsSigFun, mkHsSigFun, lookupHsSig, emptyHsSigs, tcMkDeclCtxt, tcAddDeclCtxt, badMethodErr, tcATDefault ) where #include "HsVersions.h" import HsSyn import TcEnv import TcPat( addInlinePrags, completeIdSigPolyId, lookupPragEnv, emptyPragEnv ) import TcEvidence( idHsWrapper ) import TcBinds import TcUnify import TcHsType import TcMType import Type ( getClassPredTys_maybe ) import TcType import TcRnMonad import BuildTyCl( TcMethInfo ) import Class import Coercion ( pprCoAxiom ) import DynFlags import FamInst import FamInstEnv import Id import Name import NameEnv import NameSet import Var import VarEnv import VarSet import Outputable import SrcLoc import TyCon import TypeRep import Maybes import BasicTypes import Bag import FastString import BooleanFormula import Util import Control.Monad import Data.List ( mapAccumL ) {- Dictionary handling ~~~~~~~~~~~~~~~~~~~ Every class implicitly declares a new data type, corresponding to dictionaries of that class. So, for example: class (D a) => C a where op1 :: a -> a op2 :: forall b. Ord b => a -> b -> b would implicitly declare data CDict a = CDict (D a) (a -> a) (forall b. Ord b => a -> b -> b) (We could use a record decl, but that means changing more of the existing apparatus. One step at at time!) For classes with just one superclass+method, we use a newtype decl instead: class C a where op :: forallb. a -> b -> b generates newtype CDict a = CDict (forall b. a -> b -> b) Now DictTy in Type is just a form of type synomym: DictTy c t = TyConTy CDict `AppTy` t Death to "ExpandingDicts". ************************************************************************ * * Type-checking the class op signatures * * ************************************************************************ -} tcClassSigs :: Name -- Name of the class -> [LSig Name] -> LHsBinds Name -> TcM ([TcMethInfo], -- Exactly one for each method NameEnv Type) -- Types of the generic-default methods tcClassSigs clas sigs def_methods = do { traceTc "tcClassSigs 1" (ppr clas) ; gen_dm_prs <- concat <$> mapM (addLocM tc_gen_sig) gen_sigs ; let gen_dm_env = mkNameEnv gen_dm_prs ; op_info <- concat <$> mapM (addLocM (tc_sig gen_dm_env)) vanilla_sigs ; let op_names = mkNameSet [ n | (n,_,_) <- op_info ] ; sequence_ [ failWithTc (badMethodErr clas n) | n <- dm_bind_names, not (n `elemNameSet` op_names) ] -- Value binding for non class-method (ie no TypeSig) ; sequence_ [ failWithTc (badGenericMethod clas n) | (n,_) <- gen_dm_prs, not (n `elem` dm_bind_names) ] -- Generic signature without value binding ; traceTc "tcClassSigs 2" (ppr clas) ; return (op_info, gen_dm_env) } where vanilla_sigs = [L loc (nm,ty) | L loc (TypeSig nm ty _) <- sigs] gen_sigs = [L loc (nm,ty) | L loc (GenericSig nm ty) <- sigs] dm_bind_names :: [Name] -- These ones have a value binding in the class decl dm_bind_names = [op | L _ (FunBind {fun_id = L _ op}) <- bagToList def_methods] tc_sig genop_env (op_names, op_hs_ty) = do { traceTc "ClsSig 1" (ppr op_names) ; op_ty <- tcClassSigType op_hs_ty -- Class tyvars already in scope ; traceTc "ClsSig 2" (ppr op_names) ; return [ (op_name, f op_name, op_ty) | L _ op_name <- op_names ] } where f nm | nm `elemNameEnv` genop_env = GenericDM | nm `elem` dm_bind_names = VanillaDM | otherwise = NoDM tc_gen_sig (op_names, gen_hs_ty) = do { gen_op_ty <- tcClassSigType gen_hs_ty ; return [ (op_name, gen_op_ty) | L _ op_name <- op_names ] } {- ************************************************************************ * * Class Declarations * * ************************************************************************ -} tcClassDecl2 :: LTyClDecl Name -- The class declaration -> TcM (LHsBinds Id) tcClassDecl2 (L loc (ClassDecl {tcdLName = class_name, tcdSigs = sigs, tcdMeths = default_binds})) = recoverM (return emptyLHsBinds) $ setSrcSpan loc $ do { clas <- tcLookupLocatedClass class_name -- We make a separate binding for each default method. -- At one time I used a single AbsBinds for all of them, thus -- AbsBind [d] [dm1, dm2, dm3] { dm1 = ...; dm2 = ...; dm3 = ... } -- But that desugars into -- ds = \d -> (..., ..., ...) -- dm1 = \d -> case ds d of (a,b,c) -> a -- And since ds is big, it doesn't get inlined, so we don't get good -- default methods. Better to make separate AbsBinds for each ; let (tyvars, _, _, op_items) = classBigSig clas prag_fn = mkPragEnv sigs default_binds sig_fn = mkHsSigFun sigs clas_tyvars = snd (tcSuperSkolTyVars tyvars) pred = mkClassPred clas (mkTyVarTys clas_tyvars) ; this_dict <- newEvVar pred ; let tc_item (sel_id, dm_info) = case dm_info of DefMeth dm_name -> tc_dm sel_id dm_name False GenDefMeth dm_name -> tc_dm sel_id dm_name True -- For GenDefMeth, warn if the user specifies a signature -- with redundant constraints; but not for DefMeth, where -- the default method may well be 'error' or something NoDefMeth -> do { mapM_ (addLocM (badDmPrag sel_id)) (lookupPragEnv prag_fn (idName sel_id)) ; return emptyBag } tc_dm = tcDefMeth clas clas_tyvars this_dict default_binds sig_fn prag_fn ; dm_binds <- tcExtendTyVarEnv clas_tyvars $ mapM tc_item op_items ; return (unionManyBags dm_binds) } tcClassDecl2 d = pprPanic "tcClassDecl2" (ppr d) tcDefMeth :: Class -> [TyVar] -> EvVar -> LHsBinds Name -> HsSigFun -> TcPragEnv -> Id -> Name -> Bool -> TcM (LHsBinds TcId) -- Generate code for polymorphic default methods only (hence DefMeth) -- (Generic default methods have turned into instance decls by now.) -- This is incompatible with Hugs, which expects a polymorphic -- default method for every class op, regardless of whether or not -- the programmer supplied an explicit default decl for the class. -- (If necessary we can fix that, but we don't have a convenient Id to hand.) tcDefMeth clas tyvars this_dict binds_in hs_sig_fn prag_fn sel_id dm_name warn_redundant | Just (L bind_loc dm_bind, bndr_loc) <- findMethodBind sel_name binds_in -- First look up the default method -- it should be there! = do { global_dm_id <- tcLookupId dm_name ; global_dm_id <- addInlinePrags global_dm_id prags ; local_dm_name <- setSrcSpan bndr_loc (newLocalName sel_name) -- Base the local_dm_name on the selector name, because -- type errors from tcInstanceMethodBody come from here ; spec_prags <- tcSpecPrags global_dm_id prags ; warnTc (not (null spec_prags)) (ptext (sLit "Ignoring SPECIALISE pragmas on default method") <+> quotes (ppr sel_name)) ; let hs_ty = lookupHsSig hs_sig_fn sel_name `orElse` pprPanic "tc_dm" (ppr sel_name) -- We need the HsType so that we can bring the right -- type variables into scope -- -- Eg. class C a where -- op :: forall b. Eq b => a -> [b] -> a -- gen_op :: a -> a -- generic gen_op :: D a => a -> a -- The "local_dm_ty" is precisely the type in the above -- type signatures, ie with no "forall a. C a =>" prefix local_dm_ty = instantiateMethod clas global_dm_id (mkTyVarTys tyvars) lm_bind = dm_bind { fun_id = L bind_loc local_dm_name } -- Substitute the local_meth_name for the binder -- NB: the binding is always a FunBind ctxt = FunSigCtxt sel_name warn_redundant ; local_dm_sig <- instTcTySig ctxt hs_ty local_dm_ty Nothing [] local_dm_name ; (ev_binds, (tc_bind, _)) <- checkConstraints (ClsSkol clas) tyvars [this_dict] $ tcPolyCheck NonRecursive no_prag_fn local_dm_sig (L bind_loc lm_bind) ; let export = ABE { abe_poly = global_dm_id -- We have created a complete type signature in -- instTcTySig, hence it is safe to call -- completeSigPolyId , abe_mono = completeIdSigPolyId local_dm_sig , abe_wrap = idHsWrapper , abe_prags = IsDefaultMethod } full_bind = AbsBinds { abs_tvs = tyvars , abs_ev_vars = [this_dict] , abs_exports = [export] , abs_ev_binds = [ev_binds] , abs_binds = tc_bind } ; return (unitBag (L bind_loc full_bind)) } | otherwise = pprPanic "tcDefMeth" (ppr sel_id) where sel_name = idName sel_id prags = lookupPragEnv prag_fn sel_name no_prag_fn = emptyPragEnv -- No pragmas for local_meth_id; -- they are all for meth_id --------------- tcClassMinimalDef :: Name -> [LSig Name] -> [TcMethInfo] -> TcM ClassMinimalDef tcClassMinimalDef _clas sigs op_info = case findMinimalDef sigs of Nothing -> return defMindef Just mindef -> do -- Warn if the given mindef does not imply the default one -- That is, the given mindef should at least ensure that the -- class ops without default methods are required, since we -- have no way to fill them in otherwise whenIsJust (isUnsatisfied (mindef `impliesAtom`) defMindef) $ (\bf -> addWarnTc (warningMinimalDefIncomplete bf)) return mindef where -- By default require all methods without a default -- implementation whose names don't start with '_' defMindef :: ClassMinimalDef defMindef = mkAnd [ mkVar name | (name, NoDM, _) <- op_info , not (startsWithUnderscore (getOccName name)) ] instantiateMethod :: Class -> Id -> [TcType] -> TcType -- Take a class operation, say -- op :: forall ab. C a => forall c. Ix c => (b,c) -> a -- Instantiate it at [ty1,ty2] -- Return the "local method type": -- forall c. Ix x => (ty2,c) -> ty1 instantiateMethod clas sel_id inst_tys = ASSERT( ok_first_pred ) local_meth_ty where (sel_tyvars,sel_rho) = tcSplitForAllTys (idType sel_id) rho_ty = ASSERT( length sel_tyvars == length inst_tys ) substTyWith sel_tyvars inst_tys sel_rho (first_pred, local_meth_ty) = tcSplitPredFunTy_maybe rho_ty `orElse` pprPanic "tcInstanceMethod" (ppr sel_id) ok_first_pred = case getClassPredTys_maybe first_pred of Just (clas1, _tys) -> clas == clas1 Nothing -> False -- The first predicate should be of form (C a b) -- where C is the class in question --------------------------- type HsSigFun = NameEnv (LHsType Name) emptyHsSigs :: HsSigFun emptyHsSigs = emptyNameEnv mkHsSigFun :: [LSig Name] -> HsSigFun mkHsSigFun sigs = mkNameEnv [(n, hs_ty) | L _ (TypeSig ns hs_ty _) <- sigs , L _ n <- ns ] lookupHsSig :: HsSigFun -> Name -> Maybe (LHsType Name) lookupHsSig = lookupNameEnv --------------------------- findMethodBind :: Name -- Selector name -> LHsBinds Name -- A group of bindings -> Maybe (LHsBind Name, SrcSpan) -- Returns the binding, and the binding -- site of the method binder findMethodBind sel_name binds = foldlBag mplus Nothing (mapBag f binds) where f bind@(L _ (FunBind { fun_id = L bndr_loc op_name })) | op_name == sel_name = Just (bind, bndr_loc) f _other = Nothing --------------------------- findMinimalDef :: [LSig Name] -> Maybe ClassMinimalDef findMinimalDef = firstJusts . map toMinimalDef where toMinimalDef :: LSig Name -> Maybe ClassMinimalDef toMinimalDef (L _ (MinimalSig _ bf)) = Just (fmap unLoc bf) toMinimalDef _ = Nothing {- Note [Polymorphic methods] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider class Foo a where op :: forall b. Ord b => a -> b -> b -> b instance Foo c => Foo [c] where op = e When typechecking the binding 'op = e', we'll have a meth_id for op whose type is op :: forall c. Foo c => forall b. Ord b => [c] -> b -> b -> b So tcPolyBinds must be capable of dealing with nested polytypes; and so it is. See TcBinds.tcMonoBinds (with type-sig case). Note [Silly default-method bind] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ When we pass the default method binding to the type checker, it must look like op2 = e not $dmop2 = e otherwise the "$dm" stuff comes out error messages. But we want the "$dm" to come out in the interface file. So we typecheck the former, and wrap it in a let, thus $dmop2 = let op2 = e in op2 This makes the error messages right. ************************************************************************ * * Error messages * * ************************************************************************ -} tcMkDeclCtxt :: TyClDecl Name -> SDoc tcMkDeclCtxt decl = hsep [ptext (sLit "In the"), pprTyClDeclFlavour decl, ptext (sLit "declaration for"), quotes (ppr (tcdName decl))] tcAddDeclCtxt :: TyClDecl Name -> TcM a -> TcM a tcAddDeclCtxt decl thing_inside = addErrCtxt (tcMkDeclCtxt decl) thing_inside badMethodErr :: Outputable a => a -> Name -> SDoc badMethodErr clas op = hsep [ptext (sLit "Class"), quotes (ppr clas), ptext (sLit "does not have a method"), quotes (ppr op)] badGenericMethod :: Outputable a => a -> Name -> SDoc badGenericMethod clas op = hsep [ptext (sLit "Class"), quotes (ppr clas), ptext (sLit "has a generic-default signature without a binding"), quotes (ppr op)] {- badGenericInstanceType :: LHsBinds Name -> SDoc badGenericInstanceType binds = vcat [ptext (sLit "Illegal type pattern in the generic bindings"), nest 2 (ppr binds)] missingGenericInstances :: [Name] -> SDoc missingGenericInstances missing = ptext (sLit "Missing type patterns for") <+> pprQuotedList missing dupGenericInsts :: [(TyCon, InstInfo a)] -> SDoc dupGenericInsts tc_inst_infos = vcat [ptext (sLit "More than one type pattern for a single generic type constructor:"), nest 2 (vcat (map ppr_inst_ty tc_inst_infos)), ptext (sLit "All the type patterns for a generic type constructor must be identical") ] where ppr_inst_ty (_,inst) = ppr (simpleInstInfoTy inst) -} badDmPrag :: Id -> Sig Name -> TcM () badDmPrag sel_id prag = addErrTc (ptext (sLit "The") <+> hsSigDoc prag <+> ptext (sLit "for default method") <+> quotes (ppr sel_id) <+> ptext (sLit "lacks an accompanying binding")) warningMinimalDefIncomplete :: ClassMinimalDef -> SDoc warningMinimalDefIncomplete mindef = vcat [ ptext (sLit "The MINIMAL pragma does not require:") , nest 2 (pprBooleanFormulaNice mindef) , ptext (sLit "but there is no default implementation.") ] tcATDefault :: Bool -- If a warning should be emitted when a default instance -- definition is not provided by the user -> SrcSpan -> TvSubst -> NameSet -> ClassATItem -> TcM [FamInst] -- ^ Construct default instances for any associated types that -- aren't given a user definition -- Returns [] or singleton tcATDefault emit_warn loc inst_subst defined_ats (ATI fam_tc defs) -- User supplied instances ==> everything is OK | tyConName fam_tc `elemNameSet` defined_ats = return [] -- No user instance, have defaults ==> instatiate them -- Example: class C a where { type F a b :: *; type F a b = () } -- instance C [x] -- Then we want to generate the decl: type F [x] b = () | Just (rhs_ty, _loc) <- defs = do { let (subst', pat_tys') = mapAccumL subst_tv inst_subst (tyConTyVars fam_tc) rhs' = substTy subst' rhs_ty tv_set' = tyVarsOfTypes pat_tys' tvs' = varSetElemsKvsFirst tv_set' ; rep_tc_name <- newFamInstTyConName (L loc (tyConName fam_tc)) pat_tys' ; let axiom = mkSingleCoAxiom Nominal rep_tc_name tvs' fam_tc pat_tys' rhs' -- NB: no validity check. We check validity of default instances -- in the class definition. Because type instance arguments cannot -- be type family applications and cannot be polytypes, the -- validity check is redundant. ; traceTc "mk_deflt_at_instance" (vcat [ ppr fam_tc, ppr rhs_ty , pprCoAxiom axiom ]) ; fam_inst <- ASSERT( tyVarsOfType rhs' `subVarSet` tv_set' ) newFamInst SynFamilyInst axiom ; return [fam_inst] } -- No defaults ==> generate a warning | otherwise -- defs = Nothing = do { when emit_warn $ warnMissingAT (tyConName fam_tc) ; return [] } where subst_tv subst tc_tv | Just ty <- lookupVarEnv (getTvSubstEnv subst) tc_tv = (subst, ty) | otherwise = (extendTvSubst subst tc_tv ty', ty') where ty' = mkTyVarTy (updateTyVarKind (substTy subst) tc_tv) warnMissingAT :: Name -> TcM () warnMissingAT name = do { warn <- woptM Opt_WarnMissingMethods ; traceTc "warn" (ppr name <+> ppr warn) ; warnTc warn -- Warn only if -fwarn-missing-methods (ptext (sLit "No explicit") <+> text "associated type" <+> ptext (sLit "or default declaration for ") <+> quotes (ppr name)) }
ml9951/ghc
compiler/typecheck/TcClassDcl.hs
bsd-3-clause
19,570
0
20
6,343
3,377
1,769
1,608
248
3
{-# LANGUAGE Unsafe #-} {-# LANGUAGE MagicHash, UnboxedTuples #-} ----------------------------------------------------------------------------- -- | -- Module : Debug.Trace -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- Functions for tracing and monitoring execution. -- -- These can be useful for investigating bugs or performance problems. -- They should /not/ be used in production code. -- ----------------------------------------------------------------------------- module Debug.Trace ( -- * Tracing -- $tracing trace, traceId, traceShow, traceShowId, traceStack, traceIO, traceM, traceShowM, putTraceMsg, -- * Eventlog tracing -- $eventlog_tracing traceEvent, traceEventIO, -- * Execution phase markers -- $markers traceMarker, traceMarkerIO, ) where import Prelude import System.IO.Unsafe import Control.Monad import Foreign.C.String import GHC.Base import qualified GHC.Foreign import GHC.IO.Encoding import GHC.Ptr import GHC.Stack import Data.List -- $tracing -- -- The 'trace', 'traceShow' and 'traceIO' functions print messages to an output -- stream. They are intended for \"printf debugging\", that is: tracing the flow -- of execution and printing interesting values. -- The usual output stream is 'System.IO.stderr'. For Windows GUI applications -- (that have no stderr) the output is directed to the Windows debug console. -- Some implementations of these functions may decorate the string that\'s -- output to indicate that you\'re tracing. -- | The 'traceIO' function outputs the trace message from the IO monad. -- This sequences the output with respect to other IO actions. -- -- /Since: 4.5.0.0/ traceIO :: String -> IO () traceIO msg = do withCString "%s\n" $ \cfmt -> do -- NB: debugBelch can't deal with null bytes, so filter them -- out so we don't accidentally truncate the message. See Trac #9395 let (nulls, msg') = partition (=='\0') msg withCString msg' $ \cmsg -> debugBelch cfmt cmsg when (not (null nulls)) $ withCString "WARNING: previous trace message had null bytes" $ \cmsg -> debugBelch cfmt cmsg -- don't use debugBelch() directly, because we cannot call varargs functions -- using the FFI. foreign import ccall unsafe "HsBase.h debugBelch2" debugBelch :: CString -> CString -> IO () -- | putTraceMsg :: String -> IO () putTraceMsg = traceIO {-# DEPRECATED putTraceMsg "Use 'Debug.Trace.traceIO'" #-} -- deprecated in 7.4 {-# NOINLINE trace #-} {-| The 'trace' function outputs the trace message given as its first argument, before returning the second argument as its result. For example, this returns the value of @f x@ but first outputs the message. > trace ("calling f with x = " ++ show x) (f x) The 'trace' function should /only/ be used for debugging, or for monitoring execution. The function is not referentially transparent: its type indicates that it is a pure function but it has the side effect of outputting the trace message. -} trace :: String -> a -> a trace string expr = unsafePerformIO $ do traceIO string return expr {-| Like 'trace' but returns the message instead of a third value. /Since: 4.7.0.0/ -} traceId :: String -> String traceId a = trace a a {-| Like 'trace', but uses 'show' on the argument to convert it to a 'String'. This makes it convenient for printing the values of interesting variables or expressions inside a function. For example here we print the value of the variables @x@ and @z@: > f x y = > traceShow (x, z) $ result > where > z = ... > ... -} traceShow :: (Show a) => a -> b -> b traceShow = trace . show {-| Like 'traceShow' but returns the shown value instead of a third value. /Since: 4.7.0.0/ -} traceShowId :: (Show a) => a -> a traceShowId a = trace (show a) a {-| Like 'trace' but returning unit in an arbitrary monad. Allows for convenient use in do-notation. Note that the application of 'trace' is not an action in the monad, as 'traceIO' is in the 'IO' monad. > ... = do > x <- ... > traceM $ "x: " ++ show x > y <- ... > traceM $ "y: " ++ show y /Since: 4.7.0.0/ -} traceM :: (Monad m) => String -> m () traceM string = trace string $ return () {-| Like 'traceM', but uses 'show' on the argument to convert it to a 'String'. > ... = do > x <- ... > traceMShow $ x > y <- ... > traceMShow $ x + y /Since: 4.7.0.0/ -} traceShowM :: (Show a, Monad m) => a -> m () traceShowM = traceM . show -- | like 'trace', but additionally prints a call stack if one is -- available. -- -- In the current GHC implementation, the call stack is only -- availble if the program was compiled with @-prof@; otherwise -- 'traceStack' behaves exactly like 'trace'. Entries in the call -- stack correspond to @SCC@ annotations, so it is a good idea to use -- @-fprof-auto@ or @-fprof-auto-calls@ to add SCC annotations automatically. -- -- /Since: 4.5.0.0/ traceStack :: String -> a -> a traceStack str expr = unsafePerformIO $ do traceIO str stack <- currentCallStack when (not (null stack)) $ traceIO (renderStack stack) return expr -- $eventlog_tracing -- -- Eventlog tracing is a performance profiling system. These functions emit -- extra events into the eventlog. In combination with eventlog profiling -- tools these functions can be used for monitoring execution and -- investigating performance problems. -- -- Currently only GHC provides eventlog profiling, see the GHC user guide for -- details on how to use it. These function exists for other Haskell -- implementations but no events are emitted. Note that the string message is -- always evaluated, whether or not profiling is available or enabled. {-# NOINLINE traceEvent #-} -- | The 'traceEvent' function behaves like 'trace' with the difference that -- the message is emitted to the eventlog, if eventlog profiling is available -- and enabled at runtime. -- -- It is suitable for use in pure code. In an IO context use 'traceEventIO' -- instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to get -- duplicate events emitted if two CPUs simultaneously evaluate the same thunk -- that uses 'traceEvent'. -- -- /Since: 4.5.0.0/ traceEvent :: String -> a -> a traceEvent msg expr = unsafeDupablePerformIO $ do traceEventIO msg return expr -- | The 'traceEventIO' function emits a message to the eventlog, if eventlog -- profiling is available and enabled at runtime. -- -- Compared to 'traceEvent', 'traceEventIO' sequences the event with respect to -- other IO actions. -- -- /Since: 4.5.0.0/ traceEventIO :: String -> IO () traceEventIO msg = GHC.Foreign.withCString utf8 msg $ \(Ptr p) -> IO $ \s -> case traceEvent# p s of s' -> (# s', () #) -- $markers -- -- When looking at a profile for the execution of a program we often want to -- be able to mark certain points or phases in the execution and see that -- visually in the profile. -- For example, a program might have several distinct phases with different -- performance or resource behaviour in each phase. To properly interpret the -- profile graph we really want to see when each phase starts and ends. -- -- Markers let us do this: we can annotate the program to emit a marker at -- an appropriate point during execution and then see that in a profile. -- -- Currently this feature is only supported in GHC by the eventlog tracing -- system, but in future it may also be supported by the heap profiling or -- other profiling tools. These function exists for other Haskell -- implementations but they have no effect. Note that the string message is -- always evaluated, whether or not profiling is available or enabled. {-# NOINLINE traceMarker #-} -- | The 'traceMarker' function emits a marker to the eventlog, if eventlog -- profiling is available and enabled at runtime. The @String@ is the name of -- the marker. The name is just used in the profiling tools to help you keep -- clear which marker is which. -- -- This function is suitable for use in pure code. In an IO context use -- 'traceMarkerIO' instead. -- -- Note that when using GHC's SMP runtime, it is possible (but rare) to get -- duplicate events emitted if two CPUs simultaneously evaluate the same thunk -- that uses 'traceMarker'. -- -- /Since: 4.7.0.0/ traceMarker :: String -> a -> a traceMarker msg expr = unsafeDupablePerformIO $ do traceMarkerIO msg return expr -- | The 'traceMarkerIO' function emits a marker to the eventlog, if eventlog -- profiling is available and enabled at runtime. -- -- Compared to 'traceMarker', 'traceMarkerIO' sequences the event with respect to -- other IO actions. -- -- /Since: 4.7.0.0/ traceMarkerIO :: String -> IO () traceMarkerIO msg = GHC.Foreign.withCString utf8 msg $ \(Ptr p) -> IO $ \s -> case traceMarker# p s of s' -> (# s', () #)
lukexi/ghc
libraries/base/Debug/Trace.hs
bsd-3-clause
9,104
0
17
1,845
914
532
382
79
1
{-# LANGUAGE Haskell98 #-} {-# LINE 1 "Data/Text/Encoding.hs" #-} {-# LANGUAGE BangPatterns, CPP, ForeignFunctionInterface, GeneralizedNewtypeDeriving, MagicHash, UnliftedFFITypes #-} {-# LANGUAGE Trustworthy #-} -- | -- Module : Data.Text.Encoding -- Copyright : (c) 2009, 2010, 2011 Bryan O'Sullivan, -- (c) 2009 Duncan Coutts, -- (c) 2008, 2009 Tom Harper -- -- License : BSD-style -- Maintainer : [email protected] -- Stability : experimental -- Portability : portable -- -- Functions for converting 'Text' values to and from 'ByteString', -- using several standard encodings. -- -- To gain access to a much larger family of encodings, use the -- @text-icu@ package: <http://hackage.haskell.org/package/text-icu> module Data.Text.Encoding ( -- * Decoding ByteStrings to Text -- $strict decodeASCII , decodeLatin1 , decodeUtf8 , decodeUtf16LE , decodeUtf16BE , decodeUtf32LE , decodeUtf32BE -- ** Catchable failure , decodeUtf8' -- ** Controllable error handling , decodeUtf8With , decodeUtf16LEWith , decodeUtf16BEWith , decodeUtf32LEWith , decodeUtf32BEWith -- ** Stream oriented decoding -- $stream , streamDecodeUtf8 , streamDecodeUtf8With , Decoding(..) -- * Encoding Text to ByteStrings , encodeUtf8 , encodeUtf16LE , encodeUtf16BE , encodeUtf32LE , encodeUtf32BE -- * Encoding Text using ByteString Builders , encodeUtf8Builder , encodeUtf8BuilderEscaped ) where import Control.Monad.ST.Unsafe (unsafeIOToST, unsafeSTToIO) import Control.Exception (evaluate, try) import Control.Monad.ST (runST) import Data.Bits ((.&.)) import Data.ByteString as B import Data.ByteString.Internal as B hiding (c2w) import Data.Text.Encoding.Error (OnDecodeError, UnicodeException, strictDecode) import Data.Text.Internal (Text(..), safe, text) import Data.Text.Internal.Private (runText) import Data.Text.Internal.Unsafe.Char (ord, unsafeWrite) import Data.Text.Internal.Unsafe.Shift (shiftR) import Data.Text.Show () import Data.Text.Unsafe (unsafeDupablePerformIO) import Data.Word (Word8, Word32) import Foreign.C.Types (CSize(..)) import Foreign.ForeignPtr (withForeignPtr) import Foreign.Marshal.Utils (with) import Foreign.Ptr (Ptr, minusPtr, nullPtr, plusPtr) import Foreign.Storable (Storable, peek, poke) import GHC.Base (ByteArray#, MutableByteArray#) import qualified Data.ByteString.Builder as B import qualified Data.ByteString.Builder.Internal as B hiding (empty, append) import qualified Data.ByteString.Builder.Prim as BP import qualified Data.ByteString.Builder.Prim.Internal as BP import qualified Data.Text.Array as A import qualified Data.Text.Internal.Encoding.Fusion as E import qualified Data.Text.Internal.Encoding.Utf16 as U16 import qualified Data.Text.Internal.Fusion as F -- $strict -- -- All of the single-parameter functions for decoding bytestrings -- encoded in one of the Unicode Transformation Formats (UTF) operate -- in a /strict/ mode: each will throw an exception if given invalid -- input. -- -- Each function has a variant, whose name is suffixed with -'With', -- that gives greater control over the handling of decoding errors. -- For instance, 'decodeUtf8' will throw an exception, but -- 'decodeUtf8With' allows the programmer to determine what to do on a -- decoding error. -- | /Deprecated/. Decode a 'ByteString' containing 7-bit ASCII -- encoded text. decodeASCII :: ByteString -> Text decodeASCII = decodeUtf8 {-# DEPRECATED decodeASCII "Use decodeUtf8 instead" #-} -- | Decode a 'ByteString' containing Latin-1 (aka ISO-8859-1) encoded text. -- -- 'decodeLatin1' is semantically equivalent to -- @Data.Text.pack . Data.ByteString.Char8.unpack@ decodeLatin1 :: ByteString -> Text decodeLatin1 (PS fp off len) = text a 0 len where a = A.run (A.new len >>= unsafeIOToST . go) go dest = withForeignPtr fp $ \ptr -> do c_decode_latin1 (A.maBA dest) (ptr `plusPtr` off) (ptr `plusPtr` (off+len)) return dest -- | Decode a 'ByteString' containing UTF-8 encoded text. decodeUtf8With :: OnDecodeError -> ByteString -> Text decodeUtf8With onErr (PS fp off len) = runText $ \done -> do let go dest = withForeignPtr fp $ \ptr -> with (0::CSize) $ \destOffPtr -> do let end = ptr `plusPtr` (off + len) loop curPtr = do curPtr' <- c_decode_utf8 (A.maBA dest) destOffPtr curPtr end if curPtr' == end then do n <- peek destOffPtr unsafeSTToIO (done dest (fromIntegral n)) else do x <- peek curPtr' case onErr desc (Just x) of Nothing -> loop $ curPtr' `plusPtr` 1 Just c -> do destOff <- peek destOffPtr w <- unsafeSTToIO $ unsafeWrite dest (fromIntegral destOff) (safe c) poke destOffPtr (destOff + fromIntegral w) loop $ curPtr' `plusPtr` 1 loop (ptr `plusPtr` off) (unsafeIOToST . go) =<< A.new len where desc = "Data.Text.Internal.Encoding.decodeUtf8: Invalid UTF-8 stream" {- INLINE[0] decodeUtf8With #-} -- $stream -- -- The 'streamDecodeUtf8' and 'streamDecodeUtf8With' functions accept -- a 'ByteString' that represents a possibly incomplete input (e.g. a -- packet from a network stream) that may not end on a UTF-8 boundary. -- -- 1. The maximal prefix of 'Text' that could be decoded from the -- given input. -- -- 2. The suffix of the 'ByteString' that could not be decoded due to -- insufficient input. -- -- 3. A function that accepts another 'ByteString'. That string will -- be assumed to directly follow the string that was passed as -- input to the original function, and it will in turn be decoded. -- -- To help understand the use of these functions, consider the Unicode -- string @\"hi &#9731;\"@. If encoded as UTF-8, this becomes @\"hi -- \\xe2\\x98\\x83\"@; the final @\'&#9731;\'@ is encoded as 3 bytes. -- -- Now suppose that we receive this encoded string as 3 packets that -- are split up on untidy boundaries: @[\"hi \\xe2\", \"\\x98\", -- \"\\x83\"]@. We cannot decode the entire Unicode string until we -- have received all three packets, but we would like to make progress -- as we receive each one. -- -- @ -- ghci> let s0\@('Some' _ _ f0) = 'streamDecodeUtf8' \"hi \\xe2\" -- ghci> s0 -- 'Some' \"hi \" \"\\xe2\" _ -- @ -- -- We use the continuation @f0@ to decode our second packet. -- -- @ -- ghci> let s1\@('Some' _ _ f1) = f0 \"\\x98\" -- ghci> s1 -- 'Some' \"\" \"\\xe2\\x98\" -- @ -- -- We could not give @f0@ enough input to decode anything, so it -- returned an empty string. Once we feed our second continuation @f1@ -- the last byte of input, it will make progress. -- -- @ -- ghci> let s2\@('Some' _ _ f2) = f1 \"\\x83\" -- ghci> s2 -- 'Some' \"\\x2603\" \"\" _ -- @ -- -- If given invalid input, an exception will be thrown by the function -- or continuation where it is encountered. -- | A stream oriented decoding result. data Decoding = Some Text ByteString (ByteString -> Decoding) instance Show Decoding where showsPrec d (Some t bs _) = showParen (d > prec) $ showString "Some " . showsPrec prec' t . showChar ' ' . showsPrec prec' bs . showString " _" where prec = 10; prec' = prec + 1 newtype CodePoint = CodePoint Word32 deriving (Eq, Show, Num, Storable) newtype DecoderState = DecoderState Word32 deriving (Eq, Show, Num, Storable) -- | Decode, in a stream oriented way, a 'ByteString' containing UTF-8 -- encoded text that is known to be valid. -- -- If the input contains any invalid UTF-8 data, an exception will be -- thrown (either by this function or a continuation) that cannot be -- caught in pure code. For more control over the handling of invalid -- data, use 'streamDecodeUtf8With'. streamDecodeUtf8 :: ByteString -> Decoding streamDecodeUtf8 = streamDecodeUtf8With strictDecode -- | Decode, in a stream oriented way, a 'ByteString' containing UTF-8 -- encoded text. streamDecodeUtf8With :: OnDecodeError -> ByteString -> Decoding streamDecodeUtf8With onErr = decodeChunk B.empty 0 0 where -- We create a slightly larger than necessary buffer to accommodate a -- potential surrogate pair started in the last buffer decodeChunk :: ByteString -> CodePoint -> DecoderState -> ByteString -> Decoding decodeChunk undecoded0 codepoint0 state0 bs@(PS fp off len) = runST $ (unsafeIOToST . decodeChunkToBuffer) =<< A.new (len+1) where decodeChunkToBuffer :: A.MArray s -> IO Decoding decodeChunkToBuffer dest = withForeignPtr fp $ \ptr -> with (0::CSize) $ \destOffPtr -> with codepoint0 $ \codepointPtr -> with state0 $ \statePtr -> with nullPtr $ \curPtrPtr -> let end = ptr `plusPtr` (off + len) loop curPtr = do poke curPtrPtr curPtr curPtr' <- c_decode_utf8_with_state (A.maBA dest) destOffPtr curPtrPtr end codepointPtr statePtr state <- peek statePtr case state of 12 -> do -- We encountered an encoding error x <- peek curPtr' poke statePtr 0 case onErr desc (Just x) of Nothing -> loop $ curPtr' `plusPtr` 1 Just c -> do destOff <- peek destOffPtr w <- unsafeSTToIO $ unsafeWrite dest (fromIntegral destOff) (safe c) poke destOffPtr (destOff + fromIntegral w) loop $ curPtr' `plusPtr` 1 _ -> do -- We encountered the end of the buffer while decoding n <- peek destOffPtr codepoint <- peek codepointPtr chunkText <- unsafeSTToIO $ do arr <- A.unsafeFreeze dest return $! text arr 0 (fromIntegral n) lastPtr <- peek curPtrPtr let left = lastPtr `minusPtr` curPtr !undecoded = case state of 0 -> B.empty _ -> B.append undecoded0 (B.drop left bs) return $ Some chunkText undecoded (decodeChunk undecoded codepoint state) in loop (ptr `plusPtr` off) desc = "Data.Text.Internal.Encoding.streamDecodeUtf8With: Invalid UTF-8 stream" -- | Decode a 'ByteString' containing UTF-8 encoded text that is known -- to be valid. -- -- If the input contains any invalid UTF-8 data, an exception will be -- thrown that cannot be caught in pure code. For more control over -- the handling of invalid data, use 'decodeUtf8'' or -- 'decodeUtf8With'. decodeUtf8 :: ByteString -> Text decodeUtf8 = decodeUtf8With strictDecode {-# INLINE[0] decodeUtf8 #-} {-# RULES "STREAM stream/decodeUtf8 fusion" [1] forall bs. F.stream (decodeUtf8 bs) = E.streamUtf8 strictDecode bs #-} -- | Decode a 'ByteString' containing UTF-8 encoded text. -- -- If the input contains any invalid UTF-8 data, the relevant -- exception will be returned, otherwise the decoded text. decodeUtf8' :: ByteString -> Either UnicodeException Text decodeUtf8' = unsafeDupablePerformIO . try . evaluate . decodeUtf8With strictDecode {-# INLINE decodeUtf8' #-} -- | Encode text to a ByteString 'B.Builder' using UTF-8 encoding. encodeUtf8Builder :: Text -> B.Builder encodeUtf8Builder = encodeUtf8BuilderEscaped (BP.liftFixedToBounded BP.word8) -- | Encode text using UTF-8 encoding and escape the ASCII characters using -- a 'BP.BoundedPrim'. -- -- Use this function is to implement efficient encoders for text-based formats -- like JSON or HTML. {-# INLINE encodeUtf8BuilderEscaped #-} -- TODO: Extend documentation with references to source code in @blaze-html@ -- or @aeson@ that uses this function. encodeUtf8BuilderEscaped :: BP.BoundedPrim Word8 -> Text -> B.Builder encodeUtf8BuilderEscaped be = -- manual eta-expansion to ensure inlining works as expected \txt -> B.builder (mkBuildstep txt) where bound = max 4 $ BP.sizeBound be mkBuildstep (Text arr off len) !k = outerLoop off where iend = off + len outerLoop !i0 !br@(B.BufferRange op0 ope) | i0 >= iend = k br | outRemaining > 0 = goPartial (i0 + min outRemaining inpRemaining) -- TODO: Use a loop with an integrated bound's check if outRemaining -- is smaller than 8, as this will save on divisions. | otherwise = return $ B.bufferFull bound op0 (outerLoop i0) where outRemaining = (ope `minusPtr` op0) `div` bound inpRemaining = iend - i0 goPartial !iendTmp = go i0 op0 where go !i !op | i < iendTmp = case A.unsafeIndex arr i of w | w <= 0x7F -> do BP.runB be (fromIntegral w) op >>= go (i + 1) | w <= 0x7FF -> do poke8 0 $ (w `shiftR` 6) + 0xC0 poke8 1 $ (w .&. 0x3f) + 0x80 go (i + 1) (op `plusPtr` 2) | 0xD800 <= w && w <= 0xDBFF -> do let c = ord $ U16.chr2 w (A.unsafeIndex arr (i+1)) poke8 0 $ (c `shiftR` 18) + 0xF0 poke8 1 $ ((c `shiftR` 12) .&. 0x3F) + 0x80 poke8 2 $ ((c `shiftR` 6) .&. 0x3F) + 0x80 poke8 3 $ (c .&. 0x3F) + 0x80 go (i + 2) (op `plusPtr` 4) | otherwise -> do poke8 0 $ (w `shiftR` 12) + 0xE0 poke8 1 $ ((w `shiftR` 6) .&. 0x3F) + 0x80 poke8 2 $ (w .&. 0x3F) + 0x80 go (i + 1) (op `plusPtr` 3) | otherwise = outerLoop i (B.BufferRange op ope) where poke8 j v = poke (op `plusPtr` j) (fromIntegral v :: Word8) -- | Encode text using UTF-8 encoding. encodeUtf8 :: Text -> ByteString encodeUtf8 (Text arr off len) | len == 0 = B.empty | otherwise = unsafeDupablePerformIO $ do fp <- mallocByteString (len*4) withForeignPtr fp $ \ptr -> with ptr $ \destPtr -> do c_encode_utf8 destPtr (A.aBA arr) (fromIntegral off) (fromIntegral len) newDest <- peek destPtr let utf8len = newDest `minusPtr` ptr if utf8len >= len `shiftR` 1 then return (PS fp 0 utf8len) else do fp' <- mallocByteString utf8len withForeignPtr fp' $ \ptr' -> do memcpy ptr' ptr (fromIntegral utf8len) return (PS fp' 0 utf8len) -- | Decode text from little endian UTF-16 encoding. decodeUtf16LEWith :: OnDecodeError -> ByteString -> Text decodeUtf16LEWith onErr bs = F.unstream (E.streamUtf16LE onErr bs) {-# INLINE decodeUtf16LEWith #-} -- | Decode text from little endian UTF-16 encoding. -- -- If the input contains any invalid little endian UTF-16 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf16LEWith'. decodeUtf16LE :: ByteString -> Text decodeUtf16LE = decodeUtf16LEWith strictDecode {-# INLINE decodeUtf16LE #-} -- | Decode text from big endian UTF-16 encoding. decodeUtf16BEWith :: OnDecodeError -> ByteString -> Text decodeUtf16BEWith onErr bs = F.unstream (E.streamUtf16BE onErr bs) {-# INLINE decodeUtf16BEWith #-} -- | Decode text from big endian UTF-16 encoding. -- -- If the input contains any invalid big endian UTF-16 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf16BEWith'. decodeUtf16BE :: ByteString -> Text decodeUtf16BE = decodeUtf16BEWith strictDecode {-# INLINE decodeUtf16BE #-} -- | Encode text using little endian UTF-16 encoding. encodeUtf16LE :: Text -> ByteString encodeUtf16LE txt = E.unstream (E.restreamUtf16LE (F.stream txt)) {-# INLINE encodeUtf16LE #-} -- | Encode text using big endian UTF-16 encoding. encodeUtf16BE :: Text -> ByteString encodeUtf16BE txt = E.unstream (E.restreamUtf16BE (F.stream txt)) {-# INLINE encodeUtf16BE #-} -- | Decode text from little endian UTF-32 encoding. decodeUtf32LEWith :: OnDecodeError -> ByteString -> Text decodeUtf32LEWith onErr bs = F.unstream (E.streamUtf32LE onErr bs) {-# INLINE decodeUtf32LEWith #-} -- | Decode text from little endian UTF-32 encoding. -- -- If the input contains any invalid little endian UTF-32 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf32LEWith'. decodeUtf32LE :: ByteString -> Text decodeUtf32LE = decodeUtf32LEWith strictDecode {-# INLINE decodeUtf32LE #-} -- | Decode text from big endian UTF-32 encoding. decodeUtf32BEWith :: OnDecodeError -> ByteString -> Text decodeUtf32BEWith onErr bs = F.unstream (E.streamUtf32BE onErr bs) {-# INLINE decodeUtf32BEWith #-} -- | Decode text from big endian UTF-32 encoding. -- -- If the input contains any invalid big endian UTF-32 data, an -- exception will be thrown. For more control over the handling of -- invalid data, use 'decodeUtf32BEWith'. decodeUtf32BE :: ByteString -> Text decodeUtf32BE = decodeUtf32BEWith strictDecode {-# INLINE decodeUtf32BE #-} -- | Encode text using little endian UTF-32 encoding. encodeUtf32LE :: Text -> ByteString encodeUtf32LE txt = E.unstream (E.restreamUtf32LE (F.stream txt)) {-# INLINE encodeUtf32LE #-} -- | Encode text using big endian UTF-32 encoding. encodeUtf32BE :: Text -> ByteString encodeUtf32BE txt = E.unstream (E.restreamUtf32BE (F.stream txt)) {-# INLINE encodeUtf32BE #-} foreign import ccall unsafe "_hs_text_decode_utf8" c_decode_utf8 :: MutableByteArray# s -> Ptr CSize -> Ptr Word8 -> Ptr Word8 -> IO (Ptr Word8) foreign import ccall unsafe "_hs_text_decode_utf8_state" c_decode_utf8_with_state :: MutableByteArray# s -> Ptr CSize -> Ptr (Ptr Word8) -> Ptr Word8 -> Ptr CodePoint -> Ptr DecoderState -> IO (Ptr Word8) foreign import ccall unsafe "_hs_text_decode_latin1" c_decode_latin1 :: MutableByteArray# s -> Ptr Word8 -> Ptr Word8 -> IO () foreign import ccall unsafe "_hs_text_encode_utf8" c_encode_utf8 :: Ptr (Ptr Word8) -> ByteArray# -> CSize -> CSize -> IO ()
phischu/fragnix
tests/packages/scotty/Data.Text.Encoding.hs
bsd-3-clause
18,760
0
39
4,932
3,556
1,931
1,625
259
4
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1998 Desugaring foreign declarations (see also DsCCall). -} {-# LANGUAGE CPP #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module DsForeign ( dsForeigns ) where #include "HsVersions.h" import GhcPrelude import TcRnMonad -- temp import CoreSyn import DsCCall import DsMonad import HsSyn import DataCon import CoreUnfold import Id import Literal import Module import Name import Type import RepType import TyCon import Coercion import TcEnv import TcType import CmmExpr import CmmUtils import HscTypes import ForeignCall import TysWiredIn import TysPrim import PrelNames import BasicTypes import SrcLoc import Outputable import FastString import DynFlags import Platform import Config import OrdList import Pair import Util import Hooks import Encoding import Data.Maybe import Data.List {- Desugaring of @foreign@ declarations is naturally split up into parts, an @import@ and an @export@ part. A @foreign import@ declaration \begin{verbatim} foreign import cc nm f :: prim_args -> IO prim_res \end{verbatim} is the same as \begin{verbatim} f :: prim_args -> IO prim_res f a1 ... an = _ccall_ nm cc a1 ... an \end{verbatim} so we reuse the desugaring code in @DsCCall@ to deal with these. -} type Binding = (Id, CoreExpr) -- No rec/nonrec structure; -- the occurrence analyser will sort it all out dsForeigns :: [LForeignDecl GhcTc] -> DsM (ForeignStubs, OrdList Binding) dsForeigns fos = getHooked dsForeignsHook dsForeigns' >>= ($ fos) dsForeigns' :: [LForeignDecl GhcTc] -> DsM (ForeignStubs, OrdList Binding) dsForeigns' [] = return (NoStubs, nilOL) dsForeigns' fos = do fives <- mapM do_ldecl fos let (hs, cs, idss, bindss) = unzip4 fives fe_ids = concat idss fe_init_code = map foreignExportInitialiser fe_ids -- return (ForeignStubs (vcat hs) (vcat cs $$ vcat fe_init_code), foldr (appOL . toOL) nilOL bindss) where do_ldecl (L loc decl) = putSrcSpanDs loc (do_decl decl) do_decl (ForeignImport { fd_name = id, fd_co = co, fd_fi = spec }) = do traceIf (text "fi start" <+> ppr id) let id' = unLoc id (bs, h, c) <- dsFImport id' co spec traceIf (text "fi end" <+> ppr id) return (h, c, [], bs) do_decl (ForeignExport { fd_name = L _ id, fd_co = co , fd_fe = CExport (L _ (CExportStatic _ ext_nm cconv)) _ }) = do (h, c, _, _) <- dsFExport id co ext_nm cconv False return (h, c, [id], []) {- ************************************************************************ * * \subsection{Foreign import} * * ************************************************************************ Desugaring foreign imports is just the matter of creating a binding that on its RHS unboxes its arguments, performs the external call (using the @CCallOp@ primop), before boxing the result up and returning it. However, we create a worker/wrapper pair, thus: foreign import f :: Int -> IO Int ==> f x = IO ( \s -> case x of { I# x# -> case fw s x# of { (# s1, y# #) -> (# s1, I# y# #)}}) fw s x# = ccall f s x# The strictness/CPR analyser won't do this automatically because it doesn't look inside returned tuples; but inlining this wrapper is a Really Good Idea because it exposes the boxing to the call site. -} dsFImport :: Id -> Coercion -> ForeignImport -> DsM ([Binding], SDoc, SDoc) dsFImport id co (CImport cconv safety mHeader spec _) = dsCImport id co spec (unLoc cconv) (unLoc safety) mHeader dsCImport :: Id -> Coercion -> CImportSpec -> CCallConv -> Safety -> Maybe Header -> DsM ([Binding], SDoc, SDoc) dsCImport id co (CLabel cid) cconv _ _ = do dflags <- getDynFlags let ty = pFst $ coercionKind co fod = case tyConAppTyCon_maybe (dropForAlls ty) of Just tycon | tyConUnique tycon == funPtrTyConKey -> IsFunction _ -> IsData (resTy, foRhs) <- resultWrapper ty ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this let rhs = foRhs (Lit (MachLabel cid stdcall_info fod)) rhs' = Cast rhs co stdcall_info = fun_type_arg_stdcall_info dflags cconv ty in return ([(id, rhs')], empty, empty) dsCImport id co (CFunction target) cconv@PrimCallConv safety _ = dsPrimCall id co (CCall (CCallSpec target cconv safety)) dsCImport id co (CFunction target) cconv safety mHeader = dsFCall id co (CCall (CCallSpec target cconv safety)) mHeader dsCImport id co CWrapper cconv _ _ = dsFExportDynamic id co cconv -- For stdcall labels, if the type was a FunPtr or newtype thereof, -- then we need to calculate the size of the arguments in order to add -- the @n suffix to the label. fun_type_arg_stdcall_info :: DynFlags -> CCallConv -> Type -> Maybe Int fun_type_arg_stdcall_info dflags StdCallConv ty | Just (tc,[arg_ty]) <- splitTyConApp_maybe ty, tyConUnique tc == funPtrTyConKey = let (bndrs, _) = tcSplitPiTys arg_ty fe_arg_tys = mapMaybe binderRelevantType_maybe bndrs in Just $ sum (map (widthInBytes . typeWidth . typeCmmType dflags . getPrimTyOf) fe_arg_tys) fun_type_arg_stdcall_info _ _other_conv _ = Nothing {- ************************************************************************ * * \subsection{Foreign calls} * * ************************************************************************ -} dsFCall :: Id -> Coercion -> ForeignCall -> Maybe Header -> DsM ([(Id, Expr TyVar)], SDoc, SDoc) dsFCall fn_id co fcall mDeclHeader = do let ty = pFst $ coercionKind co (tv_bndrs, rho) = tcSplitForAllTyVarBndrs ty (arg_tys, io_res_ty) = tcSplitFunTys rho args <- newSysLocalsDs arg_tys -- no FFI levity-polymorphism (val_args, arg_wrappers) <- mapAndUnzipM unboxArg (map Var args) let work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars (ccall_result_ty, res_wrapper) <- boxResult io_res_ty ccall_uniq <- newUnique work_uniq <- newUnique dflags <- getDynFlags (fcall', cDoc) <- case fcall of CCall (CCallSpec (StaticTarget _ cName mUnitId isFun) CApiConv safety) -> do wrapperName <- mkWrapperName "ghc_wrapper" (unpackFS cName) let fcall' = CCall (CCallSpec (StaticTarget NoSourceText wrapperName mUnitId True) CApiConv safety) c = includes $$ fun_proto <+> braces (cRet <> semi) includes = vcat [ text "#include <" <> ftext h <> text ">" | Header _ h <- nub headers ] fun_proto = cResType <+> pprCconv <+> ppr wrapperName <> parens argTypes cRet | isVoidRes = cCall | otherwise = text "return" <+> cCall cCall = if isFun then ppr cName <> parens argVals else if null arg_tys then ppr cName else panic "dsFCall: Unexpected arguments to FFI value import" raw_res_ty = case tcSplitIOType_maybe io_res_ty of Just (_ioTyCon, res_ty) -> res_ty Nothing -> io_res_ty isVoidRes = raw_res_ty `eqType` unitTy (mHeader, cResType) | isVoidRes = (Nothing, text "void") | otherwise = toCType raw_res_ty pprCconv = ccallConvAttribute CApiConv mHeadersArgTypeList = [ (header, cType <+> char 'a' <> int n) | (t, n) <- zip arg_tys [1..] , let (header, cType) = toCType t ] (mHeaders, argTypeList) = unzip mHeadersArgTypeList argTypes = if null argTypeList then text "void" else hsep $ punctuate comma argTypeList mHeaders' = mDeclHeader : mHeader : mHeaders headers = catMaybes mHeaders' argVals = hsep $ punctuate comma [ char 'a' <> int n | (_, n) <- zip arg_tys [1..] ] return (fcall', c) _ -> return (fcall, empty) let -- Build the worker worker_ty = mkForAllTys tv_bndrs (mkFunTys (map idType work_arg_ids) ccall_result_ty) tvs = map binderVar tv_bndrs the_ccall_app = mkFCall dflags ccall_uniq fcall' val_args ccall_result_ty work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app) work_id = mkSysLocal (fsLit "$wccall") work_uniq worker_ty -- Build the wrapper work_app = mkApps (mkVarApps (Var work_id) tvs) val_args wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers wrap_rhs = mkLams (tvs ++ args) wrapper_body wrap_rhs' = Cast wrap_rhs co fn_id_w_inl = fn_id `setIdUnfolding` mkInlineUnfoldingWithArity (length args) wrap_rhs' return ([(work_id, work_rhs), (fn_id_w_inl, wrap_rhs')], empty, cDoc) {- ************************************************************************ * * \subsection{Primitive calls} * * ************************************************************************ This is for `@foreign import prim@' declarations. Currently, at the core level we pretend that these primitive calls are foreign calls. It may make more sense in future to have them as a distinct kind of Id, or perhaps to bundle them with PrimOps since semantically and for calling convention they are really prim ops. -} dsPrimCall :: Id -> Coercion -> ForeignCall -> DsM ([(Id, Expr TyVar)], SDoc, SDoc) dsPrimCall fn_id co fcall = do let ty = pFst $ coercionKind co (tvs, fun_ty) = tcSplitForAllTys ty (arg_tys, io_res_ty) = tcSplitFunTys fun_ty args <- newSysLocalsDs arg_tys -- no FFI levity-polymorphism ccall_uniq <- newUnique dflags <- getDynFlags let call_app = mkFCall dflags ccall_uniq fcall (map Var args) io_res_ty rhs = mkLams tvs (mkLams args call_app) rhs' = Cast rhs co return ([(fn_id, rhs')], empty, empty) {- ************************************************************************ * * \subsection{Foreign export} * * ************************************************************************ The function that does most of the work for `@foreign export@' declarations. (see below for the boilerplate code a `@foreign export@' declaration expands into.) For each `@foreign export foo@' in a module M we generate: \begin{itemize} \item a C function `@foo@', which calls \item a Haskell stub `@M.\$ffoo@', which calls \end{itemize} the user-written Haskell function `@M.foo@'. -} dsFExport :: Id -- Either the exported Id, -- or the foreign-export-dynamic constructor -> Coercion -- Coercion between the Haskell type callable -- from C, and its representation type -> CLabelString -- The name to export to C land -> CCallConv -> Bool -- True => foreign export dynamic -- so invoke IO action that's hanging off -- the first argument's stable pointer -> DsM ( SDoc -- contents of Module_stub.h , SDoc -- contents of Module_stub.c , String -- string describing type to pass to createAdj. , Int -- size of args to stub function ) dsFExport fn_id co ext_name cconv isDyn = do let ty = pSnd $ coercionKind co (bndrs, orig_res_ty) = tcSplitPiTys ty fe_arg_tys' = mapMaybe binderRelevantType_maybe bndrs -- We must use tcSplits here, because we want to see -- the (IO t) in the corner of the type! fe_arg_tys | isDyn = tail fe_arg_tys' | otherwise = fe_arg_tys' -- Look at the result type of the exported function, orig_res_ty -- If it's IO t, return (t, True) -- If it's plain t, return (t, False) (res_ty, is_IO_res_ty) = case tcSplitIOType_maybe orig_res_ty of -- The function already returns IO t Just (_ioTyCon, res_ty) -> (res_ty, True) -- The function returns t Nothing -> (orig_res_ty, False) dflags <- getDynFlags return $ mkFExportCBits dflags ext_name (if isDyn then Nothing else Just fn_id) fe_arg_tys res_ty is_IO_res_ty cconv {- @foreign import "wrapper"@ (previously "foreign export dynamic") lets you dress up Haskell IO actions of some fixed type behind an externally callable interface (i.e., as a C function pointer). Useful for callbacks and stuff. \begin{verbatim} type Fun = Bool -> Int -> IO Int foreign import "wrapper" f :: Fun -> IO (FunPtr Fun) -- Haskell-visible constructor, which is generated from the above: -- SUP: No check for NULL from createAdjustor anymore??? f :: Fun -> IO (FunPtr Fun) f cback = bindIO (newStablePtr cback) (\StablePtr sp# -> IO (\s1# -> case _ccall_ createAdjustor cconv sp# ``f_helper'' <arg info> s1# of (# s2#, a# #) -> (# s2#, A# a# #))) foreign import "&f_helper" f_helper :: FunPtr (StablePtr Fun -> Fun) -- and the helper in C: (approximately; see `mkFExportCBits` below) f_helper(StablePtr s, HsBool b, HsInt i) { Capability *cap; cap = rts_lock(); rts_evalIO(&cap, rts_apply(rts_apply(deRefStablePtr(s), rts_mkBool(b)), rts_mkInt(i))); rts_unlock(cap); } \end{verbatim} -} dsFExportDynamic :: Id -> Coercion -> CCallConv -> DsM ([Binding], SDoc, SDoc) dsFExportDynamic id co0 cconv = do mod <- getModule dflags <- getDynFlags let fe_nm = mkFastString $ zEncodeString (moduleStableString mod ++ "$" ++ toCName dflags id) -- Construct the label based on the passed id, don't use names -- depending on Unique. See #13807 and Note [Unique Determinism]. cback <- newSysLocalDs arg_ty newStablePtrId <- dsLookupGlobalId newStablePtrName stable_ptr_tycon <- dsLookupTyCon stablePtrTyConName let stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty] export_ty = mkFunTy stable_ptr_ty arg_ty bindIOId <- dsLookupGlobalId bindIOName stbl_value <- newSysLocalDs stable_ptr_ty (h_code, c_code, typestring, args_size) <- dsFExport id (mkRepReflCo export_ty) fe_nm cconv True let {- The arguments to the external function which will create a little bit of (template) code on the fly for allowing the (stable pointed) Haskell closure to be entered using an external calling convention (stdcall, ccall). -} adj_args = [ mkIntLitInt dflags (ccallConvToInt cconv) , Var stbl_value , Lit (MachLabel fe_nm mb_sz_args IsFunction) , Lit (mkMachString typestring) ] -- name of external entry point providing these services. -- (probably in the RTS.) adjustor = fsLit "createAdjustor" -- Determine the number of bytes of arguments to the stub function, -- so that we can attach the '@N' suffix to its label if it is a -- stdcall on Windows. mb_sz_args = case cconv of StdCallConv -> Just args_size _ -> Nothing ccall_adj <- dsCCall adjustor adj_args PlayRisky (mkTyConApp io_tc [res_ty]) -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback let io_app = mkLams tvs $ Lam cback $ mkApps (Var bindIOId) [ Type stable_ptr_ty , Type res_ty , mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ] , Lam stbl_value ccall_adj ] fed = (id `setInlineActivation` NeverActive, Cast io_app co0) -- Never inline the f.e.d. function, because the litlit -- might not be in scope in other modules. return ([fed], h_code, c_code) where ty = pFst (coercionKind co0) (tvs,sans_foralls) = tcSplitForAllTys ty ([arg_ty], fn_res_ty) = tcSplitFunTys sans_foralls Just (io_tc, res_ty) = tcSplitIOType_maybe fn_res_ty -- Must have an IO type; hence Just toCName :: DynFlags -> Id -> String toCName dflags i = showSDoc dflags (pprCode CStyle (ppr (idName i))) {- * \subsection{Generating @foreign export@ stubs} * For each @foreign export@ function, a C stub function is generated. The C stub constructs the application of the exported Haskell function using the hugs/ghc rts invocation API. -} mkFExportCBits :: DynFlags -> FastString -> Maybe Id -- Just==static, Nothing==dynamic -> [Type] -> Type -> Bool -- True <=> returns an IO type -> CCallConv -> (SDoc, SDoc, String, -- the argument reps Int -- total size of arguments ) mkFExportCBits dflags c_nm maybe_target arg_htys res_hty is_IO_res_ty cc = (header_bits, c_bits, type_string, sum [ widthInBytes (typeWidth rep) | (_,_,_,rep) <- aug_arg_info] -- all the args -- NB. the calculation here isn't strictly speaking correct. -- We have a primitive Haskell type (eg. Int#, Double#), and -- we want to know the size, when passed on the C stack, of -- the associated C type (eg. HsInt, HsDouble). We don't have -- this information to hand, but we know what GHC's conventions -- are for passing around the primitive Haskell types, so we -- use that instead. I hope the two coincide --SDM ) where -- list the arguments to the C function arg_info :: [(SDoc, -- arg name SDoc, -- C type Type, -- Haskell type CmmType)] -- the CmmType arg_info = [ let stg_type = showStgType ty in (arg_cname n stg_type, stg_type, ty, typeCmmType dflags (getPrimTyOf ty)) | (ty,n) <- zip arg_htys [1::Int ..] ] arg_cname n stg_ty | libffi = char '*' <> parens (stg_ty <> char '*') <> text "args" <> brackets (int (n-1)) | otherwise = text ('a':show n) -- generate a libffi-style stub if this is a "wrapper" and libffi is enabled libffi = cLibFFI && isNothing maybe_target type_string -- libffi needs to know the result type too: | libffi = primTyDescChar dflags res_hty : arg_type_string | otherwise = arg_type_string arg_type_string = [primTyDescChar dflags ty | (_,_,ty,_) <- arg_info] -- just the real args -- add some auxiliary args; the stable ptr in the wrapper case, and -- a slot for the dummy return address in the wrapper + ccall case aug_arg_info | isNothing maybe_target = stable_ptr_arg : insertRetAddr dflags cc arg_info | otherwise = arg_info stable_ptr_arg = (text "the_stableptr", text "StgStablePtr", undefined, typeCmmType dflags (mkStablePtrPrimTy alphaTy)) -- stuff to do with the return type of the C function res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes cResType | res_hty_is_unit = text "void" | otherwise = showStgType res_hty -- when the return type is integral and word-sized or smaller, it -- must be assigned as type ffi_arg (#3516). To see what type -- libffi is expecting here, take a look in its own testsuite, e.g. -- libffi/testsuite/libffi.call/cls_align_ulonglong.c ffi_cResType | is_ffi_arg_type = text "ffi_arg" | otherwise = cResType where res_ty_key = getUnique (getName (typeTyCon res_hty)) is_ffi_arg_type = res_ty_key `notElem` [floatTyConKey, doubleTyConKey, int64TyConKey, word64TyConKey] -- Now we can cook up the prototype for the exported function. pprCconv = ccallConvAttribute cc header_bits = text "extern" <+> fun_proto <> semi fun_args | null aug_arg_info = text "void" | otherwise = hsep $ punctuate comma $ map (\(nm,ty,_,_) -> ty <+> nm) aug_arg_info fun_proto | libffi = text "void" <+> ftext c_nm <> parens (text "void *cif STG_UNUSED, void* resp, void** args, void* the_stableptr") | otherwise = cResType <+> pprCconv <+> ftext c_nm <> parens fun_args -- the target which will form the root of what we ask rts_evalIO to run the_cfun = case maybe_target of Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)" Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure" cap = text "cap" <> comma -- the expression we give to rts_evalIO expr_to_run = foldl appArg the_cfun arg_info -- NOT aug_arg_info where appArg acc (arg_cname, _, arg_hty, _) = text "rts_apply" <> parens (cap <> acc <> comma <> mkHObj arg_hty <> parens (cap <> arg_cname)) -- various other bits for inside the fn declareResult = text "HaskellObj ret;" declareCResult | res_hty_is_unit = empty | otherwise = cResType <+> text "cret;" assignCResult | res_hty_is_unit = empty | otherwise = text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi -- an extern decl for the fn being called extern_decl = case maybe_target of Nothing -> empty Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi -- finally, the whole darn thing c_bits = space $$ extern_decl $$ fun_proto $$ vcat [ lbrace , text "Capability *cap;" , declareResult , declareCResult , text "cap = rts_lock();" -- create the application + perform it. , text "rts_evalIO" <> parens ( char '&' <> cap <> text "rts_apply" <> parens ( cap <> text "(HaskellObj)" <> ptext (if is_IO_res_ty then (sLit "runIO_closure") else (sLit "runNonIO_closure")) <> comma <> expr_to_run ) <+> comma <> text "&ret" ) <> semi , text "rts_checkSchedStatus" <> parens (doubleQuotes (ftext c_nm) <> comma <> text "cap") <> semi , assignCResult , text "rts_unlock(cap);" , ppUnless res_hty_is_unit $ if libffi then char '*' <> parens (ffi_cResType <> char '*') <> text "resp = cret;" else text "return cret;" , rbrace ] foreignExportInitialiser :: Id -> SDoc foreignExportInitialiser hs_fn = -- Initialise foreign exports by registering a stable pointer from an -- __attribute__((constructor)) function. -- The alternative is to do this from stginit functions generated in -- codeGen/CodeGen.hs; however, stginit functions have a negative impact -- on binary sizes and link times because the static linker will think that -- all modules that are imported directly or indirectly are actually used by -- the program. -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL) vcat [ text "static void stginit_export_" <> ppr hs_fn <> text "() __attribute__((constructor));" , text "static void stginit_export_" <> ppr hs_fn <> text "()" , braces (text "foreignExportStablePtr" <> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure") <> semi) ] mkHObj :: Type -> SDoc mkHObj t = text "rts_mk" <> text (showFFIType t) unpackHObj :: Type -> SDoc unpackHObj t = text "rts_get" <> text (showFFIType t) showStgType :: Type -> SDoc showStgType t = text "Hs" <> text (showFFIType t) showFFIType :: Type -> String showFFIType t = getOccString (getName (typeTyCon t)) toCType :: Type -> (Maybe Header, SDoc) toCType = f False where f voidOK t -- First, if we have (Ptr t) of (FunPtr t), then we need to -- convert t to a C type and put a * after it. If we don't -- know a type for t, then "void" is fine, though. | Just (ptr, [t']) <- splitTyConApp_maybe t , tyConName ptr `elem` [ptrTyConName, funPtrTyConName] = case f True t' of (mh, cType') -> (mh, cType' <> char '*') -- Otherwise, if we have a type constructor application, then -- see if there is a C type associated with that constructor. -- Note that we aren't looking through type synonyms or -- anything, as it may be the synonym that is annotated. | Just tycon <- tyConAppTyConPicky_maybe t , Just (CType _ mHeader (_,cType)) <- tyConCType_maybe tycon = (mHeader, ftext cType) -- If we don't know a C type for this type, then try looking -- through one layer of type synonym etc. | Just t' <- coreView t = f voidOK t' -- This may be an 'UnliftedFFITypes'-style ByteArray# argument -- (which is marshalled like a Ptr) | Just byteArrayPrimTyCon == tyConAppTyConPicky_maybe t = (Nothing, text "const void*") | Just mutableByteArrayPrimTyCon == tyConAppTyConPicky_maybe t = (Nothing, text "void*") -- Otherwise we don't know the C type. If we are allowing -- void then return that; otherwise something has gone wrong. | voidOK = (Nothing, text "void") | otherwise = pprPanic "toCType" (ppr t) typeTyCon :: Type -> TyCon typeTyCon ty | Just (tc, _) <- tcSplitTyConApp_maybe (unwrapType ty) = tc | otherwise = pprPanic "DsForeign.typeTyCon" (ppr ty) insertRetAddr :: DynFlags -> CCallConv -> [(SDoc, SDoc, Type, CmmType)] -> [(SDoc, SDoc, Type, CmmType)] insertRetAddr dflags CCallConv args = case platformArch platform of ArchX86_64 | platformOS platform == OSMinGW32 -> -- On other Windows x86_64 we insert the return address -- after the 4th argument, because this is the point -- at which we need to flush a register argument to the stack -- (See rts/Adjustor.c for details). let go :: Int -> [(SDoc, SDoc, Type, CmmType)] -> [(SDoc, SDoc, Type, CmmType)] go 4 args = ret_addr_arg dflags : args go n (arg:args) = arg : go (n+1) args go _ [] = [] in go 0 args | otherwise -> -- On other x86_64 platforms we insert the return address -- after the 6th integer argument, because this is the point -- at which we need to flush a register argument to the stack -- (See rts/Adjustor.c for details). let go :: Int -> [(SDoc, SDoc, Type, CmmType)] -> [(SDoc, SDoc, Type, CmmType)] go 6 args = ret_addr_arg dflags : args go n (arg@(_,_,_,rep):args) | cmmEqType_ignoring_ptrhood rep b64 = arg : go (n+1) args | otherwise = arg : go n args go _ [] = [] in go 0 args _ -> ret_addr_arg dflags : args where platform = targetPlatform dflags insertRetAddr _ _ args = args ret_addr_arg :: DynFlags -> (SDoc, SDoc, Type, CmmType) ret_addr_arg dflags = (text "original_return_addr", text "void*", undefined, typeCmmType dflags addrPrimTy) -- This function returns the primitive type associated with the boxed -- type argument to a foreign export (eg. Int ==> Int#). getPrimTyOf :: Type -> UnaryType getPrimTyOf ty | isBoolTy rep_ty = intPrimTy -- Except for Bool, the types we are interested in have a single constructor -- with a single primitive-typed argument (see TcType.legalFEArgTyCon). | otherwise = case splitDataProductType_maybe rep_ty of Just (_, _, data_con, [prim_ty]) -> ASSERT(dataConSourceArity data_con == 1) ASSERT2(isUnliftedType prim_ty, ppr prim_ty) prim_ty _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty) where rep_ty = unwrapType ty -- represent a primitive type as a Char, for building a string that -- described the foreign function type. The types are size-dependent, -- e.g. 'W' is a signed 32-bit integer. primTyDescChar :: DynFlags -> Type -> Char primTyDescChar dflags ty | ty `eqType` unitTy = 'v' | otherwise = case typePrimRep1 (getPrimTyOf ty) of IntRep -> signed_word WordRep -> unsigned_word Int64Rep -> 'L' Word64Rep -> 'l' AddrRep -> 'p' FloatRep -> 'f' DoubleRep -> 'd' _ -> pprPanic "primTyDescChar" (ppr ty) where (signed_word, unsigned_word) | wORD_SIZE dflags == 4 = ('W','w') | wORD_SIZE dflags == 8 = ('L','l') | otherwise = panic "primTyDescChar"
shlevy/ghc
compiler/deSugar/DsForeign.hs
bsd-3-clause
31,422
0
26
10,716
5,859
3,025
2,834
-1
-1
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-} module Idris.Core.DeepSeq where import Idris.Core.TT import Idris.Core.CaseTree import Idris.Core.Evaluate import Control.DeepSeq instance NFData Name where rnf (UN x1) = rnf x1 `seq` () rnf (NS x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (MN x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf NErased = () rnf (SN x1) = rnf x1 `seq` () rnf (SymRef x1) = rnf x1 `seq` () instance NFData SpecialName where rnf (WhereN x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (WithN x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (InstanceN x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (ParentN x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (MethodN x1) = rnf x1 `seq` () rnf (CaseN x1) = rnf x1 `seq` () rnf (ElimN x1) = rnf x1 `seq` () rnf (InstanceCtorN x1) = rnf x1 `seq` () rnf (MetaN x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData Universe where rnf NullType = () rnf UniqueType = () rnf AllTypes = () instance NFData Raw where rnf (Var x1) = rnf x1 `seq` () rnf (RBind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (RApp x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf RType = () rnf (RUType x1) = rnf x1 `seq` () rnf (RForce x1) = rnf x1 `seq` () rnf (RConstant x1) = x1 `seq` () instance NFData FC where rnf (FC x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf NoFC = () rnf (FileFC f) = rnf f `seq` () instance NFData Provenance where rnf ExpectedType = () rnf InferredVal = () rnf GivenVal = () rnf (SourceTerm x1) = rnf x1 `seq` () rnf (TooManyArgs x1) = rnf x1 `seq` () instance NFData UConstraint where rnf (ULT x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (ULE x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData ConstraintFC where rnf (ConstraintFC x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData Err where rnf (Msg x1) = rnf x1 `seq` () rnf (InternalMsg x1) = rnf x1 `seq` () rnf (CantUnify x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () rnf (InfiniteUnify x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (CantConvert x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (UnifyScope x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (ElaboratingArg x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () rnf (CantInferType x1) = rnf x1 `seq` () rnf (CantMatch x1) = rnf x1 `seq` () rnf (ReflectionError x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (ReflectionFailed x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (CantSolveGoal x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (UniqueError x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (UniqueKindError x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (NotEquality x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (NonFunctionType x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (CantIntroduce x1) = rnf x1 `seq` () rnf (TooManyArguments x1) = rnf x1 `seq` () rnf (WithFnType x1) = rnf x1 `seq` () rnf (NoSuchVariable x1) = rnf x1 `seq` () rnf (NoTypeDecl x1) = rnf x1 `seq` () rnf (NotInjective x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (CantResolve x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (InvalidTCArg x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (CantResolveAlts x1) = rnf x1 `seq` () rnf (NoValidAlts x1) = rnf x1 `seq` () rnf (IncompleteTerm x1) = rnf x1 `seq` () rnf (NoEliminator x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (UniverseError x1 x2 x3 x4 x5) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` () rnf ProgramLineComment = () rnf (Inaccessible x1) = rnf x1 `seq` () rnf (UnknownImplicit x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (NonCollapsiblePostulate x1) = rnf x1 `seq` () rnf (AlreadyDefined x1) = rnf x1 `seq` () rnf (ProofSearchFail x1) = rnf x1 `seq` () rnf (NoRewriting x1) = rnf x1 `seq` () rnf (At x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (Elaborating x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (ProviderError x1) = rnf x1 `seq` () rnf (LoadingFailed x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (ElabScriptDebug x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (ElabScriptStuck x1) = rnf x1 `seq` () instance NFData ErrorReportPart where rnf (TextPart x1) = rnf x1 `seq` () rnf (TermPart x1) = rnf x1 `seq` () rnf (RawPart x1) = rnf x1 `seq` () rnf (NamePart x1) = rnf x1 `seq` () rnf (SubReport x1) = rnf x1 `seq` () instance NFData ImplicitInfo where rnf (Impl x1) = rnf x1 `seq` () instance (NFData b) => NFData (Binder b) where rnf (Lam x1) = rnf x1 `seq` () rnf (Pi x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (Let x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (NLet x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (Hole x1) = rnf x1 `seq` () rnf (GHole x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (Guess x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (PVar x1) = rnf x1 `seq` () rnf (PVTy x1) = rnf x1 `seq` () instance NFData UExp where rnf (UVar x1) = rnf x1 `seq` () rnf (UVal x1) = rnf x1 `seq` () instance NFData NameType where rnf Bound = () rnf Ref = () rnf (DCon x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (TCon x1 x2) = rnf x1 `seq` rnf x2 `seq` () instance NFData NativeTy where rnf IT8 = () rnf IT16 = () rnf IT32 = () rnf IT64 = () instance NFData IntTy where rnf (ITFixed x1) = rnf x1 `seq` () rnf ITNative = () rnf ITBig = () rnf ITChar = () instance NFData ArithTy where rnf (ATInt x1) = rnf x1 `seq` () rnf ATFloat = () instance NFData Const where rnf (I x1) = rnf x1 `seq` () rnf (BI x1) = rnf x1 `seq` () rnf (Fl x1) = rnf x1 `seq` () rnf (Ch x1) = rnf x1 `seq` () rnf (Str x1) = rnf x1 `seq` () rnf (B8 x1) = rnf x1 `seq` () rnf (B16 x1) = rnf x1 `seq` () rnf (B32 x1) = rnf x1 `seq` () rnf (B64 x1) = rnf x1 `seq` () rnf (AType x1) = rnf x1 `seq` () rnf WorldType = () rnf TheWorld = () rnf StrType = () rnf VoidType = () rnf Forgot = () instance (NFData n) => NFData (TT n) where rnf (P x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (V x1) = rnf x1 `seq` () rnf (Bind x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (App x1 x2 x3) = rnf x2 `seq` rnf x3 `seq` () rnf (Constant x1) = rnf x1 `seq` () rnf (Proj x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf Erased = () rnf Impossible = () rnf (TType x1) = rnf x1 `seq` () rnf (UType _) = () instance NFData Accessibility where rnf Public = () rnf Frozen = () rnf Hidden = () instance NFData Totality where rnf (Total x1) = rnf x1 `seq` () rnf Productive = () rnf (Partial x1) = rnf x1 `seq` () rnf Unchecked = () rnf Generated = () instance NFData PReason where rnf (Other x1) = rnf x1 `seq` () rnf Itself = () rnf NotCovering = () rnf NotPositive = () rnf (UseUndef x1) = rnf x1 `seq` () rnf ExternalIO = () rnf BelieveMe = () rnf (Mutual x1) = rnf x1 `seq` () rnf NotProductive = () instance NFData MetaInformation where rnf EmptyMI = () rnf (DataMI x1) = rnf x1 `seq` () instance NFData Def where rnf (Function x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (TyDecl x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (Operator x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () rnf (CaseOp x1 x2 x3 x4 x5 x6) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` rnf x5 `seq` rnf x6 `seq` () instance NFData CaseInfo where rnf (CaseInfo x1 x2 x3) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` () instance NFData CaseDefs where rnf (CaseDefs x1 x2 x3 x4) = rnf x1 `seq` rnf x2 `seq` rnf x3 `seq` rnf x4 `seq` () instance (NFData t) => NFData (SC' t) where rnf (Case _ x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (ProjCase x1 x2) = rnf x1 `seq` rnf x2 `seq` () rnf (STerm x1) = rnf x1 `seq` () rnf (UnmatchedCase x1) = rnf x1 `seq` () rnf ImpossibleCase = () instance (NFData t) => NFData (CaseAlt' t) where rnf (ConCase x1 x2 x3 x4) = x1 `seq` x2 `seq` x3 `seq` rnf x4 `seq` () rnf (FnCase x1 x2 x3) = x1 `seq` x2 `seq` rnf x3 `seq` () rnf (ConstCase x1 x2) = x1 `seq` rnf x2 `seq` () rnf (SucCase x1 x2) = x1 `seq` rnf x2 `seq` () rnf (DefaultCase x1) = rnf x1 `seq` ()
raichoo/Idris-dev
src/Idris/Core/DeepSeq.hs
bsd-3-clause
9,317
0
12
3,168
4,919
2,581
2,338
215
0
{-# LANGUAGE TupleSections #-} ----------------------------------------------------------------------------- -- | -- Module : System.Taffybar.Information.CPU2 -- Copyright : (c) José A. Romero L. -- License : BSD3-style (see LICENSE) -- -- Maintainer : José A. Romero L. <[email protected]> -- Stability : unstable -- Portability : unportable -- -- Provides information about used CPU times, obtained from parsing the -- @\/proc\/stat@ file using some of the facilities included in the -- "System.Taffybar.Information.StreamInfo" module. -- And also provides information about the temperature of cores. -- (Now supports only physical cpu). -- ----------------------------------------------------------------------------- module System.Taffybar.Information.CPU2 where import Control.Monad import Data.List import Data.Maybe import Safe import System.Directory import System.FilePath import System.Taffybar.Information.StreamInfo -- | Returns a list of 5 to 7 elements containing all the values available for -- the given core (or all of them aggregated, if "cpu" is passed). getCPUInfo :: String -> IO [Int] getCPUInfo = getParsedInfo "/proc/stat" parse parse :: String -> [(String, [Int])] parse = mapMaybe (tuplize . words) . filter (\x -> take 3 x == "cpu") . lines tuplize :: [String] -> Maybe (String, [Int]) tuplize s = do cpu <- s `atMay` 0 return (cpu, map (readDef (-1)) (tailSafe s)) -- | Returns a two-element list containing relative system and user times -- calculated using two almost simultaneous samples of the @\/proc\/stat@ file -- for the given core (or all of them aggregated, if \"cpu\" is passed). getCPULoad :: String -> IO [Double] getCPULoad cpu = do load <- getLoad 0.05 $ getCPUInfo cpu case load of l0:l1:l2:_ -> return [ l0 + l1, l2 ] _ -> return [] -- | Get the directory in which core temperature files are kept. getCPUTemperatureDirectory :: IO FilePath getCPUTemperatureDirectory = (baseDir </>) . fromMaybe "hwmon0" . find (isPrefixOf "hwmon") <$> listDirectory baseDir where baseDir = "/" </> "sys" </> "bus" </> "platform" </> "devices" </> "coretemp.0" </> "hwmon" readCPUTempFile :: FilePath -> IO Double readCPUTempFile cpuTempFilePath = (/ 1000) . read <$> readFile cpuTempFilePath getAllTemperatureFiles :: FilePath -> IO [FilePath] getAllTemperatureFiles temperaturesDirectory = filter (liftM2 (&&) (isPrefixOf "temp") (isSuffixOf "input")) <$> listDirectory temperaturesDirectory getCPUTemperatures :: IO [(String, Double)] getCPUTemperatures = do dir <- getCPUTemperatureDirectory let mkPair filename = (filename,) <$> readCPUTempFile (dir </> filename) getAllTemperatureFiles dir >>= mapM mkPair
teleshoes/taffybar
src/System/Taffybar/Information/CPU2.hs
bsd-3-clause
2,733
0
13
452
563
306
257
42
2
{-# LANGUAGE CPP #-} -- | -- Module: Data.Aeson.Internal.Time -- Copyright: (c) 2015-2016 Bryan O'Sullivan -- License: BSD3 -- Maintainer: Bryan O'Sullivan <[email protected]> -- Stability: experimental -- Portability: portable module Data.Aeson.Internal.Time ( TimeOfDay64(..) , fromPico , toPico , diffTimeOfDay64 , toTimeOfDay64 ) where import Data.Attoparsec.Time.Internal
dmjio/aeson
src/Data/Aeson/Internal/Time.hs
bsd-3-clause
425
0
5
92
44
33
11
9
0
module M (T(..), k) where data T = C2 Float Float k = 54
kmate/HaRe
old/testing/removeCon/M_TokOut.hs
bsd-3-clause
61
0
6
18
32
20
12
3
1
module TFFMonad where import Syntax import TypesTerms import Char(chr,ord) -------------------------------------------------------------------------------- -- The monad -- type Env = [(HsName, Term)] type FreshVars = (Int, Int, Int) tvarCtr (x,_,_) = x funCtr (_,x,_) = x valCtr (_,_,x) = x incTvarCtr (x,y,z) = (x+1, y, z) incFunCtr (x,y,z) = (x, y+1, z) incValCtr (x,y,z) = (x, y, z+1) valName fvs = UnQual $ 'x' : show (valCtr fvs) funName fvs = UnQual $ [chr (funCtr fvs + ord 'f')] tvarName fvs = UnQual $ [chr (tvarCtr fvs + ord 'A')] newtype FM a = FM ( (FreshVars, Env) -> (a, FreshVars) ) instance Monad FM where return x = FM (\(fvs, e) -> (x, fvs)) FM f >>= g = FM bind where bind (fvs, e) = let (a, fvs') = f (fvs, e) FM h = g a in h (fvs', e) inExtendedEnv :: HsName -> Term -> FM a -> FM a inExtendedEnv n t (FM f) = FM (\(fvs, e) -> f (fvs, (n, t):e)) lookUp :: HsName -> FM Term lookUp n = FM (\(fvs, e) -> (maybe no id (lookup n e), fvs)) where no = error $ "lookUp: " ++ (show n) ++ " not in environment." newVar :: Type -> FM Term newVar t = FM f where f (fvs, e) = if isFun t then ( (hsEVar (funName fvs) ,t) , incFunCtr fvs ) else ( (hsEVar (valName fvs) ,t) , incValCtr fvs ) newTVar :: FM Type newTVar = FM f where f (fvs, e) = (mkTyVar (tvarName fvs), incTvarCtr fvs) run :: FM a -> a run (FM f) = let (v, _) = f ((0,0,0), []) in v -- --------------------------------------------------------------------------------
forste/haReFork
tools/TFF/TFFMonad.hs
bsd-3-clause
1,623
0
13
461
804
442
362
38
2
{-# LANGUAGE ScopedTypeVariables #-} module Main where import Prelude hiding ( mod, id, mapM ) import GHC --import Packages import HscTypes ( isBootSummary ) import Digraph ( flattenSCCs ) import DriverPhases ( isHaskellSrcFilename ) import HscTypes ( msHsFilePath ) import Name ( getOccString ) --import ErrUtils ( printBagOfErrors ) import Panic ( panic ) import DynFlags ( defaultFatalMessager, defaultFlushOut ) import Bag import Exception import FastString import MonadUtils ( liftIO ) import SrcLoc import Distribution.Simple.GHC ( componentGhcOptions ) import Distribution.Simple.Configure ( getPersistBuildConfig ) import Distribution.Simple.Program.GHC ( renderGhcOptions ) import Distribution.PackageDescription ( libBuildInfo ) import Distribution.Simple.LocalBuildInfo import Distribution.Types.LocalBuildInfo ( componentNameTargets' ) import Distribution.Types.TargetInfo import qualified Distribution.Verbosity as V import Control.Monad hiding (mapM) import System.Environment import System.Console.GetOpt import System.Exit import System.IO import Data.List as List hiding ( group ) import Data.Traversable (mapM) import Data.Map ( Map ) import qualified Data.Map as M --import UniqFM --import Debug.Trace -- search for definitions of things -- we do this by parsing the source and grabbing top-level definitions -- We generate both CTAGS and ETAGS format tags files -- The former is for use in most sensible editors, while EMACS uses ETAGS ---------------------------------- ---- CENTRAL DATA TYPES ---------- type FileName = String type ThingName = String -- name of a defined entity in a Haskell program -- A definition we have found (we know its containing module, name, and location) data FoundThing = FoundThing ModuleName ThingName RealSrcLoc -- Data we have obtained from a file (list of things we found) data FileData = FileData FileName [FoundThing] (Map Int String) --- invariant (not checked): every found thing has a source location in that file? ------------------------------ -------- MAIN PROGRAM -------- main :: IO () main = do progName <- getProgName let usageString = "Usage: " ++ progName ++ " [OPTION...] [-- GHC OPTION... --] [files...]" args <- getArgs let (ghcArgs', ourArgs, unbalanced) = splitArgs args let (flags, filenames, errs) = getOpt Permute options ourArgs let (hsfiles, otherfiles) = List.partition isHaskellSrcFilename filenames let ghc_topdir = case [ d | FlagTopDir d <- flags ] of [] -> "" (x:_) -> x mapM_ (\n -> putStr $ "Warning: ignoring non-Haskellish file " ++ n ++ "\n") otherfiles if unbalanced || errs /= [] || elem FlagHelp flags || hsfiles == [] then do putStr $ unlines errs putStr $ usageInfo usageString options exitWith (ExitFailure 1) else return () ghcArgs <- case [ d | FlagUseCabalConfig d <- flags ] of [distPref] -> do cabalOpts <- flagsFromCabal distPref return (cabalOpts ++ ghcArgs') [] -> return ghcArgs' _ -> error "Too many --use-cabal-config flags" print ghcArgs let modes = getMode flags let openFileMode = if elem FlagAppend flags then AppendMode else WriteMode ctags_hdl <- if CTags `elem` modes then Just `liftM` openFile "tags" openFileMode else return Nothing etags_hdl <- if ETags `elem` modes then Just `liftM` openFile "TAGS" openFileMode else return Nothing GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ runGhc (Just ghc_topdir) $ do --liftIO $ print "starting up session" dflags <- getSessionDynFlags (pflags, unrec, warns) <- parseDynamicFlags dflags{ verbosity=1 } (map noLoc ghcArgs) unless (null unrec) $ liftIO $ putStrLn $ "Unrecognised options:\n" ++ show (map unLoc unrec) liftIO $ mapM_ putStrLn (map unLoc warns) let dflags2 = pflags { hscTarget = HscNothing } -- don't generate anything -- liftIO $ print ("pkgDB", case (pkgDatabase dflags2) of Nothing -> 0 -- Just m -> sizeUFM m) _ <- setSessionDynFlags dflags2 --liftIO $ print (length pkgs) targetsAtOneGo hsfiles (ctags_hdl,etags_hdl) mapM_ (mapM (liftIO . hClose)) [ctags_hdl, etags_hdl] ---------------------------------------------- ---------- ARGUMENT PROCESSING -------------- data Flag = FlagETags | FlagCTags | FlagBoth | FlagAppend | FlagHelp | FlagTopDir FilePath | FlagUseCabalConfig FilePath | FlagFilesFromCabal deriving (Ord, Eq, Show) -- ^Represents options passed to the program data Mode = ETags | CTags deriving Eq getMode :: [Flag] -> [Mode] getMode fs = go (concatMap modeLike fs) where go [] = [ETags,CTags] go [x] = [x] go more = nub more modeLike FlagETags = [ETags] modeLike FlagCTags = [CTags] modeLike FlagBoth = [ETags,CTags] modeLike _ = [] splitArgs :: [String] -> ([String], [String], Bool) -- ^Pull out arguments between -- for GHC splitArgs args0 = split [] [] False args0 where split ghc' tags' unbal ("--" : args) = split tags' ghc' (not unbal) args split ghc' tags' unbal (arg : args) = split ghc' (arg:tags') unbal args split ghc' tags' unbal [] = (reverse ghc', reverse tags', unbal) options :: [OptDescr Flag] -- supports getopt options = [ Option "" ["topdir"] (ReqArg FlagTopDir "DIR") "root of GHC installation (optional)" , Option "c" ["ctags"] (NoArg FlagCTags) "generate CTAGS file (ctags)" , Option "e" ["etags"] (NoArg FlagETags) "generate ETAGS file (etags)" , Option "b" ["both"] (NoArg FlagBoth) ("generate both CTAGS and ETAGS") , Option "a" ["append"] (NoArg FlagAppend) ("append to existing CTAGS and/or ETAGS file(s)") , Option "" ["use-cabal-config"] (ReqArg FlagUseCabalConfig "DIR") "use local cabal configuration from dist dir" , Option "" ["files-from-cabal"] (NoArg FlagFilesFromCabal) "use files from cabal" , Option "h" ["help"] (NoArg FlagHelp) "This help" ] flagsFromCabal :: FilePath -> IO [String] flagsFromCabal distPref = do lbi <- getPersistBuildConfig distPref let pd = localPkgDescr lbi case componentNameTargets' pd lbi CLibName of [target] -> let clbi = targetCLBI target CLib lib = getComponent pd (componentLocalName clbi) bi = libBuildInfo lib odir = buildDir lbi opts = componentGhcOptions V.normal lbi bi clbi odir in return $ renderGhcOptions (compiler lbi) (hostPlatform lbi) opts [] -> error "no library" _ -> error "more libraries than we know how to handle" ---------------------------------------------------------------- --- LOADING HASKELL SOURCE --- (these bits actually run the compiler and produce abstract syntax) safeLoad :: LoadHowMuch -> Ghc SuccessFlag -- like GHC.load, but does not stop process on exception safeLoad mode = do _dflags <- getSessionDynFlags ghandle (\(e :: SomeException) -> liftIO (print e) >> return Failed ) $ handleSourceError (\e -> printException e >> return Failed) $ load mode targetsAtOneGo :: [FileName] -> (Maybe Handle, Maybe Handle) -> Ghc () -- load a list of targets targetsAtOneGo hsfiles handles = do targets <- mapM (\f -> guessTarget f Nothing) hsfiles setTargets targets modgraph <- depanal [] False let mods = flattenSCCs $ topSortModuleGraph False modgraph Nothing graphData mods handles fileTarget :: FileName -> Target fileTarget filename = Target (TargetFile filename Nothing) True Nothing --------------------------------------------------------------- ----- CRAWLING ABSTRACT SYNTAX TO SNAFFLE THE DEFINITIONS ----- graphData :: ModuleGraph -> (Maybe Handle, Maybe Handle) -> Ghc () graphData graph handles = do mapM_ foundthings graph where foundthings ms = let filename = msHsFilePath ms modname = moduleName $ ms_mod ms in handleSourceError (\e -> do printException e liftIO $ exitWith (ExitFailure 1)) $ do liftIO $ putStrLn ("loading " ++ filename) mod <- loadModule =<< typecheckModule =<< parseModule ms case mod of _ | isBootSummary ms -> return () _ | Just s <- renamedSource mod -> liftIO (writeTagsData handles =<< fileData filename modname s) _otherwise -> liftIO $ exitWith (ExitFailure 1) fileData :: FileName -> ModuleName -> RenamedSource -> IO FileData fileData filename modname (group, _imports, _lie, _doc) = do -- lie is related to type checking and so is irrelevant -- imports contains import declarations and no definitions -- doc and haddock seem haddock-related; let's hope to ignore them ls <- lines `fmap` readFile filename let line_map = M.fromAscList $ zip [1..] ls line_map' <- evaluate line_map return $ FileData filename (boundValues modname group) line_map' boundValues :: ModuleName -> HsGroup Name -> [FoundThing] -- ^Finds all the top-level definitions in a module boundValues mod group = let vals = case hs_valds group of ValBindsOut nest _sigs -> [ x | (_rec, binds) <- nest , bind <- bagToList binds , x <- boundThings mod bind ] _other -> error "boundValues" tys = [ n | ns <- map (fst . hsLTyClDeclBinders) (hs_tyclds group >>= group_tyclds) , n <- map found ns ] fors = concat $ map forBound (hs_fords group) where forBound lford = case unLoc lford of ForeignImport n _ _ _ -> [found n] ForeignExport { } -> [] in vals ++ tys ++ fors where found = foundOfLName mod startOfLocated :: Located a -> RealSrcLoc startOfLocated lHs = case getLoc lHs of RealSrcSpan l -> realSrcSpanStart l UnhelpfulSpan _ -> panic "startOfLocated UnhelpfulSpan" foundOfLName :: ModuleName -> Located Name -> FoundThing foundOfLName mod id = FoundThing mod (getOccString $ unLoc id) (startOfLocated id) boundThings :: ModuleName -> LHsBind Name -> [FoundThing] boundThings modname lbinding = case unLoc lbinding of FunBind { fun_id = id } -> [thing id] PatBind { pat_lhs = lhs } -> patThings lhs [] VarBind { var_id = id } -> [FoundThing modname (getOccString id) (startOfLocated lbinding)] AbsBinds { } -> [] -- nothing interesting in a type abstraction AbsBindsSig { } -> [] PatSynBind PSB{ psb_id = id } -> [thing id] where thing = foundOfLName modname patThings lpat tl = let loc = startOfLocated lpat lid id = FoundThing modname (getOccString id) loc in case unLoc lpat of WildPat _ -> tl VarPat (L _ name) -> lid name : tl LazyPat p -> patThings p tl AsPat id p -> patThings p (thing id : tl) ParPat p -> patThings p tl BangPat p -> patThings p tl ListPat ps _ _ -> foldr patThings tl ps TuplePat ps _ _ -> foldr patThings tl ps PArrPat ps _ -> foldr patThings tl ps ConPatIn _ conargs -> conArgs conargs tl ConPatOut{ pat_args = conargs } -> conArgs conargs tl LitPat _ -> tl NPat {} -> tl -- form of literal pattern? NPlusKPat id _ _ _ _ _ -> thing id : tl SigPatIn p _ -> patThings p tl SigPatOut p _ -> patThings p tl _ -> error "boundThings" conArgs (PrefixCon ps) tl = foldr patThings tl ps conArgs (RecCon (HsRecFields { rec_flds = flds })) tl = foldr (\(L _ f) tl' -> patThings (hsRecFieldArg f) tl') tl flds conArgs (InfixCon p1 p2) tl = patThings p1 $ patThings p2 tl -- stuff for dealing with ctags output format writeTagsData :: (Maybe Handle, Maybe Handle) -> FileData -> IO () writeTagsData (mb_ctags_hdl, mb_etags_hdl) fd = do maybe (return ()) (\hdl -> writectagsfile hdl fd) mb_ctags_hdl maybe (return ()) (\hdl -> writeetagsfile hdl fd) mb_etags_hdl writectagsfile :: Handle -> FileData -> IO () writectagsfile ctagsfile filedata = do let things = getfoundthings filedata mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing False x) things mapM_ (\x -> hPutStrLn ctagsfile $ dumpthing True x) things getfoundthings :: FileData -> [FoundThing] getfoundthings (FileData _filename things _src_lines) = things dumpthing :: Bool -> FoundThing -> String dumpthing showmod (FoundThing modname name loc) = fullname ++ "\t" ++ filename ++ "\t" ++ (show line) where line = srcLocLine loc filename = unpackFS $ srcLocFile loc fullname = if showmod then moduleNameString modname ++ "." ++ name else name -- stuff for dealing with etags output format writeetagsfile :: Handle -> FileData -> IO () writeetagsfile etagsfile = hPutStr etagsfile . e_dumpfiledata e_dumpfiledata :: FileData -> String e_dumpfiledata (FileData filename things line_map) = "\x0c\n" ++ filename ++ "," ++ (show thingslength) ++ "\n" ++ thingsdump where thingsdump = concat $ map (e_dumpthing line_map) things thingslength = length thingsdump e_dumpthing :: Map Int String -> FoundThing -> String e_dumpthing src_lines (FoundThing modname name loc) = tagline name ++ tagline (moduleNameString modname ++ "." ++ name) where tagline n = src_code ++ "\x7f" ++ n ++ "\x01" ++ (show line) ++ "," ++ (show $ column) ++ "\n" line = srcLocLine loc column = srcLocCol loc src_code = case M.lookup line src_lines of Just l -> take (column + length name) l Nothing -> --trace (show ("not found: ", moduleNameString modname, name, line, column)) name
olsner/ghc
utils/ghctags/Main.hs
bsd-3-clause
14,654
0
19
4,227
3,908
1,982
1,926
275
24
module ListSort () where import Language.Haskell.Liquid.Prelude split :: [a] -> ([a], [a]) split (x:(y:zs)) = (x:xs, y:ys) where (xs, ys) = split zs split xs = (xs, []) merge :: Ord a => [a] -> [a] -> [a] merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) | x <= y = x:(merge xs (y:ys)) | otherwise = y:(merge (x:xs) ys) {-@ mergesort :: (Ord a) => xs:[a] -> [a]<{\fld v -> (v < fld)}> @-} mergesort :: Ord a => [a] -> [a] mergesort [] = [] mergesort [x] = [x] mergesort xs = merge (mergesort xs1) (mergesort xs2) where (xs1, xs2) = split xs chk [] = liquidAssertB True chk (x1:xs) = case xs of [] -> liquidAssertB True x2:xs2 -> liquidAssertB (x1 <= x2) && chk xs rlist = map choose [1 .. 10] bar = mergesort rlist prop0 = chk bar
abakst/liquidhaskell
tests/neg/ListMSort.hs
bsd-3-clause
824
2
11
238
436
232
204
24
2
module Poly0 () where import Language.Haskell.Liquid.Prelude myabs x = if x `gt` 0 then x else 0 `minus` x myid arg = arg ---------------------------------------------------------- x = choose 0 prop_id1 = let x' = myabs x in let x'' = myid x' in liquidAssertB (x'' `geq` 0) prop_id2 = liquidAssertB (x'' `geq` 0) where x' = myabs x x'' = myid x' prop_id3 = liquidAssertB (x' `geq` 20) where x' = myid $ myabs x
mightymoose/liquidhaskell
tests/neg/poly0.hs
bsd-3-clause
467
0
11
130
170
94
76
13
2
{-# LANGUAGE CPP #-} -- ----------------------------------------------------------------------------- -- -- (c) The University of Glasgow 1994-2004 -- -- ----------------------------------------------------------------------------- module PPC.Regs ( -- squeeze functions virtualRegSqueeze, realRegSqueeze, mkVirtualReg, regDotColor, -- immediates Imm(..), strImmLit, litToImm, -- addressing modes AddrMode(..), addrOffset, -- registers spRel, argRegs, allArgRegs, callClobberedRegs, allMachRegNos, classOfRealReg, showReg, -- machine specific allFPArgRegs, fits16Bits, makeImmediate, fReg, r0, sp, toc, r3, r4, r11, r12, r27, r28, r30, tmpReg, f1, f20, f21, allocatableRegs ) where #include "nativeGen/NCG.h" #include "HsVersions.h" import Reg import RegClass import Format import Cmm import CLabel ( CLabel ) import Unique import CodeGen.Platform import DynFlags import Outputable import Platform import Data.Word ( Word8, Word16, Word32, Word64 ) import Data.Int ( Int8, Int16, Int32, Int64 ) -- squeese functions for the graph allocator ----------------------------------- -- | regSqueeze_class reg -- Calculuate the maximum number of register colors that could be -- denied to a node of this class due to having this reg -- as a neighbour. -- {-# INLINE virtualRegSqueeze #-} virtualRegSqueeze :: RegClass -> VirtualReg -> Int virtualRegSqueeze cls vr = case cls of RcInteger -> case vr of VirtualRegI{} -> 1 VirtualRegHi{} -> 1 _other -> 0 RcDouble -> case vr of VirtualRegD{} -> 1 VirtualRegF{} -> 0 _other -> 0 _other -> 0 {-# INLINE realRegSqueeze #-} realRegSqueeze :: RegClass -> RealReg -> Int realRegSqueeze cls rr = case cls of RcInteger -> case rr of RealRegSingle regNo | regNo < 32 -> 1 -- first fp reg is 32 | otherwise -> 0 RealRegPair{} -> 0 RcDouble -> case rr of RealRegSingle regNo | regNo < 32 -> 0 | otherwise -> 1 RealRegPair{} -> 0 _other -> 0 mkVirtualReg :: Unique -> Format -> VirtualReg mkVirtualReg u format | not (isFloatFormat format) = VirtualRegI u | otherwise = case format of FF32 -> VirtualRegD u FF64 -> VirtualRegD u _ -> panic "mkVirtualReg" regDotColor :: RealReg -> SDoc regDotColor reg = case classOfRealReg reg of RcInteger -> text "blue" RcFloat -> text "red" RcDouble -> text "green" RcDoubleSSE -> text "yellow" -- immediates ------------------------------------------------------------------ data Imm = ImmInt Int | ImmInteger Integer -- Sigh. | ImmCLbl CLabel -- AbstractC Label (with baggage) | ImmLit SDoc -- Simple string | ImmIndex CLabel Int | ImmFloat Rational | ImmDouble Rational | ImmConstantSum Imm Imm | ImmConstantDiff Imm Imm | LO Imm | HI Imm | HA Imm {- high halfword adjusted -} | HIGHERA Imm | HIGHESTA Imm strImmLit :: String -> Imm strImmLit s = ImmLit (text s) litToImm :: CmmLit -> Imm litToImm (CmmInt i w) = ImmInteger (narrowS w i) -- narrow to the width: a CmmInt might be out of -- range, but we assume that ImmInteger only contains -- in-range values. A signed value should be fine here. litToImm (CmmFloat f W32) = ImmFloat f litToImm (CmmFloat f W64) = ImmDouble f litToImm (CmmLabel l) = ImmCLbl l litToImm (CmmLabelOff l off) = ImmIndex l off litToImm (CmmLabelDiffOff l1 l2 off) = ImmConstantSum (ImmConstantDiff (ImmCLbl l1) (ImmCLbl l2)) (ImmInt off) litToImm _ = panic "PPC.Regs.litToImm: no match" -- addressing modes ------------------------------------------------------------ data AddrMode = AddrRegReg Reg Reg | AddrRegImm Reg Imm addrOffset :: AddrMode -> Int -> Maybe AddrMode addrOffset addr off = case addr of AddrRegImm r (ImmInt n) | fits16Bits n2 -> Just (AddrRegImm r (ImmInt n2)) | otherwise -> Nothing where n2 = n + off AddrRegImm r (ImmInteger n) | fits16Bits n2 -> Just (AddrRegImm r (ImmInt (fromInteger n2))) | otherwise -> Nothing where n2 = n + toInteger off _ -> Nothing -- registers ------------------------------------------------------------------- -- @spRel@ gives us a stack relative addressing mode for volatile -- temporaries and for excess call arguments. @fpRel@, where -- applicable, is the same but for the frame pointer. spRel :: DynFlags -> Int -- desired stack offset in words, positive or negative -> AddrMode spRel dflags n = AddrRegImm sp (ImmInt (n * wORD_SIZE dflags)) -- argRegs is the set of regs which are read for an n-argument call to C. -- For archs which pass all args on the stack (x86), is empty. -- Sparc passes up to the first 6 args in regs. argRegs :: RegNo -> [Reg] argRegs 0 = [] argRegs 1 = map regSingle [3] argRegs 2 = map regSingle [3,4] argRegs 3 = map regSingle [3..5] argRegs 4 = map regSingle [3..6] argRegs 5 = map regSingle [3..7] argRegs 6 = map regSingle [3..8] argRegs 7 = map regSingle [3..9] argRegs 8 = map regSingle [3..10] argRegs _ = panic "MachRegs.argRegs(powerpc): don't know about >8 arguments!" allArgRegs :: [Reg] allArgRegs = map regSingle [3..10] -- these are the regs which we cannot assume stay alive over a C call. callClobberedRegs :: Platform -> [Reg] callClobberedRegs platform = case platformOS platform of OSAIX -> map regSingle (0:[2..12] ++ map fReg [0..13]) OSDarwin -> map regSingle (0:[2..12] ++ map fReg [0..13]) OSLinux -> map regSingle (0:[2..13] ++ map fReg [0..13]) _ -> panic "PPC.Regs.callClobberedRegs: not defined for this architecture" allMachRegNos :: [RegNo] allMachRegNos = [0..63] {-# INLINE classOfRealReg #-} classOfRealReg :: RealReg -> RegClass classOfRealReg (RealRegSingle i) | i < 32 = RcInteger | otherwise = RcDouble classOfRealReg (RealRegPair{}) = panic "regClass(ppr): no reg pairs on this architecture" showReg :: RegNo -> String showReg n | n >= 0 && n <= 31 = "%r" ++ show n | n >= 32 && n <= 63 = "%f" ++ show (n - 32) | otherwise = "%unknown_powerpc_real_reg_" ++ show n -- machine specific ------------------------------------------------------------ allFPArgRegs :: Platform -> [Reg] allFPArgRegs platform = case platformOS platform of OSAIX -> map (regSingle . fReg) [1..13] OSDarwin -> map (regSingle . fReg) [1..13] OSLinux -> case platformArch platform of ArchPPC -> map (regSingle . fReg) [1..8] ArchPPC_64 _ -> map (regSingle . fReg) [1..13] _ -> panic "PPC.Regs.allFPArgRegs: unknown PPC Linux" _ -> panic "PPC.Regs.allFPArgRegs: not defined for this architecture" fits16Bits :: Integral a => a -> Bool fits16Bits x = x >= -32768 && x < 32768 makeImmediate :: Integral a => Width -> Bool -> a -> Maybe Imm makeImmediate rep signed x = fmap ImmInt (toI16 rep signed) where narrow W64 False = fromIntegral (fromIntegral x :: Word64) narrow W32 False = fromIntegral (fromIntegral x :: Word32) narrow W16 False = fromIntegral (fromIntegral x :: Word16) narrow W8 False = fromIntegral (fromIntegral x :: Word8) narrow W64 True = fromIntegral (fromIntegral x :: Int64) narrow W32 True = fromIntegral (fromIntegral x :: Int32) narrow W16 True = fromIntegral (fromIntegral x :: Int16) narrow W8 True = fromIntegral (fromIntegral x :: Int8) narrow _ _ = panic "PPC.Regs.narrow: no match" narrowed = narrow rep signed toI16 W32 True | narrowed >= -32768 && narrowed < 32768 = Just narrowed | otherwise = Nothing toI16 W32 False | narrowed >= 0 && narrowed < 65536 = Just narrowed | otherwise = Nothing toI16 W64 True | narrowed >= -32768 && narrowed < 32768 = Just narrowed | otherwise = Nothing toI16 W64 False | narrowed >= 0 && narrowed < 65536 = Just narrowed | otherwise = Nothing toI16 _ _ = Just narrowed {- The PowerPC has 64 registers of interest; 32 integer registers and 32 floating point registers. -} fReg :: Int -> RegNo fReg x = (32 + x) r0, sp, toc, r3, r4, r11, r12, r27, r28, r30, f1, f20, f21 :: Reg r0 = regSingle 0 sp = regSingle 1 toc = regSingle 2 r3 = regSingle 3 r4 = regSingle 4 r11 = regSingle 11 r12 = regSingle 12 r27 = regSingle 27 r28 = regSingle 28 r30 = regSingle 30 f1 = regSingle $ fReg 1 f20 = regSingle $ fReg 20 f21 = regSingle $ fReg 21 -- allocatableRegs is allMachRegNos with the fixed-use regs removed. -- i.e., these are the regs for which we are prepared to allow the -- register allocator to attempt to map VRegs to. allocatableRegs :: Platform -> [RealReg] allocatableRegs platform = let isFree i = freeReg platform i in map RealRegSingle $ filter isFree allMachRegNos -- temporary register for compiler use tmpReg :: Platform -> Reg tmpReg platform = case platformArch platform of ArchPPC -> regSingle 13 ArchPPC_64 _ -> regSingle 30 _ -> panic "PPC.Regs.tmpReg: unknowm arch"
snoyberg/ghc
compiler/nativeGen/PPC/Regs.hs
bsd-3-clause
10,210
0
15
3,235
2,541
1,319
1,222
229
13
{- This module handles generation of position independent code and dynamic-linking related issues for the native code generator. This depends both the architecture and OS, so we define it here instead of in one of the architecture specific modules. Things outside this module which are related to this: + module CLabel - PIC base label (pretty printed as local label 1) - DynamicLinkerLabels - several kinds: CodeStub, SymbolPtr, GotSymbolPtr, GotSymbolOffset - labelDynamic predicate + module Cmm - The GlobalReg datatype has a PicBaseReg constructor - The CmmLit datatype has a CmmLabelDiffOff constructor + codeGen & RTS - When tablesNextToCode, no absolute addresses are stored in info tables any more. Instead, offsets from the info label are used. - For Win32 only, SRTs might contain addresses of __imp_ symbol pointers because Win32 doesn't support external references in data sections. TODO: make sure this still works, it might be bitrotted + NCG - The cmmToCmm pass in AsmCodeGen calls cmmMakeDynamicReference for all labels. - nativeCodeGen calls pprImportedSymbol and pprGotDeclaration to output all the necessary stuff for imported symbols. - The NCG monad keeps track of a list of imported symbols. - MachCodeGen invokes initializePicBase to generate code to initialize the PIC base register when needed. - MachCodeGen calls cmmMakeDynamicReference whenever it uses a CLabel that wasn't in the original Cmm code (e.g. floating point literals). -} module PIC ( cmmMakeDynamicReference, CmmMakeDynamicReferenceM(..), ReferenceKind(..), needImportedSymbols, pprImportedSymbol, pprGotDeclaration, initializePicBase_ppc, initializePicBase_x86 ) where import qualified PPC.Instr as PPC import qualified PPC.Regs as PPC import qualified X86.Instr as X86 import Platform import Instruction import Reg import NCGMonad import Hoopl import Cmm import CLabel ( CLabel, ForeignLabelSource(..), pprCLabel, mkDynamicLinkerLabel, DynamicLinkerLabelInfo(..), dynamicLinkerLabelInfo, mkPicBaseLabel, labelDynamic, externallyVisibleCLabel ) import CLabel ( mkForeignLabel ) import BasicTypes import Module import Outputable import DynFlags import FastString -------------------------------------------------------------------------------- -- It gets called by the cmmToCmm pass for every CmmLabel in the Cmm -- code. It does The Right Thing(tm) to convert the CmmLabel into a -- position-independent, dynamic-linking-aware reference to the thing -- in question. -- Note that this also has to be called from MachCodeGen in order to -- access static data like floating point literals (labels that were -- created after the cmmToCmm pass). -- The function must run in a monad that can keep track of imported symbols -- A function for recording an imported symbol must be passed in: -- - addImportCmmOpt for the CmmOptM monad -- - addImportNat for the NatM monad. data ReferenceKind = DataReference | CallReference | JumpReference deriving(Eq) class Monad m => CmmMakeDynamicReferenceM m where addImport :: CLabel -> m () getThisModule :: m Module instance CmmMakeDynamicReferenceM NatM where addImport = addImportNat getThisModule = getThisModuleNat cmmMakeDynamicReference :: CmmMakeDynamicReferenceM m => DynFlags -> ReferenceKind -- whether this is the target of a jump -> CLabel -- the label -> m CmmExpr cmmMakeDynamicReference dflags referenceKind lbl | Just _ <- dynamicLinkerLabelInfo lbl = return $ CmmLit $ CmmLabel lbl -- already processed it, pass through | otherwise = do this_mod <- getThisModule case howToAccessLabel dflags (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) this_mod referenceKind lbl of AccessViaStub -> do let stub = mkDynamicLinkerLabel CodeStub lbl addImport stub return $ CmmLit $ CmmLabel stub AccessViaSymbolPtr -> do let symbolPtr = mkDynamicLinkerLabel SymbolPtr lbl addImport symbolPtr return $ CmmLoad (cmmMakePicReference dflags symbolPtr) (bWord dflags) AccessDirectly -> case referenceKind of -- for data, we might have to make some calculations: DataReference -> return $ cmmMakePicReference dflags lbl -- all currently supported processors support -- PC-relative branch and call instructions, -- so just jump there if it's a call or a jump _ -> return $ CmmLit $ CmmLabel lbl -- ----------------------------------------------------------------------------- -- Create a position independent reference to a label. -- (but do not bother with dynamic linking). -- We calculate the label's address by adding some (platform-dependent) -- offset to our base register; this offset is calculated by -- the function picRelative in the platform-dependent part below. cmmMakePicReference :: DynFlags -> CLabel -> CmmExpr cmmMakePicReference dflags lbl -- Windows doesn't need PIC, -- everything gets relocated at runtime | OSMinGW32 <- platformOS $ targetPlatform dflags = CmmLit $ CmmLabel lbl -- both ABI versions default to medium code model | ArchPPC_64 _ <- platformArch $ targetPlatform dflags = CmmMachOp (MO_Add W32) -- code model medium [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] | (gopt Opt_PIC dflags || not (gopt Opt_Static dflags)) && absoluteLabel lbl = CmmMachOp (MO_Add (wordWidth dflags)) [ CmmReg (CmmGlobal PicBaseReg) , CmmLit $ picRelative (platformArch $ targetPlatform dflags) (platformOS $ targetPlatform dflags) lbl ] | otherwise = CmmLit $ CmmLabel lbl absoluteLabel :: CLabel -> Bool absoluteLabel lbl = case dynamicLinkerLabelInfo lbl of Just (GotSymbolPtr, _) -> False Just (GotSymbolOffset, _) -> False _ -> True -------------------------------------------------------------------------------- -- Knowledge about how special dynamic linker labels like symbol -- pointers, code stubs and GOT offsets look like is located in the -- module CLabel. -- We have to decide which labels need to be accessed -- indirectly or via a piece of stub code. data LabelAccessStyle = AccessViaStub | AccessViaSymbolPtr | AccessDirectly howToAccessLabel :: DynFlags -> Arch -> OS -> Module -> ReferenceKind -> CLabel -> LabelAccessStyle -- Windows -- In Windows speak, a "module" is a set of objects linked into the -- same Portable Exectuable (PE) file. (both .exe and .dll files are PEs). -- -- If we're compiling a multi-module program then symbols from other modules -- are accessed by a symbol pointer named __imp_SYMBOL. At runtime we have the -- following. -- -- (in the local module) -- __imp_SYMBOL: addr of SYMBOL -- -- (in the other module) -- SYMBOL: the real function / data. -- -- To access the function at SYMBOL from our local module, we just need to -- dereference the local __imp_SYMBOL. -- -- If Opt_Static is set then we assume that all our code will be linked -- into the same .exe file. In this case we always access symbols directly, -- and never use __imp_SYMBOL. -- howToAccessLabel dflags _ OSMinGW32 this_mod _ lbl -- Assume all symbols will be in the same PE, so just access them directly. | gopt Opt_Static dflags = AccessDirectly -- If the target symbol is in another PE we need to access it via the -- appropriate __imp_SYMBOL pointer. | labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaSymbolPtr -- Target symbol is in the same PE as the caller, so just access it directly. | otherwise = AccessDirectly -- Mach-O (Darwin, Mac OS X) -- -- Indirect access is required in the following cases: -- * things imported from a dynamic library -- * (not on x86_64) data from a different module, if we're generating PIC code -- It is always possible to access something indirectly, -- even when it's not necessary. -- howToAccessLabel dflags arch OSDarwin this_mod DataReference lbl -- data access to a dynamic library goes via a symbol pointer | labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaSymbolPtr -- when generating PIC code, all cross-module data references must -- must go via a symbol pointer, too, because the assembler -- cannot generate code for a label difference where one -- label is undefined. Doesn't apply t x86_64. -- Unfortunately, we don't know whether it's cross-module, -- so we do it for all externally visible labels. -- This is a slight waste of time and space, but otherwise -- we'd need to pass the current Module all the way in to -- this function. | arch /= ArchX86_64 , gopt Opt_PIC dflags && externallyVisibleCLabel lbl = AccessViaSymbolPtr | otherwise = AccessDirectly howToAccessLabel dflags arch OSDarwin this_mod JumpReference lbl -- dyld code stubs don't work for tailcalls because the -- stack alignment is only right for regular calls. -- Therefore, we have to go via a symbol pointer: | arch == ArchX86 || arch == ArchX86_64 , labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaSymbolPtr howToAccessLabel dflags arch OSDarwin this_mod _ lbl -- Code stubs are the usual method of choice for imported code; -- not needed on x86_64 because Apple's new linker, ld64, generates -- them automatically. | arch /= ArchX86_64 , labelDynamic dflags (thisPackage dflags) this_mod lbl = AccessViaStub | otherwise = AccessDirectly -- ELF (Linux) -- -- ELF tries to pretend to the main application code that dynamic linking does -- not exist. While this may sound convenient, it tends to mess things up in -- very bad ways, so we have to be careful when we generate code for the main -- program (-dynamic but no -fPIC). -- -- Indirect access is required for references to imported symbols -- from position independent code. It is also required from the main program -- when dynamic libraries containing Haskell code are used. howToAccessLabel _ (ArchPPC_64 _) os _ kind _ | osElfTarget os = case kind of -- ELF PPC64 (powerpc64-linux), AIX, MacOS 9, BeOS/PPC DataReference -> AccessViaSymbolPtr -- RTLD does not generate stubs for function descriptors -- in tail calls. Create a symbol pointer and generate -- the code to load the function descriptor at the call site. JumpReference -> AccessViaSymbolPtr -- regular calls are handled by the runtime linker _ -> AccessDirectly howToAccessLabel dflags _ os _ _ _ -- no PIC -> the dynamic linker does everything for us; -- if we don't dynamically link to Haskell code, -- it actually manages to do so without messing things up. | osElfTarget os , not (gopt Opt_PIC dflags) && gopt Opt_Static dflags = AccessDirectly howToAccessLabel dflags arch os this_mod DataReference lbl | osElfTarget os = case () of -- A dynamic label needs to be accessed via a symbol pointer. _ | labelDynamic dflags (thisPackage dflags) this_mod lbl -> AccessViaSymbolPtr -- For PowerPC32 -fPIC, we have to access even static data -- via a symbol pointer (see below for an explanation why -- PowerPC32 Linux is especially broken). | arch == ArchPPC , gopt Opt_PIC dflags -> AccessViaSymbolPtr | otherwise -> AccessDirectly -- In most cases, we have to avoid symbol stubs on ELF, for the following reasons: -- on i386, the position-independent symbol stubs in the Procedure Linkage Table -- require the address of the GOT to be loaded into register %ebx on entry. -- The linker will take any reference to the symbol stub as a hint that -- the label in question is a code label. When linking executables, this -- will cause the linker to replace even data references to the label with -- references to the symbol stub. -- This leaves calling a (foreign) function from non-PIC code -- (AccessDirectly, because we get an implicit symbol stub) -- and calling functions from PIC code on non-i386 platforms (via a symbol stub) howToAccessLabel dflags arch os this_mod CallReference lbl | osElfTarget os , labelDynamic dflags (thisPackage dflags) this_mod lbl && not (gopt Opt_PIC dflags) = AccessDirectly | osElfTarget os , arch /= ArchX86 , labelDynamic dflags (thisPackage dflags) this_mod lbl && gopt Opt_PIC dflags = AccessViaStub howToAccessLabel dflags _ os this_mod _ lbl | osElfTarget os = if labelDynamic dflags (thisPackage dflags) this_mod lbl then AccessViaSymbolPtr else AccessDirectly -- all other platforms howToAccessLabel dflags _ _ _ _ _ | not (gopt Opt_PIC dflags) = AccessDirectly | otherwise = panic "howToAccessLabel: PIC not defined for this platform" -- ------------------------------------------------------------------- -- | Says what we we have to add to our 'PIC base register' in order to -- get the address of a label. picRelative :: Arch -> OS -> CLabel -> CmmLit -- Darwin, but not x86_64: -- The PIC base register points to the PIC base label at the beginning -- of the current CmmDecl. We just have to use a label difference to -- get the offset. -- We have already made sure that all labels that are not from the current -- module are accessed indirectly ('as' can't calculate differences between -- undefined labels). picRelative arch OSDarwin lbl | arch /= ArchX86_64 = CmmLabelDiffOff lbl mkPicBaseLabel 0 -- PowerPC Linux: -- The PIC base register points to our fake GOT. Use a label difference -- to get the offset. -- We have made sure that *everything* is accessed indirectly, so this -- is only used for offsets from the GOT to symbol pointers inside the -- GOT. picRelative ArchPPC os lbl | osElfTarget os = CmmLabelDiffOff lbl gotLabel 0 -- Most Linux versions: -- The PIC base register points to the GOT. Use foo@got for symbol -- pointers, and foo@gotoff for everything else. -- Linux and Darwin on x86_64: -- The PIC base register is %rip, we use foo@gotpcrel for symbol pointers, -- and a GotSymbolOffset label for other things. -- For reasons of tradition, the symbol offset label is written as a plain label. picRelative arch os lbl | osElfTarget os || (os == OSDarwin && arch == ArchX86_64) = let result | Just (SymbolPtr, lbl') <- dynamicLinkerLabelInfo lbl = CmmLabel $ mkDynamicLinkerLabel GotSymbolPtr lbl' | otherwise = CmmLabel $ mkDynamicLinkerLabel GotSymbolOffset lbl in result picRelative _ _ _ = panic "PositionIndependentCode.picRelative undefined for this platform" -------------------------------------------------------------------------------- needImportedSymbols :: DynFlags -> Arch -> OS -> Bool needImportedSymbols dflags arch os | os == OSDarwin , arch /= ArchX86_64 = True -- PowerPC Linux: -fPIC or -dynamic | osElfTarget os , arch == ArchPPC = gopt Opt_PIC dflags || not (gopt Opt_Static dflags) -- PowerPC 64 Linux: always | osElfTarget os , arch == ArchPPC_64 ELF_V1 || arch == ArchPPC_64 ELF_V2 = True -- i386 (and others?): -dynamic but not -fPIC | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 = not (gopt Opt_Static dflags) && not (gopt Opt_PIC dflags) | otherwise = False -- gotLabel -- The label used to refer to our "fake GOT" from -- position-independent code. gotLabel :: CLabel gotLabel -- HACK: this label isn't really foreign = mkForeignLabel (fsLit ".LCTOC1") Nothing ForeignLabelInThisPackage IsData -------------------------------------------------------------------------------- -- We don't need to declare any offset tables. -- However, for PIC on x86, we need a small helper function. pprGotDeclaration :: DynFlags -> Arch -> OS -> SDoc pprGotDeclaration dflags ArchX86 OSDarwin | gopt Opt_PIC dflags = vcat [ ptext (sLit ".section __TEXT,__textcoal_nt,coalesced,no_toc"), ptext (sLit ".weak_definition ___i686.get_pc_thunk.ax"), ptext (sLit ".private_extern ___i686.get_pc_thunk.ax"), ptext (sLit "___i686.get_pc_thunk.ax:"), ptext (sLit "\tmovl (%esp), %eax"), ptext (sLit "\tret") ] pprGotDeclaration _ _ OSDarwin = empty -- PPC 64 ELF v1needs a Table Of Contents (TOC) on Linux pprGotDeclaration _ (ArchPPC_64 ELF_V1) OSLinux = ptext (sLit ".section \".toc\",\"aw\"") -- In ELF v2 we also need to tell the assembler that we want ABI -- version 2. This would normally be done at the top of the file -- right after a file directive, but I could not figure out how -- to do that. pprGotDeclaration _ (ArchPPC_64 ELF_V2) OSLinux = vcat [ ptext (sLit ".abiversion 2"), ptext (sLit ".section \".toc\",\"aw\"") ] pprGotDeclaration _ (ArchPPC_64 _) _ = panic "pprGotDeclaration: ArchPPC_64 only Linux supported" -- Emit GOT declaration -- Output whatever needs to be output once per .s file. pprGotDeclaration dflags arch os | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 , not (gopt Opt_PIC dflags) = empty | osElfTarget os , arch /= ArchPPC_64 ELF_V1 && arch /= ArchPPC_64 ELF_V2 = vcat [ -- See Note [.LCTOC1 in PPC PIC code] ptext (sLit ".section \".got2\",\"aw\""), ptext (sLit ".LCTOC1 = .+32768") ] pprGotDeclaration _ _ _ = panic "pprGotDeclaration: no match" -------------------------------------------------------------------------------- -- On Darwin, we have to generate our own stub code for lazy binding.. -- For each processor architecture, there are two versions, one for PIC -- and one for non-PIC. -- -- Whenever you change something in this assembler output, make sure -- the splitter in driver/split/ghc-split.lprl recognizes the new output pprImportedSymbol :: DynFlags -> Platform -> CLabel -> SDoc pprImportedSymbol dflags platform@(Platform { platformArch = ArchPPC, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ ptext (sLit ".symbol_stub"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tlis r11,ha16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr)"), ptext (sLit "\tlwz r12,lo16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr)(r11)"), ptext (sLit "\tmtctr r12"), ptext (sLit "\taddi r11,r11,lo16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr)"), ptext (sLit "\tbctr") ] True -> vcat [ ptext (sLit ".section __TEXT,__picsymbolstub1,") <> ptext (sLit "symbol_stubs,pure_instructions,32"), ptext (sLit "\t.align 2"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tmflr r0"), ptext (sLit "\tbcl 20,31,L0$") <> pprCLabel platform lbl, ptext (sLit "L0$") <> pprCLabel platform lbl <> char ':', ptext (sLit "\tmflr r11"), ptext (sLit "\taddis r11,r11,ha16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-L0$") <> pprCLabel platform lbl <> char ')', ptext (sLit "\tmtlr r0"), ptext (sLit "\tlwzu r12,lo16(L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-L0$") <> pprCLabel platform lbl <> ptext (sLit ")(r11)"), ptext (sLit "\tmtctr r12"), ptext (sLit "\tbctr") ] $+$ vcat [ ptext (sLit ".lazy_symbol_pointer"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long dyld_stub_binding_helper")] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ ptext (sLit ".non_lazy_symbol_pointer"), char 'L' <> pprCLabel platform lbl <> ptext (sLit "$non_lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long\t0")] | otherwise = empty pprImportedSymbol dflags platform@(Platform { platformArch = ArchX86, platformOS = OSDarwin }) importedLbl | Just (CodeStub, lbl) <- dynamicLinkerLabelInfo importedLbl = case gopt Opt_PIC dflags of False -> vcat [ ptext (sLit ".symbol_stub"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tjmp *L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub_binder:"), ptext (sLit "\tpushl $L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr"), ptext (sLit "\tjmp dyld_stub_binding_helper") ] True -> vcat [ ptext (sLit ".section __TEXT,__picsymbolstub2,") <> ptext (sLit "symbol_stubs,pure_instructions,25"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\tcall ___i686.get_pc_thunk.ax"), ptext (sLit "1:"), ptext (sLit "\tmovl L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-1b(%eax),%edx"), ptext (sLit "\tjmp *%edx"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$stub_binder:"), ptext (sLit "\tlea L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr-1b(%eax),%eax"), ptext (sLit "\tpushl %eax"), ptext (sLit "\tjmp dyld_stub_binding_helper") ] $+$ vcat [ ptext (sLit ".section __DATA, __la_sym_ptr") <> (if gopt Opt_PIC dflags then int 2 else int 3) <> ptext (sLit ",lazy_symbol_pointers"), ptext (sLit "L") <> pprCLabel platform lbl <> ptext (sLit "$lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long L") <> pprCLabel platform lbl <> ptext (sLit "$stub_binder")] | Just (SymbolPtr, lbl) <- dynamicLinkerLabelInfo importedLbl = vcat [ ptext (sLit ".non_lazy_symbol_pointer"), char 'L' <> pprCLabel platform lbl <> ptext (sLit "$non_lazy_ptr:"), ptext (sLit "\t.indirect_symbol") <+> pprCLabel platform lbl, ptext (sLit "\t.long\t0")] | otherwise = empty pprImportedSymbol _ (Platform { platformOS = OSDarwin }) _ = empty -- ELF / Linux -- -- In theory, we don't need to generate any stubs or symbol pointers -- by hand for Linux. -- -- Reality differs from this in two areas. -- -- 1) If we just use a dynamically imported symbol directly in a read-only -- section of the main executable (as GCC does), ld generates R_*_COPY -- relocations, which are fundamentally incompatible with reversed info -- tables. Therefore, we need a table of imported addresses in a writable -- section. -- The "official" GOT mechanism (label@got) isn't intended to be used -- in position dependent code, so we have to create our own "fake GOT" -- when not Opt_PIC && not (gopt Opt_Static dflags). -- -- 2) PowerPC Linux is just plain broken. -- While it's theoretically possible to use GOT offsets larger -- than 16 bit, the standard crt*.o files don't, which leads to -- linker errors as soon as the GOT size exceeds 16 bit. -- Also, the assembler doesn't support @gotoff labels. -- In order to be able to use a larger GOT, we have to circumvent the -- entire GOT mechanism and do it ourselves (this is also what GCC does). -- When needImportedSymbols is defined, -- the NCG will keep track of all DynamicLinkerLabels it uses -- and output each of them using pprImportedSymbol. pprImportedSymbol _ platform@(Platform { platformArch = ArchPPC_64 _ }) importedLbl | osElfTarget (platformOS platform) = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> vcat [ ptext (sLit ".section \".toc\", \"aw\""), ptext (sLit ".LC_") <> pprCLabel platform lbl <> char ':', ptext (sLit "\t.quad") <+> pprCLabel platform lbl ] _ -> empty pprImportedSymbol dflags platform importedLbl | osElfTarget (platformOS platform) = case dynamicLinkerLabelInfo importedLbl of Just (SymbolPtr, lbl) -> let symbolSize = case wordWidth dflags of W32 -> sLit "\t.long" W64 -> sLit "\t.quad" _ -> panic "Unknown wordRep in pprImportedSymbol" in vcat [ ptext (sLit ".section \".got2\", \"aw\""), ptext (sLit ".LC_") <> pprCLabel platform lbl <> char ':', ptext symbolSize <+> pprCLabel platform lbl ] -- PLT code stubs are generated automatically by the dynamic linker. _ -> empty pprImportedSymbol _ _ _ = panic "PIC.pprImportedSymbol: no match" -------------------------------------------------------------------------------- -- Generate code to calculate the address that should be put in the -- PIC base register. -- This is called by MachCodeGen for every CmmProc that accessed the -- PIC base register. It adds the appropriate instructions to the -- top of the CmmProc. -- It is assumed that the first NatCmmDecl in the input list is a Proc -- and the rest are CmmDatas. -- Darwin is simple: just fetch the address of a local label. -- The FETCHPC pseudo-instruction is expanded to multiple instructions -- during pretty-printing so that we don't have to deal with the -- local label: -- PowerPC version: -- bcl 20,31,1f. -- 1: mflr picReg -- i386 version: -- call 1f -- 1: popl %picReg -- Get a pointer to our own fake GOT, which is defined on a per-module basis. -- This is exactly how GCC does it in linux. initializePicBase_ppc :: Arch -> OS -> Reg -> [NatCmmDecl CmmStatics PPC.Instr] -> NatM [NatCmmDecl CmmStatics PPC.Instr] initializePicBase_ppc ArchPPC os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = do let gotOffset = PPC.ImmConstantDiff (PPC.ImmCLbl gotLabel) (PPC.ImmCLbl mkPicBaseLabel) blocks' = case blocks of [] -> [] (b:bs) -> fetchPC b : map maybeFetchPC bs maybeFetchPC b@(BasicBlock bID _) | bID `mapMember` info = fetchPC b | otherwise = b -- GCC does PIC prologs thusly: -- bcl 20,31,.L1 -- .L1: -- mflr 30 -- addis 30,30,.LCTOC1-.L1@ha -- addi 30,30,.LCTOC1-.L1@l -- TODO: below we use it over temporary register, -- it can and should be optimised by picking -- correct PIC reg. fetchPC (BasicBlock bID insns) = BasicBlock bID (PPC.FETCHPC picReg : PPC.ADDIS picReg picReg (PPC.HA gotOffset) : PPC.ADDI picReg picReg (PPC.LO gotOffset) : PPC.MR PPC.r30 picReg : insns) return (CmmProc info lab live (ListGraph blocks') : statics) initializePicBase_ppc ArchPPC OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) -- just one entry because of splitting = return (CmmProc info lab live (ListGraph (b':blocks)) : statics) where BasicBlock bID insns = entry b' = BasicBlock bID (PPC.FETCHPC picReg : insns) ------------------------------------------------------------------------- -- Load TOC into register 2 -- PowerPC 64-bit ELF ABI 2.0 requires the address of the callee -- in register 12. -- We pass the label to FETCHTOC and create a .localentry too. -- TODO: Explain this better and refer to ABI spec! {- We would like to do approximately this, but spill slot allocation might be added before the first BasicBlock. That violates the ABI. For now we will emit the prologue code in the pretty printer, which is also what we do for ELF v1. initializePicBase_ppc (ArchPPC_64 ELF_V2) OSLinux picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = do bID <-getUniqueM return (CmmProc info lab live (ListGraph (b':entry:blocks)) : statics) where BasicBlock entryID _ = entry b' = BasicBlock bID [PPC.FETCHTOC picReg lab, PPC.BCC PPC.ALWAYS entryID] -} initializePicBase_ppc _ _ _ _ = panic "initializePicBase_ppc: not needed" -- We cheat a bit here by defining a pseudo-instruction named FETCHGOT -- which pretty-prints as: -- call 1f -- 1: popl %picReg -- addl __GLOBAL_OFFSET_TABLE__+.-1b, %picReg -- (See PprMach.hs) initializePicBase_x86 :: Arch -> OS -> Reg -> [NatCmmDecl (Alignment, CmmStatics) X86.Instr] -> NatM [NatCmmDecl (Alignment, CmmStatics) X86.Instr] initializePicBase_x86 ArchX86 os picReg (CmmProc info lab live (ListGraph blocks) : statics) | osElfTarget os = return (CmmProc info lab live (ListGraph blocks') : statics) where blocks' = case blocks of [] -> [] (b:bs) -> fetchGOT b : map maybeFetchGOT bs -- we want to add a FETCHGOT instruction to the beginning of -- every block that is an entry point, which corresponds to -- the blocks that have entries in the info-table mapping. maybeFetchGOT b@(BasicBlock bID _) | bID `mapMember` info = fetchGOT b | otherwise = b fetchGOT (BasicBlock bID insns) = BasicBlock bID (X86.FETCHGOT picReg : insns) initializePicBase_x86 ArchX86 OSDarwin picReg (CmmProc info lab live (ListGraph (entry:blocks)) : statics) = return (CmmProc info lab live (ListGraph (block':blocks)) : statics) where BasicBlock bID insns = entry block' = BasicBlock bID (X86.FETCHPC picReg : insns) initializePicBase_x86 _ _ _ _ = panic "initializePicBase_x86: not needed"
urbanslug/ghc
compiler/nativeGen/PIC.hs
bsd-3-clause
33,373
0
20
10,002
5,190
2,629
2,561
409
8
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} -- This program must be called with GHC's libdir as the single command line -- argument. module Main where -- import Data.Generics import Data.Data import Data.List import System.IO import GHC import BasicTypes import DynFlags import FastString import ForeignCall import MonadUtils import Outputable import HsDecls import Bag (filterBag,isEmptyBag) import System.Directory (removeFile) import System.Environment( getArgs ) import qualified Data.Map as Map import Data.Dynamic ( fromDynamic,Dynamic ) main::IO() main = do [libdir,fileName] <- getArgs testOneFile libdir fileName testOneFile libdir fileName = do ((anns,cs),p) <- runGhc (Just libdir) $ do dflags <- getSessionDynFlags setSessionDynFlags dflags let mn =mkModuleName fileName addTarget Target { targetId = TargetModule mn , targetAllowObjCode = True , targetContents = Nothing } load LoadAllTargets modSum <- getModSummary mn p <- parseModule modSum return (pm_annotations p,p) let tupArgs = gq (pm_parsed_source p) putStrLn (pp tupArgs) -- putStrLn (intercalate "\n" [showAnns anns]) where gq ast = everything (++) ([] `mkQ` doWarningTxt `extQ` doImportDecl `extQ` doCType `extQ` doRuleDecl `extQ` doCCallTarget `extQ` doHsExpr ) ast doWarningTxt :: WarningTxt -> [(String,[Located (SourceText,FastString)])] doWarningTxt ((WarningTxt _ ss)) = [("w",map conv ss)] doWarningTxt ((DeprecatedTxt _ ss)) = [("d",map conv ss)] doImportDecl :: ImportDecl RdrName -> [(String,[Located (SourceText,FastString)])] doImportDecl (ImportDecl _ _ Nothing _ _ _ _ _ _) = [] doImportDecl (ImportDecl _ _ (Just ss) _ _ _ _ _ _) = [("i",[conv (noLoc ss)])] doCType :: CType -> [(String,[Located (SourceText,FastString)])] doCType (CType src (Just (Header hs hf)) c) = [("c",[noLoc (hs,hf),noLoc c])] doCType (CType src Nothing c) = [("c",[noLoc c])] doRuleDecl :: RuleDecl RdrName -> [(String,[Located (SourceText,FastString)])] doRuleDecl (HsRule ss _ _ _ _ _ _) = [("r",[ss])] doCCallTarget :: CCallTarget -> [(String,[Located (SourceText,FastString)])] doCCallTarget (StaticTarget s f _ _) = [("st",[(noLoc (s,f))])] doHsExpr :: HsExpr RdrName -> [(String,[Located (SourceText,FastString)])] doHsExpr (HsCoreAnn src ss _) = [("co",[conv (noLoc ss)])] doHsExpr (HsSCC src ss _) = [("sc",[conv (noLoc ss)])] doHsExpr (HsTickPragma src (ss,_,_) _) = [("tp",[conv (noLoc ss)])] doHsExpr _ = [] conv (GHC.L l (StringLiteral st fs)) = GHC.L l (st,fs) showAnns anns = "[\n" ++ (intercalate "\n" $ map (\((s,k),v) -> ("(AK " ++ pp s ++ " " ++ show k ++" = " ++ pp v ++ ")\n")) $ Map.toList anns) ++ "]\n" pp a = showPpr unsafeGlobalDynFlags a -- --------------------------------------------------------------------- -- Copied from syb for the test -- | Generic queries of type \"r\", -- i.e., take any \"a\" and return an \"r\" -- type GenericQ r = forall a. Data a => a -> r -- | Make a generic query; -- start from a type-specific case; -- return a constant otherwise -- mkQ :: ( Typeable a , Typeable b ) => r -> (b -> r) -> a -> r (r `mkQ` br) a = case cast a of Just b -> br b Nothing -> r -- | Extend a generic query by a type-specific case extQ :: ( Typeable a , Typeable b ) => (a -> q) -> (b -> q) -> a -> q extQ f g a = maybe (f a) g (cast a) -- | Summarise all nodes in top-down, left-to-right order everything :: (r -> r -> r) -> GenericQ r -> GenericQ r -- Apply f to x to summarise top-level node; -- use gmapQ to recurse into immediate subterms; -- use ordinary foldl to reduce list of intermediate results everything k f x = foldl k (f x) (gmapQ (everything k f) x)
acowley/ghc
testsuite/tests/ghc-api/annotations/stringSource.hs
bsd-3-clause
4,554
1
20
1,504
1,433
782
651
94
7
{-# LANGUAGE InstanceSigs, PartialTypeSignatures #-} module T11670 where import Foreign.C.Types import Foreign.Storable import Foreign.Ptr peek :: Ptr a -> IO CLong peek ptr = peekElemOff undefined 0 :: IO _ peek2 :: Ptr a -> IO CLong peek2 ptr = peekElemOff undefined 0 :: _ => IO _ -- castPtr :: Ptr a -> Ptr b -- peekElemOff :: Storable a => Ptr a -> Int -> IO a
olsner/ghc
testsuite/tests/partial-sigs/should_compile/T11670.hs
bsd-3-clause
371
0
6
74
96
50
46
9
1
module ShouldFail where -- !!! constraining the type variable in a class head is illegal -- Simpler version of tcfail149 class Foo a where op :: Eq a => a -> a
urbanslug/ghc
testsuite/tests/typecheck/should_fail/tcfail150.hs
bsd-3-clause
163
0
8
35
31
17
14
3
0
module Language.Haskell.Expression.Lexer ( Token(..) , tokenize ) where data Token = Identifier String deriving (Eq, Show) tokenize :: String -> [Token] tokenize input = [Identifier input]
beni55/interpolate
src/Language/Haskell/Expression/Lexer.hs
mit
196
0
6
33
66
39
27
7
1
import Test.HUnit import Q14 assertEqualIntList :: String -> [Int] -> [Int] -> Assertion assertEqualIntList = assertEqual test1 = TestCase (assertEqualIntList "dupli [] should be [] ." ([] ) (dupli [] )) test2 = TestCase (assertEqualIntList "dupli [1] should be [1,1] ." ([1,1] ) (dupli [1] )) test3 = TestCase (assertEqualIntList "dupli [1,2] should be [1,1,2,2]." ([1,1,2,2]) (dupli [1,2])) main = runTestTT $ TestList [test1,test2,test3]
cshung/MiscLab
Haskell99/q14.test.hs
mit
475
0
10
98
170
95
75
8
1
import Data.List isInAny2 needle haystack = any (\s -> needle `isInfixOf` s) haystack isInAny needle haystack = any inSequence haystack where inSequence s = needle `isInfixOf`s
tamasgal/haskell_exercises
Real_World_Haskell/ch04/Partial.hs
mit
182
0
8
31
66
35
31
4
1
{-# LANGUAGE CPP #-} module GHCJS.DOM.WebGLCompressedTextureATC ( #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) module GHCJS.DOM.JSFFI.Generated.WebGLCompressedTextureATC #else #endif ) where #if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT) import GHCJS.DOM.JSFFI.Generated.WebGLCompressedTextureATC #else #endif
plow-technologies/ghcjs-dom
src/GHCJS/DOM/WebGLCompressedTextureATC.hs
mit
388
0
5
33
33
26
7
4
0
import System.Environment import Debug.Trace -- List of [I.C.] -> t -> [Xs] type Coord = Double type Coords = [Coord] type ODE = Coords->Time->Coord type Time = Double type ErrFun = Coords->Coords->Bool -- Applies each function to a single argument, returns list applyeach :: [a->b] -> a -> [b] -> [b] applyeach (h:t) v p = applyeach t v (p++[h v]) applyeach [] v p = p -- adds vectors and weighs second one: return v + (w*u) mult_weight :: Double -> [Double] -> [Double] -> [Double] mult_weight w = zipWith (\a b -> a + (w*b)) -- maps a function which takes four arguments fourmap :: (t -> t1 -> t2 -> t3 -> a) -> [t] -> [t1] -> [t2] -> [t3] -> [a] -> [a] fourmap f (h1:t1) (h2:t2) (h3:t3) (h4:t4) p = fourmap f t1 t2 t3 t4 (p++[f h1 h2 h3 h4]) fourmap f [] [] [] [] p = p fourmap _ _ _ _ _ _ = error ("PM: List of different length") -- rk4 integration single step rk4_step :: [ODE] -> [Coord] -> Time -> Time -> [Coord] rk4_step derivs knots t dt = let tbar = dt/2 in let d_t = map (\d c-> d c t) derivs in let d_tbar = map (\d c-> d c (t+tbar)) derivs in let d_tdt = map (\d c-> d c (t+dt)) derivs in let k1 = applyeach d_t knots [] in -- For each initial condition do q1 = dq q0 t let k2 = applyeach d_tbar (mult_weight tbar knots k1) [] in let k3 = applyeach d_tbar (mult_weight tbar knots k2) [] in let k4 = applyeach d_tdt (mult_weight dt knots k3) [] in let toadd = fourmap (\a b c d -> (1/6)*dt*(a + (2*b) + (2*c) + d)) k1 k2 k3 k4 [] in zipWith (+) knots toadd -- rk4 integration rk4 :: [ODE] -> Coords -> Time -> Time -> Time -> Coords rk4 derivs ics start_t end_t step_size = let time_table = [start_t,step_size .. end_t] in foldl rk4_step_fun ics time_table where rk4_step_fun k0s t = rk4_step derivs k0s t step_size -- rk4 variable -- ODES -> I.C. -> Err -> Start_T -> End_T -> I.dt -> Out rk4v :: [ODE] -> Coords -> ErrFun -> Time -> Time -> Time -> Coords rk4v derivs ics errf start_t end_t step_size = let c1 = rk4 derivs ics start_t end_t step_size in let c2 = rk4 derivs ics start_t end_t (step_size/2.0) in if errf c1 c2 then rk4v derivs ics errf start_t end_t (step_size/2.0) else c2 -- rk4 step variable rk4sv :: [ODE] -> Coords -> ErrFun -> Time -> Time -> Time -> Coords rk4sv derivs ics errf start_t end_t step_size = let use_dt = min (end_t - start_t) step_size in let basec = rk4_step derivs ics start_t use_dt in let (newc, newdt) = rk4sv_helper ics basec start_t use_dt in if (start_t+newdt >= end_t) then newc else rk4sv derivs newc errf (start_t+newdt) end_t newdt where -- rk4sv_helper :: Coords -> Coords -> Time -> Time -> (Coords, Time) rk4sv_helper basec intc t dt = let halfc = rk4_step derivs basec t (dt/2.0) in let c2 = rk4_step derivs halfc (t+(dt/2.0)) (dt/2.0) in if errf intc c2 then rk4sv_helper basec c2 t (dt/2.0) else (c2, dt) main :: IO() main = print (show (rk4 [\xs t -> head xs] [1] 0 1 0.001))
Renmusxd/rk4
rk4.hs
mit
2,981
0
34
697
1,333
693
640
55
3
{-# LANGUAGE OverloadedStrings #-} module View.Search where import Data.Time.Clock () import Lucid import Model import Static import View.Utils searchPage :: SessionInfo -> Int -> [Snippet] -> Html () searchPage u itermPerPage ss = doctypehtml_ . html_ $ do pageTitle "Introduction | jsm" body_ $ do topBar u div_ [class_ "Content"] $ h1_ "Search for:" div_ [class_ "Content"] $ ul_ $ mapM_ (li_ [class_ "Code"] . codePreview) (take itermPerPage ss) script_ searchScript
winterland1989/jsmServer
src/View/Search.hs
mit
592
0
17
192
168
83
85
16
1
{-# LANGUAGE OverloadedStrings #-} import System.Random import Network.WebSockets import Control.Concurrent import Control.Monad import Data.Text type Price = (String, Double) main :: IO () main = do chan <- newChan forkIO (notifyClients chan) runServer "127.0.0.1" 3000 $ \pc -> do conn <- acceptRequest pc c <- dupChan chan handleConnection conn c notifyClients :: Chan Price -> IO () notifyClients chan = forever $ do prices <- getAllPrices forM_ prices (writeChan chan) threadDelay 1000000 handleConnection :: Connection -> Chan Price -> IO () handleConnection conn chan = forever $ do (symbol, price) <- readChan chan let message = pack (symbol ++ ":" ++ show price) sendTextData conn message -- Just returns some random prices getAllPrices :: IO [Price] getAllPrices = mapM randomPrice ["IAN", "SUL", "BRAM", "CAT"] where randomPrice s = randomRIO (100, 200) >>= \p -> return (s, p)
iansullivan88/stock-ticker
Main.hs
mit
927
0
14
175
330
164
166
28
1
{-# LANGUAGE ScopedTypeVariables #-} module Data.Yaml.Frontmatter where import Data.Attoparsec.ByteString import Data.Frontmatter.Internal import Data.Yaml (FromJSON, Value, decodeEither) -- | -- Parses a YAML frontmatter or JSON frontmatter from a 'ByteString' as a -- 'Value'. Because of how @Data.Yaml@ is implemented using @aeson@, this will -- succeed for JSON frontmatters as well as YAML ones. frontmatterYaml :: FromJSON a => Parser a frontmatterYaml = frontmatterYaml' <?> "frontmatterYaml" where frontmatterYaml' = do f <- frontmatter case decodeEither f of Left e -> fail e Right v -> return v
yamadapc/haskell-frontmatter
src/Data/Yaml/Frontmatter.hs
mit
700
0
12
181
112
61
51
12
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.Gamepad (js_getId, getId, js_getIndex, getIndex, js_getConnected, getConnected, js_getTimestamp, getTimestamp, js_getMapping, getMapping, js_getAxes, getAxes, js_getButtons, getButtons, Gamepad, castToGamepad, gTypeGamepad) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSVal(..), JSString) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSVal(..), FromJSVal(..)) import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.JSFFI.Generated.Enums foreign import javascript unsafe "$1[\"id\"]" js_getId :: Gamepad -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad.id Mozilla Gamepad.id documentation> getId :: (MonadIO m, FromJSString result) => Gamepad -> m result getId self = liftIO (fromJSString <$> (js_getId (self))) foreign import javascript unsafe "$1[\"index\"]" js_getIndex :: Gamepad -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad.index Mozilla Gamepad.index documentation> getIndex :: (MonadIO m) => Gamepad -> m Word getIndex self = liftIO (js_getIndex (self)) foreign import javascript unsafe "($1[\"connected\"] ? 1 : 0)" js_getConnected :: Gamepad -> IO Bool -- | <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad.connected Mozilla Gamepad.connected documentation> getConnected :: (MonadIO m) => Gamepad -> m Bool getConnected self = liftIO (js_getConnected (self)) foreign import javascript unsafe "$1[\"timestamp\"]" js_getTimestamp :: Gamepad -> IO Double -- | <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad.timestamp Mozilla Gamepad.timestamp documentation> getTimestamp :: (MonadIO m) => Gamepad -> m Double getTimestamp self = liftIO (js_getTimestamp (self)) foreign import javascript unsafe "$1[\"mapping\"]" js_getMapping :: Gamepad -> IO JSString -- | <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad.mapping Mozilla Gamepad.mapping documentation> getMapping :: (MonadIO m, FromJSString result) => Gamepad -> m result getMapping self = liftIO (fromJSString <$> (js_getMapping (self))) foreign import javascript unsafe "$1[\"axes\"]" js_getAxes :: Gamepad -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad.axes Mozilla Gamepad.axes documentation> getAxes :: (MonadIO m) => Gamepad -> m [Double] getAxes self = liftIO ((js_getAxes (self)) >>= fromJSValUnchecked) foreign import javascript unsafe "$1[\"buttons\"]" js_getButtons :: Gamepad -> IO JSVal -- | <https://developer.mozilla.org/en-US/docs/Web/API/Gamepad.buttons Mozilla Gamepad.buttons documentation> getButtons :: (MonadIO m) => Gamepad -> m [Maybe GamepadButton] getButtons self = liftIO ((js_getButtons (self)) >>= fromJSValUnchecked)
manyoo/ghcjs-dom
ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/Gamepad.hs
mit
3,400
42
10
469
821
475
346
50
1
module Main where import Solidran.Output import Solidran.Cons.Detail main :: IO () main = do c <- getContents let ls = readInput c putStrLn . consensus $ ls putStrLn . output . profileMat $ ls
Jefffrey/Solidran
src/Solidran/Cons/Main.hs
mit
211
0
10
52
75
38
37
9
1
{-# OPTIONS_GHC -F -pgmF htfpp #-} module Primes.Test (htf_thisModulesTests) where import Data.List import Primes import Test.Framework test_primeFactorisation_5 = assertEqual (primeFactorisation 5) [5] test_primeFactorisation_55 = assertEqual (primeFactorisation 55) [5,11] test_primeFactorisation_24 = assertEqual (primeFactorisation 24) [2,2,2,3]
NorfairKing/project-euler
test/haskell/Primes/Test.hs
gpl-2.0
385
0
7
69
94
54
40
8
1
{-# LANGUAGE TemplateHaskell, RankNTypes #-} module Ocram.Analysis.Filter -- exports {{{1 ( global_constraints, critical_constraints, ErrorCode(..) ) where -- imports {{{1 import Control.Monad (guard) import Data.Generics (mkQ, everything, extQ) import Data.Data (Data) import Data.List (findIndices) import Data.Maybe (fromMaybe, mapMaybe) import Language.C.Data.Ident (Ident(Ident)) import Language.C.Data.Node (NodeInfo, nodeInfo) import Language.C.Syntax.AST import Ocram.Analysis.CallGraph (start_functions, is_critical) import Ocram.Analysis.Fgl (find_loop, edge_label) import Ocram.Analysis.Types (CallGraph(..), Label(lblName)) import Ocram.Names (ecPrefix, blockingAttr, startAttr) import Ocram.Query (is_start_function, is_blocking_function, function_parameters_cd, return_type_fd, function_parameters_fd) import Ocram.Symbols (symbol) import Ocram.Text (OcramError, new_error) import Ocram.Util (fromJust_s, head_s, lookup_s) import qualified Data.Graph.Inductive.Graph as G import qualified Data.List as L -- errors {{{1 data ErrorCode = -- {{{2 ArrayInitializerList | AssemblerCode | BuiltinExpr | CaseRange | CriticalGroup | CriticalRecursion | Ellipses | GnucAttribute | GotoPtr | IllFormedSwitch | MainFunction | NestedFunction | NoParameterList | NoReturnType | NoThreads | NoVarName | OldStyleParams | RangeDesignator | ReservedPrefix | StartFunctionSignature | StatExpression | ThreadLocalStorage | ThreadNotBlocking | VolatileQualifier deriving (Eq, Enum, Show) errorText :: ErrorCode -> String -- {{{2 errorText ArrayInitializerList = "Sorry, initializer list for arrays are not supported for critical functions." errorText AssemblerCode = "transformation of assembler code is not supported" errorText BuiltinExpr = "GNU C builtin expressions are not supported" errorText CaseRange = "case ranges are not part of C99 and are thus not supported" errorText CriticalGroup = "A declarator of critical function must be contained in its own declaration" errorText CriticalRecursion = "recursion of critical functions" errorText Ellipses = "No ellipses for critical functions" errorText GnucAttribute = "__attribute__ is a GNU extension and is only allowed to declare thread start functions and blocking functions" errorText GotoPtr = "Computed gotos are not part of C99 and are thus not supported" errorText IllFormedSwitch = "Ill-formed switch statement" errorText MainFunction = "A T-code application must not have a 'main' function." errorText NestedFunction = "nested functions are not part of C99 and are thus not supported" errorText NoParameterList = "function without parameter list" errorText NoReturnType = "function without explicit return type" errorText NoThreads = "at least one thread must be started" errorText NoVarName = "Function parameters of blocking functions must have names." errorText OldStyleParams = "Old style parameter declarations are not supported." errorText RangeDesignator = "GNU C array range designators are not supported" errorText ReservedPrefix = "The prefix 'ec_' is reserved, you may not use it." errorText StartFunctionSignature = "thread start functions must have the following signature 'void name()'" errorText StatExpression = "GNU C compound statement as expressions are not supported" errorText ThreadLocalStorage = "GNU C thread local storage is not supported" errorText ThreadNotBlocking = "thread does not call any blocking functions" errorText VolatileQualifier = "volatile type qualifiers are not supported in critical functions" newError :: ErrorCode -> Maybe String -> Maybe NodeInfo -> OcramError -- {{{2 newError code extraWhat where_ = let extraWhat' = fromMaybe "" extraWhat what = errorText code ++ extraWhat' in new_error (fromEnum code) what where_ global_constraints :: CTranslUnit -> Either [OcramError] () -- {{{1 global_constraints ast = failOrPass $ everything (++) (mkQ [] scanExtDecl `extQ` scanBlockItem `extQ` scanStorageSpec `extQ` scanIdent) ast where scanExtDecl :: CExtDecl -> [OcramError] scanExtDecl (CDeclExt (CDecl _ ds ni)) | any ((== Just "main") . fmap symbol . (\(x, _, _)->x)) ds = [newError MainFunction Nothing (Just ni)] | otherwise = [] scanExtDecl (CFDefExt fd) | symbol fd == "main" = [newError MainFunction Nothing (Just (nodeInfo fd))] | otherwise = [] scanExtDecl _ = [] scanBlockItem :: CBlockItem -> [OcramError] scanBlockItem (CNestedFunDef o) = [newError NestedFunction Nothing (Just (nodeInfo o))] scanBlockItem _ = [] scanStorageSpec :: CStorageSpec -> [OcramError] scanStorageSpec (CThread ni) = [newError ThreadLocalStorage Nothing (Just ni)] scanStorageSpec _ = [] scanIdent :: Ident -> [OcramError] scanIdent ident | ecPrefix `L.isPrefixOf` symbol ident = [newError ReservedPrefix Nothing (Just (nodeInfo ident))] | otherwise = [] critical_constraints :: CallGraph -> CTranslUnit -> Either [OcramError] () -- {{{1 critical_constraints cg ast = failOrPass $ checkRecursion cg ++ checkStartFunctions cg ast ++ checkThreads cg ++ checkFeatures cg ast checkRecursion :: CallGraph -> [OcramError] -- {{{2 checkRecursion cg@(CallGraph gd gi) = mapMaybe (fmap (createRecError cg) . find_loop gd . $lookup_s gi) $ start_functions cg createRecError :: CallGraph -> [G.Node] -> OcramError createRecError (CallGraph gd _) call_stack = newError CriticalRecursion (Just errText) (Just location) where errText = L.intercalate " -> " $ map (show . lblName . $fromJust_s . G.lab gd) call_stack (callee:caller:[]) = take 2 $ L.reverse call_stack location = $head_s $ edge_label gd caller callee checkStartFunctions :: CallGraph -> CTranslUnit -> [OcramError] -- {{{2 checkStartFunctions cg (CTranslUnit ds _) = foldr go [] ds where go (CFDefExt f@(CFunDef _ _ _ _ ni)) es | not (is_start_function f) = es | not (is_critical cg (symbol f)) = newError ThreadNotBlocking Nothing (Just ni) : es | (not . isVoid . fst . return_type_fd) f = newError StartFunctionSignature Nothing (Just ni) : es | (not . null . function_parameters_fd) f = newError StartFunctionSignature Nothing (Just ni) : es | otherwise = es where isVoid (CVoidType _) = True isVoid _ = False go _ es = es checkThreads :: CallGraph -> [OcramError] -- {{{2 checkThreads cg | null (start_functions cg) = [newError NoThreads Nothing Nothing] | otherwise = [] checkFeatures :: CallGraph -> CTranslUnit -> [OcramError] -- {{{2 checkFeatures cg (CTranslUnit ds _) = concatMap filt ds where filt (CDeclExt cd@(CDecl ts dds ni)) | length dds /= 1 = concatMap criticalGroup dds | not (is_critical cg (symbol cd)) = [] | not (hasReturnType ts) = [newError NoReturnType Nothing (Just ni)] | is_blocking_function cd = noVarNames cd ++ blockingFunctionConstraints cd | otherwise = criticalFunctionConstraints cd where noVarNames = mapMaybe noVarName . function_parameters_cd noVarName p@(CDecl _ [] _) = Just $ newError NoVarName Nothing (Just (nodeInfo p)) noVarName _ = Nothing criticalGroup (Nothing, _, _) = [] criticalGroup (Just declr, _, _) = [newError CriticalGroup Nothing (Just ni) | is_critical cg (symbol declr)] filt (CFDefExt fd@(CFunDef ts (CDeclr _ ps _ _ _) _ _ ni)) | not (is_critical cg (symbol fd)) = [] | not (hasReturnType ts) = [newError NoReturnType Nothing (Just ni)] | null ps = [newError NoParameterList Nothing (Just ni)] | otherwise = criticalFunctionConstraints fd filt _ = [] criticalFunctionConstraints :: forall a. Data a => a -> [OcramError] criticalFunctionConstraints = everything (++) (mkQ [] scanAttribute `extQ` scanDerivedDeclr `extQ` scanDecl `extQ` scanStat `extQ` scanExpr `extQ` scanPartDesig `extQ` scanTypeQualifier ) blockingFunctionConstraints = everything (++) (mkQ [] scanAttribute `extQ` scanDerivedDeclr) hasReturnType = any isTypeSpec where isTypeSpec (CTypeSpec _) = True isTypeSpec _ = False scanAttribute :: CAttribute NodeInfo -> [OcramError] scanAttribute (CAttr (Ident name _ _) _ ni) | name `elem` [blockingAttr, startAttr] = [] | otherwise = [newError GnucAttribute Nothing (Just ni)] scanTypeQualifier :: CTypeQualifier NodeInfo -> [OcramError] scanTypeQualifier (CVolatQual ni) = [newError VolatileQualifier Nothing (Just ni)] scanTypeQualifier _ = [] scanDerivedDeclr :: CDerivedDeclr -> [OcramError] scanDerivedDeclr x@(CFunDeclr (Right (_, True)) _ _) = [newError Ellipses Nothing (Just (nodeInfo x))] scanDerivedDeclr x@(CFunDeclr (Left _) _ _) = [newError OldStyleParams Nothing (Just (nodeInfo x))] scanDerivedDeclr _ = [] scanDecl (CDecl _ l ni) | any containsArrayInitList l = [newError ArrayInitializerList Nothing (Just ni)] | otherwise = [] where containsArrayInitList (Just declr, Just (CInitList _ _), _) = containsArrayDeclr declr containsArrayInitList _ = False containsArrayDeclr (CDeclr _ dds _ _ _) = any isArrayDeclr dds isArrayDeclr (CArrDeclr _ _ _) = True isArrayDeclr _ = False scanStat (CAsm _ ni) = [newError AssemblerCode Nothing (Just ni)] scanStat (CCases _ _ _ ni) = [newError CaseRange Nothing (Just ni)] scanStat (CGotoPtr _ ni) = [newError GotoPtr Nothing (Just ni)] -- The restrictions on switch statements are not strictly required, but -- make the implementation of desugar_control_structures easier. -- Furthermore, we see little sense in using these cases deliberately. scanStat (CSwitch _ body ni) = let isCase (CCase _ _ _) = True isCase _ = False isCases (CCases _ _ _ _) = True isCases _ = False isDefault (CDefault _ _) = True isDefault _ = False extract (CBlockStmt s) = Just s extract _ = Nothing test = let flt = or . sequence [isCase, isCases, isDefault] in do -- Enforce a switch "code block"... (CCompound _ items _) <- Just body -- ...which must start with a statement... ((CBlockStmt stmt):_) <- Just items -- ...that has to be a case(es) or a default statement. guard $ flt stmt -- And finally make sure that there is at most one default -- statement and that no case(es) statement follows. let allcases = filter flt $ mapMaybe extract items dfltcases = findIndices isDefault allcases guard (null dfltcases || head dfltcases == (length allcases) - 1) in case test of Nothing -> [newError IllFormedSwitch Nothing (Just ni)] Just () -> [] scanStat _ = [] scanExpr (CStatExpr _ ni) = [newError StatExpression Nothing (Just ni)] scanExpr o@(CBuiltinExpr _) = [newError BuiltinExpr Nothing (Just (nodeInfo o))] scanExpr _ = [] scanPartDesig (CRangeDesig _ _ ni) = [newError RangeDesignator Nothing (Just ni)] scanPartDesig _ = [] -- util {{{1 failOrPass :: [a] -> Either [a] () failOrPass [] = Right () failOrPass x = Left x
copton/ocram
ocram/src/Ocram/Analysis/Filter.hs
gpl-2.0
11,704
0
20
2,803
3,319
1,716
1,603
256
23
import XMonad import XMonad.Layout.NoBorders (noBorders) import XMonad.Layout.PerWorkspace (onWorkspace) import XMonad.Layout.Spacing import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Util.Run import XMonad.Util.EZConfig import System.IO import Control.Monad import qualified XMonad.StackSet as W import XMonad.Hooks.ICCCMFocus defaultLayouts = tiled ||| Mirror tiled ||| Full where -- default tiling algorithm partitions the screen into two panes tiled = spacing 3 $ Tall nmaster delta ratio -- The default number of windows in the master pane nmaster = 1 -- Default proportion of screen occupied by master pane ratio = 2/3 -- Percent of screen to increment by when resizing panes delta = 3/100 -- Define layout for specific workspaces nobordersLayout = noBorders $ Full myWorkspaces = ["1:web","2:shell","3:emacs","4:VM","5:long","6","7","8:AndroidStudio","9:ADT"] myManageHook = composeAll [ className =? "Gimp" --> viewShift "6" , className =? "Firefox" --> viewShift "1:web" , className =? "Emacs" --> viewShift "3:emacs" , className =? "Worker" --> viewShift "5:long" , className =? "ADT" --> viewShift "9:ADT" , className =? "jetbrains-android-studio" --> viewShift "8:AndroidStudio" , className =? "trayer" --> doIgnore , (role =? "gimp-toolbox" <||> role =? "gimp-image-window") --> (ask >>= doF . W.sink) ] where role = stringProperty "WM_WINDOW_ROLE" viewShift = doF . liftM2 (.) W.greedyView W.shift myLayout = onWorkspace "1:web" nobordersLayout $ onWorkspace "8:AndroidStudio" nobordersLayout $ onWorkspace "9:ADT" nobordersLayout $ layoutHook defaultConfig main = do init <- spawnPipe "/home/aitzol/.xmonad/autostart" xmproc <- spawnPipe "/usr/bin/xmobar /home/aitzol/.xmonad/xmobarrc" xmonad $ defaultConfig { terminal = "urxvt" , logHook = takeTopFocus , modMask = mod4Mask , borderWidth = 1 , normalBorderColor = "#60A1AD" , focusedBorderColor = "#68e862" , workspaces = myWorkspaces , manageHook = myManageHook <+> manageHook defaultConfig , layoutHook = avoidStruts $ myLayout , logHook = dynamicLogWithPP $ xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor "green" "" . shorten 50 } , focusFollowsMouse = False } `additionalKeys` [ ((mod4Mask .|. shiftMask, xK_z), spawn "xscreensaver-command -lock") , ((mod4Mask .|. shiftMask, xK_F4), spawn "sudo shutdown -h now") , ((controlMask, xK_Print), spawn "sleep 0.2; scrot -s") , ((0, xK_Print), spawn "scrot") , ((mod4Mask .|. controlMask, xK_f), spawn "firefox") , ((mod4Mask .|. controlMask, xK_e), spawn "emacs") , ((mod4Mask, xK_F1), spawn "mpc -h /tmp/mpdsocket toggle") , ((mod4Mask, xK_F2), spawn "mpc -h /tmp/mpdsocket prev") , ((mod4Mask, xK_F3), spawn "mpc -h /tmp/mpdsocket next") , ((mod4Mask, xK_F4), spawn "mpc -h /tmp/mpdsocket volume -2") , ((mod4Mask, xK_F5), spawn "mpc -h /tmp/mpdsocket volume +2") , ((mod4Mask, xK_F9), kill) -- to kill applications ]
aitzol/dotfiles
.xmonad/xmonad.hs
gpl-2.0
3,287
0
15
790
771
443
328
61
1
{- | Module : $Header$ Description : A formula wrapper from formulae defined in CASL.AS_Basic_CASL to data Formula defined in Common.Normalization Copyright : (c) Immanuel Normann, Uni Bremen 2007 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable -} module Search.CASL.FormulaWrapper where import Search.Common.Normalization import qualified Common.Id as Id import qualified CASL.AS_Basic_CASL as Casl {- TODO: - wrapFormula und wrapTerm vervollständigen! Vielleicht wäre es ausserdem sauberer, wenn man formeln unterteilt in: 1) TypesAsFormula 2) TermsAsFormula -} data CaslVar = PredSymb Casl.PRED_SYMB | OpSymb Casl.OP_SYMB | VarSymb Casl.VAR Casl.SORT | TypeSymb Casl.SORT deriving (Eq,Ord) instance Show CaslVar where show (PredSymb v) = show v show (OpSymb v) = show v show (VarSymb v _) = show v show (TypeSymb t) = ":" ++ show t data CaslConst = TrueAtom | FalseAtom | EEqual | SEqual | Definedness | Function | Predicate | Total | Partial | Cartesian | Untyped deriving (Eq,Ord,Show) {- TODO: Provisorische Typkodierung: typeBool, typeEqual, typeQuantifier, defaultVar, defaultXXX -} wrapTermB :: Casl.QUANTIFIER -> (Constant CaslConst) wrapTermB Casl.Universal = All wrapTermB Casl.Existential = Some -- wrapTermB Unique_existential = ??? wrapSort :: Casl.SORT -> Formula (Constant CaslConst) CaslVar wrapSort sort = Var (TypeSymb sort) [] -- todo: bei Casl.Op_typ bleibt noch der FunKind unberücksichtigt. Wie müsste er kodiert werden? wrapOpType :: Casl.OP_TYPE -> Formula (Constant CaslConst) CaslVar wrapOpType (Casl.Op_type caslFunKind doms cod _) = Const (LogicDependent Function) [funkind,Const (LogicDependent Cartesian) (map wrapSort doms), wrapSort cod] where funkind = case caslFunKind of Casl.Total -> Const (LogicDependent Total) [] Casl.Partial -> Const (LogicDependent Partial) [] wrapTerm :: Casl.TERM f -> Formula (Constant CaslConst) (Formula (Constant CaslConst) CaslVar) wrapTerm (Casl.Qual_var var sort _) = Var (Var (VarSymb var sort) [wrapSort sort]) [] wrapTerm (Casl.Application opSymb terms _) = Var wrappedOpSymb (map wrapTerm terms) where wrappedOpSymb = case opSymb of (Casl.Op_name opName) -> Var (OpSymb opSymb) [Const (LogicDependent Untyped) []] (Casl.Qual_op_name opName opType _) -> Var (OpSymb opSymb) [wrapOpType opType] {- Warning: Pattern match(es) are non-exhaustive In the definition of `wrapTerm': Patterns not matched: CASL.AS_Basic_CASL.Simple_id _ CASL.AS_Basic_CASL.Sorted_term _ _ _ CASL.AS_Basic_CASL.Cast _ _ _ CASL.AS_Basic_CASL.Conditional _ _ _ _ ... -} -- todo: wrapVarName, zipvardecl in wrapFormula verstecken wrapVarName :: Casl.VAR -> Casl.SORT -> Formula (Constant CaslConst) CaslVar wrapVarName var sort = Var (VarSymb var sort) [(wrapSort sort)] zipvardecl :: Casl.VAR_DECL -> [Formula (Constant CaslConst) CaslVar] zipvardecl (Casl.Var_decl cvars sort _) = map (\cvar -> (wrapVarName cvar sort)) cvars wrapPredType :: Casl.PRED_TYPE -> Formula (Constant CaslConst) CaslVar wrapPredType (Casl.Pred_type doms _) = Const (LogicDependent Predicate) (map wrapSort doms) wrapFormula :: Casl.FORMULA f -> Formula (Constant CaslConst) (Formula (Constant CaslConst) CaslVar) wrapFormula (Casl.Quantification cb cvardecls cf _) = Binder b vars f where b = wrapTermB cb vars = foldr (++) [] (map zipvardecl cvardecls) f = wrapFormula cf wrapFormula (Casl.Negation f _) = Const Not [wrapFormula f] wrapFormula (Casl.Conjunction fs _) = Const And (map wrapFormula fs) wrapFormula (Casl.Disjunction fs _) = Const Or (map wrapFormula fs) wrapFormula (Casl.Implication f1 f2 _ _) = Const Imp [wrapFormula f1,wrapFormula f2] wrapFormula (Casl.Equivalence f1 f2 _) = Const Eqv [wrapFormula f1,wrapFormula f2] wrapFormula (Casl.True_atom _) = Const (LogicDependent TrueAtom) [] wrapFormula (Casl.False_atom _) = Const (LogicDependent FalseAtom) [] wrapFormula (Casl.Predication predSymb terms _) = Var wrappedOpSymb (map wrapTerm terms) where wrappedOpSymb = case predSymb of (Casl.Pred_name predName) -> Var (PredSymb predSymb) [Const (LogicDependent Untyped) []] (Casl.Qual_pred_name predName predType _) -> Var (PredSymb predSymb) [wrapPredType predType] wrapFormula (Casl.Definedness t _) = Const (LogicDependent Definedness) [wrapTerm t] wrapFormula (Casl.Existl_equation t1 t2 _) = Const (LogicDependent EEqual) [wrapTerm t1,wrapTerm t2] wrapFormula (Casl.Strong_equation t1 t2 _) = Const (LogicDependent SEqual) [wrapTerm t1,wrapTerm t2] --wrapFormula (Casl.Membership term sort _) = Const (LogicDependent Membership) [wrapTerm term,wrappedSort] -- where wrappedSort = Var (Var (VarSymb var sort) [wrapSort sort]) [] -- so nicht, aber so aehnlich mit Const wrapFormula f = error ("wrapFormula currently can't wrap this formula") {- xxx -- TODO: Warning: Pattern match(es) are non-exhaustive In the definition of `wrapFormula': Patterns not matched: CASL.AS_Basic_CASL.Membership _ _ _ CASL.AS_Basic_CASL.Mixfix_formula _ CASL.AS_Basic_CASL.Unparsed_formula _ _ CASL.AS_Basic_CASL.Sort_gen_ax CASL.AS_Basic_CASL.ExtFORMULA -} normalizeCaslFormula :: Casl.FORMULA f -> (Skeleton CaslConst,[CaslVar]) normalizeCaslFormula f = (sceleton,symbols) where nf = normalizeTyped $ wrapFormula f sceleton = fst nf symbols = concatMap getVs (snd nf) getVs (_,vs,_) = vs {- Aus CASL.AS_Basic_CASL.hs und Common.Id.hs data TERM f = Simple_id SIMPLE_ID | Qual_var VAR SORT Range data OP_SYMB = Op_name OP_NAME | Qual_op_name OP_NAME OP_TYPE Range -- pos: "(", op, colon, ")" deriving (Show, Eq, Ord) data OP_TYPE = Op_type FunKind [SORT] SORT Range data PRED_SYMB = Pred_name PRED_NAME | Qual_pred_name PRED_NAME PRED_TYPE Range data PRED_TYPE = Pred_type [SORT] Range type OP_NAME = Id type PRED_NAME = Id type SORT = Id data Id = Id [Token] [Id] Range type VAR = SIMPLE_ID type SIMPLE_ID = Token data Token = Token { tokStr :: String , tokPos :: Range } deriving (Eq, Ord) -}
nevrenato/Hets_Fork
Search/CASL/FormulaWrapper.hs
gpl-2.0
6,339
12
14
1,240
1,498
765
733
64
2
-- PolOperaciones.hs -- Operaciones con polinomios. -- José A. Alonso Jiménez https://jaalonso.github.com -- ===================================================================== {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Tema_21.PolOperaciones (module Pol, module Tema_21.PolOperaciones) where -- --------------------------------------------------------------------- -- Importación de librerías -- -- --------------------------------------------------------------------- -- Nota: Hay que elegir una implementación del TAD de los polinomios. import Tema_21.PolRepTDA as Pol -- import Tema_21.PolRepDensa as Pol -- import Tema_21.PolRepDispersa as Pol -- import I1M.Pol as Pol import Test.QuickCheck -- --------------------------------------------------------------------- -- Ejemplos -- -- --------------------------------------------------------------------- -- Ejemplos de polinomios: ejPol1, ejPol2, ejPol3, ejTerm :: Polinomio Int ejPol1 = consPol 4 3 (consPol 2 (-5) (consPol 0 3 polCero)) ejPol2 = consPol 5 1 (consPol 2 5 (consPol 1 4 polCero)) ejPol3 = consPol 4 6 (consPol 1 2 polCero) ejTerm = consPol 1 4 polCero -- --------------------------------------------------------------------- -- Generador de polinomios -- -- --------------------------------------------------------------------- -- (genPol n) es un generador de polinomios. Por ejemplo, -- λ> sample (genPol 1) -- 7*x^9 + 9*x^8 + 10*x^7 + -14*x^5 + -15*x^2 + -10 -- -4*x^8 + 2*x -- -8*x^9 + 4*x^8 + 2*x^6 + 4*x^5 + -6*x^4 + 5*x^2 + -8*x -- -9*x^9 + x^5 + -7 -- 8*x^10 + -9*x^7 + 7*x^6 + 9*x^5 + 10*x^3 + -1*x^2 -- 7*x^10 + 5*x^9 + -5 -- -8*x^10 + -7 -- -5*x -- 5*x^10 + 4*x^4 + -3 -- 3*x^3 + -4 -- 10*x genPol :: (Arbitrary a, Num a, Eq a) => Int -> Gen (Polinomio a) genPol 0 = return polCero genPol _ = do n <- choose (0,10) b <- arbitrary p <- genPol (div n 2) return (consPol n b p) instance (Arbitrary a, Num a, Eq a) => Arbitrary (Polinomio a) where arbitrary = sized genPol -- --------------------------------------------------------------------- -- Funciones sobre términos -- -- --------------------------------------------------------------------- -- (creaTermino n a) es el término a*x^n. Por ejemplo, -- creaTermino 2 5 == 5*x^2 creaTermino :: (Num t, Eq t) => Int -> t -> Polinomio t creaTermino n a = consPol n a polCero -- (termLider p) es el término líder del polinomio p. Por ejemplo, -- ejPol2 == x^5 + 5*x^2 + 4*x -- termLider ejPol2 == x^5 termLider :: (Num t, Eq t) => Polinomio t -> Polinomio t termLider p = creaTermino (grado p) (coefLider p) -- --------------------------------------------------------------------- -- Suma de polinomios -- -- --------------------------------------------------------------------- -- (sumaPol p q) es la suma de los polinomios p y q. Por ejemplo, -- ejPol1 == 3*x^4 + -5*x^2 + 3 -- ejPol2 == x^5 + 5*x^2 + 4*x -- sumaPol ejPol1 ejPol2 == x^5 + 3*x^4 + 4*x + 3 sumaPol :: (Num a, Eq a) => Polinomio a -> Polinomio a -> Polinomio a sumaPol p q | esPolCero p = q | esPolCero q = p | n1 > n2 = consPol n1 a1 (sumaPol r1 q) | n1 < n2 = consPol n2 a2 (sumaPol p r2) | otherwise = consPol n1 (a1+a2) (sumaPol r1 r2) where n1 = grado p a1 = coefLider p r1 = restoPol p n2 = grado q a2 = coefLider q r2 = restoPol q -- Propiedad. El polinomio cero es el elemento neutro de la suma. prop_neutroSumaPol :: Polinomio Int -> Bool prop_neutroSumaPol p = sumaPol polCero p == p -- Comprobación con QuickCheck. -- λ> quickCheck prop_neutroSumaPol -- OK, passed 100 tests. -- Propiedad. La suma es conmutativa. prop_conmutativaSuma :: Polinomio Int -> Polinomio Int -> Bool prop_conmutativaSuma p q = sumaPol p q == sumaPol q p -- Comprobación: -- λ> quickCheck prop_conmutativaSuma -- OK, passed 100 tests. -- --------------------------------------------------------------------- -- Producto de polinomios -- -- --------------------------------------------------------------------- -- (multPorTerm t p) es el producto del término t por el polinomio -- p. Por ejemplo, -- ejTerm == 4*x -- ejPol2 == x^5 + 5*x^2 + 4*x -- multPorTerm ejTerm ejPol2 == 4*x^6 + 20*x^3 + 16*x^2 multPorTerm :: (Num t, Eq t) => Polinomio t -> Polinomio t -> Polinomio t multPorTerm term pol | esPolCero pol = polCero | otherwise = consPol (n+m) (a*b) (multPorTerm term r) where n = grado term a = coefLider term m = grado pol b = coefLider pol r = restoPol pol -- (multPol p q) es el producto de los polinomios p y q. Por -- ejemplo, -- λ> ejPol1 -- 3*x^4 + -5*x^2 + 3 -- λ> ejPol2 -- x^5 + 5*x^2 + 4*x -- λ> multPol ejPol1 ejPol2 -- 3*x^9 + -5*x^7 + 15*x^6 + 15*x^5 + -25*x^4 + -20*x^3 + 15*x^2 + 12*x multPol :: (Num a, Eq a) => Polinomio a -> Polinomio a -> Polinomio a multPol p q | esPolCero p = polCero | otherwise = sumaPol (multPorTerm (termLider p) q) (multPol (restoPol p) q) -- Propiedad. El producto de polinomios es conmutativo. prop_conmutativaProducto :: Polinomio Int -> Polinomio Int -> Bool prop_conmutativaProducto p q = multPol p q == multPol q p -- La comprobación es -- λ> quickCheck prop_conmutativaProducto -- OK, passed 100 tests. -- El producto es distributivo respecto de la suma. prop_distributivaProductoSuma :: Polinomio Int -> Polinomio Int -> Polinomio Int -> Bool prop_distributivaProductoSuma p q r = multPol p (sumaPol q r) == sumaPol (multPol p q) (multPol p r) -- Comprobación: -- λ> quickCheck prop_distributivaProductoSuma -- OK, passed 100 tests. -- polUnidad es el polinomio unidad. Por ejemplo, -- λ> polUnidad -- 1 polUnidad :: (Num t, Eq t) => Polinomio t polUnidad = consPol 0 1 polCero -- Propiedad. El polinomio unidad es el elemento neutro del producto. prop_polUnidad :: Polinomio Int -> Bool prop_polUnidad p = multPol p polUnidad == p -- Comprobación: -- λ> quickCheck prop_polUnidad -- OK, passed 100 tests. -- --------------------------------------------------------------------- -- Valor de un polinomio en un punto -- -- --------------------------------------------------------------------- -- (valor p c) es el valor del polinomio p al sustituir su variable por -- c. Por ejemplo, -- ejPol1 == 3*x^4 + -5*x^2 + 3 -- valor ejPol1 0 == 3 -- valor ejPol1 1 == 1 -- valor ejPol1 (-2) == 31 valor:: (Num a, Eq a) => Polinomio a -> a -> a valor p c | esPolCero p = 0 | otherwise = b*c^n + valor r c where n = grado p b = coefLider p r = restoPol p -- --------------------------------------------------------------------- -- Verificación de raices de polinomios -- -- --------------------------------------------------------------------- -- (esRaiz c p) se verifica si c es una raiz del polinomio p. por -- ejemplo, -- ejPol3 == 6*x^4 + 2*x -- esRaiz 1 ejPol3 == False -- esRaiz 0 ejPol3 == True esRaiz :: (Num a, Eq a) => a -> Polinomio a -> Bool esRaiz c p = valor p c == 0 -- --------------------------------------------------------------------- -- Derivación de polinomios -- -- --------------------------------------------------------------------- -- (derivada p) es la derivada del polinomio p. Por ejemplo, -- ejPol2 == x^5 + 5*x^2 + 4*x -- derivada ejPol2 == 5*x^4 + 10*x + 4 derivada :: (Eq a, Num a) => Polinomio a -> Polinomio a derivada p | n == 0 = polCero | otherwise = consPol (n-1) (b * fromIntegral n) (derivada r) where n = grado p b = coefLider p r = restoPol p -- Propiedad. La derivada de la suma es la suma de las derivadas. prop_derivada :: Polinomio Int -> Polinomio Int -> Bool prop_derivada p q = derivada (sumaPol p q) == sumaPol (derivada p) (derivada q) -- Comprobación -- λ> quickCheck prop_derivada -- OK, passed 100 tests. -- --------------------------------------------------------------------- -- Resta de polinomios -- -- --------------------------------------------------------------------- -- (resta p q) es la el polinomio obtenido restándole a p el q. Por -- ejemplo, -- ejPol1 == 3*x^4 + -5*x^2 + 3 -- ejPol2 == x^5 + 5*x^2 + 4*x -- restaPol ejPol1 ejPol2 == -1*x^5 + 3*x^4 + -10*x^2 + -4*x + 3 restaPol :: (Num a, Eq a) => Polinomio a -> Polinomio a -> Polinomio a restaPol p q = sumaPol p (multPorTerm (creaTermino 0 (-1)) q) -- --------------------------------------------------------------------- -- § Verificación -- -- --------------------------------------------------------------------- return [] verificaPolOperaciones :: IO Bool verificaPolOperaciones = $quickCheckAll -- La verificación es -- λ> verificaPolOperaciones -- === prop_neutroSumaPol from PolOperaciones.hs:103 === -- +++ OK, passed 100 tests. -- -- === prop_conmutativaSuma from PolOperaciones.hs:112 === -- +++ OK, passed 100 tests. -- -- === prop_conmutativaProducto from PolOperaciones.hs:154 === -- +++ OK, passed 100 tests. -- -- === prop_distributivaProductoSuma from PolOperaciones.hs:163 === -- +++ OK, passed 100 tests. -- -- === prop_polUnidad from PolOperaciones.hs:179 === -- +++ OK, passed 100 tests. -- -- === prop_derivada from PolOperaciones.hs:233 === -- +++ OK, passed 100 tests. -- -- True
jaalonso/I1M-Cod-Temas
src/Tema_21/PolOperaciones.hs
gpl-2.0
10,157
0
11
2,609
1,670
892
778
95
1
data Vector t = Vector t t t deriving(Show) vplus::(Num t)=>Vector t->Vector t->Vector t Vector i j k `vplus` Vector x y z = Vector (i+x) (j+y) (k+z)
srijanshetty/haskell-sample
Vector.hs
gpl-2.0
152
0
8
30
108
55
53
3
1
{- Copyright (C) 2009 John Millikin <[email protected]> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. -} module Tests.Core (coreTests) where import Control.Monad (unless) import Test.HUnit import Network.Protocol.XMPP coreTests = "coreTests" ~: TestList [jidTests] ------------------------------------------------------------------------------- jidTests = "jidTests" ~: TestList [ buildNodeTests ,buildDomainTests ,buildResourceTests ,buildJIDTests ,parseJIDTests ,formatJIDTests ,jidPartTests ] buildNodeTests = "buildNodeTests" ~: TestList [ -- TODO: stringprep, validation testStr "" Nothing ,testStr "a" (Just "a") ] where testStr s expected = let maybeNode = mkJIDNode s value = maybe Nothing (\x -> Just (jidNodeStr x)) maybeNode in expected ~=? value buildDomainTests = "buildDomainTests" ~: TestList [ -- TODO: stringprep, validation testStr "" Nothing ,testStr "a" (Just "a") ] where testStr s expected = let maybeDomain = mkJIDDomain s value = maybe Nothing (\x -> Just (jidDomainStr x)) maybeDomain in expected ~=? value buildResourceTests = "buildResourceTests" ~: TestList [ -- TODO: stringprep, validation testStr "" Nothing ,testStr "a" (Just "a") ] where testStr s expected = let maybeResource = mkJIDResource s value = maybe Nothing (\x -> Just (jidResourceStr x)) maybeResource in expected ~=? value buildJIDTests = "buildJIDTests" ~: TestList [ -- TODO: stringprep, validation of segments mkJID "" "" "" ~?= Nothing ,mkJID "a" "" "" ~?= Nothing ,mkJID "" "b" "" ~?/= Nothing ,mkJID "" "" "c" ~?= Nothing ,mkJID "a" "b" "" ~?/= Nothing ,mkJID "a" "" "c" ~?= Nothing ,mkJID "" "b" "c" ~?/= Nothing ,mkJID "a" "b" "c" ~?/= Nothing ] parseJIDTests = "parseJIDTests" ~: TestList [ testJIDParse "b" (mkJID "" "b" "") ,testJIDParse "a@b" (mkJID "a" "b" "") ,testJIDParse "b/c" (mkJID "" "b" "c") ,testJIDParse "a@b/c" (mkJID "a" "b" "c") ] where testJIDParse s expected = expected ~=? (jidParse s) formatJIDTests = "formatJIDTests" ~: TestList [ testJIDFormat (mkJID "" "b" "") "b" ,testJIDFormat (mkJID "a" "b" "") "a@b" ,testJIDFormat (mkJID "" "b" "c") "b/c" ,testJIDFormat (mkJID "a" "b" "c") "a@b/c" ] where testJIDFormat maybeJID expected = TestCase $ case maybeJID of Nothing -> assertFailure "mkJID returned Nothing" (Just jid) -> expected @=? (jidFormat jid) jidPartTests = "jidPartTests" ~: TestList [ testJIDPart (mkJID "" "b" "") jidNode "" ,testJIDPart (mkJID "a" "b" "") jidNode "a" ,testJIDPart (mkJID "" "b" "") jidDomain "b" ,testJIDPart (mkJID "" "b" "") jidResource "" ,testJIDPart (mkJID "" "b" "c") jidResource "c" ] where testJIDPart maybeJID f expected = TestCase $ case maybeJID of Nothing -> assertFailure "mkJID returned Nothing" (Just jid) -> expected @=? (f jid) ------------------------------------------------------------------------------- assertNotEqual :: (Eq a, Show a) => String -> a -> a -> Assertion assertNotEqual preface unexpected actual = unless (actual /= unexpected) (assertFailure msg) where msg = (if null preface then "" else preface ++ "\n") ++ "got unexpected: " ++ show actual (@/=?) :: (Eq a, Show a) => a -> a -> Assertion unexpected @/=? actual = assertNotEqual "" unexpected actual (@?/=) :: (Eq a, Show a) => a -> a -> Assertion actual @?/= unexpected = assertNotEqual "" unexpected actual (~/=?) :: (Eq a, Show a) => a -> a -> Test unexpected ~/=? actual = TestCase (unexpected @/=? actual) (~?/=) :: (Eq a, Show a) => a -> a -> Test actual ~?/= unexpected = TestCase (actual @?/= unexpected)
astro/network-protocol-xmpp
Tests/Core.hs
gpl-3.0
4,198
36
16
799
1,228
630
598
79
2
{-# LANGUAGE DeriveDataTypeable #-} -- | -- Copyright : (c) 2010, 2011 Benedikt Schmidt & Simon Meier -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <[email protected]> -- Portability : GHC only -- -- Helpers for inspecting the environment of the Tamarin prover. module Main.Environment where import Data.Char (isSpace, toLower) import Data.List import Data.Maybe (fromMaybe) import Control.Exception as E import System.Console.CmdArgs.Explicit import System.Environment import System.Exit import System.IO import System.Process import Main.Console ------------------------------------------------------------------------------ -- Retrieving the paths to required tools. ------------------------------------------------------------------------------ -- | Flags for handing over the path to the maude and 'dot' tool. toolFlags :: [Flag Arguments] toolFlags = [ flagOpt "dot" ["with-dot"] (updateArg "withDot") "FILE" "Path to GraphViz 'dot' tool" , flagOpt "maude" ["with-maude"] (updateArg "withMaude") "FILE" "Path to 'maude' rewriting tool" ] -- | Path to maude tool maudePath :: Arguments -> FilePath maudePath = fromMaybe "maude" . findArg "withMaude" -- | Path to dot tool dotPath :: Arguments -> FilePath dotPath = fromMaybe "dot" . findArg "withDot" ------------------------------------------------------------------------------ -- Inspecting the environment ------------------------------------------------------------------------------ -- | Get the string constituting the command line. getCommandLine :: IO String getCommandLine = do arguments <- getArgs return . concat . intersperse " " $ programName : arguments -- | Read the cpu info using a call to cat /proc/cpuinfo getCpuModel :: IO String getCpuModel = handle handler $ do (_, info, _) <- readProcessWithExitCode "cat" ["/proc/cpuinfo"] [] return $ maybe errMsg (("Linux running on an "++) . drop 2 . dropWhile (/=':')) (find (isPrefixOf "model name") $ lines info) where errMsg = "could not extract CPU model" handler :: IOException -> IO String handler _ = return errMsg -- | Build the command line corresponding to a program arguments tuple. commandLine :: String -> [String] -> String commandLine prog args = concat $ intersperse " " $ prog : args -- | Test if a process is executable and check its response. This is used to -- determine the versions and capabilities of tools that we depend on. testProcess :: (String -> String -> Either String String) -- ^ Analysis of stdout, stderr. Use 'Left' to report error. -> String -- ^ Default error message to display to the user. -> String -- ^ Test description to display. -> FilePath -- ^ Process to start -> [String] -- ^ Arguments -> String -- ^ Stdin -> IO Bool -- ^ True, if test was successful testProcess check defaultMsg testName prog args inp = do putStr testName hFlush stdout handle handler $ do (exitCode, out, err) <- readProcessWithExitCode prog args inp let errMsg reason = do putStrLn reason putStrLn $ "Detailed results from testing '" ++ prog ++ "'" putStrLn $ " command: " ++ commandLine prog args putStrLn $ " stdin: " ++ inp putStrLn $ " stdout:\n" ++ out putStrLn $ " stderr:\n" ++ err return False case exitCode of ExitFailure code -> errMsg $ "failed with exit code " ++ show code ++ "\n\n" ++ defaultMsg ExitSuccess -> case check out err of Left msg -> errMsg msg Right msg -> do putStrLn msg return True where handler :: IOException -> IO Bool handler _ = do putStrLn "caught exception while executing:" putStrLn $ commandLine prog args putStrLn $ "with input: " ++ inp return False -- | Ensure a suitable version of the Graphviz dot tool is installed. ensureGraphVizDot :: Arguments -> IO Bool ensureGraphVizDot as = do putStrLn $ "GraphViz tool: '" ++ dot ++ "'" testProcess check errMsg " checking version: " dot ["-V"] "" where dot = dotPath as check _ err | "graphviz" `isInfixOf` map toLower err = Right $ init err ++ ". OK." | otherwise = Left $ errMsg errMsg = unlines [ "WARNING:" , "" , " The dot tool seems not to be provided by Graphviz." , " Graph generation might not work." , " Please download an official version from:" , " http://www.graphviz.org/" ] -- | Ensure a suitable version of Maude is installed. ensureMaude :: Arguments -> IO Bool ensureMaude as = do putStrLn $ "maude tool: '" ++ maude ++ "'" t1 <- testProcess checkVersion errMsg' " checking version: " maude ["--version"] "" t2 <- testProcess checkInstall errMsg' " checking installation: " maude [] "quit\n" return (t1 && t2) where maude = maudePath as checkVersion out _ | filter (not . isSpace) out == "2.6" = Right "2.6. OK." | filter (not . isSpace) out == "2.7" = Right "2.7. OK." | otherwise = Left $ errMsg $ " 'maude --version' returned wrong version '" ++ out ++ "'" checkInstall _ [] = Right "OK." checkInstall _ err = Left $ errMsg err errMsg' = errMsg $ "'" ++ maude ++ "' executable not found / does not work" errMsg reason = unlines [ "WARNING:" , "" , reason , " " ++ programName ++ " will likely not work." , " Please download 'Core Maude 2.7' (or 2.6) from:" , " http://maude.cs.uiuc.edu/download/" , " Note that 'prelude.maude' must be in the same directory as the 'maude' executable." ]
ekr/tamarin-prover
src/Main/Environment.hs
gpl-3.0
6,102
0
18
1,788
1,197
607
590
108
3
<?xml version='1.0' encoding='ISO-8859-1' ?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 1.0//EN" "http://java.sun.com/products/javahelp/helpset_1_0.dtd"> <helpset version="1.0"> <!-- title --> <title>Xena - Help</title> <!-- maps --> <maps> <mapref location="xena/plugin/basic/Map.jhm"/> </maps> <view mergetype="javax.help.UniteAppendMerge"> <name>TOC</name> <label>Table Of Contents</label> <type>javax.help.TOCView</type> <data>xena/plugin/basic/TOC.xml</data> </view> </helpset>
srnsw/xena
plugins/basic/doc/BasicHelp.hs
gpl-3.0
585
41
32
104
213
108
105
-1
-1
{- ============================================================================ | Copyright 2011 Matthew D. Steele <[email protected]> | | | | This file is part of Fallback. | | | | Fallback 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. | | | | Fallback 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 Fallback. If not, see <http://www.gnu.org/licenses/>. | ============================================================================ -} module Fallback.View.Region (RegionAction(..), newRegionView) where import Control.Applicative ((<$>)) import Data.Foldable (traverse_) import Data.List (find) import qualified Data.Set as Set import Fallback.Data.Clock (clockZigzag) import Fallback.Data.Color (Tint(Tint), whiteColor) import Fallback.Data.Couple (flattenCoupleSet, fromCouple) import Fallback.Data.Point import Fallback.Draw import Fallback.Event import Fallback.Scenario.Areas (areaLinks, areaLocation) import Fallback.State.Party (partyClearedArea) import Fallback.State.Region import Fallback.State.Resources (FontTag(FontChancery18), Resources, rsrcFont) import Fallback.State.Tags (AreaTag, areaName, regionAreas) import Fallback.View.Base import Fallback.View.Widget (newSimpleTextButton) ------------------------------------------------------------------------------- data RegionAction = SelectAreaNode AreaTag | TravelToSelectedArea | ShowMenu newRegionView :: (MonadDraw m) => Resources -> String -> m (View RegionState RegionAction) newRegionView resources bgPath = do compoundViewM [(newRegionMapView resources bgPath), (subView_ (Rect 20 436 120 24) <$> newSimpleTextButton resources "Menu" [KeyEscape, KeyM] ShowMenu), (subView_ (Rect 500 436 120 24) <$> newSimpleTextButton resources "Travel" [KeyReturn] TravelToSelectedArea)] newRegionMapView :: (MonadDraw m) => Resources -> String -> m (View RegionState RegionAction) newRegionMapView resources bgPath = do clearedNodeSprite <- loadSubSprite "gui/area-nodes.png" $ Rect 0 0 14 12 unclearedNodeSprite <- loadSubSprite "gui/area-nodes.png" $ Rect 14 0 14 12 selectedNodeStrip <- loadVStrip "gui/area-select.png" 4 backgroundSprite <- loadSprite bgPath let paint rs = do -- Paint background: rect <- canvasRect blitStretch backgroundSprite rect -- Paint selected area name: let selected = rsSelectedArea rs drawText (rsrcFont resources FontChancery18) whiteColor (LocCenter (Point 320 448 :: IPoint)) (areaName selected) -- Paint links: let foundLinks = rsFoundAreaLinks rs let drawLink (tag1, tag2) = do let pos1 = fmap fromIntegral $ areaLocation tag1 let pos2 = fmap fromIntegral $ areaLocation tag2 let perp = pPolar (2 :: Double) (pAtan2 (pos2 `pSub` pos1) + pi/2) let selectedTint = Tint 255 0 0 192 let normalTint = Tint 255 255 0 192 let (tint1, tint2) = if (tag1, tag2) == (selected, rsPreviousArea rs) then (selectedTint, normalTint) else if (tag1, tag2) == (rsPreviousArea rs, selected) then (normalTint, selectedTint) else (normalTint, normalTint) gradientPolygon [(tint1, pos1 `pAdd` perp), (tint1, pos1 `pSub` perp), (tint2, pos2 `pSub` perp), (tint2, pos2 `pAdd` perp)] let isRealLink (tag1, tag2) = Set.member tag1 $ areaLinks tag2 traverse_ drawLink (filter isRealLink $ map fromCouple $ Set.toList $ foundLinks) -- Paint area nodes: let party = rsParty rs let paintAreaNode tag = do let sprite = if partyClearedArea party tag then clearedNodeSprite else unclearedNodeSprite blitLoc sprite $ LocCenter $ areaLocation tag traverse_ paintAreaNode $ flattenCoupleSet foundLinks -- Paint selection marker: blitLoc (selectedNodeStrip ! clockZigzag 4 2 (rsClock rs)) $ LocCenter $ areaLocation $ selected handler rs (EvMouseDown pt) = do let hit tag = pDist (fromIntegral <$> pt) (fromIntegral <$> areaLocation tag) <= (20 :: Double) return $ maybe Ignore Action $ fmap SelectAreaNode $ find hit $ regionAreas $ rsRegion rs handler _ _ = return Ignore return $ View paint handler -------------------------------------------------------------------------------
mdsteele/fallback
src/Fallback/View/Region.hs
gpl-3.0
5,589
0
26
1,752
1,155
607
548
80
5
-- Copyright 2016, 2017 Robin Raymond -- -- This file is part of Purple Muon -- -- Purple Muon 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. -- -- Purple Muon 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 Purple Muon. If not, see <http://www.gnu.org/licenses/>. {-| Module : Client.States.Types Description : Abstraction over states the client can be in. Copyright : (c) Robin Raymond, 2016-2017 License : GPL-3 Maintainer : [email protected] Portability : POSIX -} {-# LANGUAGE TemplateHaskell #-} module Client.States.Types ( State(..), inGameState, menuState , CommonState(..), resolution, events ) where import qualified Control.Lens as CLE import qualified SDL import qualified Client.States.InGameState.Types as CSIT import qualified Client.States.MenuState.Types as CSMT import qualified Client.Video.Types as CVT -- Info that is used by all states data CommonState = CommonState { _resolution :: CVT.Resolution -- ^ The current resolution of the screen , _events :: [SDL.Event] -- ^ Events to be handled by the state } data State = InGameState { _inGameState :: CSIT.State } | MenuState { _menuState :: CSMT.State } CLE.makeLenses ''State CLE.makeLenses ''CommonState
r-raymond/purple-muon
src/Client/States/Types.hs
gpl-3.0
1,774
0
10
389
175
120
55
20
0
{-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-} module Object ( Object(..) , objectCenter, objectRadius, objectFaces , Face(..) , faceColor, facePlane , inReach , intersectObject ) where import Linear import Linear.Affine import Control.Lens hiding (transform) import Constraints.Scalar import Constraints.Vector import Geometry.Hyperplane import Color import Transformation -- A graphical object. data Object v a = Object { _objectCenter :: Point v a , _objectRadius :: a , _objectFaces :: [Face v a] } deriving (Functor, Show) -- A face of an object. data Face v a = Face { _faceColor :: Color , _facePlane :: Hyperplane v a } deriving (Functor, Show) makeLenses ''Object makeLenses ''Face instance (SomeVector v) => Transformable v (Face v) where transform = over facePlane . transform instance (SomeVector v) => Transformable v (Object v) where transform t = (objectFaces . each %~ transform t) . (objectCenter %~ transform t) inReach :: (SomeVector v, SomeScalar a) => Point v a -> a -> Object v a -> Bool inReach p r o = distance p (o ^. objectCenter) <= r + (o ^. objectRadius) -- Intersect an object with a linear subspace. intersectObject :: (Additive v', Metric v, Floating a, Ord a) => Lens' (v a) (v' a) -> Object v a -> Maybe (Object v' a) intersectObject lens o = if dist >= (o ^. objectRadius) then Nothing else Just $ Object newCenter newRadius newFaces where dist = norm $ (o ^. objectCenter . _Point) & lens .~ zero newCenter = (o ^. objectCenter . _Point . lens . from _Point) newRadius = sqrt $ (o ^. objectRadius)^2 - dist^2 newFaces = (o ^. objectFaces) & each . facePlane . planeNormal %~ view lens
MatthiasHu/4d-labyrinth
src/Object.hs
gpl-3.0
1,829
0
12
379
605
330
275
-1
-1
module Main ( main ) where import EightPuzzle import EightPuzzle.PriorityQueue import Control.Monad.ST (runST, ST) import Control.Monad.IO.Class (liftIO) import Control.Monad.Writer (runWriter, tell, runWriterT, Writer, writer, WriterT, execWriterT) import Control.Monad.Trans.Class (lift) import Control.Monad (forM_) main :: IO () main = do let result = runST $ execWriterT $ run2 mapM_ putStrLn result run2 :: WriterT [String] (ST s) () run2 = do pq <- lift $ newPQ forM_ [1..130000] $ \num -> do lift $ insert pq num forM_ [1..130000] $ \_ -> do lift $ delMin pq run1 :: WriterT [String] (ST s) () run1 = do logMsg "starting..." pq <- lift $ newPQ logSTOp "new pq, initial size" $ size pq lift $ insert pq (3 :: Int) logSTOp "after insert 3, size" $ size pq logSTOp "after insert 3, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete 3, size" $ size pq logSTOp "after delete 3, min" $ minOfPQ pq lift $ insert pq 4 logSTOp "after insert 4, size" $ size pq logSTOp "after insert 4, min" $ minOfPQ pq lift $ insert pq 2 logSTOp "after insert 2, size" $ size pq logSTOp "after insert 2, min" $ minOfPQ pq lift $ insert pq 5 logSTOp "after insert 5, size" $ size pq logSTOp "after insert 5, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete 2, size" $ size pq logSTOp "after delete 2, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete 4, size" $ size pq logSTOp "after delete 4, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete 5, size" $ size pq logSTOp "after delete 5, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete ?, size" $ size pq logSTOp "after delete ?, min" $ minOfPQ pq lift $ insert pq 9 logSTOp "after insert 9, size" $ size pq logSTOp "after insert 9, min" $ minOfPQ pq lift $ insert pq 8 logSTOp "after insert 8, size" $ size pq logSTOp "after insert 8, min" $ minOfPQ pq lift $ insert pq 7 logSTOp "after insert 7, size" $ size pq logSTOp "after insert 7, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete 7, size" $ size pq logSTOp "after delete 7, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete 8, size" $ size pq logSTOp "after delete 8, min" $ minOfPQ pq lift $ delMin pq logSTOp "after delete 9, size" $ size pq logSTOp "after delete 9, min" $ minOfPQ pq {- lift $ insert pq 1 logSTOp "after insert 1, size" $ size pq logSTOp "after insert 1, min" $ minOfPQ pq lift $ insert pq 5 logSTOp "after insert 5, size" $ size pq logSTOp "after insert 5, min" $ minOfPQ pq -} return () where --logSTOp :: (Monad m, Show a) => String -> ST s a -> WriterT [String] (ST s) () logSTOp :: (Monad m, Show a) => String -> m a -> WriterT [String] m () logSTOp message stOperation = do result <- lift stOperation logMsg (message ++ ": " ++ show result) logMsg :: (Monad m) => String -> WriterT [String] m () logMsg message = tell [message]
cdepillabout/coursera
algorithms1/week4/src/Main.hs
gpl-3.0
3,400
0
12
1,136
992
446
546
76
1
module HTCF.TcfParser ( mkTcfElement , mkTcfElementButStructure , mkTcfText , mkTcfTextFromCharRef , mkTcfStructure , mkTcfLineBreak ) where import Text.XML.HXT.Core import qualified Text.XML.HXT.DOM.XmlNode as XN import Data.Maybe import HTCF.TcfParserTypeDefs import HTCF.Position import HTCF.ConfigParser import HTCF.ArrowXml -- | @mkTcfElement@ can be used to generate a (deterministic) list of -- 'TcfElement's, which can then be feed to the tokenizer or a -- serializer for the text layer or structure layer. It simply -- combines the arrows for the different layers and additional -- tokenizer information. -- -- Usage: @multi mkTcfElement@ mkTcfElement :: [Config] -> IOSLA (XIOState [Int]) XmlTree TcfElement mkTcfElement cfg = mkTcfStructure <+> mkTcfText <+> mkTcfTextFromCharRef <+> mkTcfLineBreak cfg -- | Like 'mkTcfElement', but without structure elements. Use this -- instead of @mkTcfElement@ if no structure layer is to be produced. mkTcfElementButStructure :: [Config] -> IOSLA (XIOState [Int]) XmlTree TcfElement mkTcfElementButStructure cfg = mkTcfText <+> mkTcfTextFromCharRef <+> mkTcfLineBreak cfg -- | An arrow for parsing text nodes into the text layer. mkTcfText :: IOSLA (XIOState [Int]) XmlTree TcfElement mkTcfText = getText &&& arr (const 0) &&& -- text offset getXmlPosition >>> arr (\(t, (tOffset, xPos)) -> TcfText t tOffset (mkCharPositions t xPos)) where mkCharPositions t ((Just start), (Just end)) | length t == end - start + 1 = [((Just i), (Just i)) | i <- [start .. end]] mkCharPositions t (_, _) = replicate (length t) (Nothing, Nothing) -- | An arrow for parsing char refs into the text layer. mkTcfTextFromCharRef :: IOSLA (XIOState [Int]) XmlTree TcfElement mkTcfTextFromCharRef = isCharRef >>> getCharRef &&& arr (const 0) &&& getXmlPosition >>> arr (\(i, (tOffset, xPos)) -> TcfText [toEnum i] tOffset [xPos]) -- | An arrow for parsing tags into the structure layer. mkTcfStructure :: IOSLA (XIOState [Int]) XmlTree TcfElement mkTcfStructure = isElem >>> getQName &&& arr (const 0) &&& -- start position in text layer arr (length . collectText) &&& -- length in text layer getXmlPosition >>> arr (\(qN, (tStart, (tLength, xPos))) -> TcfStructure qN tStart tLength (fst xPos) (snd xPos)) -- | Collect all text nodes in the current subtree. collectText :: XmlTree -> String collectText (XN.NTree n cs) | XN.isElem n = concatMap collectText cs | XN.isText n = fromMaybe "" $ XN.getText n | XN.isCharRef n = fromMaybe "" $ fmap (\i -> [toEnum i]) $ XN.getCharRef n | otherwise = "" -- | An arrow for parsing line breaks and gerating a signal for the -- tokenizer. mkTcfLineBreak :: [Config] -> IOSLA (XIOState [Int]) XmlTree TcfElement mkTcfLineBreak cfg = isElem >>> (qNameIn $ getLineBreaks cfg) >>> arr (const TcfLineBreak)
lueck/htcf
src/HTCF/TcfParser.hs
gpl-3.0
2,883
0
13
532
784
421
363
62
2
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Gmail.Users.Settings.Filters.Create -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Creates a filter. -- -- /See:/ <https://developers.google.com/gmail/api/ Gmail API Reference> for @gmail.users.settings.filters.create@. module Network.Google.Resource.Gmail.Users.Settings.Filters.Create ( -- * REST Resource UsersSettingsFiltersCreateResource -- * Creating a Request , usersSettingsFiltersCreate , UsersSettingsFiltersCreate -- * Request Lenses , usfcPayload , usfcUserId ) where import Network.Google.Gmail.Types import Network.Google.Prelude -- | A resource alias for @gmail.users.settings.filters.create@ method which the -- 'UsersSettingsFiltersCreate' request conforms to. type UsersSettingsFiltersCreateResource = "gmail" :> "v1" :> "users" :> Capture "userId" Text :> "settings" :> "filters" :> QueryParam "alt" AltJSON :> ReqBody '[JSON] Filter :> Post '[JSON] Filter -- | Creates a filter. -- -- /See:/ 'usersSettingsFiltersCreate' smart constructor. data UsersSettingsFiltersCreate = UsersSettingsFiltersCreate' { _usfcPayload :: !Filter , _usfcUserId :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'UsersSettingsFiltersCreate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'usfcPayload' -- -- * 'usfcUserId' usersSettingsFiltersCreate :: Filter -- ^ 'usfcPayload' -> UsersSettingsFiltersCreate usersSettingsFiltersCreate pUsfcPayload_ = UsersSettingsFiltersCreate' { _usfcPayload = pUsfcPayload_ , _usfcUserId = "me" } -- | Multipart request metadata. usfcPayload :: Lens' UsersSettingsFiltersCreate Filter usfcPayload = lens _usfcPayload (\ s a -> s{_usfcPayload = a}) -- | User\'s email address. The special value \"me\" can be used to indicate -- the authenticated user. usfcUserId :: Lens' UsersSettingsFiltersCreate Text usfcUserId = lens _usfcUserId (\ s a -> s{_usfcUserId = a}) instance GoogleRequest UsersSettingsFiltersCreate where type Rs UsersSettingsFiltersCreate = Filter type Scopes UsersSettingsFiltersCreate = '["https://www.googleapis.com/auth/gmail.settings.basic"] requestClient UsersSettingsFiltersCreate'{..} = go _usfcUserId (Just AltJSON) _usfcPayload gmailService where go = buildClient (Proxy :: Proxy UsersSettingsFiltersCreateResource) mempty
rueshyna/gogol
gogol-gmail/gen/Network/Google/Resource/Gmail/Users/Settings/Filters/Create.hs
mpl-2.0
3,349
0
15
750
386
233
153
62
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS_GHC -fno-warn-duplicate-exports #-} {-# OPTIONS_GHC -fno-warn-unused-binds #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.Resource.Compute.TargetHTTPSProxies.Delete -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <[email protected]> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Deletes the specified TargetHttpsProxy resource. -- -- /See:/ <https://developers.google.com/compute/docs/reference/latest/ Compute Engine API Reference> for @compute.targetHttpsProxies.delete@. module Network.Google.Resource.Compute.TargetHTTPSProxies.Delete ( -- * REST Resource TargetHTTPSProxiesDeleteResource -- * Creating a Request , targetHTTPSProxiesDelete , TargetHTTPSProxiesDelete -- * Request Lenses , thpdProject , thpdTargetHTTPSProxy ) where import Network.Google.Compute.Types import Network.Google.Prelude -- | A resource alias for @compute.targetHttpsProxies.delete@ method which the -- 'TargetHTTPSProxiesDelete' request conforms to. type TargetHTTPSProxiesDeleteResource = "compute" :> "v1" :> "projects" :> Capture "project" Text :> "global" :> "targetHttpsProxies" :> Capture "targetHttpsProxy" Text :> QueryParam "alt" AltJSON :> Delete '[JSON] Operation -- | Deletes the specified TargetHttpsProxy resource. -- -- /See:/ 'targetHTTPSProxiesDelete' smart constructor. data TargetHTTPSProxiesDelete = TargetHTTPSProxiesDelete' { _thpdProject :: !Text , _thpdTargetHTTPSProxy :: !Text } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'TargetHTTPSProxiesDelete' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'thpdProject' -- -- * 'thpdTargetHTTPSProxy' targetHTTPSProxiesDelete :: Text -- ^ 'thpdProject' -> Text -- ^ 'thpdTargetHTTPSProxy' -> TargetHTTPSProxiesDelete targetHTTPSProxiesDelete pThpdProject_ pThpdTargetHTTPSProxy_ = TargetHTTPSProxiesDelete' { _thpdProject = pThpdProject_ , _thpdTargetHTTPSProxy = pThpdTargetHTTPSProxy_ } -- | Project ID for this request. thpdProject :: Lens' TargetHTTPSProxiesDelete Text thpdProject = lens _thpdProject (\ s a -> s{_thpdProject = a}) -- | Name of the TargetHttpsProxy resource to delete. thpdTargetHTTPSProxy :: Lens' TargetHTTPSProxiesDelete Text thpdTargetHTTPSProxy = lens _thpdTargetHTTPSProxy (\ s a -> s{_thpdTargetHTTPSProxy = a}) instance GoogleRequest TargetHTTPSProxiesDelete where type Rs TargetHTTPSProxiesDelete = Operation type Scopes TargetHTTPSProxiesDelete = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute"] requestClient TargetHTTPSProxiesDelete'{..} = go _thpdProject _thpdTargetHTTPSProxy (Just AltJSON) computeService where go = buildClient (Proxy :: Proxy TargetHTTPSProxiesDeleteResource) mempty
rueshyna/gogol
gogol-compute/gen/Network/Google/Resource/Compute/TargetHTTPSProxies/Delete.hs
mpl-2.0
3,615
0
15
793
388
233
155
66
1
{-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} module Language.Haskell.Brittany.Internal.Layouters.Pattern where import qualified Data.Foldable as Foldable import qualified Data.Sequence as Seq import qualified Data.Text as Text import GHC (GenLocated(L), ol_val) import GHC.Hs import qualified GHC.OldList as List import GHC.Types.Basic import Language.Haskell.Brittany.Internal.LayouterBasics import {-# SOURCE #-} Language.Haskell.Brittany.Internal.Layouters.Expr import Language.Haskell.Brittany.Internal.Layouters.Type import Language.Haskell.Brittany.Internal.Prelude import Language.Haskell.Brittany.Internal.PreludeUtils import Language.Haskell.Brittany.Internal.Types -- | layouts patterns (inside function bindings, case alternatives, let -- bindings or do notation). E.g. for input -- > case computation of -- > (warnings, Success a b) -> .. -- This part ^^^^^^^^^^^^^^^^^^^^^^^ of the syntax tree is layouted by -- 'layoutPat'. Similarly for -- > func abc True 0 = [] -- ^^^^^^^^^^ this part -- We will use `case .. of` as the imagined prefix to the examples used in -- the different cases below. layoutPat :: LPat GhcPs -> ToBriDocM (Seq BriDocNumbered) layoutPat lpat@(L _ pat) = docWrapNode lpat $ case pat of WildPat _ -> fmap Seq.singleton $ docLit $ Text.pack "_" -- _ -> expr VarPat _ n -> fmap Seq.singleton $ docLit $ lrdrNameToText n -- abc -> expr LitPat _ lit -> fmap Seq.singleton $ allocateNode $ litBriDoc lit -- 0 -> expr ParPat _ inner -> do -- (nestedpat) -> expr left <- docLit $ Text.pack "(" right <- docLit $ Text.pack ")" innerDocs <- colsWrapPat =<< layoutPat inner return $ Seq.empty Seq.|> left Seq.|> innerDocs Seq.|> right -- return $ (left Seq.<| innerDocs) Seq.|> right -- case Seq.viewl innerDocs of -- Seq.EmptyL -> fmap return $ docLit $ Text.pack "()" -- this should never occur.. -- x1 Seq.:< rest -> case Seq.viewr rest of -- Seq.EmptyR -> -- fmap return $ docSeq -- [ docLit $ Text.pack "(" -- , return x1 -- , docLit $ Text.pack ")" -- ] -- middle Seq.:> xN -> do -- x1' <- docSeq [docLit $ Text.pack "(", return x1] -- xN' <- docSeq [return xN, docLit $ Text.pack ")"] -- return $ (x1' Seq.<| middle) Seq.|> xN' ConPat _ lname (PrefixCon args) -> do -- Abc a b c -> expr nameDoc <- lrdrNameToTextAnn lname argDocs <- layoutPat `mapM` args if null argDocs then return <$> docLit nameDoc else do x1 <- appSep (docLit nameDoc) xR <- fmap Seq.fromList $ sequence $ spacifyDocs $ fmap colsWrapPat argDocs return $ x1 Seq.<| xR ConPat _ lname (InfixCon left right) -> do -- a :< b -> expr nameDoc <- lrdrNameToTextAnn lname leftDoc <- appSep . colsWrapPat =<< layoutPat left rightDoc <- colsWrapPat =<< layoutPat right middle <- appSep $ docLit nameDoc return $ Seq.empty Seq.|> leftDoc Seq.|> middle Seq.|> rightDoc ConPat _ lname (RecCon (HsRecFields [] Nothing)) -> do -- Abc{} -> expr let t = lrdrNameToText lname fmap Seq.singleton $ docLit $ t <> Text.pack "{}" ConPat _ lname (RecCon (HsRecFields fs@(_ : _) Nothing)) -> do -- Abc { a = locA, b = locB, c = locC } -> expr1 -- Abc { a, b, c } -> expr2 let t = lrdrNameToText lname fds <- fs `forM` \(L _ (HsRecField (L _ fieldOcc) fPat pun)) -> do let FieldOcc _ lnameF = fieldOcc fExpDoc <- if pun then return Nothing else Just <$> docSharedWrapper layoutPat fPat return (lrdrNameToText lnameF, fExpDoc) Seq.singleton <$> docSeq [ appSep $ docLit t , appSep $ docLit $ Text.pack "{" , docSeq $ List.intersperse docCommaSep $ fds <&> \case (fieldName, Just fieldDoc) -> docSeq [ appSep $ docLit fieldName , appSep $ docLit $ Text.pack "=" , fieldDoc >>= colsWrapPat ] (fieldName, Nothing) -> docLit fieldName , docSeparator , docLit $ Text.pack "}" ] ConPat _ lname (RecCon (HsRecFields [] (Just (L _ 0)))) -> do -- Abc { .. } -> expr let t = lrdrNameToText lname Seq.singleton <$> docSeq [appSep $ docLit t, docLit $ Text.pack "{..}"] ConPat _ lname (RecCon (HsRecFields fs@(_ : _) (Just (L _ dotdoti)))) | dotdoti == length fs -> do -- Abc { a = locA, .. } let t = lrdrNameToText lname fds <- fs `forM` \(L _ (HsRecField (L _ fieldOcc) fPat pun)) -> do let FieldOcc _ lnameF = fieldOcc fExpDoc <- if pun then return Nothing else Just <$> docSharedWrapper layoutPat fPat return (lrdrNameToText lnameF, fExpDoc) Seq.singleton <$> docSeq [ appSep $ docLit t , appSep $ docLit $ Text.pack "{" , docSeq $ fds >>= \case (fieldName, Just fieldDoc) -> [ appSep $ docLit fieldName , appSep $ docLit $ Text.pack "=" , fieldDoc >>= colsWrapPat , docCommaSep ] (fieldName, Nothing) -> [docLit fieldName, docCommaSep] , docLit $ Text.pack "..}" ] TuplePat _ args boxity -> do -- (nestedpat1, nestedpat2, nestedpat3) -> expr -- (#nestedpat1, nestedpat2, nestedpat3#) -> expr case boxity of Boxed -> wrapPatListy args "()" docParenL docParenR Unboxed -> wrapPatListy args "(##)" docParenHashLSep docParenHashRSep AsPat _ asName asPat -> do -- bind@nestedpat -> expr wrapPatPrepend asPat (docLit $ lrdrNameToText asName <> Text.pack "@") SigPat _ pat1 (HsPS _ ty1) -> do -- i :: Int -> expr patDocs <- layoutPat pat1 tyDoc <- docSharedWrapper layoutType ty1 case Seq.viewr patDocs of Seq.EmptyR -> error "cannot happen ljoiuxoasdcoviuasd" xR Seq.:> xN -> do xN' <- -- at the moment, we don't support splitting patterns into -- multiple lines. but we cannot enforce pasting everything -- into one line either, because the type signature will ignore -- this if we overflow sufficiently. -- In order to prevent syntactically invalid results in such -- cases, we need the AddBaseY here. -- This can all change when patterns get multiline support. docAddBaseY BrIndentRegular $ docSeq [ appSep $ return xN , appSep $ docLit $ Text.pack "::" , docForceSingleline tyDoc ] return $ xR Seq.|> xN' ListPat _ elems -> -- [] -> expr1 -- [nestedpat1, nestedpat2, nestedpat3] -> expr2 wrapPatListy elems "[]" docBracketL docBracketR BangPat _ pat1 -> do -- !nestedpat -> expr wrapPatPrepend pat1 (docLit $ Text.pack "!") LazyPat _ pat1 -> do -- ~nestedpat -> expr wrapPatPrepend pat1 (docLit $ Text.pack "~") NPat _ llit@(L _ ol) mNegative _ -> do -- -13 -> expr litDoc <- docWrapNode llit $ allocateNode $ overLitValBriDoc $ GHC.ol_val ol negDoc <- docLit $ Text.pack "-" pure $ case mNegative of Just{} -> Seq.fromList [negDoc, litDoc] Nothing -> Seq.singleton litDoc _ -> return <$> briDocByExactInlineOnly "some unknown pattern" lpat colsWrapPat :: Seq BriDocNumbered -> ToBriDocM BriDocNumbered colsWrapPat = docCols ColPatterns . fmap return . Foldable.toList wrapPatPrepend :: LPat GhcPs -> ToBriDocM BriDocNumbered -> ToBriDocM (Seq BriDocNumbered) wrapPatPrepend pat prepElem = do patDocs <- layoutPat pat case Seq.viewl patDocs of Seq.EmptyL -> return Seq.empty x1 Seq.:< xR -> do x1' <- docSeq [prepElem, return x1] return $ x1' Seq.<| xR wrapPatListy :: [LPat GhcPs] -> String -> ToBriDocM BriDocNumbered -> ToBriDocM BriDocNumbered -> ToBriDocM (Seq BriDocNumbered) wrapPatListy elems both start end = do elemDocs <- Seq.fromList elems `forM` (layoutPat >=> colsWrapPat) case Seq.viewl elemDocs of Seq.EmptyL -> fmap Seq.singleton $ docLit $ Text.pack both x1 Seq.:< rest -> do sDoc <- start eDoc <- end rest' <- rest `forM` \bd -> docSeq [docCommaSep, return bd] return $ (sDoc Seq.<| x1 Seq.<| rest') Seq.|> eDoc
lspitzner/brittany
source/library/Language/Haskell/Brittany/Internal/Layouters/Pattern.hs
agpl-3.0
8,239
0
22
2,194
2,166
1,086
1,080
145
26
import System.Environment (getArgs) interactWith function inputFile outputFile = do input <- readFile inputFile writeFile outputFile (function input) splitLines [] = [] splitLines cs = let (pre, suf) = break isLineTerminator cs in pre : case suf of ('\r':'\n':rest) -> splitLines rest ('\r':rest) -> splitLines rest ('\n':rest) -> splitLines rest _ -> [] isLineTerminator c = c == '\r' || c == '\n' fixLines :: String -> String fixLines input = unlines (splitLines input) main = mainWith myFunction where mainWith function = do args <- getArgs case args of [input,output] -> interactWith function input output _ -> putStrLn "error: exactly two arguments needed" -- replace "id" with the name of our function below myFunction = fixLines
caiorss/Functional-Programming
haskell/rwh/ch04/FixLines.hs
unlicense
909
0
12
288
266
131
135
22
4
module EKG.A169845Spec (main, spec) where import Test.Hspec import EKG.A169845 (a169845) main :: IO () main = hspec spec spec :: Spec spec = describe "A169845" $ it "correctly computes the first 20 elements" $ take 20 (map a169845 [1..]) `shouldBe` expectedValue where expectedValue = [7,14,2,4,6,3,9,12,8,10,5,15,18,16,20,22,11,33,21,24]
peterokagey/haskellOEIS
test/EKG/A169845Spec.hs
apache-2.0
353
0
10
59
160
95
65
10
1
----------------------------------------------------------------------------- -- Copyright 2019, Ideas project team. This file is distributed under the -- terms of the Apache License 2.0. For more information, see the files -- "LICENSE.txt" and "NOTICE.txt", which are included in the distribution. ----------------------------------------------------------------------------- -- | -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable (depends on ghc) -- -- Analysis of a feedbackscript -- ----------------------------------------------------------------------------- module Ideas.Service.FeedbackScript.Analysis ( -- Analysis functions makeScriptFor, parseAndAnalyzeScript, analyzeScript -- Message type , Message(..) ) where import Data.Either import Data.List import Ideas.Common.Library import Ideas.Service.DomainReasoner import Ideas.Service.FeedbackScript.Parser import Ideas.Service.FeedbackScript.Run import Ideas.Service.FeedbackScript.Syntax import Ideas.Utils.Uniplate makeScriptFor :: IsId a => DomainReasoner -> a -> IO () makeScriptFor dr exId = do Some ex <- findExercise dr (newId exId) let (brs, nrs) = partition isBuggy (ruleset ex) print $ makeScript $ Supports [getId ex] : [ feedbackDecl s mempty | s <- feedbackIds ] ++ [ textForIdDecl r (makeText (description r)) | r <- nrs ] ++ [ textForIdDecl r (makeText (description r)) | r <- brs ] parseAndAnalyzeScript :: DomainReasoner -> FilePath -> IO () parseAndAnalyzeScript dr file = do putStrLn $ "Parsing " ++ show file script <- parseScript file let exs = [ maybe unknown Right (findExercise dr a) | Supports as <- scriptDecls script , a <- as , let unknown = Left (UnknownExercise a) ] let ms = lefts exs ++ analyzeScript (rights exs) script putStrLn $ unlines $ map show ms putStrLn $ "(errors: " ++ show (length ms) ++ ")" analyzeScript :: [Some Exercise] -> Script -> [Message] analyzeScript exs script = map FeedbackUndefined (filter (`notElem` fbids) feedbackIds) ++ map UnknownFeedback (filter (`notElem`feedbackIds ) fbids) ++ [ NoTextForRule (getId r) (getId ex) | Some ex <- exs, r <- ruleset ex, noTextFor (getId r) ] ++ [ UnknownAttribute a | a <- textRefs , a `notElem` feedbackIds ++ attributeIds ++ strids ] ++ [ UnknownCondAttr a | a <- condRefs, a `notElem` conditionIds ] where decls = scriptDecls script fbids = [ a | Simple Feedback as _ <- decls, a <- as ] ++ [ a | Guarded Feedback as _ <- decls, a <- as ] txids = [ a | Simple TextForId as _ <- decls, a <- as ] ++ [ a | Guarded TextForId as _ <- decls, a <- as ] strids = [ a | Simple StringDecl as _ <- decls, a <- as ] ++ [ a | Guarded StringDecl as _ <- decls, a <- as ] namespaces = nub $ mempty : [ a | NameSpace as <- scriptDecls script, a <- as ] noTextFor a = null [ () | n <- namespaces, b <- txids, n#b == a ] texts = [ t | Simple _ _ t <- decls ] ++ [ t | Guarded _ _ xs <- decls, (_, t) <- xs ] textRefs = [ a | t <- texts, TextRef a <- universe t ] conditions = [ c | Guarded _ _ xs <- decls , (c, _) <- xs ] condRefs = [ a | c <- conditions, CondRef a <- universe c ] data Message = UnknownExercise Id | UnknownFeedback Id | FeedbackUndefined Id | NoTextForRule Id Id | UnknownAttribute Id | UnknownCondAttr Id instance Show Message where show message = case message of UnknownExercise a -> "Unknown exercise id " ++ show a UnknownFeedback a -> "Unknown feedback category " ++ show a FeedbackUndefined a -> "Feedback category " ++ show a ++ " is not defined" NoTextForRule a b -> "No text for rule " ++ show a ++ " of exercise " ++ show b UnknownAttribute a -> "Unknown attribute @" ++ show a ++ " in text" UnknownCondAttr a -> "Unknown attribute @" ++ show a ++ " in condition"
ideas-edu/ideas
src/Ideas/Service/FeedbackScript/Analysis.hs
apache-2.0
4,164
0
17
1,114
1,268
649
619
71
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE BangPatterns #-} module Main(main) where import Data.Int import qualified Data.Vector.Storable as S import DNA import DDP import DDP_Slice ---------------------------------------------------------------- -- Distributed dot product -- -- Note that actors which do not spawn actors on other nodes do not -- receive CAD. ---------------------------------------------------------------- -- | Actor for calculating dot product ddpDotProduct :: Actor Slice Double ddpDotProduct = actor $ \size -> do -- Chunk local product rnk <- rank gSize <- groupSize let slice = scatterSlice gSize size !! rnk -- Chunk & send out res <- selectMany (Frac 1) (NNodes 1) [UseLocal] shell <- startGroup res Failout $(mkStaticClosure 'ddpProductSlice) sendParam slice $ broadcast shell partials <- delayGroup shell x <- duration "collecting vectors" $ gather partials (+) 0 return x remotable [ 'ddpDotProduct ] ddpDotProductMaster :: Actor Slice Double ddpDotProductMaster = actor $ \size -> do res <- selectMany (Frac 1) (NWorkers 3) [UseLocal] shell <- startGroup res Normal $(mkStaticClosure 'ddpDotProduct) sendParam size $ broadcast shell partials <- delayGroup shell x <- duration "collection partials" $ gather partials (+) 0 return x main :: IO () main = dnaRun rtable $ do -- Vector size: -- -- > 100e4 doubles per node = 800 MB per node -- > 20 nodes let n = 2000*1000*1000 expected = fromIntegral n*(fromIntegral n-1)/2 * 0.1 -- Run it b <- eval ddpDotProduct (Slice 0 n) liftIO $ putStrLn $ concat [ "RESULT: ", show b , " EXPECTED: ", show expected , if b == expected then " -- ok" else " -- WRONG!" ] where rtable = DDP.__remoteTable . DDP_Slice.__remoteTable . Main.__remoteTable
SKA-ScienceDataProcessor/RC
MS2/dna-programs/ddp-in-memory-hierarchical.hs
apache-2.0
1,950
0
16
465
502
255
247
41
2
-- |Command-line interface to the Javascript analysis (jsaz). module Main where import System.Console.Editline.Readline import System.Console.GetOpt import System.Environment import System.IO import System.IO.Error import Data.Char (toLower) import Data.Maybe (fromJust) import Control.Monad import Control.Monad.Identity import Control.Monad.Trans import Data.List (isPrefixOf,isSuffixOf) import CFA.Labels (buildLabels) import CFA.Class import CFA.Impl import qualified Data.Zipper as Z import qualified Data.Map as M import qualified Data.Set as S import WebBits.JavaScript.JavaScript (parseJavaScriptFromFile) import Ovid.Analysis import Data.List (intersperse) import WebBits.Html.PermissiveParser (parseHtmlFromFile) import WebBits.Html.PrettyPrint() import WebBits.JavaScript.Crawl (getPageJavaScript) import Data.InductiveGraph.Class (verticesToMzSchemeReadable) import Data.InductiveGraph.XML (writeGraphML) buildTime = #ifdef __TIME__ __TIME__ #else #error "__TIME__ is not defined" #endif buildDate = #ifdef __DATE__ __DATE__ #else #error "__DATE__ is not defined" #endif -------------------------------------------------------------------------------- -- Interpreting command line arguments data Argument = InputHtml String | InputJavascript String | OutputScheme String | OutputXML String | BuildCFG Int | ApplyCFA Int | BuildRGA Int | FullDetail | DisableExponentialHacks String deriving (Show) argSpec = [ Option ['o'] ["output"] (ReqArg OutputScheme "FILE") "output as a PLT Scheme expression" , Option ['x'] ["xml"] (ReqArg OutputXML "FILE") "output as GraphML" , Option [] ["cfa"] (ReqArg (ApplyCFA . read) "K") "perform a control flow analysis only" , Option [] ["cfg"] (ReqArg (BuildCFG . read) "K") "build a control flow graph" , Option [] ["rga"] (ReqArg (BuildRGA . read) "K") "build randomization information" , Option [] ["mmx"] (NoArg (error "MMX optimizations require a Pentium MMX processor")) "enable Pentium MMX optimizations" , Option [] ["no-dom"] (NoArg $ error "--no-dom is not yet supported") "do not include the DOM model" , Option ['a'] ["full-detail"] (NoArg FullDetail) "see the analysis in its full glory" , Option ['p'] ["no-approximations"] (ReqArg DisableExponentialHacks "FILE") "Disable approximations for this file" , Option ['m'] ["html"] (ReqArg InputHtml "FILE") "parse this file as HTML" , Option ['j'] ["javascript"] (ReqArg InputJavascript "FILE") "parse this file as Javascript" ] usage = concat [ "jsaz pre-release (Ovid), built on " ++ buildTime ++ ", " ++ buildDate ++"\n" , "Usage: jsaz [options] file ...\n" , usageInfo "" argSpec , "\n" , "Specify multiple files to perform a multi-page analysis. The type of a\n" , "file is determined by its extension. However, you may use the --html\n" , "and --javascript options to force a file to be treated in a particular\n" , "way.\n" , "\n" , "By default, the analysis detects some common calling patterns that cause\n" , "exponential time complexity. --no-approximations disables these checks\n" , "for a specified file. The file may be one that is indirectly included\n" , "for analysis (e.g. \"flapjax.js\").\n" , "\n" , "You may generate a Scheme expression and a GraphML file simultaneously.\n" , "However, you can only perform a single type of analysis in a particular\n" , "run.\n" ] warn s = hPutStrLn stderr s main = do catch main' $ \err -> if isUserError err then do putStrLn (ioeGetErrorString err) else ioError err main' = do rawArgs <- getArgs when (null rawArgs) $ putStrLn usage >> fail "No arguments specified." let (args,options,errors) = getOpt RequireOrder argSpec rawArgs unless (null errors) $ do mapM_ (\e -> putStrLn (show e)) errors fail "Could not parse command line arguments." (schemeOut,args) <- getSchemeOutputHandle args (xmlOut,args) <- getXMLOutputHandle args schemeOut <- pickDefaultOutput schemeOut xmlOut (analyzeFn,args) <- getAnalysisFunction args (isFullGlory,args) <- getFullGlory args (noExponentialFiles,args) <- getNoExponentialHacksOn args inFiles <- validateInputFiles args options result <- analyzeFn isFullGlory noExponentialFiles inFiles unless (schemeOut == Nothing) $ printScheme (fromJust schemeOut) result unless (xmlOut == Nothing) $ printXML (fromJust xmlOut) result getSchemeOutputHandle ((OutputScheme path):rest) = do handle <- openFile path WriteMode return (Just handle,rest) getSchemeOutputHandle rest = return (Nothing,rest) getXMLOutputHandle ((OutputXML path):rest) = do handle <- openFile path WriteMode return (Just handle,rest) getXMLOutputHandle rest = return (Nothing,rest) getNoExponentialHacksOn ((DisableExponentialHacks f):args) = do (fs,args') <- getNoExponentialHacksOn args return (f:fs,args') getNoExponentialHacksOn args = do jsazPath <- getEnv "JSAZ_PATH" return ([jsazPath ++ "/DOM.js"],args) pickDefaultOutput Nothing Nothing = do warn $ "No output format specified. We wil print the result as a Scheme\n" ++ "value to standard out." return (Just stdout) pickDefaultOutput schemeOut _ = return schemeOut getFullGlory (FullDetail:rest) = return (True,rest) getFullGlory rest = return (False,rest) getAnalysisFunction ((BuildCFG k):rest) = do when (k < 0) $ fail "argument to --cfg must be non-negative" return (doCFG k,rest) getAnalysisFunction ((ApplyCFA k):rest) = do when (k < 0) $ fail "argument to --cfa must be non-negative" return (doCFA k,rest) getAnalysisFunction ((BuildRGA k):rest) = do when (k < 0) $ fail "argument to --rga must be non-negative" return (doRandomization k, rest) getAnalysisFunction rest = do warn $ "Neither --cfa nor --cfg was specified. We are assuming --cfg=10." return (doCFG 10,rest) validateInputFiles args options = do let toInput (InputHtml s) = return (HtmlFile s) toInput (InputJavascript s) = return (JavascriptFile s) toInput _ = fail "Invalid arguments." let guessType path = do let path' = map toLower path if ".html" `isSuffixOf` path' || ".htm" `isSuffixOf` path' then return (HtmlFile path) else if ".js" `isSuffixOf` path' then return (JavascriptFile path') else fail $ "Prefix `" ++ path ++ "\' with --html or --javascript." explicits <- mapM toInput args implicits <- mapM guessType options return (explicits ++ implicits) ------------------------------------------------------------------------------------------------------------------------ -- Running an analysis and printing results data InputFile = HtmlFile String | JavascriptFile String getStatements (JavascriptFile path) = do stmts <- parseJavascriptFromFile path return (path,stmts) getStatements (HtmlFile path) = do eitherS <- parseHtmlFromFile path case eitherS of Left parseError -> fail (show parseError) Right (html,warnings) -> do unless (null warnings) (warn $ show warnings) jsazPath <- getEnv "JSAZ_PATH" domStmts <- parseJavaScriptFromFile (jsazPath ++ "/DOM.js") stmts <- getPageJavaScript html return (path,domStmts ++ stmts) doCFG _ _ _ [] = fail "No input files were specified." doCFG nCFA isDetailed noExpFiles files = do pathsAndStmts <- mapM getStatements files buildRequestGraphs nCFA noExpFiles pathsAndStmts isDetailed doRandomization nCFA isDetailed noExpFiles files = do pathsAndStmts <- mapM getStatements files buildRandomizationAnnotations nCFA noExpFiles pathsAndStmts doCFA _ _ _ [] = fail "No input files were specified" doCFA nCFA isDetailed noExpFiles [file] = do (_,stmts) <- getStatements file _ <- analyzeStatements nCFA stmts warn $ "Analysis complete. We don\'t know how to print all the value sets." return [] doCFA _ _ _ _ = do fail "Multi-file control flow analysis is not supported on the command-line, you probably want a control flow graph" printScheme handle result = do hPutStrLn handle (verticesToMzSchemeReadable result) hClose handle printXML handle result = do writeGraphML handle result hClose handle
brownplt/ovid
src/Jsaz.hs
bsd-2-clause
8,255
0
16
1,546
2,163
1,104
1,059
-1
-1
module Main where import Code20 main :: IO () main = putStrLn $ display (countdown2 831 [1,3,7,10,25,50])
sampou-org/pfad
Code/countdown2.hs
bsd-3-clause
108
0
9
19
55
32
23
4
1
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} -- Module : Wwdcc -- Copyright : Copyright © 2013, Quixoftic, LLC <[email protected]> -- License : BSD3 (see LICENSE file) -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC -- -- Check https://developer.apple.com/wwdc/ repeatedly, and look for a -- possible 2013 announcement. -- module Wwdcc ( startChecks , sendMail , sendSms , sendSms' , HttpException ) where import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Text.Lazy as TL import qualified Data.Text.Lazy.Encoding as TLE import qualified Data.ByteString.Lazy.UTF8 as BS import Control.Concurrent (threadDelay) import System.Exit import Network.HTTP.Conduit hiding (def) import Text.HTML.TagSoup import Data.Maybe import Control.Monad import qualified Control.Exception as E import Control.Monad.Reader import Network.Mail.Mime import Config import Logging data SiteStatus = Unmodified | Modified | NotResponding deriving Show startChecks :: Config -> IO () startChecks config = getStatus Unmodified Unmodified config getStatus :: SiteStatus -> SiteStatus -> Config -> IO () getStatus oldestStatus oldStatus config = do newStatus <- siteStatus $ url config action oldestStatus oldStatus newStatus config threadDelay ((period config) * 10^6) getStatus oldStatus newStatus config -- Take action depending on the last 3 site statuses. -- action :: SiteStatus -> SiteStatus -> SiteStatus -> Config -> IO () action _ NotResponding Unmodified config = logInfo $ T.unwords [url config, "is back up, but unchanged."] action _ _ Unmodified config = logInfo $ T.unwords [url config, "unchanged."] -- Modified: send notifications and exit. -- action _ _ Modified config = let msg = T.unwords [url config, "has changed!"] ntotal = notifications config nTotalStr = T.pack $ show ntotal msgNumber n = T.concat [ "(" , T.pack $ show n , "/" , nTotalStr , ")" ] sendNotification 0 = do logNotice "Exiting." exitSuccess -- quit the program. sendNotification 1 = do sendMail msg (T.unlines ["Hi!", "", msg, "", "This is the last notification I will send. I am now exiting.", "", "FYI,", "The wwdcc service" ]) (email config) sendSms (T.unwords [msg, msgNumber ntotal]) (twilio config) sendNotification 0 sendNotification nleft = do sendMail msg (T.unlines ["Hi!", "", msg, "", "FYI,", "The wwdcc service" ]) (email config) sendSms (T.unwords [msg, msgNumber $ ntotal - nleft + 1]) (twilio config) threadDelay ((wait config) * 10^6) sendNotification $ nleft - 1 in do logWarning msg sendNotification ntotal -- Email once, as soon as the site doesn't respond twice in a row, to -- give the user a heads-up that things may be about to change. -- -- Don't email for one-time timeouts, nor during extended outages. -- action Unmodified NotResponding NotResponding config = let msg = T.unwords [url config, "is not responding."] in do logWarning msg sendMail msg msg (email config) sendSms msg (twilio config) action _ _ NotResponding config = logInfo $ T.unwords [url config, "is not responding."] -- SMS generation -- twilioSendSmsUri :: T.Text -> T.Text twilioSendSmsUri accountSid = T.concat [ "https://api.twilio.com/2010-04-01/Accounts/" , accountSid , "/SMS/Messages.json" ] sendSms' :: T.Text -> Maybe Twilio -> IO () sendSms' _ Nothing = return () sendSms' body (Just twilio) = do logNotice $ T.unwords ["Sending SMS to", toPhone twilio, "with text:", body] request' <- parseUrl $ T.unpack $ twilioSendSmsUri (accountSid twilio) let request = urlEncodedBody [ ("From", TE.encodeUtf8 $ fromPhone twilio) , ("To", TE.encodeUtf8 $ toPhone twilio) , ("Body", TE.encodeUtf8 body) ] $ applyBasicAuth (TE.encodeUtf8 $ accountSid twilio) (TE.encodeUtf8 $ authToken twilio) request' result <- withManager $ httpLbs request return () sendSms :: T.Text -> Maybe Twilio -> IO () sendSms body twilio = do E.catch (sendSms' body twilio) handler where handler :: HttpException -> IO () handler err = logError $ T.concat [ "Unable to send SMS notification! (" , T.pack $ show err , ")" ] -- Email generation -- sendMail :: T.Text -> T.Text -> Maybe Email -> IO () sendMail _ _ Nothing = return () sendMail subject body (Just email) = do logNotice $ T.unwords ["Sending email to", toEmail email] renderSendMail Mail { mailFrom = (toAddr $ fromEmail email) , mailTo = [(toAddr $ toEmail email)] , mailCc = [] , mailBcc = [] , mailHeaders = [("Subject", subject)] , mailParts = [[ Part "text/plain; charset=utf-8" QuotedPrintableText Nothing [] $ TLE.encodeUtf8 $ TL.fromChunks [body] ]] } where toAddr :: T.Text -> Address toAddr str = Address { addressName = Nothing, addressEmail = str } -- Site-related stuff. -- siteStatus :: T.Text -> IO (SiteStatus) siteStatus url = do result <- checkWwdc url case result of Left _ -> return NotResponding Right False -> return Unmodified Right True -> return Modified checkWwdc :: T.Text -> IO (Either HttpException Bool) checkWwdc url = E.try $ do xml <- simpleHttp $ T.unpack url return $ pageIsModified xml expected = "WWDC 2012. June 11-15 in San Francisco. It's the week we've all been waiting for." pageIsModified :: BS.ByteString -> Bool pageIsModified xml = maybe True (/= expected) (findCanary $ parseTags xml) -- A little trick to avoid all the ::String type signatures that are -- needed with TagSoup and OverloadedString. Thanks to sclv at Stack -- Overflow for the tip. s :: String -> String s = id findCanary :: [Tag BS.ByteString] -> Maybe BS.ByteString findCanary = liftM (fromAttrib "alt" . head) . listToMaybe . sections (~== s "<img>") . takeWhile (~/= s "</a>") . dropWhile (~/= s "<header class=\"hero\">")
quixoftic/wwdcc
src/Wwdcc.hs
bsd-3-clause
7,091
0
17
2,325
1,728
904
824
138
3
module Settings.Builders.GenPrimopCode (genPrimopCodeBuilderArgs) where import Expression import Predicates (builder, file) -- Stdin/stdout are handled in a special way. See Rules/Actions.hs. genPrimopCodeBuilderArgs :: Args genPrimopCodeBuilderArgs = builder GenPrimopCode ? mconcat [ file "//PrimopWrappers.hs" ? arg "--make-haskell-wrappers" , file "//Prim.hs" ? arg "--make-haskell-source" , file "//primop-data-decl.hs-incl" ? arg "--data-decl" , file "//primop-tag.hs-incl" ? arg "--primop-tag" , file "//primop-list.hs-incl" ? arg "--primop-list" , file "//primop-has-side-effects.hs-incl" ? arg "--has-side-effects" , file "//primop-out-of-line.hs-incl" ? arg "--out-of-line" , file "//primop-commutable.hs-incl" ? arg "--commutable" , file "//primop-code-size.hs-incl" ? arg "--code-size" , file "//primop-can-fail.hs-incl" ? arg "--can-fail" , file "//primop-strictness.hs-incl" ? arg "--strictness" , file "//primop-fixity.hs-incl" ? arg "--fixity" , file "//primop-primop-info.hs-incl" ? arg "--primop-primop-info" , file "//primop-vector-uniques.hs-incl" ? arg "--primop-vector-uniques" , file "//primop-vector-tys.hs-incl" ? arg "--primop-vector-tys" , file "//primop-vector-tys-exports.hs-incl" ? arg "--primop-vector-tys-exports" , file "//primop-vector-tycons.hs-incl" ? arg "--primop-vector-tycons" , file "//primop-usage.hs-incl" ? arg "--usage" ]
quchen/shaking-up-ghc
src/Settings/Builders/GenPrimopCode.hs
bsd-3-clause
1,614
0
9
385
281
136
145
23
1
module Frenetic.Pattern ( Matchable (..) ) where import Data.Maybe {-| A class for types that compose similar to wildcards. All instances must satisfy the following: * @match@ defines a partial order; @top@ is the top element of this order and @intersect@ is a meet. * Meets are exact: if @match x y@ and @match x z@, then @match x (fromJust (intersect y z))@, if such a meet exists. Minimal complete definition: top and intersect. -} class (Eq a) => Matchable a where top :: a intersect :: a -> a -> Maybe a match :: a -> a -> Bool overlap :: a -> a -> Bool disjoint :: a -> a -> Bool match x y = intersect x y == Just x overlap x y = isJust $ intersect x y disjoint x y = isNothing $ intersect x y
frenetic-lang/netcore-1.0
src/Frenetic/Pattern.hs
bsd-3-clause
747
0
9
189
159
83
76
12
0
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings, GADTs, FlexibleContexts, MultiParamTypeClasses, GeneralizedNewtypeDeriving, RankNTypes, NamedFieldPuns #-} -- | Global sqlite database shared by all projects. -- Warning: this is currently only accessible from __outside__ a Docker container. module Stack.Docker.GlobalDB (updateDockerImageLastUsed ,getDockerImagesLastUsed ,pruneDockerImagesLastUsed ,DockerImageLastUsed ,DockerImageProjectId ,getDockerImageExe ,setDockerImageExe ,DockerImageExeId) where import Control.Monad (forM_, when) import Control.Monad.Logger (NoLoggingT) import Control.Monad.IO.Unlift import Data.List (sortBy, isInfixOf, stripPrefix) import Data.List.Extra (stripSuffix) import qualified Data.Map.Strict as Map import Data.Maybe (fromMaybe) import qualified Data.Text as T import Data.Time.Clock (UTCTime,getCurrentTime) import Database.Persist import Database.Persist.Sqlite import Database.Persist.TH import Path (toFilePath, parent) import Path.IO (ensureDir) import Stack.Types.Config import Stack.Types.Docker import Stack.Types.StringError share [mkPersist sqlSettings, mkMigrate "migrateTables"] [persistLowerCase| DockerImageProject imageHash String projectPath FilePath lastUsedTime UTCTime DockerImageProjectPathKey imageHash projectPath deriving Show DockerImageExe imageHash String exePath FilePath exeTimestamp UTCTime compatible Bool DockerImageExeUnique imageHash exePath exeTimestamp deriving Show |] -- | Update last used time and project for a Docker image hash. updateDockerImageLastUsed :: Config -> String -> FilePath -> IO () updateDockerImageLastUsed config imageId projectPath = do curTime <- getCurrentTime _ <- withGlobalDB config (upsert (DockerImageProject imageId projectPath curTime) []) return () -- | Get a list of Docker image hashes and when they were last used. getDockerImagesLastUsed :: Config -> IO [DockerImageLastUsed] getDockerImagesLastUsed config = do imageProjects <- withGlobalDB config (selectList [] [Asc DockerImageProjectLastUsedTime]) return (sortBy (flip sortImage) (Map.toDescList (Map.fromListWith (++) (map mapImageProject imageProjects)))) where mapImageProject (Entity _ imageProject) = (dockerImageProjectImageHash imageProject ,[(dockerImageProjectLastUsedTime imageProject ,dockerImageProjectProjectPath imageProject)]) sortImage (_,(a,_):_) (_,(b,_):_) = compare a b sortImage _ _ = EQ -- | Given a list of all existing Docker images, remove any that no longer exist from -- the database. pruneDockerImagesLastUsed :: Config -> [String] -> IO () pruneDockerImagesLastUsed config existingHashes = withGlobalDB config go where go = do l <- selectList [] [] forM_ l (\(Entity k DockerImageProject{dockerImageProjectImageHash = h}) -> when (h `notElem` existingHashes) $ delete k) -- | Get the record of whether an executable is compatible with a Docker image getDockerImageExe :: Config -> String -> FilePath -> UTCTime -> IO (Maybe Bool) getDockerImageExe config imageId exePath exeTimestamp = withGlobalDB config $ do mentity <- getBy (DockerImageExeUnique imageId exePath exeTimestamp) return (fmap (dockerImageExeCompatible . entityVal) mentity) -- | Seet the record of whether an executable is compatible with a Docker image setDockerImageExe :: Config -> String -> FilePath -> UTCTime -> Bool -> IO () setDockerImageExe config imageId exePath exeTimestamp compatible = withGlobalDB config $ do _ <- upsert (DockerImageExe imageId exePath exeTimestamp compatible) [] return () -- | Run an action with the global database. This performs any needed migrations as well. withGlobalDB :: forall a. Config -> SqlPersistT (NoLoggingT (ResourceT IO)) a -> IO a withGlobalDB config action = do let db = dockerDatabasePath (configDocker config) ensureDir (parent db) runSqlite (T.pack (toFilePath db)) (do _ <- runMigrationSilent migrateTables action) `catch` \ex -> do let str = show ex str' = fromMaybe str $ stripPrefix "user error (" $ fromMaybe str $ stripSuffix ")" str if "ErrorReadOnly" `isInfixOf` str then throwString $ str' ++ " This likely indicates that your DB file, " ++ toFilePath db ++ ", has incorrect permissions or ownership." else throwIO (ex :: IOException) -- | Date and project path where Docker image hash last used. type DockerImageLastUsed = (String, [(UTCTime, FilePath)])
martin-kolinek/stack
src/Stack/Docker/GlobalDB.hs
bsd-3-clause
5,063
0
17
1,288
1,028
547
481
81
2
module RefacDuplicates(detectDuplicates,detectSpecDuplicates) where import PrettyPrint import PosSyntax import Maybe import TypedIds import UniqueNames hiding (srcLoc) import PNT import TiPNT import List import RefacUtils import PFE0 (findFile, getCurrentModuleGraph) import AbstractIO import Prelude hiding (putStrLn, putStr) import Char import Time type Drip = (String, LocInfo) type ExpDrip = (HsExpP, LocInfo) type Bucket = [Drip] type ExpBucket = [ExpDrip] type BucketGroup = [Bucket] type ExpBucketGroup = [ExpBucket] type LocInfo = (String, Int, Int) -- ************************************************** -- ***** ***** -- ***** File: RefacDuplicates.hs ***** -- ***** Module Name: RefacDuplicates ***** -- ***** Author: Jonathan Cowie ***** -- ***** Email: [email protected] ***** -- ***** ***** -- ***** Created as a summer internship project ***** -- ***** between July and August 2004 ***** -- ***** ***** -- ************************************************** detectDuplicates args = do let fileName = args!!0 timeone <- AbstractIO.getClockTime modName <- fileNameToModName fileName (inscps, exps, mod, tokList) <- parseSourceFile fileName putStrLn "\nComputing list of duplicates from the following files..." servers<-serverModsAndFiles modName let directory = getDirectory fileName servers' = stripServers servers directory -- mods <- getModules putStrLn $ show servers' expmods <- makeFullASTList (map snd servers') let dups = getDuplicates expmods displayDuplicates dups putStrLn "Duplicate code refactoring complete!\n" timetwo <- AbstractIO.getClockTime putStrLn $ show $ diffClockTimes timetwo timeone getDirectory :: String -> String getDirectory f = reverse $ dropWhile (=='/') (dropWhile (/='/') (reverse f)) -- stripServers :: [(ModuleName, String)] -> String -> [(ModuleName, String)] stripServers [] d = [] stripServers (a@(x,y):xs) d | d == getDirectory y = a : stripServers xs d | otherwise = stripServers xs d detectSpecDuplicates args = do let fileName = args!!0 beginRow = read (args!!1)::Int beginCol = read (args!!2)::Int endRow = read (args!!3)::Int endCol = read (args!!4)::Int timeone <- AbstractIO.getClockTime modName <- fileNameToModName fileName (inscps, exps, mod, tokList) <- parseSourceFile fileName let exp=findExp tokList (beginRow, beginCol) (endRow, endCol) mod if exp/=defaultExp then -- (mod',((tokList',_),_))<- detectDuplicates' fileName (beginRow,beginCol)(endRow,endCol) mod tokList -- writeRefactoredFiles [((fileName,True), (tokList',mod'))] do putStrLn "\nComputing list of duplicates from the following files..." mods <- getModules putStrLn $ show mods expmods <- makeFullASTList mods let dups = getSpecificDupls exp expmods displayDuplicates dups putStrLn "Duplicate code refactoring complete!\n" else putStrLn "You have not selected a valid expression!\n" timetwo <- AbstractIO.getClockTime putStrLn $ show $ diffClockTimes timetwo timeone where findExp toks beginPos endPos t =fromMaybe defaultExp (applyTU (once_tdTU (failTU `adhocTU` exp)) t) where exp (e::HsExpP) |inScope (getStartEndLoc toks e)=Just e exp _ =Nothing inScope (startLoc,endLoc) =startLoc>=beginPos && endLoc<=endPos -- *********************************************************** -- ***** HashTable construction & manipulation functions ***** -- *********************************************************** --Takes an AST and returns a bucket containing (for each drip) the string of the Expression --name, and the start & finish locations of the Expression makeBucket :: Term t => t -> Bucket makeBucket ast = ghead "makeBucket" $ applyTU (stop_tdTU (failTU `adhocTU` addHash)) ast where addHash (a::HsExpP)= return [(showExp a,getSrcLoc a)] --Simple hash function, Takes a String and returns an Int --Currently not used, but left in just in case hashString :: String -> Int hashString = fromIntegral . foldr f 0 where f c m = ord c + (m * 128) `rem` 1500007 --Takes an AST of Type Exp and returns its start location getSrcLoc :: (Term t) => t -> LocInfo getSrcLoc exp = if length lexp == 0 then ("",0,0) else ghead "getSrcLoc" lexp where lexp = allSortedLocsRev exp --Takes an AST and returns the AST with all SrcLocs replaced with loc0 removeSrcLocs :: Term t => t -> t removeSrcLocs ast = ghead "removeSrcLocs" $ applyTP (full_tdTP (idTP `adhocTP` noSrc)) ast where noSrc (a::SrcLoc) = return loc0 --Takes a single Drip parameter, a Bucket and returns the Bucket with --all occurences of the Drip parameter removed removeHashElement :: Drip -> Bucket -> Bucket removeHashElement (x,y) xs = [(a,b) | (a,b) <- xs, a /= x] --Takes an expression and returns a string containing the data constructor name showExp :: HsExpP -> String showExp exp = case exp of (Exp (HsId (HsVar _))) -> "HsVar" (Exp (HsId (HsCon _))) -> "HsCon" (Exp (HsLit _ _)) -> "HsLit" (Exp (HsInfixApp _ _ _)) -> "HsInfixApp" (Exp (HsApp _ _)) -> "HsApp" (Exp (HsNegApp _ _)) -> "HsNegApp" (Exp (HsLambda _ _)) -> "HsLambda" (Exp (HsLet _ _)) -> "HsLet" (Exp (HsIf _ _ _)) -> "HsIf" (Exp (HsCase _ _)) -> "HsCase" (Exp (HsDo _)) -> "HsDo" (Exp (HsTuple _)) -> "HsTuple" (Exp (HsList _)) -> "HsList" (Exp (HsParen _)) -> "HsParen" (Exp (HsLeftSection _ _)) -> "HsLeftSection" (Exp (HsRightSection _ _)) -> "HsRightSection" (Exp (HsRecConstr _ _ _)) -> "HsRecConstr" (Exp (HsRecUpdate _ _ _)) -> "HsRecUpdate" (Exp (HsEnumFrom _)) -> "HsEnumFrom" (Exp (HsEnumFromTo _ _)) -> "HsEnumFromTo" (Exp (HsEnumFromThen _ _)) -> "HsEnumFromThen" (Exp (HsEnumFromThenTo _ _ _)) -> "HsEnumFromThenTo" (Exp (HsListComp _)) -> "HsListComp" (Exp (HsExpTypeSig _ _ _ _)) -> "HsExpTypeSig" (Exp (HsAsPat _ _)) -> "HsAsPat" (Exp (HsWildCard)) -> "HsWildCard" (Exp (HsIrrPat _)) -> "HsIrrPat" --Takes an AST and returns a list of tuples containing the string equivalent of the -- Expression name, and the start & finish locations of the Expression genExpList :: (Term t) => t -> [HsExpP] genExpList ast = ghead "genExpList" $ applyTU (stop_tdTU ( failTU `adhocTU` isExp)) ast where isExp (a::HsExpP)= return [a] --Modified version of allSortedLocs to include Filename allSortedLocsRev t =(sort.nub.getSrcLocsRev) t --Modified version of getSrcLocs to include Filename getSrcLocsRev=runIdentity.(applyTU (full_tdTU (constTU [] `adhocTU` pnt `adhocTU` literalInExp `adhocTU` literalInPat))) where pnt (PNT pname _ (N (Just (SrcLoc f c row col))))=return [(f,row,col)] pnt _=return [] literalInExp ((Exp (HsLit (SrcLoc f c row col) _))::HsExpP) = return [(f,row,col)] literalInExp (Exp _) =return [] literalInPat ((Pat (HsPLit (SrcLoc f c row col) _))::HsPatP) = return [(f,row,col)] literalInPat (Pat (HsPNeg (SrcLoc f c row col) _)) = return [(f,row,col)] literalInPat _ =return [] -- ********************************************************** -- ***** Initial duplicate list construction functions ***** -- ********************************************************** --Takes a Bucket, a DuplicateData List and populates the list with all duplicates --found in the Bucket constructBucketGroup :: Bucket -> BucketGroup -> BucketGroup constructBucketGroup hshtbl dupl = case hshtbl of [] -> dupl (x:xs) -> if (dripOccurences x xs) > 1 then (addAllOcc x xs dupl) ++ (constructBucketGroup (removeHashElement x xs) []) else dupl ++ (constructBucketGroup xs []) --Takes a single Drip parameter, a Bucket and returns the number of times --the Drip parameter occurs in the Bucket dripOccurences :: Drip -> Bucket -> Int dripOccurences (x,y) xs = 1 + length [a | (a,b) <- xs, a == x] --Takes a single Drip parameter, a Bucket and a BucketGroup and populates it --with all occurences of Drip in Bucket addAllOcc :: Drip -> Bucket -> BucketGroup -> BucketGroup addAllOcc (x,y) xs dupl = ((x,y) : [(a,b) | (a,b) <- xs, a == x]) : dupl -- ********************************************************* -- ***** Initial duplicate list verification functions ***** -- ********************************************************* --Takes a BucketGroup parameter and populates it with full expressions from the --HsExpP list taken as the first parameter --Returns ExpBucketGroup populateBucketGroup :: [HsExpP] -> BucketGroup -> ExpBucketGroup populateBucketGroup expl [] = [] populateBucketGroup expl (x:xs) = map (getExp expl) x : populateBucketGroup expl xs where getExp ast dupl = ghead "populateBucketGroup" (catMaybes $ map (getMatch dupl) ast) getMatch (strexp, locinfo) exp | (getSrcLoc exp) == locinfo && strexp == showExp exp = Just ((removeSrcLocs exp), locinfo) | otherwise = Nothing --Takes an ExpBucket (second param is list to store intermediate results) --and groups the elements according to duplicate matches --Returns ExpBucket groupDupls :: ExpBucket -> ExpBucket -> ExpBucket groupDupls y []= y groupDupls ys (x:xs) = let r = xmatches x xs in groupDupls (ys++r) (xs\\r) where xmatches x xs = x:filter (\y->(show (fst x)) == (show (fst y))) xs --Given an ExpBucketGroup paramater, returns a grouped list of --duplicate Expressions in ExpBucketGroup form. elemCheck :: ExpBucketGroup -> ExpBucketGroup elemCheck xs = List.groupBy (\x y ->(show(fst x)) == (show(fst y))) (groupDupls [] (concat xs)) --Takes a list of HsExpP and a BucketGroup list and verifies the duplicates in the BucketGroup list --against the HsExpP list verifyBucketGroup :: [HsExpP] -> BucketGroup -> ExpBucketGroup verifyBucketGroup ast dupl = do let expast = populateBucketGroup ast dupl [ x | x <- elemCheck expast, length x > 1] -- ******************************************************* -- ***** Module list related functions called by the ***** -- ***** refactor interface ***** -- ******************************************************* --Takes a single parameter containing a list of all the modules to be --expanded into ASTs makeFullASTList gf= do gh <- (mapM parseSourceFile gf) return [mod | (inscps, exps, mod, tokList) <- gh] --Returns a list of all modules used in the program which are in the --same directory as the initial file to be refactored getModules = do gf <- getCurrentModuleGraph return (filterNames [ f | (f, (m,_)) <- gf]) --Takes a single parameter containing a list of strings and returns --the list with all strings containing the '/' character removed filterNames :: [String] -> [String] filterNames xs = [ x | x <- xs, containsSlash x == False] --Takes a single string paramater and returns a boolean value --depending on whether or not the string contains the '/' character containsSlash :: String -> Bool containsSlash x = if gx x == 0 then False else True where gx xs = length [ x | x <- xs, x == '/'] -- ************************************************************** -- ***** Top level functions called by refactorer interface ***** -- ************************************************************** --Takes an AST and returns a list of duplicate information (Type ExpBucketGroup) getDuplicates :: Term t => t -> ExpBucketGroup getDuplicates ast = verifyBucketGroup (genExpList ast) (constructBucketGroup (makeBucket ast) []) --Takes an AST and returns a bucket containing (for each drip) the string of the Expression --name, and the start & finish locations of the Expression getSpecificDupls :: Term t => HsExpP -> t -> ExpBucketGroup getSpecificDupls exp ast = [catMaybes $ ghead "getSpecificDupls" $ (applyTU (full_tdTU (constTU [] `adhocTU` findMatches)) ast)] where findMatches (a::HsExpP)= if show(removeSrcLocs exp) == show(removeSrcLocs a) then return [Just (a,getSrcLoc a)] else return [Nothing] --Function to display duplicates returned by getDuplicates in a readable format displayDuplicates dupls = do putStrLn $ "The following duplicates have been identified (File,Line,Char):" ++ "\n" mapM putStrLn (map displayElement dupls) where displayElement xs = if length xs == 1 then "No duplicates found.\n" else (render.ppi) (fst(ghead "displayElement" xs)) ++ " at location(s) " ++ show (nub [snd x | x <- xs]) ++ "\n" --Simple function to display the raw data output by getDuplicates displayDuplicates1 dupls = putStrLn $ show dupls
forste/haReFork
refactorer/RefacDuplicates.hs
bsd-3-clause
13,540
178
15
3,339
3,397
1,831
1,566
-1
-1
{-# LANGUAGE TemplateHaskell, ViewPatterns, MultiParamTypeClasses, TypeFamilies #-} import Control.Lens import qualified Data.Indexed as I import qualified Data.Vector as V import Data.Vector ((!)) import qualified Data.Coordinates as C class (C.Coord co) => Grid grid co where type Elem grid :: * translate :: co -> (grid -> I.Indexed co (Elem grid)) coords :: grid -> [co] instance Grid (V.Vector v) (C.Point) where type Elem (V.Vector v) = v coords = undefined translate c = I.index' f c where f v (C.unP -> (x,y)) = v ! (x * 10 + y) {- data Terrain = Mud | Grass | Water | Fire data Player = Player -- data Grid = { cur :: Terrain, left :: Grid Terrain, right :: Grid Terrain, forward :: Grid Terrain, back :: Grid Terrain } data Grid a = Grid { _cur :: a, _left :: Grid a, _right :: Grid a, _forward :: Grid a, _back :: Grid a } makeLenses ''Grid data Game = Game {_players :: [Player], _world :: Grid Terrain} updateTerrain :: Grid Terrain -> Grid Terrain updateTerrain g@(view cur -> Grass) = g & cur .~ Mud -}
onomatic/sigmund
src/Grid.hs
bsd-3-clause
1,074
28
12
244
342
198
144
15
0
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} module Main where import Web.Twitter.Conduit hiding (lookup) import Web.Twitter.Types.Lens import Web.Authenticate.OAuth as OA import qualified Data.ByteString.Char8 as B8 import Network.HTTP.Client (Manager, newManager) import Network.HTTP.Client.TLS (tlsManagerSettings) import Data.Maybe import Data.Monoid import System.Environment import System.IO (hFlush, stdout) getTokens :: IO OAuth getTokens = do consumerKey <- getEnv "OAUTH_CONSUMER_KEY" consumerSecret <- getEnv "OAUTH_CONSUMER_SECRET" return $ twitterOAuth { oauthConsumerKey = B8.pack consumerKey , oauthConsumerSecret = B8.pack consumerSecret , oauthCallback = Just "oob" } authorize :: OAuth -> Manager -> IO Credential authorize oauth mgr = do cred <- OA.getTemporaryCredential oauth mgr let url = OA.authorizeUrl oauth cred pin <- getPIN url OA.getAccessToken oauth (OA.insert "oauth_verifier" pin cred) mgr where getPIN url = do putStrLn $ "Browse url: " ++ url putStrLn "> what was the PIN Twitter provided you with?: " hFlush stdout B8.getLine main :: IO () main = do tokens <- getTokens mgr <- newManager tlsManagerSettings Credential cred <- authorize tokens mgr print cred B8.putStrLn . B8.intercalate "\n" $ [ "export OAUTH_CONSUMER_KEY=\"" <> oauthConsumerKey tokens <> "\"" , "export OAUTH_CONSUMER_SECRET=\"" <> oauthConsumerSecret tokens <> "\"" , "export OAUTH_ACCESS_TOKEN=\"" <> fromMaybe "" (lookup "oauth_token" cred) <> "\"" , "export OAUTH_ACCESS_SECRET=\"" <> fromMaybe "" (lookup "oauth_token_secret" cred) <> "\"" ]
nomicflux/TwitterScraper
src/Main-Pin.hs
bsd-3-clause
2,038
0
13
666
444
227
217
40
1
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE EmptyDataDecls #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Models.User where import Data.Text (Text) import Data.Time (UTCTime) import Database.Persist.TH (mkMigrate, mkPersist, persistLowerCase, share, sqlSettings) share [mkPersist sqlSettings, mkMigrate "migrateUser"] [persistLowerCase| User json sql=users username Text email Text password Text bio Text Maybe default=NULL image Text Maybe default=NULL createdAt UTCTime default=now() updatedAt UTCTime Maybe default=NULL UniqueUser username email deriving Show |]
rpereira/servant-blog
src/Models/User.hs
bsd-3-clause
1,099
0
7
334
85
56
29
18
0
module Pages ( findAllFiles ) where import System.Directory (getDirectoryContents, doesDirectoryExist) data Tree a = Directory a [Tree a] | File a deriving (Show) traverseBF :: Tree a -> [a] traverseBF tree = tbf [tree] where tbf [] = [] tbf xs = concatMap files xs ++ tbf (concatMap directories xs) files (File a) = [a] files (Directory _ _) = [] directories (File _) = [] directories (Directory _ ys) = ys makeTheTree :: FilePath -> IO (Tree FilePath) makeTheTree path = do isDirecotry <- doesDirectoryExist path if not isDirecotry then return $ File path else do content <- getDirectoryContents path tree <- mapM makeTheTree (processFiles content) return $ Directory path tree where processFiles :: [FilePath] -> [FilePath] processFiles files = map ((path ++) . ("/" ++)) $ discardDots files discardDots :: [FilePath] -> [FilePath] discardDots = filter (\file -> file /= "." && file /= "..") findAllFiles :: FilePath -> FilePath -> IO [FilePath] findAllFiles fileName path = let length' = length fileName in (filter ((== fileName) . reverse . take length' . reverse) . traverseBF <$> makeTheTree path)
homam/stack-test
src/Pages.hs
bsd-3-clause
1,222
0
15
297
462
237
225
30
4
module EulerSpec where import Euler import Test.Hspec spec :: Spec spec = do describe "p1" $ do it "correctly calculates the example problem" $ do p1 10 `shouldBe` 23 describe "p2" $ do it "correctly calculates the example problem" $ do p2 100 `shouldBe` 44
tylerjl/euler-haskell
test/EulerSpec.hs
bsd-3-clause
309
0
14
96
86
42
44
11
1
{-# LANGUAGE GADTs , KindSignatures , DataKinds , ScopedTypeVariables , PatternGuards , Rank2Types , TypeOperators , FlexibleContexts , UndecidableInstances #-} {-# OPTIONS_GHC -Wall -fwarn-tabs #-} ---------------------------------------------------------------- -- 2016.05.28 -- | -- Module : Language.Hakaru.Pretty.Concrete -- Copyright : Copyright (c) 2016 the Hakaru team -- License : BSD3 -- Maintainer : [email protected] -- Stability : experimental -- Portability : GHC-only -- -- ---------------------------------------------------------------- module Language.Hakaru.Pretty.Concrete ( -- * The user-facing API pretty , prettyPrec , prettyType , prettyValue -- * Helper functions (semi-public internal API) ) where import Text.PrettyPrint (Doc, text, integer, int, double, (<+>), (<>), ($$), sep, cat, fsep, vcat, nest, parens, brackets, punctuate, comma, colon, equals) import qualified Data.Foldable as F import qualified Data.List.NonEmpty as L import qualified Data.Text as Text -- Because older versions of "Data.Foldable" do not export 'null' apparently... import qualified Data.Sequence as Seq import qualified Data.Vector as V import Data.Ratio import Data.Number.Natural (fromNatural, fromNonNegativeRational) import Data.Number.Nat import qualified Data.Number.LogFloat as LF import Language.Hakaru.Syntax.IClasses (fmap11, foldMap11, jmEq1, TypeEq(..)) import Language.Hakaru.Types.DataKind import Language.Hakaru.Types.Sing import Language.Hakaru.Types.Coercion import Language.Hakaru.Types.HClasses import Language.Hakaru.Syntax.AST import Language.Hakaru.Syntax.Datum import Language.Hakaru.Syntax.Value import Language.Hakaru.Syntax.ABT import Language.Hakaru.Pretty.Haskell (Associativity(..)) ---------------------------------------------------------------- -- | Pretty-print a term. pretty :: (ABT Term abt) => abt '[] a -> Doc pretty = prettyPrec 0 -- | Pretty-print a term at a given precendence level. prettyPrec :: (ABT Term abt) => Int -> abt '[] a -> Doc prettyPrec p = prettyPrec_ p . LC_ ---------------------------------------------------------------- class Pretty (f :: Hakaru -> *) where -- | A polymorphic variant if 'prettyPrec', for internal use. prettyPrec_ :: Int -> f a -> Doc mapInit :: (a -> a) -> [a] -> [a] mapInit f (x:xs@(_:_)) = f x : mapInit f xs mapInit _ xs = xs sepByR :: String -> [Doc] -> Doc sepByR s = sep . mapInit (<+> text s) sepComma :: [Doc] -> Doc sepComma = fsep . punctuate comma -- It's safe to use fsep here despite our indentation-sensitive syntax, -- because commas are not a binary operator. parensIf :: Bool -> Doc -> Doc parensIf False = id parensIf True = parens -- | Pretty-print a variable. ppVariable :: Variable (a :: Hakaru) -> Doc ppVariable x | Text.null (varHint x) = text ('x' : show (fromNat (varID x))) -- We used to use '_' but... | otherwise = text (Text.unpack (varHint x)) ppBinder :: (ABT Term abt) => abt xs a -> ([Doc], Doc) ppBinder e = go [] (viewABT e) where go :: (ABT Term abt) => [Doc] -> View (Term abt) xs a -> ([Doc], Doc) go xs (Bind x v) = go (ppVariable x : xs) v go xs (Var x) = (reverse xs, ppVariable x) go xs (Syn t) = (reverse xs, pretty (syn t)) ppBinder1 :: (ABT Term abt) => abt '[x] a -> (Doc, Doc, Doc) ppBinder1 e = caseBind e $ \x v -> (ppVariable x, prettyType 0 (varType x), caseVarSyn v ppVariable (pretty . syn)) -- TODO: since switching to ABT2, this instance requires -XFlexibleContexts; we should fix that if we can -- BUG: since switching to ABT2, this instance requires -XUndecidableInstances; must be fixed! instance (ABT Term abt) => Pretty (LC_ abt) where prettyPrec_ p (LC_ e) = caseVarSyn e ppVariable $ \t -> case t of o :$ es -> ppSCon p o es NaryOp_ o es -> if Seq.null es then identityElement o else case o of And -> asOp 3 "&&" es Or -> asOp 2 "||" es Xor -> asFun "xor" es Iff -> asFun "iff" es Min _ -> asFun "min" es Max _ -> asFun "max" es Sum _ -> case F.toList es of [e1] -> prettyPrec p e1 e1:es' -> parensIf (p > 6) $ sep $ prettyPrec 6 e1 : map ppNaryOpSum es' Prod _ -> case F.toList es of [e1] -> prettyPrec p e1 e1:e2:es' -> parensIf (p > 7) $ sep $ d1' : ppNaryOpProd second e2 : map (ppNaryOpProd False) es' where d1 = prettyPrec 7 e1 (d1', second) = caseVarSyn e1 (const (d1,False)) (\t -> case t of -- Use parens to distinguish division into 1 -- from recip Literal_ (LNat 1) -> (parens d1, False) Literal_ (LNat _) -> (d1, True) _ -> (d1, False)) where identityElement :: NaryOp a -> Doc identityElement And = text "true" identityElement Or = text "false" identityElement Xor = text "false" identityElement Iff = text "true" identityElement (Min _) = error "min cannot be used with no arguments" identityElement (Max _) = error "max cannot be used with no arguments" identityElement (Sum _) = text "0" identityElement (Prod _) = text "1" asOp :: (ABT Term abt) => Int -> String -> Seq.Seq (abt '[] a) -> Doc asOp p0 s = parensIf (p > p0) . sepByR s . map (prettyPrec (p0 + 1)) . F.toList asFun :: (ABT Term abt) => String -> Seq.Seq (abt '[] a) -> Doc asFun s = ($ p) . F.foldr1 (\a b p' -> ppFun p' s [a, b]) . fmap (flip prettyPrec) Literal_ v -> prettyPrec_ p v Empty_ typ -> parensIf (p > 5) (text "[]." <+> prettyType 0 typ) Array_ e1 e2 -> parensIf (p > 0) $ let (var, _, body) = ppBinder1 e2 in sep [ sep [ text "array" <+> var , text "of" <+> pretty e1 <> colon ] , body ] ArrayLiteral_ es -> ppList $ map pretty es Datum_ d -> prettyPrec_ p (fmap11 LC_ d) Case_ e1 [Branch (PDatum h2 _) e2, Branch (PDatum h3 _) e3] | "true" <- Text.unpack h2 , "false" <- Text.unpack h3 , ([], body2) <- ppBinder e2 , ([], body3) <- ppBinder e3 -> parensIf (p > 0) $ sep [ sep [ text "if" <+> pretty e1 <> colon, nest 2 body2 ] , sep [ text "else" <> colon, nest 2 body3 ] ] Case_ e1 bs -> parensIf (p > 0) $ sep [ text "match" <+> pretty e1 <> colon , vcat (map (prettyPrec_ 0) bs) ] Superpose_ pes -> case L.toList pes of [wm] -> ppWeight p wm wms -> parensIf (p > 1) . sepByR "<|>" $ map (ppWeight 2) wms where ppWeight p (w,m) | Syn (Literal_ (LProb 1)) <- viewABT w = prettyPrec p m | otherwise = ppApply2 p "weight" w m Reject_ typ -> parensIf (p > 5) (text "reject." <+> prettyType 0 typ) ppNaryOpSum :: forall abt a . (ABT Term abt) => abt '[] a -> Doc ppNaryOpSum e = caseVarSyn e (const d) $ \t -> case t of PrimOp_ (Negate _) :$ e1 :* End -> text "-" <+> prettyPrec 7 e1 _ -> d where d = text "+" <+> prettyPrec 7 e ppNaryOpProd :: forall abt a . (ABT Term abt) => Bool -> abt '[] a -> Doc ppNaryOpProd second e = caseVarSyn e (const d) $ \t -> case t of PrimOp_ (Recip _) :$ e1 :* End -> if not second then d' else caseVarSyn e1 (const d') $ \t' -> case t' of -- Use parens to distinguish division of nats -- from prob literal Literal_ (LNat _) -> text "/" <+> parens (pretty e1) _ -> d' where d' = text "/" <+> prettyPrec 8 e1 _ -> d where d = text "*" <+> prettyPrec 8 e -- | Pretty-print @(:$)@ nodes in the AST. ppSCon :: (ABT Term abt) => Int -> SCon args a -> SArgs abt args -> Doc ppSCon p Lam_ = \(e1 :* End) -> let (var, typ, body) = ppBinder1 e1 in parensIf (p > 0) $ sep [ text "fn" <+> var <+> typ <> colon , body ] --ppSCon p App_ = \(e1 :* e2 :* End) -> ppArg e1 ++ parens True (ppArg e2) ppSCon p App_ = \(e1 :* e2 :* End) -> prettyApps p e1 e2 ppSCon p Let_ = \(e1 :* e2 :* End) -> -- TODO: generate 'def' if possible let (var, _, body) = ppBinder1 e2 in parensIf (p > 0) $ var <+> equals <+> pretty e1 $$ body {- ppSCon p (Ann_ typ) = \(e1 :* End) -> parensIf (p > 5) (prettyPrec 6 e1 <> text "." <+> prettyType 0 typ) -} ppSCon p (PrimOp_ o) = \es -> ppPrimOp p o es ppSCon p (ArrayOp_ o) = \es -> ppArrayOp p o es ppSCon p (CoerceTo_ c) = \(e1 :* End) -> ppCoerceTo p c e1 ppSCon p (UnsafeFrom_ c) = \(e1 :* End) -> ppUnsafeFrom p c e1 ppSCon p (MeasureOp_ o) = \es -> ppMeasureOp p o es ppSCon p Dirac = \(e1 :* End) -> parensIf (p > 0) $ text "return" <+> pretty e1 ppSCon p MBind = \(e1 :* e2 :* End) -> let (var, _, body) = ppBinder1 e2 in parensIf (p > 0) $ var <+> text "<~" <+> pretty e1 $$ body ppSCon p Plate = \(e1 :* e2 :* End) -> let (var, _, body) = ppBinder1 e2 in parensIf (p > 0) $ sep [ sep [ text "plate" <+> var , text "of" <+> pretty e1 <> colon ] , body ] ppSCon p Chain = \(e1 :* e2 :* e3 :* End) -> let (var, _, body) = ppBinder1 e3 in parensIf (p > 0) $ sep [ sep [ text "chain" <+> var , text "from" <+> pretty e2 , text "of" <+> pretty e1 <> colon ] , body ] ppSCon p Integrate = \(e1 :* e2 :* e3 :* End) -> let (var, _, body) = ppBinder1 e3 in parensIf (p > 0) $ sep [ sep [ text "integrate" <+> var , text "from" <+> pretty e1 , text "to" <+> pretty e2 <> colon ] , body ] ppSCon p (Summate _ _) = \(e1 :* e2 :* e3 :* End) -> let (var, _, body) = ppBinder1 e3 in parensIf (p > 0) $ sep [ sep [ text "summate" <+> var , text "from" <+> pretty e1 , text "to" <+> pretty e2 <> colon ] , body ] ppSCon p (Product _ _) = \(e1 :* e2 :* e3 :* End) -> let (var, _, body) = ppBinder1 e3 in parensIf (p > 0) $ sep [ sep [ text "product" <+> var , text "from" <+> pretty e1 , text "to" <+> pretty e2 <> colon ] , body ] ppSCon p Expect = \(e1 :* e2 :* End) -> let (var, _, body) = ppBinder1 e2 in parensIf (p > 0) $ sep [ text "expect" <+> var <+> pretty e1 <> colon , body ] ppSCon p Observe = \(e1 :* e2 :* End) -> ppApply2 p "observe" e1 e2 ppCoerceTo :: ABT Term abt => Int -> Coercion a b -> abt '[] a -> Doc ppCoerceTo p c = ppApply1 p f -- BUG: this may not work quite right when the coercion isn't one of the special named ones... where f = case c of Signed HRing_Real `CCons` CNil -> "prob2real" Signed HRing_Int `CCons` CNil -> "nat2int" Continuous HContinuous_Real `CCons` CNil -> "int2real" Continuous HContinuous_Prob `CCons` CNil -> "nat2prob" Continuous HContinuous_Prob `CCons` Signed HRing_Real `CCons` CNil -> "nat2real" Signed HRing_Int `CCons` Continuous HContinuous_Real `CCons` CNil -> "nat2real" _ -> "coerceTo_ (" ++ show c ++ ")" ppUnsafeFrom :: ABT Term abt => Int -> Coercion a b -> abt '[] b -> Doc ppUnsafeFrom p c = ppApply1 p f -- BUG: this may not work quite right when the coercion isn't one of the special named ones... where f = case c of Signed HRing_Real `CCons` CNil -> "real2prob" Signed HRing_Int `CCons` CNil -> "int2nat" _ -> "unsafeFrom_ (" ++ show c ++ ")" -- | Pretty-print a type. prettyType :: Int -> Sing (a :: Hakaru) -> Doc prettyType _ SNat = text "nat" prettyType _ SInt = text "int" prettyType _ SProb = text "prob" prettyType _ SReal = text "real" prettyType p (SFun a b) = parensIf (p > 0) $ sep [ prettyType 1 a <+> text "->" , prettyType 0 b ] prettyType p (SMeasure a) = ppFun p "measure" [flip prettyType a] prettyType p (SArray a) = ppFun p "array" [flip prettyType a] prettyType p (SData (STyCon sym `STyApp` a `STyApp` b) _) | Just Refl <- jmEq1 sym sSymbol_Pair = ppFun p "pair" [flip prettyType a, flip prettyType b] | Just Refl <- jmEq1 sym sSymbol_Either = ppFun p "either" [flip prettyType a, flip prettyType b] prettyType p (SData (STyCon sym `STyApp` a) _) | Just Refl <- jmEq1 sym sSymbol_Maybe = ppFun p "maybe" [flip prettyType a] prettyType p (SData (STyCon sym) _) | Just Refl <- jmEq1 sym sSymbol_Bool = text "bool" | Just Refl <- jmEq1 sym sSymbol_Unit = text "unit" prettyType _ typ = parens (text (show typ)) -- | Pretty-print a 'PrimOp' @(:$)@ node in the AST. ppPrimOp :: (ABT Term abt, typs ~ UnLCs args, args ~ LCs typs) => Int -> PrimOp typs a -> SArgs abt args -> Doc ppPrimOp p Not (e1 :* End) | Syn (PrimOp_ Less{} :$ e2 :* e3 :* End) <- viewABT e1 = ppBinop "<=" 4 NonAssoc p e3 e2 | Syn (PrimOp_ Equal{} :$ e2 :* e3 :* End) <- viewABT e1 = ppBinop "/=" 4 NonAssoc p e2 e3 | otherwise = ppApply1 p "not" e1 ppPrimOp p Impl (e1 :* e2 :* End) = ppApply2 p "impl" e1 e2 ppPrimOp p Diff (e1 :* e2 :* End) = ppApply2 p "diff" e1 e2 ppPrimOp p Nand (e1 :* e2 :* End) = ppApply2 p "nand" e1 e2 ppPrimOp p Nor (e1 :* e2 :* End) = ppApply2 p "nor" e1 e2 ppPrimOp _ Pi End = text "pi" ppPrimOp p Sin (e1 :* End) = ppApply1 p "sin" e1 ppPrimOp p Cos (e1 :* End) = ppApply1 p "cos" e1 ppPrimOp p Tan (e1 :* End) = ppApply1 p "tan" e1 ppPrimOp p Asin (e1 :* End) = ppApply1 p "asin" e1 ppPrimOp p Acos (e1 :* End) = ppApply1 p "acos" e1 ppPrimOp p Atan (e1 :* End) = ppApply1 p "atan" e1 ppPrimOp p Sinh (e1 :* End) = ppApply1 p "sinh" e1 ppPrimOp p Cosh (e1 :* End) = ppApply1 p "cosh" e1 ppPrimOp p Tanh (e1 :* End) = ppApply1 p "tanh" e1 ppPrimOp p Asinh (e1 :* End) = ppApply1 p "asinh" e1 ppPrimOp p Acosh (e1 :* End) = ppApply1 p "acosh" e1 ppPrimOp p Atanh (e1 :* End) = ppApply1 p "atanh" e1 ppPrimOp p RealPow (e1 :* e2 :* End) = ppBinop "**" 8 RightAssoc p e1 e2 ppPrimOp p Exp (e1 :* End) = ppApply1 p "exp" e1 ppPrimOp p Log (e1 :* End) = ppApply1 p "log" e1 ppPrimOp _ (Infinity _) End = text "∞" ppPrimOp p GammaFunc (e1 :* End) = ppApply1 p "gammaFunc" e1 ppPrimOp p BetaFunc (e1 :* e2 :* End) = ppApply2 p "betaFunc" e1 e2 ppPrimOp p (Equal _) (e1 :* e2 :* End) = ppBinop "==" 4 NonAssoc p e1 e2 ppPrimOp p (Less _) (e1 :* e2 :* End) = ppBinop "<" 4 NonAssoc p e1 e2 ppPrimOp p (NatPow _) (e1 :* e2 :* End) = ppBinop "^" 8 RightAssoc p e1 e2 ppPrimOp p (Negate _) (e1 :* End) = ppNegate p e1 ppPrimOp p (Abs _) (e1 :* End) = ppApply1 p "abs" e1 ppPrimOp p (Signum _) (e1 :* End) = ppApply1 p "signum" e1 ppPrimOp p (Recip _) (e1 :* End) = ppRecip p e1 ppPrimOp p (NatRoot _) (e1 :* e2 :* End) = ppNatRoot p e1 e2 ppPrimOp p (Erf _) (e1 :* End) = ppApply1 p "erf" e1 ppNegate :: (ABT Term abt) => Int -> abt '[] a -> Doc ppNegate p e = parensIf (p > 6) $ caseVarSyn e (const d) $ \t -> case t of -- Use parens to distinguish between negation of nats/probs -- from int/real literal Literal_ (LNat _) -> d' Literal_ (LProb _) -> d' _ -> d where d = text "-" <> prettyPrec 7 e d' = text "-" <> parens (pretty e) ppRecip :: (ABT Term abt) => Int -> abt '[] a -> Doc ppRecip p e = parensIf (p > 7) $ caseVarSyn e (const d) $ \t -> case t of -- Use parens to distinguish between reciprocal of nat -- from prob literal Literal_ (LNat _) -> d' _ -> d where d = text "1/" <+> prettyPrec 8 e d' = text "1/" <+> parens (pretty e) ppNatRoot :: (ABT Term abt) => Int -> abt '[] a -> abt '[] 'HNat -> Doc ppNatRoot p e1 e2 = caseVarSyn e2 (const d) $ \t -> case t of Literal_ (LNat 2) -> ppApply1 p "sqrt" e1 _ -> d where d = ppApply2 p "natroot" e1 e2 -- | Pretty-print a 'ArrayOp' @(:$)@ node in the AST. ppArrayOp :: (ABT Term abt, typs ~ UnLCs args, args ~ LCs typs) => Int -> ArrayOp typs a -> SArgs abt args -> Doc ppArrayOp p (Index _) = \(e1 :* e2 :* End) -> parensIf (p > 10) $ cat [ prettyPrec 10 e1, nest 2 (brackets (pretty e2)) ] ppArrayOp p (Size _) = \(e1 :* End) -> ppApply1 p "size" e1 ppArrayOp p (Reduce _) = \(e1 :* e2 :* e3 :* End) -> ppFun p "reduce" [ flip prettyPrec e1 , flip prettyPrec e2 , flip prettyPrec e3 ] -- | Pretty-print a 'MeasureOp' @(:$)@ node in the AST. ppMeasureOp :: (ABT Term abt, typs ~ UnLCs args, args ~ LCs typs) => Int -> MeasureOp typs a -> SArgs abt args -> Doc ppMeasureOp p Lebesgue = \(e1 :* e2 :* End) -> ppApply2 p "lebesgue" e1 e2 ppMeasureOp _ Counting = \End -> text "counting" ppMeasureOp p Categorical = \(e1 :* End) -> ppApply1 p "categorical" e1 ppMeasureOp p Uniform = \(e1 :* e2 :* End) -> ppApply2 p "uniform" e1 e2 ppMeasureOp p Normal = \(e1 :* e2 :* End) -> ppApply2 p "normal" e1 e2 ppMeasureOp p Poisson = \(e1 :* End) -> ppApply1 p "poisson" e1 ppMeasureOp p Gamma = \(e1 :* e2 :* End) -> ppApply2 p "gamma" e1 e2 ppMeasureOp p Beta = \(e1 :* e2 :* End) -> ppApply2 p "beta" e1 e2 instance Pretty Literal where prettyPrec_ _ (LNat n) = integer (fromNatural n) prettyPrec_ p (LInt i) = parensIf (p > 6) $ if i < 0 then text "-" <> integer (-i) else text "+" <> integer i prettyPrec_ p (LProb l) = parensIf (p > 7) $ cat [ integer n, text "/" <> integer d ] where r = fromNonNegativeRational l n = numerator r d = denominator r prettyPrec_ p (LReal r) = parensIf (p > 6) $ if n < 0 then text "-" <> cat [ integer (-n), text "/" <> integer d ] else text "+" <> cat [ integer n , text "/" <> integer d ] where n = numerator r d = denominator r instance Pretty Value where prettyPrec_ _ (VNat n) = int (fromNat n) prettyPrec_ p (VInt i) = parensIf (p > 6) $ if i < 0 then int i else text "+" <> int i prettyPrec_ _ (VProb l) = double (LF.fromLogFloat l) prettyPrec_ p (VReal r) = parensIf (p > 6) $ if r < 0 then double r else text "+" <> double r prettyPrec_ p (VDatum d) = prettyPrec_ p d prettyPrec_ _ (VLam _) = text "<function>" prettyPrec_ _ (VMeasure _) = text "<measure>" prettyPrec_ _ (VArray a) = ppList . V.toList $ V.map (prettyPrec_ 0) a prettyValue :: Value a -> Doc prettyValue = prettyPrec_ 0 instance Pretty f => Pretty (Datum f) where prettyPrec_ p (Datum hint _typ d) | Text.null hint = ppFun p "datum_" [error "TODO: prettyPrec_@Datum"] | otherwise = case Text.unpack hint of -- Special cases for certain datums "pair" -> ppTuple p (foldMap11 (\e -> [flip prettyPrec_ e]) d) "true" -> text "true" "false" -> text "false" "unit" -> text "()" -- General case f -> parensIf (p > 5) $ ppFun 6 f (foldMap11 (\e -> [flip prettyPrec_ e]) d) <> text "." <+> prettyType 0 _typ -- HACK: need to pull this out in order to get polymorphic recursion over @xs@ ppPattern :: [Doc] -> Pattern xs a -> (Int -> Doc, [Doc]) ppPattern vars PWild = (const (text "_"), vars) ppPattern (v:vs) PVar = (const v , vs) ppPattern vars (PDatum hint d0) | Text.null hint = error "TODO: prettyPrec_@Pattern" | otherwise = case Text.unpack hint of -- Special cases for certain pDatums "true" -> (const (text "true" ), vars) "false" -> (const (text "false"), vars) "pair" -> ppFunWithVars ppTuple -- General case f -> ppFunWithVars (flip ppFun f) where ppFunWithVars ppHint = (flip ppHint g, vars') where (g, vars') = goCode d0 vars goCode :: PDatumCode xss vars a -> [Doc] -> ([Int -> Doc], [Doc]) goCode (PInr d) = goCode d goCode (PInl d) = goStruct d goStruct :: PDatumStruct xs vars a -> [Doc] -> ([Int -> Doc], [Doc]) goStruct PDone vars = ([], vars) goStruct (PEt d1 d2) vars = (gF ++ gS, vars'') where (gF, vars') = goFun d1 vars (gS, vars'') = goStruct d2 vars' goFun :: PDatumFun x vars a -> [Doc] -> ([Int -> Doc], [Doc]) goFun (PKonst d) vars = ([g], vars') where (g, vars') = ppPattern vars d goFun (PIdent d) vars = ([g], vars') where (g, vars') = ppPattern vars d instance (ABT Term abt) => Pretty (Branch a abt) where prettyPrec_ p (Branch pat e) = let (vars, body) = ppBinder e (pp, []) = ppPattern vars pat in sep [ pp 0 <> colon, nest 2 body ] ---------------------------------------------------------------- prettyApps :: (ABT Term abt) => Int -> abt '[] (a ':-> b) -> abt '[] a -> Doc prettyApps = \ p e1 e2 -> {- TODO: confirm not using reduceLams case reduceLams e1 e2 of Just e2' -> ppArg e2' Nothing -> -} uncurry (ppApp p) (collectApps e1 [flip prettyPrec e2]) where reduceLams :: (ABT Term abt) => abt '[] (a ':-> b) -> abt '[] a -> Maybe (abt '[] b) reduceLams e1 e2 = caseVarSyn e1 (const Nothing) $ \t -> case t of Lam_ :$ e1 :* End -> caseBind e1 $ \x e1' -> Just (subst x e2 e1') _ -> Nothing -- collectApps makes sure f(x,y) is not printed f(x)(y) collectApps :: (ABT Term abt) => abt '[] (a ':-> b) -> [Int -> Doc] -> (Int -> Doc, [Int -> Doc]) collectApps e es = caseVarSyn e (const ret) $ \t -> case t of App_ :$ e1 :* e2 :* End -> collectApps e1 (flip prettyPrec e2 : es) _ -> ret where ret = (flip prettyPrec e, es) ppList :: [Doc] -> Doc ppList = brackets . sepComma ppTuple :: Int -> [Int -> Doc] -> Doc ppTuple _ = parens . sepComma . map ($ 0) ppApp :: Int -> (Int -> Doc) -> [Int -> Doc] -> Doc ppApp p f ds = parensIf (p > 10) $ cat [ f 10, nest 2 (ppTuple 11 ds) ] ppFun :: Int -> String -> [Int -> Doc] -> Doc ppFun p = ppApp p . const . text ppApply1 :: (ABT Term abt) => Int -> String -> abt '[] a -> Doc ppApply1 p f e1 = ppFun p f [flip prettyPrec e1] ppApply2 :: (ABT Term abt) => Int -> String -> abt '[] a -> abt '[] b -> Doc ppApply2 p f e1 e2 = ppFun p f [flip prettyPrec e1, flip prettyPrec e2] ppBinop :: (ABT Term abt) => String -> Int -> Associativity -> Int -> abt '[] a -> abt '[] b -> Doc ppBinop op p0 assoc = let (p1,p2,f1,f2) = case assoc of NonAssoc -> (1 + p0, 1 + p0, id, (text op <+>)) LeftAssoc -> ( p0, 1 + p0, id, (text op <+>)) RightAssoc -> (1 + p0, p0, (<+> text op), id) in \p e1 e2 -> parensIf (p > p0) $ sep [ f1 (prettyPrec p1 e1) , f2 (prettyPrec p2 e2) ] ---------------------------------------------------------------- ----------------------------------------------------------- fin.
zachsully/hakaru
haskell/Language/Hakaru/Pretty/Concrete.hs
bsd-3-clause
25,260
0
28
8,903
9,310
4,730
4,580
495
7
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module Session where import Control.Lens import Class.Name import Data.Type import Storage.Cache.Env import Storage.Db.Env data Session = Session { _sessionCache :: Cache, _sessionDbEnv :: DbEnv } class HasSession a where session :: Lens' a Session sessionCache :: Lens' a Cache sessionDbEnv :: Lens' a DbEnv sessionCache = session . sessionCache sessionDbEnv = session . sessionDbEnv instance HasSession Session where session = id sessionCache = lens _sessionCache (\s a -> s { _sessionCache = a }) sessionDbEnv = lens _sessionDbEnv (\s a -> s { _sessionDbEnv = a }) instance HasCache Session where cache = sessionCache . cache instance HasCacheSlot Session Name where slot _ = cache . cacheName instance HasCacheSlot Session (Type, Name) where slot _ = cache . cacheTypeName instance HasDbEnv Session where dbEnv = sessionDbEnv . dbEnv
showpoint/refs
src/Session.hs
bsd-3-clause
1,013
0
10
237
264
147
117
30
0
{-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} {-# OPTIONS_GHC -fplugin Brisk.Plugin #-} {-# OPTIONS_GHC -fplugin-opt Brisk.Plugin:main #-} module Simple03 where import Control.Distributed.Process import Data.Binary import Data.Typeable import GHC.Generics (Generic) data PingMsg = Ping ProcessId | Pong ProcessId deriving (Typeable, Generic) instance Binary PingMsg foo :: ProcessId -> Process () foo me = do theRealMe <- getSelfPid send me (Ping theRealMe) main :: Process () main = do me <- getSelfPid spawnLocal $ foo me who <- expect case who of Ping whom -> send whom me _ -> return ()
abakst/brisk-prelude
examples/Simple03.hs
bsd-3-clause
791
0
11
209
182
94
88
24
2
{- - Capture.hs - By Steven Smith -} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleInstances #-} -- | 'Captureable' is a type class for types that can be parsed from 'Text'. -- It is used by the 'capture' 'Route' to automatically handle parsing. -- -- If you would like to make your own data type 'Captureable', then all that -- needs to be implemented is 'captureParser', which is a 'Parser' from -- <http://hackage.haskell.org/package/attoparsec attoparsec>. Do keep in mind -- when writing 'Captureable' instances that the 'Text' input will be from a -- @URI@ path segment, so not all possible characters will be available. module Web.DumpTruck.Capture where import Web.DumpTruck.Date import Control.Applicative import Data.Text (Text) import Data.Text.Encoding import Data.Attoparsec.Text import Data.ByteString.Builder import qualified Data.Text as T import qualified Data.Text.Lazy as LT import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as LBS -- | A type is 'Captureable' if a 'Parser' exists for it that can parse 'Text' -- input coming from a @URI@ path segment. -- -- Minimum definition: 'captureParser' class Captureable a where -- | The @URI@ path segment 'Parser' for this data type captureParser :: Parser a -- | Performs the 'Text' parsing, which may fail. -- -- Note: The default implementation should cover almost all use-cases for -- normal data types. This method exists solely for cases where parsing -- cannot fail, specifically for converting between various string types. performCapture :: Text -> Maybe a performCapture = either (const Nothing) Just . parseOnly captureParser instance Captureable Text where captureParser = takeText performCapture = Just instance Captureable LT.Text where captureParser = takeLazyText performCapture = Just . LT.fromStrict instance Captureable BS.ByteString where captureParser = fmap encodeUtf8 takeText performCapture = Just . encodeUtf8 instance Captureable LBS.ByteString where captureParser = fmap (toLazyByteString . encodeUtf8Builder) takeText performCapture = Just . toLazyByteString . encodeUtf8Builder instance Captureable Int where captureParser = decimal instance Captureable Double where captureParser = double instance Captureable Bool where captureParser = string "true" *> pure True <|> string "false" *> pure False instance Captureable Char where captureParser = anyChar -- String instance Captureable [Char] where captureParser = fmap T.unpack takeText performCapture = Just . T.unpack -- Note that stacking lists [[a]] is unlikely to do anything useful instance Captureable a => Captureable [a] where captureParser = captureParser `sepBy1` (char ',') instance Captureable GmtTime where captureParser = undefined -- TODO :( performCapture = parseGmtTime . encodeUtf8
stevely/DumpTruck
src/Web/DumpTruck/Capture.hs
bsd-3-clause
2,906
0
10
518
436
252
184
45
0
{-# LANGUAGE TemplateHaskell #-} module Render.GLModeT where import Control.Lens (makeLenses) import qualified Data.ByteString as B import Types data GLModeT = GLModeT { _glmName :: B.ByteString , _glmMinimize :: Int , _glmMaximize :: Int } makeLenses ''GLModeT
ksaveljev/hake-2
src/Render/GLModeT.hs
bsd-3-clause
302
0
9
76
65
40
25
10
0
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} -- | This module is a top-level convenience module which re-exports most of the -- @io-streams@ library. -- -- It is recommended to import this module qualified, as follows: -- -- @ -- import "System.IO.Streams" ('Generator', 'InputStream', 'OutputStream') -- import qualified "System.IO.Streams" as Streams -- @ -- -- For an in-depth tutorial on how to use @io-streams@, please see the -- "System.IO.Streams.Tutorial" module. -- -- Is there a function missing from this library? Interested in contributing? -- Send a pull request to <http://github.com/snapframework/io-streams>. module System.IO.Streams ( -- * Stream types InputStream , OutputStream -- ** A note about resource acquisition\/release semantics -- $resource -- * Creating streams , makeInputStream , makeOutputStream -- * Primitive stream operations , read , unRead , peek , write , writeTo , atEOF -- * Connecting streams together , connect , connectTo , supply , supplyTo , appendInputStream , concatInputStreams -- * Thread safety \/ concurrency , lockingInputStream , lockingOutputStream -- * Utility streams , nullInput , nullOutput -- * Generator monad -- $generator , Generator , fromGenerator , yield -- * Batteries included , module System.IO.Streams.Builder , module System.IO.Streams.ByteString , module System.IO.Streams.Combinators , module System.IO.Streams.Handle , module System.IO.Streams.File , module System.IO.Streams.List , module System.IO.Streams.Network , module System.IO.Streams.Process , module System.IO.Streams.Text , module System.IO.Streams.Vector , module System.IO.Streams.Zlib ) where ------------------------------------------------------------------------------ import Prelude () ------------------------------------------------------------------------------ import System.IO.Streams.Internal import System.IO.Streams.Builder import System.IO.Streams.ByteString import System.IO.Streams.Combinators import System.IO.Streams.File import System.IO.Streams.Handle import System.IO.Streams.List import System.IO.Streams.Network import System.IO.Streams.Process import System.IO.Streams.Text import System.IO.Streams.Vector import System.IO.Streams.Zlib ------------------------------------------------------------------------------ -- $generator -- #generator# -- -- The 'Generator' monad makes it easier for you to define more complicated -- 'InputStream's. Generators have a couple of basic features: -- -- 'Generator' is a 'MonadIO', so you can run IO actions from within it using -- 'liftIO': -- -- @ -- foo :: 'Generator' r a -- foo = 'liftIO' fireTheMissiles -- @ -- -- 'Generator' has a 'yield' function: -- -- @ -- 'yield' :: r -> 'Generator' r () -- @ -- -- A call to \"'yield' @x@\" causes \"'Just' @x@\" to appear when reading the -- 'InputStream'. Finally, 'Generator' comes with a function to turn a -- 'Generator' into an 'InputStream': -- -- @ -- 'fromGenerator' :: 'Generator' r a -> 'IO' ('InputStream' r) -- @ -- -- Once the 'Generator' action finishes, 'fromGenerator' will cause an -- end-of-stream 'Nothing' marker to appear at the output. Example: -- -- @ -- ghci> (Streams.'fromGenerator' $ 'Control.Monad.sequence' $ 'Prelude.map' Streams.'yield' [1..5::Int]) >>= Streams.'toList' -- [1,2,3,4,5] -- @ ------------------------------------------------------------------------------ -- $resource -- #resource# -- -- In general, the convention within this library is that input and output -- streams do not deal with resource acquisition\/release semantics, with rare -- exceptions like 'System.IO.Streams.withFileAsInput'. For example, sending -- \"end-of-stream\" to an 'OutputStream' wrapped around a 'System.IO.Handle' -- doesn't cause the handle to be closed. You can think of streams as little -- state machines that are attached to the underlying resources, and the -- finalization\/release of these resources is up to you. -- -- This means that you can use standard Haskell idioms like -- 'Control.Exception.bracket' to handle resource acquisition and cleanup in an -- exception-safe way. --
LukeHoersten/io-streams
src/System/IO/Streams.hs
bsd-3-clause
4,358
0
5
787
338
264
74
51
0
module Scanner (scan) where import Control.Monad (liftM) import Dep (Dep(Dep)) -- Convert a list of dep files into a list of deps scan :: [FilePath] -> IO [Dep] scan = liftM concat . mapM mapper where mapper fn = liftM (parse_file fn) $ readFile fn -- =================================================================== -- Pure Functions -- =================================================================== parse_file :: String -> String -> [Dep] parse_file filename = map line2dep . zip3 (repeat filename) [1..] . lines line2dep :: (FilePath, Int, String) -> Dep line2dep (filename, num, line) = do Dep name url filename num where (name, url) = parse_dep line parse_dep :: String -> (String, String) parse_dep line = (name, url) where bits = words line name = head bits url = last bits
ericmoritz/deps
src/Scanner.hs
bsd-3-clause
838
0
10
168
262
143
119
18
1
{-# LANGUAGE OverloadedStrings #-} module CacheDNS.Crypto.Common ( getSSLCryptor ) where import qualified Data.HashMap.Strict as HM import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as C import Data.IntMap.Strict (fromList, (!)) import Data.List (sortBy) import Data.Maybe (fromJust) import Data.Binary.Get (runGet, getWord64le) import Data.ByteString (ByteString) import Data.Monoid ((<>)) import Control.Concurrent.MVar ( newEmptyMVar, isEmptyMVar , putMVar, readMVar) import Crypto.Hash.MD5 (hash) import OpenSSL (withOpenSSL) import OpenSSL.EVP.Cipher (getCipherByName, CryptoMode(..)) import OpenSSL.EVP.Internal (cipherInitBS, cipherUpdateBS) import OpenSSL.Random (randBytes) methodSupported :: HM.HashMap String (Int, Int) methodSupported = HM.fromList [ ("aes-128-cfb", (16, 16)) , ("aes-192-cfb", (24, 16)) , ("aes-256-cfb", (32, 16)) , ("bf-cfb", (16, 8)) , ("camellia-128-cfb", (16, 16)) , ("camellia-192-cfb", (24, 16)) , ("camellia-256-cfb", (32, 16)) , ("cast5-cfb", (16, 8)) , ("des-cfb", (8, 8)) , ("idea-cfb", (16, 8)) , ("rc2-cfb", (16, 8)) , ("rc4", (16, 0)) , ("seed-cfb", (16, 16)) ] evpBytesToKey :: ByteString -> Int -> Int -> (ByteString, ByteString) evpBytesToKey password keyLen ivLen = let ms' = S.concat $ ms False [] key = S.take keyLen ms' iv = S.take ivLen $ S.drop keyLen ms' in (key, iv) where ms :: Bool -> [ByteString] -> [ByteString] ms False _ = ms True [hash password] -- 计算出password的md5的Hash ms True m | S.length (S.concat m) < keyLen + ivLen = -- 如果长度小于 keyLen和ivLen的和 -- 用m的最后一位和password合并后再次计算md5值 ms True (m ++ [hash (last m <> password)]) | otherwise = m getSSLCryptor :: String -> ByteString -> IO (ByteString -> IO ByteString, ByteString -> IO ByteString) getSSLCryptor method password = do let (m0, m1) = fromJust $ HM.lookup method methodSupported random_iv <- withOpenSSL $ randBytes 32 -- 得到iv let cipher_iv = S.take m1 random_iv -- 从现有的password生成Key let (key, _) = evpBytesToKey password m0 m1 -- 生成加密和解密的上下文 cipherCtx <- newEmptyMVar decipherCtx <- newEmptyMVar -- 得到加密算法 cipherMethod <- fmap fromJust $ withOpenSSL $ getCipherByName method -- 生成上下问 ctx <- cipherInitBS cipherMethod key cipher_iv Encrypt let encrypt "" = return "" encrypt buf = do empty <- isEmptyMVar cipherCtx if empty then do putMVar cipherCtx () ciphered <- withOpenSSL $ cipherUpdateBS ctx buf return $ cipher_iv <> ciphered else withOpenSSL $ cipherUpdateBS ctx buf decrypt "" = return "" decrypt buf = do empty <- isEmptyMVar decipherCtx if empty then do -- 需要在buf中先拿到IV才能初始化解谜的上下文 let decipher_iv = S.take m1 buf dctx <- cipherInitBS cipherMethod key decipher_iv Decrypt putMVar decipherCtx dctx if S.null (S.drop m1 buf) then return "" else withOpenSSL $ cipherUpdateBS dctx (S.drop m1 buf) else do dctx <- readMVar decipherCtx withOpenSSL $ cipherUpdateBS dctx buf return (encrypt, decrypt)
DavidAlphaFox/CacheDNS
src/CacheDNS/Crypto/Common.hs
bsd-3-clause
3,675
0
20
1,076
1,067
584
483
82
6
{-# LANGUAGE CPP #-} module Data.TrieMap.Representation.Instances.Vectors.Tests where import Data.TrieMap.Representation.Class import Data.TrieMap.Representation.Instances.Vectors () import Data.TrieMap.Representation.Instances.Prim () import Data.TrieMap.Representation.Tests import Data.TrieMap.Arbitrary () import Data.Vector (Vector) import Data.Int import Data.Word import Test.QuickCheck #define TEST(ty) printTestCase "Vector ty" (testRepr (toRep :: ToRep (Vector ty))) tests :: Property tests = conjoin [TEST(Int), TEST(Int8), TEST(Int16), TEST(Int32), TEST(Int64), TEST(Word), TEST(Word8), TEST(Word16), TEST(Word32), TEST(Word64), TEST(Char), TEST(Bool)]
lowasser/TrieMap
Data/TrieMap/Representation/Instances/Vectors/Tests.hs
bsd-3-clause
715
0
8
108
203
124
79
25
1
module Game.World.Biome( Biome(..) ) where import Control.DeepSeq import Control.Monad (mzero) import Data.Range import Data.Text import Data.Yaml import GHC.Generics (Generic) -- | Describing type of climatic class data Biome = Biome { -- | Display name of biome biomeName :: !Text -- | Annual precipitation (mm) from minimal to maximum (62.5 ... 16000) , biomePrecip :: !(Range Double) -- | Potential evapotranspiration ratio (0.125 ... 32) , biomeEvapor :: !(Range Double) } deriving (Generic, Show) instance NFData Biome instance ToJSON Biome where toJSON (Biome {..}) = object [ "name" .= biomeName , "precip" .= biomePrecip , "evapor" .= biomeEvapor ] instance FromJSON Biome where parseJSON (Object v) = Biome <$> v .: "name" <*> v .: "precip" <*> v .: "evapor" parseJSON _ = mzero
Teaspot-Studio/gore-and-ash-game
src/server/Game/World/Biome.hs
bsd-3-clause
850
0
11
185
223
124
99
-1
-1
{-# LANGUAGE UndecidableInstances #-} module Reflex.Monad.Supply ( SupplyT , Supply , runSupplyT , evalSupplyT , runSupply , evalSupply , runSplit , getFresh , getSplit ) where import Reflex import Reflex.Monad.Class import Control.Monad import Control.Monad.Identity import Control.Monad.State.Strict import Control.Monad.Writer.Class import Control.Monad.Reader.Class import Data.Traversable import Data.Map.Strict (Map) import Prelude class Splitable s i | s -> i where freshId :: s -> (i, s) splitSupply :: s -> (s, s) instance Enum a => Splitable [a] [a] where freshId [] = ([], [toEnum 0]) freshId (x:xs) = (x:xs, succ x:xs) splitSupply xs = (toEnum 0:xs, xs') where xs' = snd (freshId xs) newtype SupplyT s m a = SupplyT (StateT s m a) deriving (Functor, Applicative, Monad, MonadTrans, MonadFix) deriving instance MonadReader st m => MonadReader st (SupplyT s m) deriving instance MonadWriter w m => MonadWriter w (SupplyT s m) deriving instance MonadSample t m => MonadSample t (SupplyT s m) deriving instance MonadHold t m => MonadHold t (SupplyT s m) type Supply s a = SupplyT s Identity a instance MonadState st m => MonadState st (SupplyT s m) where get = lift get put = lift . put getFresh :: (Monad m, Splitable s i) => SupplyT s m i getFresh = SupplyT $ state freshId getSplit :: (Monad m, Splitable s i) => SupplyT s m s getSplit = SupplyT $ state splitSupply runSplit :: (Monad m, Splitable s i) => SupplyT s m a -> Supply s (m a) runSplit m = evalSupplyT m <$> getSplit runSupplyT :: Monad m => SupplyT s m a -> s -> m (a, s) runSupplyT (SupplyT m) = runStateT m evalSupplyT :: Monad m => SupplyT s m a -> s -> m a evalSupplyT (SupplyT m) = evalStateT m runSupply :: Supply s a -> s -> (a, s) runSupply m = runIdentity . runSupplyT m evalSupply :: Supply s a -> s -> a evalSupply m = runIdentity . evalSupplyT m -- | Helpers for switchMapM implementation runSupplyMap :: (Ord k, Monad m, Splitable s i) => Map k (SupplyT s m a) -> s -> (Map k (m a), s) runSupplyMap m = runSupply (traverse runSplit m) runSupplyMap' :: (Ord k, Monad m, Splitable s i) => Map k (Maybe (SupplyT s m a)) -> s -> (Map k (Maybe (m a)), s) runSupplyMap' m = runSupply (traverse (traverse runSplit) m) instance (MonadSwitch t m, Splitable s i) => MonadSwitch t (SupplyT s m) where switchM (Updated initial e) = do s <- getSplit rec (a, us) <- lift (split <$> switchM (Updated (runSupplyT initial s) $ attachWith (flip runSupplyT) r e)) r <- hold' us return a switchMapM (UpdatedMap initial e) = do (initial', s) <- runSupplyMap initial <$> getSplit rec let (um, us) = split $ attachWith (flip runSupplyMap') r e a <- lift (switchMapM (UpdatedMap initial' um)) r <- hold s us return a
Saulzar/reflex-host
src/Reflex/Monad/Supply.hs
bsd-3-clause
2,924
0
19
726
1,227
632
595
-1
-1
module Expr ( Value(..), Expr(..), UnOp(..), BinOp(..), Statement(..) , ($=), (.<), (.>), (.*), (.+), (.-), (.|), (.&), (.=), not_, neg , priority ) where import Text.PrettyPrint data Value = I Integer | B Bool deriving Eq data BinOp = Plus | Mul | Minus | And | Or | Less | Greater | Equals deriving Eq data UnOp = Neg | Not deriving Eq data Expr = Const Value | Var String | BinOp BinOp Expr Expr | UnOp UnOp Expr deriving Eq data Statement = Compound [Statement] | While Expr Statement | Assign String Expr | If Expr Statement (Maybe Statement) deriving Eq infixr 0 $= ($=) = Assign infix 5 .<, .>, .= (.<) = BinOp Less (.>) = BinOp Greater (.=) = BinOp Equals infixl 7 .* (.*) = BinOp Mul infixl 6 .+, .- (.+) = BinOp Plus (.-) = BinOp Minus infixl 4 .|, .& (.|) = BinOp Or (.&) = BinOp And infix 1 `else_` else_ :: (Maybe Statement -> Statement) -> Statement -> Statement else_ f e = f (Just e) not_ :: Expr -> Expr not_ = UnOp Not neg :: Expr -> Expr neg = UnOp Neg instance Show Value where show (I v) = show v show (B True) = "true" show (B False) = "false" instance Show BinOp where show Plus = " + " show Mul = " * " show Minus = " - " show And = " && " show Or = " || " show Less = " < " show Greater = " > " show Equals = " == " instance Show UnOp where show Neg = "-" show Not = "!" priority And = 4 priority Or = 4 priority Less = 5 priority Greater = 5 priority Equals = 5 priority Plus = 6 priority Minus = 6 priority Mul = 7 instance Show Expr where showsPrec _ (Const v) = shows v showsPrec _ (Var x) = showString x showsPrec p (BinOp op e1 e2) = showParen (p > priority op) $ showsPrec (priority op) e1 . shows op . showsPrec (priority op + 1) e2 showsPrec p (UnOp op e) = shows op . showsPrec 10 e instance Show Statement where show = render . pretty where if_then c t = text "if" <+> parens (text (show c)) <+> pretty t pretty (If c t Nothing) = if_then c t pretty (If c t (Just e)) = if_then c t <+> text "else" <+> pretty e pretty (While c b) = text "while" <+> parens (text (show c)) $$ pretty b pretty (Assign v e) = text v <+> equals <+> text (show e) <> semi pretty (Compound ss) = vcat [lbrace, nest 4 $ vcat (map pretty ss), rbrace]
SergeyKrivohatskiy/fp_haskell
hw11/Interpreter/Expr.hs
mit
2,373
0
14
673
1,061
574
487
79
1
----------------------------------------------------------------------------------------- {-| Module : Draw Copyright : (c) Daan Leijen 2003 License : wxWindows Maintainer : [email protected] Stability : provisional Portability : portable Drawing. -} ----------------------------------------------------------------------------------------- module Graphics.UI.WXCore.Draw ( -- * DC drawLines, drawPolygon, getTextExtent, getFullTextExtent, dcClearRect -- ** Creation , withPaintDC, withClientDC, dcDraw , withSVGFileDC, withSVGFileDCWithSize, withSVGFileDCWithSizeAndResolution -- ** Draw state , DrawState, dcEncapsulate, dcGetDrawState, dcSetDrawState, drawStateDelete -- ** Double buffering , dcBuffer, dcBufferWithRef, dcBufferWithRefEx , dcBufferWithRefExGcdc -- * Scrolled windows , windowGetViewStart, windowGetViewRect, windowCalcUnscrolledPosition -- * Font , FontStyle(..), FontFamily(..), FontShape(..), FontWeight(..) , fontDefault, fontSwiss, fontSmall, fontItalic, fontFixed , withFontStyle, dcWithFontStyle , dcSetFontStyle, dcGetFontStyle , fontCreateFromStyle, fontGetFontStyle -- * Brush , BrushStyle(..), BrushKind(..) , HatchStyle(..) , brushDefault, brushSolid, brushTransparent , dcSetBrushStyle, dcGetBrushStyle , withBrushStyle, dcWithBrushStyle, dcWithBrush , brushCreateFromStyle, brushGetBrushStyle -- * Pen , PenStyle(..), PenKind(..), CapStyle(..), JoinStyle(..), DashStyle(..) , penDefault, penColored, penTransparent , dcSetPenStyle, dcGetPenStyle , withPenStyle, dcWithPenStyle, dcWithPen , penCreateFromStyle, penGetPenStyle ) where import Graphics.UI.WXCore.WxcTypes import Graphics.UI.WXCore.WxcDefs import Graphics.UI.WXCore.WxcClasses import Graphics.UI.WXCore.WxcClassInfo import Graphics.UI.WXCore.Types import Graphics.UI.WXCore.Defines import Foreign.Storable import Foreign.Marshal.Alloc {-------------------------------------------------------------------------------- DC creation --------------------------------------------------------------------------------} -- | Safely perform a drawing operation on a DC. dcDraw :: DC a -> IO b -> IO b dcDraw dc io = bracket_ (do dcSetPenStyle dc penDefault dcSetBrushStyle dc brushDefault) (do dcSetPen dc nullPen dcSetBrush dc nullBrush) io -- | Use a 'PaintDC'. -- Draw on a window within an 'on paint' event. withPaintDC :: Window a -> (PaintDC () -> IO b) -> IO b withPaintDC window draw = bracket (paintDCCreate window) (paintDCDelete) (\dc -> dcDraw dc (draw dc)) -- | Use a 'ClientDC'. -- Draw on a window from outside an 'on paint' event. withClientDC :: Window a -> (ClientDC () -> IO b) -> IO b withClientDC window draw = bracket (clientDCCreate window) (clientDCDelete) (\dc -> dcDraw dc (draw dc)) -- | Use a 'SVGFileDC'. withSVGFileDC :: FilePath -> (SVGFileDC () -> IO b) -> IO b withSVGFileDC fname draw = bracket (svgFileDCCreate fname) (svgFileDCDelete) (\dc -> dcDraw dc (draw dc)) withSVGFileDCWithSize :: FilePath -> Size -> (SVGFileDC () -> IO b) -> IO b withSVGFileDCWithSize fname size draw = bracket (svgFileDCCreateWithSize fname size) (svgFileDCDelete) (\dc -> dcDraw dc (draw dc)) withSVGFileDCWithSizeAndResolution :: FilePath -> Size -> Float -> (SVGFileDC () -> IO b) -> IO b withSVGFileDCWithSizeAndResolution fname size dpi draw = bracket (svgFileDCCreateWithSizeAndResolution fname size dpi) (svgFileDCDelete) (\dc -> dcDraw dc (draw dc)) -- | Clear a specific rectangle with the current background brush. -- This is preferred to 'dcClear' for scrolled windows as 'dcClear' sometimes -- only clears the original view area, instead of the currently visible scrolled area. -- Unfortunately, the background brush is not set correctly on wxMAC 2.4, and -- this will always clear to a white color on mac systems. dcClearRect :: DC a -> Rect -> IO () dcClearRect dc r = bracket (dcGetBackground dc) (brushDelete) (\brush -> dcWithBrush dc brush $ dcWithPenStyle dc penTransparent $ dcDrawRectangle dc r) {- -- | Fill a rectangle with a certain color. dcFillRect :: DC a -> Rect -> Color -> IO () dcFillRect dc r color = dcWithBrushStyle dc (brushSolid color) $ dcWithPenStyle dc penTransparent $ dcDrawRectangle dc r -} {-------------------------------------------------------------------------------- Windows --------------------------------------------------------------------------------} -- | Get logical view rectangle, adjusted for scrolling. windowGetViewRect :: Window a -> IO Rect windowGetViewRect window = do size <- windowGetClientSize window org <- windowGetViewStart window return (rect org size) -- | Get logical view start, adjusted for scrolling. windowGetViewStart :: Window a -> IO Point windowGetViewStart window = do isScrolled <- objectIsScrolledWindow window -- adjust coordinates for a scrolled window if (isScrolled) then do let scrolledWindow = objectCast window (Point sx sy) <- scrolledWindowGetViewStart scrolledWindow (Point w h) <- scrolledWindowGetScrollPixelsPerUnit scrolledWindow return (Point (w*sx) (h*sy)) else return pointZero -- | Get logical coordinates adjusted for scrolling. windowCalcUnscrolledPosition :: Window a -> Point -> IO Point windowCalcUnscrolledPosition window p = do isScrolled <- objectIsScrolledWindow window -- adjust coordinates for a scrolled window if (isScrolled) then do let scrolledWindow = objectCast window scrolledWindowCalcUnscrolledPosition scrolledWindow p else return p {-------------------------------------------------------------------------------- Font --------------------------------------------------------------------------------} -- | Font descriptor. The font is normally specified thru the 'FontFamily', giving -- some degree of portability. The '_fontFace' can be used to specify the exact (platform -- dependent) font. -- -- Note that the original wxWidgets @FontStyle@ is renamed to @FontShape@. data FontStyle = FontStyle{ _fontSize :: !Int , _fontFamily :: !FontFamily , _fontShape :: !FontShape , _fontWeight :: !FontWeight , _fontUnderline :: !Bool , _fontFace :: !String -- ^ normally @\"\"@ , _fontEncoding :: !Int -- ^ normally @wxFONTENCODING_DEFAULT@ } deriving (Eq,Show) -- | Default 10pt font. fontDefault :: FontStyle fontDefault = FontStyle 10 FontDefault ShapeNormal WeightNormal False "" wxFONTENCODING_DEFAULT -- | Default 10pt sans-serif font. fontSwiss :: FontStyle fontSwiss = fontDefault{ _fontFamily = FontSwiss } -- | Default 8pt font. fontSmall :: FontStyle fontSmall = fontDefault{ _fontSize = 8 } -- | Default 10pt italic. fontItalic :: FontStyle fontItalic = fontDefault{ _fontShape = ShapeItalic } -- | Monospaced font, 10pt. fontFixed :: FontStyle fontFixed = fontDefault{ _fontFamily = FontModern } -- | Standard font families. data FontFamily = FontDefault -- ^ A system default font. | FontDecorative -- ^ Decorative font. | FontRoman -- ^ Formal serif font. | FontScript -- ^ Hand writing font. | FontSwiss -- ^ Sans-serif font. | FontModern -- ^ Fixed pitch font. | FontTeletype -- ^ A teletype (i.e. monospaced) font deriving (Eq,Show) -- | The font style. data FontShape = ShapeNormal | ShapeItalic | ShapeSlant deriving (Eq,Show) -- | The font weight. data FontWeight = WeightNormal | WeightBold | WeightLight deriving (Eq,Show) -- | Use a font that is automatically deleted at the end of the computation. withFontStyle :: FontStyle -> (Font () -> IO a) -> IO a withFontStyle fontStyle f = do (font,delete) <- fontCreateFromStyle fontStyle finally (f font) delete -- | Set a font that is automatically deleted at the end of the computation. dcWithFontStyle :: DC a -> FontStyle -> IO b -> IO b dcWithFontStyle dc fontStyle io = withFontStyle fontStyle $ \font -> bracket (do oldFont <- dcGetFont dc dcSetFont dc font return oldFont) (\oldFont -> do dcSetFont dc oldFont -- restore previous font fontDelete oldFont) (const io) -- | Set the font info of a DC. dcSetFontStyle :: DC a -> FontStyle -> IO () dcSetFontStyle dc info = do (font,del) <- fontCreateFromStyle info finalize del $ do dcSetFont dc font -- | Get the current font info. dcGetFontStyle :: DC a -> IO FontStyle dcGetFontStyle dc = do font <- dcGetFont dc finalize (fontDelete font) $ do fontGetFontStyle font -- | Create a 'Font' from 'FontStyle'. Returns both the font and a deletion procedure. fontCreateFromStyle :: FontStyle -> IO (Font (),IO ()) fontCreateFromStyle (FontStyle size family style weight underline face encoding) = do font <- fontCreate size cfamily cstyle cweight underline face encoding return (font,when (font /= objectNull) (fontDelete font)) where cfamily = case family of FontDefault -> wxFONTFAMILY_DEFAULT FontDecorative -> wxFONTFAMILY_DECORATIVE FontRoman -> wxFONTFAMILY_ROMAN FontScript -> wxFONTFAMILY_SCRIPT FontSwiss -> wxFONTFAMILY_SWISS FontModern -> wxFONTFAMILY_MODERN FontTeletype -> wxFONTFAMILY_TELETYPE cstyle = case style of ShapeNormal -> wxFONTSTYLE_NORMAL ShapeItalic -> wxFONTSTYLE_ITALIC ShapeSlant -> wxFONTSTYLE_SLANT cweight = case weight of WeightNormal -> wxFONTWEIGHT_NORMAL WeightBold -> wxFONTWEIGHT_BOLD WeightLight -> wxFONTWEIGHT_LIGHT -- | Get the 'FontStyle' from a 'Font' object. fontGetFontStyle :: Font () -> IO FontStyle fontGetFontStyle font = if (objectIsNull font) then return fontDefault else do ok <- fontIsOk font if not ok then return fontDefault else do size <- fontGetPointSize font cfamily <- fontGetFamily font cstyle <- fontGetStyle font cweight <- fontGetWeight font cunderl <- fontGetUnderlined font face <- fontGetFaceName font enc <- fontGetEncoding font return (FontStyle size (toFamily cfamily) (toStyle cstyle) (toWeight cweight) (cunderl /= 0) face enc) where toFamily f | f == wxFONTFAMILY_DECORATIVE = FontDecorative | f == wxFONTFAMILY_ROMAN = FontRoman | f == wxFONTFAMILY_SCRIPT = FontScript | f == wxFONTFAMILY_SWISS = FontSwiss | f == wxFONTFAMILY_MODERN = FontModern | f == wxFONTFAMILY_TELETYPE = FontTeletype | otherwise = FontDefault toStyle s | s == wxFONTSTYLE_ITALIC = ShapeItalic | s == wxFONTSTYLE_SLANT = ShapeSlant | otherwise = ShapeNormal toWeight w | w == wxFONTWEIGHT_BOLD = WeightBold | w == wxFONTWEIGHT_LIGHT = WeightLight | otherwise = WeightNormal {-------------------------------------------------------------------------------- Pen --------------------------------------------------------------------------------} -- | Pen style. data PenStyle = PenStyle { _penKind :: !PenKind , _penColor :: !Color , _penWidth :: !Int , _penCap :: !CapStyle , _penJoin :: !JoinStyle } deriving (Eq,Show) -- | Pen kinds. data PenKind = PenTransparent -- ^ No edge. | PenSolid | PenDash { _penDash :: !DashStyle } | PenHatch { _penHatch :: !HatchStyle } | PenStipple{ _penBitmap :: !(Bitmap ())} -- ^ @_penColor@ is ignored deriving (Eq,Show) -- | Default pen (@PenStyle PenSolid black 1 CapRound JoinRound@) penDefault :: PenStyle penDefault = PenStyle PenSolid black 1 CapRound JoinRound -- | A solid pen with a certain color and width. penColored :: Color -> Int -> PenStyle penColored color width = penDefault{ _penColor = color, _penWidth = width } -- | A transparent pen. penTransparent :: PenStyle penTransparent = penDefault{ _penKind = PenTransparent } -- | Dash style data DashStyle = DashDot | DashLong | DashShort | DashDotShort -- DashUser [Int] deriving (Eq,Show) -- | Cap style data CapStyle = CapRound -- ^ End points are rounded | CapProjecting | CapButt deriving (Eq,Show) -- | Join style. data JoinStyle = JoinRound -- ^ Corners are rounded | JoinBevel -- ^ Corners are bevelled | JoinMiter -- ^ Corners are blocked deriving (Eq,Show) -- | Hatch style. data HatchStyle = HatchBDiagonal -- ^ Backward diagonal | HatchCrossDiag -- ^ Crossed diagonal | HatchFDiagonal -- ^ Forward diagonal | HatchCross -- ^ Crossed orthogonal | HatchHorizontal -- ^ Horizontal | HatchVertical -- ^ Vertical deriving (Eq,Show) -- | Brush style. data BrushStyle = BrushStyle { _brushKind :: !BrushKind, _brushColor :: !Color } deriving (Eq,Show) -- | Brush kind. data BrushKind = BrushTransparent -- ^ No filling | BrushSolid -- ^ Solid color | BrushHatch { _brushHatch :: !HatchStyle } -- ^ Hatch pattern | BrushStipple{ _brushBitmap :: !(Bitmap ())} -- ^ Bitmap pattern (on win95 only 8x8 bitmaps are supported) deriving (Eq,Show) -- | Set a pen that is automatically deleted at the end of the computation. dcWithPenStyle :: DC a -> PenStyle -> IO b -> IO b dcWithPenStyle dc penStyle io = withPenStyle penStyle $ \pen -> dcWithPen dc pen io -- | Set a pen that is used during a certain computation. dcWithPen :: DC a -> Pen p -> IO b -> IO b dcWithPen dc pen io = bracket (do oldPen <- dcGetPen dc dcSetPen dc pen return oldPen) (\oldPen -> do dcSetPen dc oldPen -- restore previous pen penDelete oldPen) (const io) -- | Set the current pen style. The text color is also adapted. dcSetPenStyle :: DC a -> PenStyle -> IO () dcSetPenStyle dc penStyle = withPenStyle penStyle (dcSetPen dc) -- | Get the current pen style. dcGetPenStyle :: DC a -> IO PenStyle dcGetPenStyle dc = do pen <- dcGetPen dc finalize (penDelete pen) $ do penGetPenStyle pen -- | Use a pen that is automatically deleted at the end of the computation. withPenStyle :: PenStyle -> (Pen () -> IO a) -> IO a withPenStyle penStyle f = do (pen,delete) <- penCreateFromStyle penStyle finally (f pen) delete -- | Create a new pen from a 'PenStyle'. Returns both the pen and its deletion procedure. penCreateFromStyle :: PenStyle -> IO (Pen (),IO ()) penCreateFromStyle penStyle = case penStyle of PenStyle PenTransparent _color _width _cap _join -> do pen <- penCreateFromStock 5 {- transparent -} return (pen,return ()) PenStyle (PenDash DashShort) color 1 CapRound JoinRound | color == black -> do pen <- penCreateFromStock 6 {- black dashed -} return (pen,return ()) PenStyle PenSolid color 1 CapRound JoinRound -> case lookup color stockPens of Just idx -> do pen <- penCreateFromStock idx return (pen,return ()) Nothing -> colorPen color 1 wxPENSTYLE_SOLID PenStyle PenSolid color width _cap _join -> colorPen color width wxPENSTYLE_SOLID PenStyle (PenDash dash) color width _cap _join -> case dash of DashDot -> colorPen color width wxPENSTYLE_DOT DashLong -> colorPen color width wxPENSTYLE_LONG_DASH DashShort -> colorPen color width wxPENSTYLE_SHORT_DASH DashDotShort -> colorPen color width wxPENSTYLE_DOT_DASH PenStyle (PenStipple bitmap) _color width _cap _join -> do pen <- penCreateFromBitmap bitmap width setCap pen setJoin pen return (pen,penDelete pen) PenStyle (PenHatch hatch) color width _cap _join -> case hatch of HatchBDiagonal -> colorPen color width wxPENSTYLE_BDIAGONAL_HATCH HatchCrossDiag -> colorPen color width wxPENSTYLE_CROSSDIAG_HATCH HatchFDiagonal -> colorPen color width wxPENSTYLE_FDIAGONAL_HATCH HatchCross -> colorPen color width wxPENSTYLE_CROSS_HATCH HatchHorizontal -> colorPen color width wxPENSTYLE_HORIZONTAL_HATCH HatchVertical -> colorPen color width wxPENSTYLE_VERTICAL_HATCH where colorPen color width style = do pen <- penCreateFromColour color width style setCap pen setJoin pen return (pen,penDelete pen) setCap pen = case _penCap penStyle of CapRound -> return () CapProjecting -> penSetCap pen wxCAP_PROJECTING CapButt -> penSetCap pen wxCAP_BUTT setJoin pen = case _penJoin penStyle of JoinRound -> return () JoinBevel -> penSetJoin pen wxJOIN_BEVEL JoinMiter -> penSetJoin pen wxJOIN_MITER stockPens = [(red,0),(cyan,1),(green,2) ,(black,3),(white,4) ,(grey,7),(lightgrey,9) ,(mediumgrey,8) ] -- | Create a 'PenStyle' from a 'Pen'. penGetPenStyle :: Pen a -> IO PenStyle penGetPenStyle pen = if (objectIsNull pen) then return penDefault else do ok <- penIsOk pen if not ok then return penDefault else do stl <- penGetStyle pen toPenStyle stl where toPenStyle stl | stl == wxPENSTYLE_TRANSPARENT = return penTransparent | stl == wxPENSTYLE_SOLID = toPenStyleWithKind PenSolid | stl == wxPENSTYLE_DOT = toPenStyleWithKind (PenDash DashDot) | stl == wxPENSTYLE_LONG_DASH = toPenStyleWithKind (PenDash DashLong) | stl == wxPENSTYLE_SHORT_DASH = toPenStyleWithKind (PenDash DashShort) | stl == wxPENSTYLE_DOT_DASH = toPenStyleWithKind (PenDash DashDotShort) | stl == wxPENSTYLE_STIPPLE = do stipple <- penGetStipple pen toPenStyleWithKind (PenStipple stipple) | stl == wxPENSTYLE_BDIAGONAL_HATCH = toPenStyleWithKind (PenHatch HatchBDiagonal) | stl == wxPENSTYLE_CROSSDIAG_HATCH = toPenStyleWithKind (PenHatch HatchCrossDiag) | stl == wxPENSTYLE_FDIAGONAL_HATCH = toPenStyleWithKind (PenHatch HatchFDiagonal) | stl == wxPENSTYLE_CROSS_HATCH = toPenStyleWithKind (PenHatch HatchCross) | stl == wxPENSTYLE_HORIZONTAL_HATCH = toPenStyleWithKind (PenHatch HatchHorizontal) | stl == wxPENSTYLE_VERTICAL_HATCH = toPenStyleWithKind (PenHatch HatchVertical) | otherwise = toPenStyleWithKind PenSolid toPenStyleWithKind kind = do width <- penGetWidth pen color <- penGetColour pen cap <- penGetCap pen join <- penGetJoin pen return (PenStyle kind color width (toCap cap) (toJoin join)) toCap cap | cap == wxCAP_PROJECTING = CapProjecting | cap == wxCAP_BUTT = CapButt | otherwise = CapRound toJoin join | join == wxJOIN_MITER = JoinMiter | join == wxJOIN_BEVEL = JoinBevel | otherwise = JoinRound {-------------------------------------------------------------------------------- Brush --------------------------------------------------------------------------------} -- | Default brush (transparent, black). brushDefault :: BrushStyle brushDefault = BrushStyle BrushTransparent black -- | A solid brush of a specific color. brushSolid :: Color -> BrushStyle brushSolid color = BrushStyle BrushSolid color -- | A transparent brush. brushTransparent :: BrushStyle brushTransparent = BrushStyle BrushTransparent white -- | Use a brush that is automatically deleted at the end of the computation. dcWithBrushStyle :: DC a -> BrushStyle -> IO b -> IO b dcWithBrushStyle dc brushStyle io = withBrushStyle brushStyle $ \brush -> dcWithBrush dc brush io dcWithBrush :: DC b -> Brush a -> IO c -> IO c dcWithBrush dc brush io = bracket (do oldBrush <- dcGetBrush dc dcSetBrush dc brush return oldBrush) (\oldBrush -> do dcSetBrush dc oldBrush -- restore previous brush brushDelete oldBrush) (const io) -- | Set the brush style (and text background color) of a device context. dcSetBrushStyle :: DC a -> BrushStyle -> IO () dcSetBrushStyle dc brushStyle = withBrushStyle brushStyle (dcSetBrush dc) -- | Get the current brush of a device context. dcGetBrushStyle :: DC a -> IO BrushStyle dcGetBrushStyle dc = do brush <- dcGetBrush dc finalize (brushDelete brush) $ do brushGetBrushStyle brush -- | Use a brush that is automatically deleted at the end of the computation. withBrushStyle :: BrushStyle -> (Brush () -> IO a) -> IO a withBrushStyle brushStyle f = do (brush,delete) <- brushCreateFromStyle brushStyle finalize delete $ do f brush -- | Create a new brush from a 'BrushStyle'. Returns both the brush and its deletion procedure. brushCreateFromStyle :: BrushStyle -> IO (Brush (), IO ()) brushCreateFromStyle brushStyle = case brushStyle of BrushStyle BrushTransparent color -> do brush <- if (wxToolkit == WxMac) then brushCreateFromColour color wxBRUSHSTYLE_TRANSPARENT else brushCreateFromStock 7 {- transparent brush -} return (brush,return ()) BrushStyle BrushSolid color -> case lookup color stockBrushes of Just idx -> do brush <- brushCreateFromStock idx return (brush,return ()) Nothing -> colorBrush color wxBRUSHSTYLE_SOLID BrushStyle (BrushHatch HatchBDiagonal) color -> colorBrush color wxBRUSHSTYLE_BDIAGONAL_HATCH BrushStyle (BrushHatch HatchCrossDiag) color -> colorBrush color wxBRUSHSTYLE_CROSSDIAG_HATCH BrushStyle (BrushHatch HatchFDiagonal) color -> colorBrush color wxBRUSHSTYLE_FDIAGONAL_HATCH BrushStyle (BrushHatch HatchCross) color -> colorBrush color wxBRUSHSTYLE_CROSS_HATCH BrushStyle (BrushHatch HatchHorizontal) color -> colorBrush color wxBRUSHSTYLE_HORIZONTAL_HATCH BrushStyle (BrushHatch HatchVertical) color -> colorBrush color wxBRUSHSTYLE_VERTICAL_HATCH BrushStyle (BrushStipple bitmap) _color -> do brush <- brushCreateFromBitmap bitmap return (brush, brushDelete brush) where colorBrush color style = do brush <- brushCreateFromColour color style return (brush, brushDelete brush ) stockBrushes = [(blue,0),(green,1),(white,2) ,(black,3),(grey,4),(lightgrey,6) ,(cyan,8),(red,9) ,(mediumgrey,5) ] -- | Get the 'BrushStyle' of 'Brush'. brushGetBrushStyle :: Brush a -> IO BrushStyle brushGetBrushStyle brush = if (objectIsNull brush) then return brushDefault else do ok <- brushIsOk brush if not ok then return brushDefault else do stl <- brushGetStyle brush kind <- toBrushKind stl color <- brushGetColour brush return (BrushStyle kind color) where toBrushKind stl | stl == wxBRUSHSTYLE_TRANSPARENT = return BrushTransparent | stl == wxBRUSHSTYLE_SOLID = return BrushSolid | stl == wxBRUSHSTYLE_STIPPLE = do stipple <- brushGetStipple brush return (BrushStipple stipple) | stl == wxBRUSHSTYLE_BDIAGONAL_HATCH = return (BrushHatch HatchBDiagonal) | stl == wxBRUSHSTYLE_CROSSDIAG_HATCH = return (BrushHatch HatchCrossDiag) | stl == wxBRUSHSTYLE_FDIAGONAL_HATCH = return (BrushHatch HatchFDiagonal) | stl == wxBRUSHSTYLE_CROSS_HATCH = return (BrushHatch HatchCross) | stl == wxBRUSHSTYLE_HORIZONTAL_HATCH = return (BrushHatch HatchHorizontal) | stl == wxBRUSHSTYLE_VERTICAL_HATCH = return (BrushHatch HatchVertical) | otherwise = return BrushTransparent {-------------------------------------------------------------------------------- DC drawing state --------------------------------------------------------------------------------} -- | The drawing state (pen,brush,font,text color,text background color) of a device context. data DrawState = DrawState (Pen ()) (Brush ()) (Font ()) Color Color -- | Run a computation after which the original drawing state of the 'DC' is restored. dcEncapsulate :: DC a -> IO b -> IO b dcEncapsulate dc io = bracket (dcGetDrawState dc) (\drawState -> do dcSetDrawState dc drawState drawStateDelete drawState) (const io) -- | Get the drawing state. (Should be deleted with 'drawStateDelete'). dcGetDrawState :: DC a -> IO DrawState dcGetDrawState dc = do pen <- dcGetPen dc brush <- dcGetBrush dc font <- dcGetFont dc textc <- dcGetTextForeground dc backc <- dcGetTextBackground dc return (DrawState pen brush font textc backc) -- | Set the drawing state. dcSetDrawState :: DC a -> DrawState -> IO () dcSetDrawState dc (DrawState pen brush font textc backc) = do dcSetPen dc pen dcSetBrush dc brush dcSetFont dc font dcSetTextBackground dc backc dcSetTextForeground dc textc -- | Release the resources associated with a drawing state. drawStateDelete :: DrawState -> IO () drawStateDelete (DrawState pen brush font _ _) = do penDelete pen brushDelete brush fontDelete font {-------------------------------------------------------------------------------- DC utils --------------------------------------------------------------------------------} -- | Draw connected lines. drawLines :: DC a -> [Point] -> IO () drawLines _dc [] = return () drawLines dc ps = withArray xs $ \pxs -> withArray ys $ \pys -> dcDrawLines dc n pxs pys (pt 0 0) where n = length ps xs = map pointX ps ys = map pointY ps -- | Draw a polygon. The polygon is filled with the odd-even rule. drawPolygon :: DC a -> [Point] -> IO () drawPolygon _dc [] = return () drawPolygon dc ps = withArray xs $ \pxs -> withArray ys $ \pys -> dcDrawPolygon dc n pxs pys (pt 0 0) wxODDEVEN_RULE where n = length ps xs = map pointX ps ys = map pointY ps -- | Gets the dimensions of the string using the currently selected font. getTextExtent :: DC a -> String -> IO Size getTextExtent dc txt = do (sz',_,_) <- getFullTextExtent dc txt return sz' -- | Gets the dimensions of the string using the currently selected font. -- Takes text string to measure, and returns the size, /descent/ and /external leading/. -- Descent is the dimension from the baseline of the font to the bottom of the descender -- , and external leading is any extra vertical space added to the font by the font designer (is usually zero). getFullTextExtent :: DC a -> String -> IO (Size,Int,Int) getFullTextExtent dc txt = alloca $ \px -> alloca $ \py -> alloca $ \pd -> alloca $ \pe -> do dcGetTextExtent dc txt px py pd pe objectNull x <- peek px y <- peek py d <- peek pd e <- peek pe return (sz (fromCInt x) (fromCInt y), fromCInt d, fromCInt e) {-------------------------------------------------------------------------------- Double buffering --------------------------------------------------------------------------------} -- | Use double buffering to draw to a 'DC' -- reduces flicker. Note that -- the 'windowOnPaint' handler can already take care of buffering automatically. -- The rectangle argument is normally the view rectangle ('windowGetViewRect'). -- Uses a 'MemoryDC' to draw into memory first and than blit the result to -- the device context. The memory area allocated is the minimal size necessary -- to accomodate the rectangle, but is re-allocated on each invokation. dcBuffer :: WindowDC a -> Rect -> (DC () -> IO ()) -> IO () dcBuffer dc r draw = dcBufferWithRef dc Nothing r draw -- | Optimized double buffering. Takes a possible reference to a bitmap. If it is -- 'Nothing', a new bitmap is allocated everytime. Otherwise, the reference is used -- to re-use an allocated bitmap if possible. The 'Rect' argument specifies the -- the current logical view rectangle. The last argument is called to draw on the -- memory 'DC'. dcBufferWithRef :: WindowDC a -> Maybe (Var (Bitmap ())) -> Rect -> (DC () -> IO ()) -> IO () dcBufferWithRef dc mbVar viewArea draw = dcBufferWithRefEx dc (\dc' -> dcClearRect dc' viewArea) mbVar viewArea draw -- | Optimized double buffering. Takes a /clear/ routine as its first argument. -- Normally this is something like '\dc -> dcClearRect dc viewArea' but on certain platforms, like -- MacOS X, special handling is necessary. dcBufferWithRefEx :: WindowDC a -> (DC () -> IO ()) -> Maybe (Var (Bitmap ())) -> Rect -> (DC () -> IO ()) -> IO () dcBufferWithRefEx = dcBufferedAux simpleDraw simpleDraw where simpleDraw dc draw = draw $ downcastDC dc -- | Optimized double buffering with a GCDC. Takes a /clear/ routine as its first argument. -- Normally this is something like '\dc -> dcClearRect dc viewArea' but on certain platforms, like -- MacOS X, special handling is necessary. dcBufferWithRefExGcdc :: WindowDC a -> (DC () -> IO ()) -> Maybe (Var (Bitmap ())) -> Rect -> (GCDC () -> IO b) -> IO () dcBufferWithRefExGcdc = dcBufferedAux (withGC gcdcCreate) (withGC gcdcCreateFromMemory) where withGC create dc_ draw = do dc <- create dc_ _ <- draw dc gcdcDelete dc dcBufferedAux :: (WindowDC a -> f -> IO ()) -> (MemoryDC c -> f -> IO ()) -> WindowDC a -> (DC () -> IO ()) -> Maybe (Var (Bitmap ())) -> Rect -> f -> IO () dcBufferedAux _ _ _ _ _ view _ | rectSize view == sizeZero = return () dcBufferedAux withWinDC withMemoryDC dc clear mbVar view draw = bracket (initBitmap) (doneBitmap) (\bitmap -> if (bitmap==objectNull) then drawUnbuffered else bracket (do p <- memoryDCCreateCompatible dc; return (objectCast p)) (\memdc -> when (memdc/=objectNull) (memoryDCDelete memdc)) (\memdc -> if (memdc==objectNull) then drawUnbuffered else do memoryDCSelectObject memdc bitmap drawBuffered memdc memoryDCSelectObject memdc nullBitmap)) where initBitmap = case mbVar of Nothing -> bitmapCreateEmpty (rectSize view) (-1) Just v -> do bitmap <- varGet v size <- if (bitmap==objectNull) then return sizeZero else do bw <- bitmapGetWidth bitmap bh <- bitmapGetHeight bitmap return (Size bw bh) -- re-use the bitmap if possible if (sizeEncloses size (rectSize view) && bitmap /= objectNull) then return bitmap else do when (bitmap/=objectNull) (bitmapDelete bitmap) varSet v objectNull -- new size a bit larger to avoid multiple reallocs let (Size w h) = rectSize view neww = div (w*105) 100 newh = div (h*105) 100 if (w > 0 && h > 0) then do bm <- bitmapCreateEmpty (sz neww newh) (-1) varSet v bm return bm else return objectNull doneBitmap bitmap = case mbVar of Nothing -> when (bitmap/=objectNull) (bitmapDelete bitmap) Just _v -> return () drawUnbuffered = do clear (downcastDC dc) withWinDC dc draw drawBuffered memdc = do -- set the device origin for scrolled windows dcSetDeviceOrigin memdc (pointFromVec (vecNegate (vecFromPoint (rectTopLeft view)))) dcSetClippingRegion memdc view -- dcBlit memdc view dc (rectTopLeft view) wxCOPY False bracket (dcGetBackground dc) (\brush -> do dcSetBrush memdc nullBrush brushDelete brush) (\brush -> do -- set the background to the owner brush dcSetBackground memdc brush if (wxToolkit == WxMac) then withBrushStyle brushTransparent (dcSetBrush memdc) else dcSetBrush memdc brush clear (downcastDC memdc) -- and finally do the drawing! withMemoryDC memdc draw ) -- blit the memdc into the owner dc. _ <- dcBlit dc view memdc (rectTopLeft view) wxCOPY False return ()
jacekszymanski/wxHaskell
wxcore/src/haskell/Graphics/UI/WXCore/Draw.hs
lgpl-2.1
34,713
0
21
10,131
7,689
3,840
3,849
648
20
module Language.StreamIt.Core ( Exp (..) , Var (..) , CoreE (..) , Elt (..) , NumE , Const (..) , Void , Array (..) , true , false , constant , ref , not_ , (&&.) , (||.) , and_ , or_ , (==.) , (/==.) , (<.) , (<=.) , (>.) , (>=.) , (.++) , (.--) , (+=) , (-=) , (*=) , (/=.) , mod_ , cond , fcall , showConstType , gensym , genExpVar , showVarDecl , newStableName , isScalar , (!) ) where import Data.List import Data.Ratio import Data.Typeable import Data.Unique import System.Mem.StableName infixl 9 ! infixl 7 `mod_` infix 4 ==., /==., <., <=., >., >=. infix 4 .++, .--, +=, -=, *=, /=. infixl 3 &&. infixl 2 ||. infixr 0 <== -- | A mutable variable, aka an LValue in C. This includes both locations in arrays, -- as well as scalar variables. data Var a = Var { vname :: String, -- name of the variable val :: Elt a => a -- initial value } instance Show (Var a) where show (Var n _) = n class Eq a => Elt a where zero :: a const' :: a -> Const instance Elt Bool where zero = False const' = Bool instance Elt Int where zero = 0 const' = Int instance Elt Float where zero = 0 const' = Float class (Elt a, Num a, Ord a) => NumE a instance NumE Int instance NumE Float data Void instance Show Void where show _ = "Void" instance Eq Void where _ == _ = True instance Ord Void where _ <= _ = True instance Typeable Void where typeOf _ = mkTyConApp (mkTyCon3 "" "" "Void") [] instance Elt Void where zero = error "no zero element for Void" const' = Void -- | For describing StreamIt array types. data Array a = Array { bound :: Exp Int, -- array upper bound ele :: a -- array element type } deriving (Show, Eq) instance (Elt a) => Elt (Array a) where zero = Array (constant 0) zero const' (Array b e) = ArrayT b (const' e) -- | Generic variable declarations. class Monad a => CoreE a where var :: Elt b => b -> a (Var b) -- Float variable declarations. float :: a (Var Float) float' :: Float -> a (Var Float) -- Int variable declarations. int :: a (Var Int) int' :: Int -> a (Var Int) -- Bool variable declarations. bool :: a (Var Bool) bool' :: Bool -> a (Var Bool) -- Array declarations. array :: Elt b => a (Var b) -> Exp Int -> a (Var (Array b)) -- Assignments. (<==) :: Elt b => Var b -> Exp b -> a () -- Conditional statements. ifelse :: Exp Bool -> a (b) -> a (b) -> a () if_ :: Exp Bool -> a (b) -> a () -- Loops for_ :: (a (), Exp Bool, a ()) -> a (b) -> a () while_ :: Exp Bool -> a (b) -> a () -- Generate a new variable but do not add it to the AST gensym :: Elt b => b -> IO (Var b) gensym init = do n <- newUnique return $ Var ("var" ++ show (hashUnique n)) init -- Generate a new variable for a given expression Exp b genExpVar :: Elt b => Exp b -> IO (Var b) genExpVar e = case e of Ref a -> return a _ -> gensym zero -- Return a variable declaration given a Var b showVarDecl :: Elt b => (Var b) -> String showVarDecl v = showConstType (const' $ val v) ++ " " ++ vname v -- Helper function to generate new or find existing names by -- hashing the AST node pointer. newStableName :: a -> String -> IO String newStableName obj template = do n <- makeStableName obj return (template ++ show (hashStableName n)) -- | A logical, arithmetic, comparative, or conditional expression. data Exp a where Ref :: Elt a => Var a -> Exp a PopExp :: Elt a => Exp a -- INTERNAL, not typesafe to expose. PeekExp :: Elt a => Exp Int -> Exp a -- INTERNAL, not typesafe to expose. Fcall :: String -> Exp a -> Exp b Const :: Elt a => a -> Exp a Add :: NumE a => Exp a -> Exp a -> Exp a Sub :: NumE a => Exp a -> Exp a -> Exp a Mul :: NumE a => Exp a -> Exp a -> Exp a Div :: NumE a => Exp a -> Exp a -> Exp a Mod :: Exp Int -> Int -> Exp Int Not :: Exp Bool -> Exp Bool And :: Exp Bool -> Exp Bool -> Exp Bool Or :: Exp Bool -> Exp Bool -> Exp Bool Eq :: Elt a => Exp a -> Exp a -> Exp Bool Lt :: NumE a => Exp a -> Exp a -> Exp Bool Gt :: NumE a => Exp a -> Exp a -> Exp Bool Le :: NumE a => Exp a -> Exp a -> Exp Bool Ge :: NumE a => Exp a -> Exp a -> Exp Bool Cond :: Exp Bool -> Exp a -> Exp a -> Exp a instance Show (Exp a) where show a = case a of Ref a -> show a PeekExp a -> "peek(" ++ show a ++ ")" PopExp -> "pop()" Fcall f a -> f ++ "(" ++ show a ++ ")" Const a -> show $ const' a Add a b -> group [show a, "+", show b] Sub a b -> group [show a, "-", show b] Mul a b -> group [show a, "*", show b] Div a b -> group [show a, "/", show b] Mod a b -> group [show a, "%", show (const' b)] Not a -> group ["!", show a] And a b -> group [show a, "&&", show b] Or a b -> group [show a, "||", show b] Eq a b -> group [show a, "==", show b] Lt a b -> group [show a, "<", show b] Gt a b -> group [show a, ">", show b] Le a b -> group [show a, "<=", show b] Ge a b -> group [show a, ">=", show b] Cond a b c -> group [show a, "?", show b, ":", show c] where group :: [String] -> String group a = "(" ++ intercalate " " a ++ ")" instance Eq a => Eq (Exp a) where a == b = evalExp a == evalExp b instance NumE a => Num (Exp a) where (+) = Add (-) = Sub (*) = Mul negate a = 0 - a abs a = Cond (Lt a 0) (negate a) a signum a = Cond (Eq a 0) 0 $ Cond (Lt a 0) (-1) 1 fromInteger = Const . fromInteger -- RRN: FIXME: Exp Int should have an Integral instance but NOT a Fractional one. instance Fractional (Exp Int) where (/) = Div fromRational = error "fromRational " instance Fractional (Exp Float) where (/) = Div recip a = 1 / a fromRational r = Const $ fromInteger (numerator r) / fromInteger (denominator r) evalExp :: Exp a -> a evalExp e = case e of Ref a -> val a -- RRN: Is this a safe assumption? That the variable will have its initial value? -- Seems like this function should return Maybe, and this should potentially be a Nothing case... PeekExp _ -> error "evalExp: can't handle peek" PopExp -> error "evalExp: can't handle pop" Fcall _ _ -> error "evalExp: can't handle Fcall" Const a -> a Add a b -> evalExp a + evalExp b Sub a b -> evalExp a - evalExp b Mul a b -> evalExp a * evalExp b Div _ _ -> error "evalExp: can't handle div" Mod a b -> evalExp a `mod` b Not a -> not $ evalExp a And a b -> evalExp a && evalExp b Or a b -> evalExp a || evalExp b Eq a b -> evalExp a == evalExp b Lt a b -> evalExp a < evalExp b Gt a b -> evalExp a > evalExp b Le a b -> evalExp a <= evalExp b Ge a b -> evalExp a >= evalExp b Cond a b c -> if (evalExp a) then evalExp b else evalExp c data Const = Bool Bool | Int Int | Float Float | Void Void | ArrayT (Exp Int) Const deriving (Eq) isScalar :: Const -> Bool isScalar c = case c of ArrayT _ _ -> False _ -> True instance Show (Const) where show a = case a of Bool True -> "true" Bool False -> "false" Int a -> show a Float a -> show a Void _ -> "" ArrayT b e -> "{" ++ (intercalate "," $ replicate (evalExp b) (show e)) ++ "}" showConstType :: Const -> String showConstType a = case a of Bool _ -> "boolean" Int _ -> "int" Float _ -> "float" Void _ -> "void" ArrayT b e -> (showConstType e) ++ "[" ++ show b ++ "]" -- | True term. true :: Exp Bool true = Const True -- | False term. false :: Exp Bool false = Const False -- | Arbitrary constants. constant :: Elt a => a -> Exp a constant = Const -- | Logical negation. not_ :: Exp Bool -> Exp Bool not_ = Not -- | Logical AND. (&&.) :: Exp Bool -> Exp Bool -> Exp Bool (&&.) = And -- | Logical OR. (||.) :: Exp Bool -> Exp Bool -> Exp Bool (||.) = Or boundsCheck :: Exp Int -> Array a -> Bool boundsCheck idx arr = (x <= y) where x = evalExp idx y = evalExp (bound arr) -- | Array Dereference: (!) :: Elt a => Var (Array a) -> Exp Int -> Var a (Var name arr) ! idx = Var (name ++ "[" ++ show idx ++ "]") $ ele arr -- ADK: First, need to fix evalExpr before we can -- do bounds checking. -- if (boundsCheck idx arr) -- then Var (name ++ "[" ++ show idx ++ "]") $ ele arr -- else error $ "invalid array index: " ++ show idx ++ " in " ++ show (Var name arr) -- | The conjunction of a Exp Bool list. and_ :: [Exp Bool] -> Exp Bool and_ = foldl (&&.) true -- | The disjunction of a Exp Bool list. or_ :: [Exp Bool] -> Exp Bool or_ = foldl (||.) false -- | Equal. (==.) :: Elt a => Exp a -> Exp a -> Exp Bool (==.) = Eq -- | Not equal. (/==.) :: Elt a => Exp a -> Exp a -> Exp Bool a /==. b = not_ (a ==. b) -- | Less than. (<.) :: NumE a => Exp a -> Exp a -> Exp Bool (<.) = Lt -- | Greater than. (>.) :: NumE a => Exp a -> Exp a -> Exp Bool (>.) = Gt -- | Less than or equal. (<=.) :: NumE a => Exp a -> Exp a -> Exp Bool (<=.) = Le -- | Greater than or equal. (>=.) :: NumE a => Exp a -> Exp a -> Exp Bool (>=.) = Ge -- | Expression level conditionals. cond :: Elt a => Exp Bool -> Exp a -> Exp a -> Exp a cond = Cond -- | Modulo. mod_ :: Exp Int -> Int -> Exp Int mod_ _ 0 = error "divide by zero (mod_)" mod_ a b = Mod a b -- | References a variable to be used in an expression. ref :: Elt a => Var a -> Exp a ref = Ref -- | Increments a Var Int. (.++) :: CoreE a => Var Int -> a () (.++) a = a <== ref a + 1 -- | Decrements a Var Int. (.--) :: CoreE a => Var Int -> a () (.--) a = a <== ref a - 1 -- | Sum assign a Var Int. (+=) :: (NumE n, CoreE a) => Var n -> Exp n -> a () a += b = a <== ref a + b -- | Subtract and assign a Var. (-=) :: (NumE n, CoreE a) => Var n -> Exp n -> a () a -= b = a <== ref a - b -- | Product assign a Var. (*=) :: (NumE n, CoreE a) => Var n -> Exp n -> a () a *= b = a <== ref a * b -- | Divide and assign a Var Int. (/=.) :: CoreE a => Var Int -> Exp Int -> a () a /=. b = a <== ref a / b -- | FFI. This takes an arbitrary function name and arguments, and -- | splices it directly in the translated program. fcall :: String -> Exp a -> Exp b fcall = Fcall
adk9/haskell-streamit
Language/StreamIt/Core.hs
bsd-3-clause
10,249
0
15
2,985
4,349
2,202
2,147
-1
-1
------------------------------------------------------------------------------- --- $Id: BSort.hs#1 2009/03/06 10:53:15 REDMOND\\satnams $ ------------------------------------------------------------------------------- module Main where import System.Mem import System.Random import System.Time ------------------------------------------------------------------------------- infixr 5 >-> ------------------------------------------------------------------------------- (>->) :: (a-> b) -> (b-> c) -> (a-> c) (>->) circuit1 circuit2 input1 = circuit2 (circuit1 input1) ------------------------------------------------------------------------------- halve :: [a] -> ([a], [a]) halve l = (take n l, drop n l) where n = length l `div` 2 ------------------------------------------------------------------------------- unhalve :: ([a], [a]) -> [a] unhalve (a, b) = a ++ b ------------------------------------------------------------------------------- pair :: [a] -> [[a]] pair [] = [] pair lst | odd (length lst) = error ("pair given odd length list of size " ++ show (length lst)) pair (a:b:cs) = [a,b]:rest where rest = pair cs ------------------------------------------------------------------------------- unpair :: [[a]] -> [a] unpair list = concat list ------------------------------------------------------------------------------- par2 :: (a -> b) -> (c -> d) -> (a, c) -> (b, d) par2 circuit1 circuit2 (input1, input2) = (output1, output2) where output1 = circuit1 input1 output2 = circuit2 input2 ------------------------------------------------------------------------------- halveList :: [a] -> [[a]] halveList l = [take n l, drop n l] where n = length l `div` 2 ------------------------------------------------------------------------------- unhalveList :: [[a]] -> [a] unhalveList [a, b] = a ++ b ------------------------------------------------------------------------------- chop :: Int -> [a] -> [[a]] chop n [] = [] chop n l = (take n l) : chop n (drop n l) ------------------------------------------------------------------------------- zipList :: [[a]] -> [[a]] zipList [[], _] = [] zipList [_, []] = [] zipList [a:as, b:bs] = [a,b] : zipList [as, bs] ------------------------------------------------------------------------------- unzipList :: [[a]] -> [[a]] unzipList list = [map fstListPair list, map sndListPair list] ------------------------------------------------------------------------------- fsT :: (a -> b) -> (a, c) -> (b, c) fsT f (a, b) = (f a, b) ------------------------------------------------------------------------------- snD :: (b -> c) -> (a, b) -> (a, c) snD f (a, b) = (a, f b) ------------------------------------------------------------------------------- sndList :: ([a] -> [a]) -> [a] -> [a] sndList f = halve >-> snD f >-> unhalve ------------------------------------------------------------------------------- fstListPair :: [a] -> a fstListPair [a, _] = a ------------------------------------------------------------------------------- sndListPair :: [a] -> a sndListPair [_, b] = b ------------------------------------------------------------------------------- two :: ([a] -> [b]) -> [a] -> [b] two r = halve >-> par2 r r >-> unhalve ------------------------------------------------------------------------------- -- Many twos. twoN :: Int -> ([a] -> [b]) -> [a] -> [b] twoN 0 r = r twoN n r = two (twoN (n-1) r) ------------------------------------------------------------------------------- riffle :: [a] -> [a] riffle = halveList >-> zipList >-> unpair ------------------------------------------------------------------------------- unriffle :: [a] -> [a] unriffle = pair >-> unzipList >-> unhalveList ------------------------------------------------------------------------------- ilv :: ([a] -> [b]) -> [a] -> [b] ilv r = unriffle >-> two r >-> riffle ------------------------------------------------------------------------------- ilvN :: Int -> ([a] -> [b]) -> [a] -> [b] ilvN 0 r = r ilvN n r = ilv (ilvN (n-1) r) ------------------------------------------------------------------------------- evens :: ([a] -> [b]) -> [a] -> [b] evens f = chop 2 >-> map f >-> concat ------------------------------------------------------------------------------- type ButterflyElement a = [a] -> [a] type Butterfly a = [a] -> [a] ------------------------------------------------------------------------------- butterfly :: ButterflyElement a -> Butterfly a butterfly circuit [x,y] = circuit [x,y] butterfly circuit input = (ilv (butterfly circuit) >-> evens circuit) input ------------------------------------------------------------------------------- sortB cmp [x, y] = cmp [x, y] sortB cmp input = (two (sortB cmp) >-> sndList reverse >-> butterfly cmp) input ------------------------------------------------------------------------------- twoSorter :: [Int] -> [Int] twoSorter [a, b] = if a <= b then [a, b] else [b, a] ------------------------------------------------------------------------------- bsort :: [Int] -> [Int] bsort = sortB twoSorter ------------------------------------------------------------------------------- main :: IO () main = do nums <- sequence (replicate (2^14) (getStdRandom (randomR (1,255)))) tStart <- getClockTime performGC let r = bsort nums seq r (return ()) tEnd <- getClockTime putStrLn (show (sum r)) putStrLn ("Time: " ++ show (secDiff tStart tEnd) ++ " seconds.") ------------------------------------------------------------------------------- secDiff :: ClockTime -> ClockTime -> Float secDiff (TOD secs1 psecs1) (TOD secs2 psecs2) = fromInteger (psecs2 - psecs1) / 1e12 + fromInteger (secs2 - secs1) -------------------------------------------------------------------------------
ml9951/ThreadScope
papers/haskell_symposium_2009/bsort/BSort.hs
bsd-3-clause
6,086
0
15
1,072
1,799
998
801
102
2
module Views.BanList where import ClientState import Control.Lens import Graphics.Vty.Image import Irc.Format import Irc.Model banListImage :: Char -> Identifier -> ClientState -> [Image] banListImage mode chan st = case view (connChannels . ix chan . chanMaskLists . at mode) conn of Nothing -> [string (withForeColor defAttr red) "Unknown list"] Just [] -> [string (withForeColor defAttr green) "Empty list"] Just xs -> map renderEntry xs where conn = view (clientServer0 . ccConnection) st renderEntry :: IrcMaskEntry -> Image renderEntry entry = utf8Bytestring' (withForeColor defAttr red) (view maskEntryMask entry) <|> string defAttr " - " <|> utf8Bytestring' (withForeColor defAttr green) (view maskEntryWho entry) <|> string defAttr " - " <|> string (withForeColor defAttr yellow) (show (view maskEntryStamp entry))
bitemyapp/irc-core
driver/Views/BanList.hs
bsd-3-clause
861
0
11
152
286
144
142
20
3
{-# OPTIONS -XTypeOperators -XMultiParamTypeClasses #-} module TestInh where -- class (:<) r1 r2 where -- to :: r1 -> r2 -- override :: r1 -> (r2 -> r2) -> r1 newtype R1 = R1 {fun1 :: Int -> Int} data R2 = R2 {toR1 :: R1, fun2 :: Int -> Int} t1 this = R1 (\n -> if (n==0) then 1 else fun1 this (n-1)) t2 this = R2 (toR1 this) (\n -> if (n==1) then fun1 (toR1 this) n else fun2 this (n-1)) new f = let r = f r in r wrapT1 f this = R2 (f (toR1 this)) (fun2 this) p = new (t2 . wrapT1 t1)
bixuanzju/fcore
lib/TestInh.hs
bsd-2-clause
500
0
11
125
234
127
107
9
2
-- Test purpose: -- RebindableSyntax does not play that well with MonadFail, so here we ensure -- that when both settings are enabled we get the proper warning. {-# OPTIONS_GHC -fwarn-missing-monadfail-instance #-} {-# LANGUAGE RebindableSyntax #-} module MonadFailWarningsWithRebindableSyntax where import Prelude test1 f g = do Just x <- f g
gridaphobe/ghc
testsuite/tests/monadfail/MonadFailWarningsWithRebindableSyntax.hs
bsd-3-clause
356
0
8
63
35
20
15
7
1
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Network.Wai.Middleware.RequestLogger import Network.Wai.Middleware.Gzip import Web.Scotty main :: IO () main = scotty 3000 $ do -- Note that files are not gzip'd by the default settings. middleware $ gzip $ def { gzipFiles = GzipCompress } middleware logStdoutDev -- gzip a normal response get "/" $ text "It works" -- gzip a file response (note non-default gzip settings above) get "/afile" $ do setHeader "content-type" "text/plain" file "gzip.hs"
edofic/scotty
examples/gzip.hs
bsd-3-clause
566
0
11
126
116
60
56
13
1
{-# LANGUAGE OverloadedStrings #-} import System.Random import System.Environment import Debug.Trace import Data.List import Control.DeepSeq import Data.Map (Map) import qualified Data.Map as Map -- ---------------------------------------------------------------------------- -- <<Talk newtype Talk = Talk Int deriving (Eq,Ord) instance NFData Talk where rnf (Talk x) = x `seq` () instance Show Talk where show (Talk t) = show t -- >> -- <<Person data Person = Person { name :: String , talks :: [Talk] } deriving (Show) -- >> -- <<TimeTable type TimeTable = [[Talk]] -- >> -- ---------------------------------------------------------------------------- -- <<timetable timetable :: [Person] -> [Talk] -> Int -> Int -> [TimeTable] timetable people allTalks maxTrack maxSlot = -- >> -- <<generate_call generate 0 0 [] [] allTalks allTalks -- >> where -- <<generate_type generate :: Int -- current slot number -> Int -- current track number -> [[Talk]] -- slots allocated so far -> [Talk] -- talks in this slot -> [Talk] -- talks that can be allocated in this slot -> [Talk] -- all talks remaining to be allocated -> [TimeTable] -- all possible solutions -- >> -- <<generate generate slotNo trackNo slots slot slotTalks talks | slotNo == maxSlot = [slots] -- <1> | trackNo == maxTrack = generate (slotNo+1) 0 (slot:slots) [] talks talks -- <2> | otherwise = concat -- <3> [ generate slotNo (trackNo+1) slots (t:slot) slotTalks' talks' -- <8> | (t, ts) <- selects slotTalks -- <4> , let clashesWithT = Map.findWithDefault [] t clashes -- <5> , let slotTalks' = filter (`notElem` clashesWithT) ts -- <6> , let talks' = filter (/= t) talks -- <7> ] -- >> -- <<clashes clashes :: Map Talk [Talk] clashes = Map.fromListWith union [ (t, ts) | s <- people , (t, ts) <- selects (talks s) ] -- >> -- ---------------------------------------------------------------------------- -- Utils -- <<selects selects :: [a] -> [(a,[a])] selects xs0 = go [] xs0 where go xs [] = [] go xs (y:ys) = (y,xs++ys) : go (y:xs) ys -- >> -- ---------------------------------------------------------------------------- -- Benchmarking / Testing bench :: Int -> Int -> Int -> Int -> Int -> StdGen -> ([Person],[Talk],[TimeTable]) bench nslots ntracks ntalks npersons c_per_s gen = (persons,talks, timetable persons talks ntracks nslots) where total_talks = nslots * ntracks talks = map Talk [1..total_talks] persons = mkpersons npersons gen mkpersons :: Int -> StdGen -> [Person] mkpersons 0 g = [] mkpersons n g = Person ('P':show n) (take c_per_s cs) : rest where (g1,g2) = split g rest = mkpersons (n-1) g2 cs = nub [ talks !! n | n <- randomRs (0,ntalks-1) g ] main = do [ a, b, c, d, e ] <- fmap (fmap read) getArgs let g = mkStdGen 1001 let (ss,cs,ts) = bench a b c d e g print ss print (length ts) -- [ a, b ] <- fmap (fmap read) getArgs -- print (head (test2 a b)) test = timetable testPersons cs 2 2 where cs@[c1,c2,c3,c4] = map Talk [1..4] testPersons = [ Person "P" [c1,c2] , Person "Q" [c2,c3] , Person "R" [c3,c4] , Person "S" [c1,c4] ] test2 n m = timetable testPersons cs m n where cs = map Talk [1 .. (n * m)] testPersons = [ Person "1" (take n cs) ]
AndrewRademacher/parconc-examples
timetable.hs
bsd-3-clause
3,686
22
14
1,088
1,306
669
637
78
2
{-# LANGUAGE CPP #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} #if __GLASGOW_HASKELL__ >= 711 {-# OPTIONS_GHC -fno-warn-redundant-constraints #-} #endif #ifndef MIN_VERSION_base #define MIN_VERSION_base(x,y,z) 1 #endif ----------------------------------------------------------------------------- -- | -- Module : Generics.Deriving.Lens -- Copyright : (C) 2012-15 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : experimental -- Portability : GHC -- -- Note: @Generics.Deriving@ exports a number of names that collide with @Control.Lens@. -- -- You can use hiding to mitigate this to an extent, and the following import -- represents a fair compromise for user code: -- -- > import Generics.Deriving hiding (from, to) -- -- You can use 'generic' to replace 'Generics.Deriving.from' and -- 'Generics.Deriving.to' from @Generics.Deriving@. ---------------------------------------------------------------------------- module Generics.Deriving.Lens ( -- * Isomorphisms for @GHC.Generics@ generic , generic1 -- * Generic Traversal , tinplate , GTraversal ) where import Control.Lens import Data.Maybe (fromJust) import Data.Typeable import qualified GHC.Generics as Generic import GHC.Generics hiding (from, to) #if !MIN_VERSION_base(4,8,0) import Control.Applicative #endif -- $setup -- >>> :set -XNoOverloadedStrings -- | Convert from the data type to its representation (or back) -- -- >>> "hello"^.generic.from generic :: String -- "hello" generic :: Generic a => Iso' a (Generic.Rep a b) generic = iso Generic.from Generic.to {-# INLINE generic #-} -- | Convert from the data type to its representation (or back) generic1 :: Generic1 f => Iso' (f a) (Rep1 f a) generic1 = iso from1 to1 {-# INLINE generic1 #-} -- | A 'GHC.Generics.Generic' 'Traversal' that visits every occurrence -- of something 'Typeable' anywhere in a container. -- -- >>> allOf tinplate (=="Hello") (1::Int,2::Double,(),"Hello",["Hello"]) -- True -- -- >>> mapMOf_ tinplate putStrLn ("hello",[(2 :: Int, "world!")]) -- hello -- world! tinplate :: (Generic a, GTraversal (Generic.Rep a), Typeable b) => Traversal' a b tinplate = generic . tinplated Nothing {-# INLINE tinplate #-} maybeArg1Of :: Maybe c -> (c -> d) -> Maybe c maybeArg1Of = const {-# INLINE maybeArg1Of #-} -- | Used to traverse 'Generic' data by 'uniplate'. class GTraversal f where tinplated :: Typeable b => Maybe TypeRep -> Traversal' (f a) b instance (Generic a, GTraversal (Generic.Rep a), Typeable a) => GTraversal (K1 i a) where tinplated prev f (K1 a) = case cast a `maybeArg1Of` f of Just b -> K1 . fromJust . cast <$> f b Nothing -> case prev of Just rep | rep == typeOf a -> pure (K1 a) _ -> K1 <$> fmap generic (tinplated (Just (typeOf a))) f a {-# INLINE tinplated #-} instance GTraversal U1 where tinplated _ _ U1 = pure U1 {-# INLINE tinplated #-} instance GTraversal V1 where tinplated _ _ v = v `seq` undefined {-# INLINE tinplated #-} instance (GTraversal f, GTraversal g) => GTraversal (f :*: g) where tinplated _ f (x :*: y) = (:*:) <$> tinplated Nothing f x <*> tinplated Nothing f y {-# INLINE tinplated #-} instance (GTraversal f, GTraversal g) => GTraversal (f :+: g) where tinplated _ f (L1 x) = L1 <$> tinplated Nothing f x tinplated _ f (R1 x) = R1 <$> tinplated Nothing f x {-# INLINE tinplated #-} instance GTraversal a => GTraversal (M1 i c a) where tinplated prev f (M1 x) = M1 <$> tinplated prev f x {-# INLINE tinplated #-}
danidiaz/lens
src/Generics/Deriving/Lens.hs
bsd-3-clause
3,733
0
19
732
774
424
350
53
1
module EnvMT (module IxEnvMT, F.MT(..), F.HasEnv, getEnv, inEnv, inModEnv) where import IxEnvMT hiding (HasEnv(..)) import qualified MT as F getEnv :: F.HasEnv m F.Z e => m e inEnv :: F.HasEnv m F.Z e => e -> m a -> m a inModEnv :: F.HasEnv m F.Z e => (e -> e) -> m a -> m a getEnv = F.getEnv F.this inEnv = F.inEnv F.this inModEnv = F.inModEnv F.this
forste/haReFork
tools/base/lib/Monads/EnvMT.hs
bsd-3-clause
380
0
8
98
186
101
85
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 HsImpExp: Abstract syntax: imports, exports, interfaces -} {-# LANGUAGE DeriveDataTypeable #-} module HsImpExp where import Module ( ModuleName ) import HsDoc ( HsDocString ) import OccName ( HasOccName(..), isTcOcc, isSymOcc ) import BasicTypes ( SourceText, StringLiteral(..) ) import Outputable import FastString import SrcLoc import Data.Data {- ************************************************************************ * * \subsection{Import and export declaration lists} * * ************************************************************************ One per \tr{import} declaration in a module. -} type LImportDecl name = Located (ImportDecl name) -- ^ When in a list this may have -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' -- For details on above see note [Api annotations] in ApiAnnotation -- | A single Haskell @import@ declaration. data ImportDecl name = ImportDecl { ideclSourceSrc :: Maybe SourceText, -- Note [Pragma source text] in BasicTypes ideclName :: Located ModuleName, -- ^ Module name. ideclPkgQual :: Maybe StringLiteral, -- ^ Package qualifier. ideclSource :: Bool, -- ^ True <=> {-\# SOURCE \#-} import ideclSafe :: Bool, -- ^ True => safe import ideclQualified :: Bool, -- ^ True => qualified ideclImplicit :: Bool, -- ^ True => implicit import (of Prelude) ideclAs :: Maybe ModuleName, -- ^ as Module ideclHiding :: Maybe (Bool, Located [LIE name]) -- ^ (True => hiding, names) } -- ^ -- 'ApiAnnotation.AnnKeywordId's -- -- - 'ApiAnnotation.AnnImport' -- -- - 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnClose' for ideclSource -- -- - 'ApiAnnotation.AnnSafe','ApiAnnotation.AnnQualified', -- 'ApiAnnotation.AnnPackageName','ApiAnnotation.AnnAs', -- 'ApiAnnotation.AnnVal' -- -- - 'ApiAnnotation.AnnHiding','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' attached -- to location in ideclHiding -- For details on above see note [Api annotations] in ApiAnnotation deriving (Data, Typeable) simpleImportDecl :: ModuleName -> ImportDecl name simpleImportDecl mn = ImportDecl { ideclSourceSrc = Nothing, ideclName = noLoc mn, ideclPkgQual = Nothing, ideclSource = False, ideclSafe = False, ideclImplicit = False, ideclQualified = False, ideclAs = Nothing, ideclHiding = Nothing } instance (OutputableBndr name, HasOccName name) => Outputable (ImportDecl name) where ppr (ImportDecl { ideclName = mod', ideclPkgQual = pkg , ideclSource = from, ideclSafe = safe , ideclQualified = qual, ideclImplicit = implicit , ideclAs = as, ideclHiding = spec }) = hang (hsep [ptext (sLit "import"), ppr_imp from, pp_implicit implicit, pp_safe safe, pp_qual qual, pp_pkg pkg, ppr mod', pp_as as]) 4 (pp_spec spec) where pp_implicit False = empty pp_implicit True = ptext (sLit ("(implicit)")) pp_pkg Nothing = empty pp_pkg (Just (StringLiteral _ p)) = doubleQuotes (ftext p) pp_qual False = empty pp_qual True = ptext (sLit "qualified") pp_safe False = empty pp_safe True = ptext (sLit "safe") pp_as Nothing = empty pp_as (Just a) = ptext (sLit "as") <+> ppr a ppr_imp True = ptext (sLit "{-# SOURCE #-}") ppr_imp False = empty pp_spec Nothing = empty pp_spec (Just (False, (L _ ies))) = ppr_ies ies pp_spec (Just (True, (L _ ies))) = ptext (sLit "hiding") <+> ppr_ies ies ppr_ies [] = ptext (sLit "()") ppr_ies ies = char '(' <+> interpp'SP ies <+> char ')' {- ************************************************************************ * * \subsection{Imported and exported entities} * * ************************************************************************ -} type LIE name = Located (IE name) -- ^ When in a list this may have -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation -- | Imported or exported entity. data IE name = IEVar (Located name) -- ^ - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnPattern', -- 'ApiAnnotation.AnnType' -- For details on above see note [Api annotations] in ApiAnnotation | IEThingAbs (Located name) -- ^ Class/Type (can't tell) -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnPattern', -- 'ApiAnnotation.AnnType','ApiAnnotation.AnnVal' -- For details on above see note [Api annotations] in ApiAnnotation | IEThingAll (Located name) -- ^ Class/Type plus all methods/constructors -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnType' -- For details on above see note [Api annotations] in ApiAnnotation | IEThingWith (Located name) [Located name] -- ^ Class/Type plus some methods/constructors -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnType' -- For details on above see note [Api annotations] in ApiAnnotation | IEModuleContents (Located ModuleName) -- ^ (Export Only) -- -- - 'ApiAnnotation.AnnKeywordId's : 'ApiAnnotation.AnnModule' -- For details on above see note [Api annotations] in ApiAnnotation | IEGroup Int HsDocString -- ^ Doc section heading | IEDoc HsDocString -- ^ Some documentation | IEDocNamed String -- ^ Reference to named doc deriving (Eq, Data, Typeable) ieName :: IE name -> name ieName (IEVar (L _ n)) = n ieName (IEThingAbs (L _ n)) = n ieName (IEThingWith (L _ n) _) = n ieName (IEThingAll (L _ n)) = n ieName _ = panic "ieName failed pattern match!" ieNames :: IE a -> [a] ieNames (IEVar (L _ n) ) = [n] ieNames (IEThingAbs (L _ n) ) = [n] ieNames (IEThingAll (L _ n) ) = [n] ieNames (IEThingWith (L _ n) ns) = n : map unLoc ns ieNames (IEModuleContents _ ) = [] ieNames (IEGroup _ _ ) = [] ieNames (IEDoc _ ) = [] ieNames (IEDocNamed _ ) = [] pprImpExp :: (HasOccName name, OutputableBndr name) => name -> SDoc pprImpExp name = type_pref <+> pprPrefixOcc name where occ = occName name type_pref | isTcOcc occ && isSymOcc occ = ptext (sLit "type") | otherwise = empty instance (HasOccName name, OutputableBndr name) => Outputable (IE name) where ppr (IEVar var) = pprPrefixOcc (unLoc var) ppr (IEThingAbs thing) = pprImpExp (unLoc thing) ppr (IEThingAll thing) = hcat [pprImpExp (unLoc thing), text "(..)"] ppr (IEThingWith thing withs) = pprImpExp (unLoc thing) <> parens (fsep (punctuate comma (map pprImpExp $ map unLoc withs))) ppr (IEModuleContents mod') = ptext (sLit "module") <+> ppr mod' ppr (IEGroup n _) = text ("<IEGroup: " ++ (show n) ++ ">") ppr (IEDoc doc) = ppr doc ppr (IEDocNamed string) = text ("<IEDocNamed: " ++ string ++ ">")
acowley/ghc
compiler/hsSyn/HsImpExp.hs
bsd-3-clause
8,272
0
14
2,696
1,592
861
731
102
1
{-# OPTIONS_GHC -funbox-strict-fields #-} module T5252Take2a ( WriteMessage(..) , WriteDevice ) where import qualified Data.ByteString as ByteString data WriteMessage = WriteMessage !WriteDevice newtype WriteDevice = WriteDevice ByteString.ByteString
wxwxwwxxx/ghc
testsuite/tests/deSugar/should_compile/T5252Take2a.hs
bsd-3-clause
255
0
7
31
45
29
16
7
0
module B where import A b x = x
wxwxwwxxx/ghc
testsuite/tests/ghci.debugger/scripts/break023/B.hs
bsd-3-clause
34
0
5
11
15
9
6
3
1
module Haggcat.TestHelper where import Control.Monad import qualified Data.Aeson as Aeson import qualified Data.ByteString.Lazy as LBS import Haggcat.Client import Haggcat.Types getTestConfig :: FilePath -> IO Config getTestConfig = liftM read . readFile loadTestClient :: IO Client loadTestClient = loadClient =<< getTestConfig "test-files/config" writeInstutions :: Client -> IO () writeInstutions client = do eitherInsts <- getInstitutions client case eitherInsts of Right insts -> writeFile "test-files/institutions" $ show insts Left msg -> error msg loadInstitutions :: IO [Institution] loadInstitutions = do content <- readFile "test-files/institutions" let insts = read content :: [Institution] return insts
carymrobbins/haggcat
src/Haggcat/TestHelper.hs
mit
798
0
11
173
202
103
99
21
2
module Hasql.Private.Encoders.Params where import Hasql.Private.Prelude import qualified Database.PostgreSQL.LibPQ as A import qualified PostgreSQL.Binary.Encoding as B import qualified Hasql.Private.Encoders.Value as C import qualified Hasql.Private.PTI as D import qualified Text.Builder as E -- | -- Encoder of some representation of a parameters product. newtype Params a = Params (Op (DList (A.Oid, A.Format, Bool -> Maybe ByteString, Text)) a) deriving (Contravariant, Divisible, Decidable, Semigroup, Monoid) value :: C.Value a -> Params a value = contramap Just . nullableValue nullableValue :: C.Value a -> Params (Maybe a) nullableValue (C.Value valueOID arrayOID encode render) = Params $ Op $ \ input -> let D.OID _ pqOid format = valueOID encoder env = fmap (B.encodingBytes . encode env) input rendering = maybe "null" (E.run . render) input in pure (pqOid, format, encoder, rendering)
nikita-volkov/hasql
library/Hasql/Private/Encoders/Params.hs
mit
949
0
14
176
299
169
130
24
1
{-# LANGUAGE FlexibleInstances, ImplicitParams #-} import Numeric.LinearAlgebra.LAPACK import Numeric.LinearAlgebra.Algorithms import Data.Packed.Matrix import qualified Data.Matrix as M import Extensions.Units import Extensions.UnitsSolve import Extensions.UnitsEnvironment import Data.Ratio import Data.List import System.Random import System.IO.Unsafe import Control.Exception import Debug.Trace import Test.QuickCheck coeff :: Num a => [[a]] coeff = [[1, 0, 1, 0], [0, 4, 0, 3], [0, 0, 2, 0]] rhs :: Num a => [a] rhs = [1, 2, 3] rhs' = [[0, 1, 0], [0, 2, 0], [0, 0, 3]] {- Lapack -} coeffL, rhsL :: Matrix Double coeffL = fromLists $ coeff rhsL = fromLists $ map (\x -> [x]) rhs -- (map (\x -> x) rhs) solveL = linearSolveSVDR Nothing coeffL rhsL {- CamFort -} coeffC :: M.Matrix Rational coeffC = M.fromLists coeff rhsC = map (\x -> Unitless x) rhs linearSys = (coeffC, rhsC) solveC = let ?solver = Custom in solveSystem linearSys data LSystem a = LSystem (M.Matrix a) [a] Int deriving (Show, Eq) instance Random (Ratio Integer) where random g = let (n, g') = random g (d, g'') = random g' in (n % d, g'') randomR (l, h) g = let (ln, hn) = (numerator l, numerator h) (ld, hd) = (denominator l, denominator h) (n, g') = randomR (ln, hn) g (d, g'') = randomR (ld, hd) g' in (n % d, g'') instance (Arbitrary a, Num a, Random a) => Arbitrary (LSystem a) where -- NB: for square matrices, but row echelon form arbitrary = sized (\n -> do m <- choose(1, n) xs <- vectorOf (n*m) (choose (1, 20)) -- arbitrary v <- vectorOf n (choose (1, 20)) -- arbitrary let mx = M.matrix n m (\(i, j) -> if (i <= j) then xs !! ((i-1)*n + (j-1)) else 0) return $ LSystem mx v n) {- speedTest = do let g = (resize 40 arbitrary)::(Gen (LSystem Rational)) lapackSolve g camfortSolve g -} toLapack :: LSystem Rational -> (Matrix Double, Matrix Double) toLapack (LSystem m v n) = (fromLists (map (map fromRational) (M.toLists $ m)), fromLists (map (\x -> [fromRational x]) v)) -- fromLists (map (\x -> ((fromRational x) : (take (n - 1) (repeat 0)))) v)) fromLapack :: (Matrix Double, Matrix Double) -> [Double] fromLapack (m, v) = map (\x -> head x) (toLists v) fromLapackSol :: Matrix Double -> [Double] fromLapackSol v = map (\x -> toNearestEps $ head x) (toLists v) toCamfort :: LSystem Rational -> LinearSystem toCamfort (LSystem m v n) = (m, map (\x -> Unitless x) v) fromCamfort :: LinearSystem -> [Double] fromCamfort (m, v) = map (\(Unitless r) -> fromRational r) v fromCamfortSol :: Consistency LinearSystem -> TestResult fromCamfortSol (Ok m) = Solved $ fromCamfort m fromCamfortSol (Bad m _) = "Error" `trace` Solved $ fromCamfort m -- sometimes the partial result is similar data TestResult = Solved [Double] | Unsolved deriving Show lapackSolve x = unsafePerformIO $ do x <- catch (evaluate $ (uncurry linearSolveLSR) . toLapack $ x) (\e -> let x = (e :: SomeException) in return $ fromLists []) if (toLists x == []) then return Unsolved else return $ Solved . fromLapackSol $ x --lapackSolve x = fromLapackSol . (uncurry linearSolveR) . toLapack $ x camfortSolve = let ?solver = Custom in fromCamfortSol . solveSystem . toCamfort class ApproxEq t where (~~) :: t -> t -> Bool instance ApproxEq Double where x ~~ y = -- abs (x - y) <= 0.00001 let x' = toNearestEps x y' = toNearestEps y in x' == y' instance ApproxEq a => ApproxEq [a] where x ~~ y = and (zipWith (~~) x y) instance ApproxEq TestResult where (Solved x) ~~ (Solved y) = x ~~ y Unsolved ~~ Unsolved = True x ~~ y = False convTest = quickCheck (\x -> ((fromLapack . toLapack) x) == ((fromCamfort . toCamfort) x)) solveTest = quickCheck (\x@(LSystem _ _ n) -> if n >= 1 then let l = lapackSolve x c = camfortSolve x in l ~~ c else True) foo = LSystem (M.fromLists [[15 % 1, 17 % 1], [0 % 1, 8 % 1], [0 % 1, 0 % 1]]) [4 % 1, 5 % 1, 10 % 1] 3 foo2 = LSystem (M.fromLists [[10 % 1, 2 % 1], [0 % 1, 0 % 1]]) [(-8) % 1,(-5) % 1] 2 fooExample = LSystem (M.fromLists (map (map toRational) m)) rhs 10 where m = [[ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 ] , [ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0 ] , [ 0.0, 1.0, 0.0, 0.0, 0.0, 1.0, -1.0, 0.0, 0.0, 0.0 ] , [ 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0 ] , [ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0 ] , [ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0 ] , [ 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 ]] rhs = [ 0.0, 1.0 , 0.0 , 0.0 , 0.0 , 0.0 , 0.0 ] fooExample2 = linearSolveSVDR Nothing (fromLists m) (fromLists rhs) where m = [[ 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ,[ 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ,[ 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ,[ 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ,[ 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ,[ 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] ,[ 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0] ,[ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 2.0, 0.0, -1.0] ,[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, -1.0, 1.0 ]] rhs = [[ 0.0, 0.0, 0.0] ,[0.0, 1.0, 0.0] ,[0.0, 0.0, 1.0] ,[0.0, 0.0, 0.0] ,[0.0, 0.0, 0.0] ,[0.0, 0.0, 0.0] ,[0.0, 0.0, 0.0] ,[0.0, 0.0, 0.0] ,[0.0, 0.0, 0.0 ]]
ucam-cl-dtg/naps-camfort
dev/lapack-test.hs
mit
6,676
34
23
2,386
2,764
1,532
1,232
120
2
{-| Module : Text.Microparsec Description : A lightweight parser combinator library inspired by parsec Copyright : © 2015 Dathan Ault-McCoy License : GPL-3 Maintainer : [email protected] Portability : POSIX Microparsec is a lightweight parser combinator library sharing many features with the parsec library. While, on the surface, microparsec and parsec may seem very similar, there are several major differences that users should be aware of. First, microparsec attempts absolutely __no error reporting__. This means that it is probably not an ideal choice for the parsing of programming languages or similar applications where error reporting is a critical aspect of the parser. The second major difference is that the microparsec 'ParserT' can return /any/ instance of 'MonadPlus', including user defined types. This allows for somewhat more flexibility in error handling, but it also requires more care when crafting type declerations. Other than these differences, those well-versed in parsec should feel at home using microparsec. Microparsec is generally very fast, but speed will of course differ between systems, so I strongly advise running a benchmark yourself to determine if its performance fits your needs. (Microparsec, unlike Parsec, does not export type restricted versions of the 'Alternative' manipulation functions ('many', '<|>', etc.), so the program must import 'Control.Applicative' to make use of them.) -} module Text.Microparsec ( ParserT, parse, -- * Parser constructors satisfy, peek, symbol, symbols, anySymbol, eof, try, option, notReq, oneOf, -- * Parser combinators notFollowedBy, count, choice, till, endBy1, endBy, sepBy1, sepBy, sepEndBy1, sepEndBy, between, -- * Character matching space, spaces, digit, digits, alpha, alphaNum, upper, lower ) where import Data.Functor import Control.Applicative import Control.Monad import Text.Microparsec.Prim import Text.Microparsec.Core import Text.Microparsec.Char ----------------------- -- Parser generators -- ----------------------- -- | Matches a single symbol. symbol :: (MonadPlus m, Eq s) => s -> ParserT s m s symbol c = satisfy (==c) -- | Matches a list of symbols. symbols :: (MonadPlus m, Eq s) => [s] -> ParserT s m [s] symbols = mapM symbol -- | Will not consume any input iff the provided parser -- fails. Provides this functionality only when used -- on the left hand side of a '<|>' expression. try :: (MonadPlus m, Functor m) => ParserT s m a -> ParserT s m a try e = peek e >> e -- | Attempts to match the provided pattern first. If -- that fails it will the default expression. option :: (MonadPlus m, Alternative m) => a -> ParserT s m a -> ParserT s m a option d e = try e <|> return d -- | Parses zero or one occurences of an expression, -- discarding the result. notReq :: (MonadPlus m, Alternative m) => ParserT s m a' -> ParserT s m () notReq e = option undefined e >> return () -- | Matches any symbol in the provided list. oneOf :: (MonadPlus m, Eq s) => [s] -> ParserT s m s oneOf cs = satisfy (`elem` cs) ------------------------ -- Parser combinators -- ------------------------ -- | Matches and returns any symbol. anySymbol :: (MonadPlus m) => ParserT s m s anySymbol = satisfy $ const True -- | End of input (does not actually match -- the unicode eof character, but rather -- succeeds only when there are no more -- symbols to parse) eof :: (MonadPlus m, Eq (m (s,[s]))) => ParserT s m () eof = notFollowedBy anySymbol >> return () -- | Matches one or more expressions followed by a -- delimiter and returns a list of the matched -- expressions. endBy1 :: (MonadPlus m, Alternative m) => ParserT s m a -> ParserT s m a' -> ParserT s m [a] endBy1 e s = some $ e <* s -- | Matches zero or more expressions followed by a -- delimiter and returns a list of the matched -- expressions. endBy :: (MonadPlus m, Alternative m) => ParserT s m a -> ParserT s m a' -> ParserT s m [a] endBy e s = many $ e <* s -- | Matches one or more expressions seperated by a -- delimiter and returns a list of the matched -- expressions. sepBy1 :: (MonadPlus m, Alternative m) => ParserT s m a -> ParserT s m a' -> ParserT s m [a] sepBy1 e s = do { rs <- endBy e s ; ((rs++) . (:[])) <$> e } -- | Matches zero or more expressions seperated by a -- delimiter and returns a list of the matched -- expressions. sepBy :: (MonadPlus m, Alternative m) => ParserT s m a -> ParserT s m a' -> ParserT s m [a] sepBy e s = sepBy1 e s <|> return [] -- | Matches one or more expressions seperated and -- optionally ended by a delimeter and returs a -- list of the matched expressions. sepEndBy1 :: (MonadPlus m, Alternative m) => ParserT s m a -> ParserT s m a' -> ParserT s m [a] sepEndBy1 e s = sepBy1 e s <* optional s -- | Matches zero or more expressions seperated and -- optionally ended by a delimeter and returs a -- list of the matched expressions. sepEndBy :: (MonadPlus m, Alternative m) => ParserT s m a -> ParserT s m a' -> ParserT s m [a] sepEndBy e s = sepEndBy1 e s <|> return [] -- | Matches an expression surrounded by a symbol. -- Returns the result of the surrounded expression. -- Usually used infix. between :: (MonadPlus m, Applicative m) => ParserT s m a -> ParserT s m a' -> ParserT s m a between e s = s *> e <* s -- | Parses a fixed number of occurences of an -- expression. count :: (MonadPlus m) => Int -> ParserT s m a -> ParserT s m [a] count n e = sequence $ replicate n e -- | Takes a list of parsers, runs each one in order, -- and returns the value of the first that succeeds. choice :: (MonadPlus m, Alternative m) => [ParserT s m a] -> ParserT s m a choice = foldr (<|>) mzero -- | Matches zero or more expressions until a termination -- parser succeeds. The value of the terminator is discarded. till :: (MonadPlus m) => ParserT s m a -> ParserT s m a' -> ParserT s m [a] till e x = let go = x *> return [] <|> (:) <$> e <*> go in go
Kwarrtz/microparsec
src/Text/Microparsec.hs
mit
6,291
0
14
1,517
1,334
719
615
126
1
{-# LANGUAGE OverloadedStrings #-} module CFDI.PAC.FelSpec ( spec ) where import CFDI import CFDI.PAC ( StampError(PacError) , cancelCFDI , getPacStamp , stamp , stampLookup ) import CFDI.PAC.Fel import Control.Monad (when) import Data.Either (isLeft, isRight) import Data.Maybe (isNothing) import Data.Text (Text, take, unpack) import Data.Time.Calendar (Day(ModifiedJulianDay), addDays) import Data.Time.LocalTime (LocalTime(..), TimeOfDay(..), localDay) import Data.Time.Clock (getCurrentTime) import Data.Time.Format (defaultTimeLocale, formatTime, parseTimeM) import Data.Yaml ( FromJSON , Value(Object) , (.:) , decodeFile , parseJSON ) import Prelude hiding (take) import System.Directory (doesFileExist, removeFile) import System.IO.Temp (writeSystemTempFile) import Test.Hspec data FelCreds = FelCreds Text Text Text Text String Text Text Text instance FromJSON FelCreds where parseJSON (Object v) = FelCreds <$> v .: "user" <*> v .: "pass" <*> v .: "rfc" <*> v .: "csdCert" <*> v .: "csdPem" <*> v .: "csdPfxPass" <*> v .: "csdPfxPem" <*> v .: "csdSerial" cfdi :: CFDI cfdi = CFDI Nothing Nothing Nothing Income Nothing (Concepts [ Concept (Amount 1090.52) [] (ProductDescription "COMIDA MEXICANA O ESPAÑOLA") Nothing MU_ACT (Just (ProductId "PROD12")) (ProductOrService 91111700) Nothing (Quantity 1) (Just (ConceptTaxes Nothing (Just (ConceptTransferedTaxes [ ConceptTransferedTax (Just (Amount 174.48)) (Amount 1090.52) Rate (Just (TaxRate 0.16)) IVA ])))) (Just (ProductUnit "NA")) (Amount 1090.52) ]) Nothing CUR_MXN Nothing Nothing (Just (Folio "12")) (LocalTime (ModifiedJulianDay 57953) (TimeOfDay 14 27 3)) (ZipCode 22115) (Issuer (Just (Name "EMISOR DE PRUEBA")) (RFC "TEST010203001") PeopleWithBusinessActivities) (Just (PaymentConditions "CONDICIONES DE PAGO DE PRUEBA")) (Just OneTimePayment) (Recipient (Just GeneralExpenses) (Just (Name "RECEPTOR DE PRUEBA")) (RFC "TES030201001") Nothing Nothing) Nothing (Just (Series "ABC")) Nothing (Amount 1090.52) (Just (Taxes Nothing (Just (Amount 174.48)) Nothing (Just (TransferedTaxes [ TransferedTax (Amount 174.48) Rate (TaxRate 0.16) IVA ])))) (Amount 1265) (Version 3.3) (Just Cash) spec :: Spec spec = do let credsFilePath = "test/yaml/pac-credentials/fel.yml" credsFileExist <- runIO $ doesFileExist credsFilePath when credsFileExist $ do (fel, pem, crt, crtNum) <- runIO $ do Just (FelCreds usr pass_ rfc_ crt pem pfxPwd pfxPem crtNum) <- decodeFile credsFilePath return (Fel usr pass_ rfc_ pfxPwd pfxPem FelTestingEnv, pem, crt, crtNum) describe "CFDI.PAC.Fel.Fel instance of PAC" $ do it "implements getPacStamp function" $ do currentTimeStr <- formatTime defaultTimeLocale f <$> getCurrentTime now <- parseTimeM True defaultTimeLocale f currentTimeStr pemFilePath <- writeSystemTempFile "csd.pem" pem let cfdi' = cfdi { certNum = Just (CertificateNumber crtNum) , certText = Just crt , issuedAt = time } time = now { localDay = addDays (-1) (localDay now) } Right signedCfdi@CFDI{signature = Just sig} <- signWith pemFilePath cfdi' let cfdiId = take 12 sig eitherErrOrStamp <- getPacStamp signedCfdi fel cfdiId eitherErrOrStamp `shouldSatisfy` isRight removeFile pemFilePath it "implements stampLookup function" $ do -- We need to stamp a CFDI first to test this. currentTimeStr <- formatTime defaultTimeLocale f <$> getCurrentTime now <- parseTimeM True defaultTimeLocale f currentTimeStr pemFilePath <- writeSystemTempFile "csd.pem" pem let cfdi' = cfdi { certNum = Just (CertificateNumber crtNum) , certText = Just crt , issuedAt = time } time = now { localDay = addDays (-1) (localDay now) } Right signedCfdi@CFDI{signature = Just sig} <- signWith pemFilePath cfdi' let cfdiId = take 12 sig eitherErrOrStamp <- getPacStamp signedCfdi fel cfdiId eitherErrOrStamp `shouldSatisfy` isRight eitherErrOrStamp' <- getPacStamp signedCfdi fel cfdiId eitherErrOrStamp' `shouldSatisfy` isLeft let Left (PacError _ code) = eitherErrOrStamp' code `shouldBe` Just "801" eitherErrOrStamp'' <- stampLookup fel cfdiId eitherErrOrStamp'' `shouldSatisfy` isRight removeFile pemFilePath where f = "%Y-%m-%d-%H-%M-%S-%Z"
yusent/cfdis
test/unit/CFDI/PAC/FelSpec.hs
mit
5,200
0
23
1,654
1,411
729
682
154
1
module Logger where import Control.Concurrent --import Data.List import Parser (Cmd) type Log = (String, Cmd) newLogCache :: IO (MVar [Log]) newLogCache = newMVar [] log :: String -> Cmd -> MVar [Log] -> IO () log nick cmd cache = do modifyMVar_ cache (\cache -> do return $ cache ++ [(nick, cmd)])
osa1/dolap-chat
src/Logger.hs
mit
315
0
14
68
133
73
60
10
1
module Users.Controller ( module Users.Actions.Index , module Users.Actions.Show ) where import Users.Actions.Index import Users.Actions.Show
toddmohney/json-api
example/src/Users/Controller.hs
mit
150
0
5
22
34
23
11
5
0
{-# LANGUAGE RankNTypes #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeFamilies #-} module Main where import Control.Applicative ((<$>), (<*>)) import Control.Lens (IndexPreservingGetter, both, each, ix, over, to, use, view, (%=), (&), (*~), (+=), (+~), (-~), (.=), (.~), (^.), (^?!), _1, _2, _3) import Control.Lens.At (Index, IxValue, Ixed, at) import Control.Lens.TH (makeClassy, makeLenses) import Control.Monad (msum, unless, void, when) import Control.Monad.Loops (unfoldM) import Control.Monad.State.Strict (StateT, runStateT) import Control.Monad.Trans.Class (MonadTrans, lift) import Data.Foldable (foldMap) import Data.List (tails,maximum) import Data.Maybe (fromJust, isJust, mapMaybe) import Data.Monoid (Endo (Endo), appEndo, (<>)) import Data.Traversable (traverse) import Data.Word (Word8) import Debug.Trace (trace) import Graphics.UI.SDL.Color (Color (..)) import Graphics.UI.SDL.Events (Event (..), pollEvent) import Graphics.UI.SDL.Keysym (Scancode (LeftShift, LeftControl)) import qualified Graphics.UI.SDL.Rect as SDLRect import qualified Graphics.UI.SDL.Render as SDLR import qualified Graphics.UI.SDL.TTF as SDLTtf import Graphics.UI.SDL.TTF.Types (TTFFont) import qualified Graphics.UI.SDL.Types as SDLT import Linear.Matrix ((!*)) import Linear.Metric (dot,distance) import Linear.V2 (V2 (..), _x, _y) import Linear.V3 (V3 (..), cross, _z) import Linear.Vector ((*^), (^*), (^/)) import Physie.Colors import Physie.ContactPoints (findContactPoints) import Physie.Debug (traceShowId) import Physie.Line import Physie.Sat (satIntersects) import Physie.SDL (createFontTexture, destroyTexture, drawLine, isKeydownEvent, isQuitEvent, withFontInit, withImgInit, withRenderer, withWindow,sizeText) import Physie.Time (TimeDelta, TimeTicks, fromSeconds, getTicks, tickDelta, toSeconds) import System.FilePath toIntPoint :: (RealFrac a,Integral b) => V2 a -> V2 b toIntPoint (V2 x y) = V2 (floor x) (floor y) minmax :: Ord a => [a] -> (a,a) minmax ls = (minimum ls,maximum ls) cross2 :: V2 Double -> V2 Double -> Double cross2 (V2 x1 y1) (V2 x2 y2) = x1 * y2 - y1 * x2 lineIntersection :: Double -> Line (V2 Double) -> Line (V2 Double) -> Maybe (V2 Double) lineIntersection delta (Line p to1) (Line q to2) | collinear && overlapping = Just (p + ((tnom/denom) *^ r)) | collinear && not overlapping = Nothing | abs denom <= delta && abs unom > delta = Nothing | abs denom > delta && isNormalized (tnom / denom) && isNormalized (unom / denom) = Just (p + (tnom/denom) *^ r) | otherwise = Nothing where r = to1 - p s = to2 - q denom = r `cross2` s tnom = (q - p) `cross2` s unom = (q - p) `cross2` r isNormalized z = z >= 0 && z <= 1 collinear = abs denom <= delta && abs unom <= delta overlapping = (0 <= ((q - p) `dot` r) && ((q - p) `dot` r) <= (r `dot` r)) || (0 <= (p - q) `dot` s && (p - q) `dot` s <= s `dot` s) extractMaybe1of2 :: (Maybe a,b) -> Maybe (a,b) extractMaybe1of2 (Nothing,_) = Nothing extractMaybe1of2 (Just a,b) = Just (a,b) extractMaybe3of3 :: (a,b,Maybe c) -> Maybe (a,b,c) extractMaybe3of3 (_,_,Nothing) = Nothing extractMaybe3of3 (a,b,Just c) = Just (a,b,c) data Rectangle = Rectangle Double Double deriving(Show) rectangleInertia :: Double -> Rectangle -> Double rectangleInertia m (Rectangle w h) = 1.0/12.0 * m * (w*w + h*h) data RigidBody = RigidBody { _bodyPosition :: V2 Double , _bodyRotation :: Double , _bodyLinearVelocity :: V2 Double , _bodyAngularVelocity :: Double , _bodyLinearForce :: V2 Double , _bodyTorque :: V2 Double , _bodyMass :: Maybe Double , _bodyShape :: Rectangle } deriving(Show) $(makeLenses ''RigidBody) bodyInertia :: IndexPreservingGetter RigidBody (Maybe Double) bodyInertia = to $ \b -> (\m -> rectangleInertia m (b ^. bodyShape)) <$> (b ^. bodyMass) data Collision = Collision { _collContactPoints :: [V2 Double] , _collNormal :: V2 Double } deriving(Show) $(makeLenses ''Collision) rectanglePoints :: V2 Double -> Double -> Rectangle -> [V2 Double] rectanglePoints (V2 x y) rot (Rectangle w h) = (to2 . (rmatrix !*) . to3) <$> points where hw = w/2 hh = h/2 --points = reverse [V2 (x-hw) (y-hh),V2 (x-hw) (y+hh),V2 (x+hw) (y+hh),V2 (x+hw) (y-hh)] -- FIXME points = [V2 (x-hw) (y-hh),V2 (x-hw) (y+hh),V2 (x+hw) (y+hh),V2 (x+hw) (y-hh)] r00 = cos rot r01 = -(sin rot) r10 = sin rot r11 = cos rot rmatrix = V3 (V3 r00 r01 (x-r00 * x - r01 * y)) (V3 r10 r11 (y - r10 * x - r11 * y)) (V3 0 0 1) to3 (V2 x' y') = V3 x' y' 1 to2 (V3 x' y' _) = V2 x' y' rectangleLines :: V2 Double -> Double -> Rectangle -> [Line (V2 Double)] rectangleLines pos rot rect = zipWith Line <*> (tail . cycle) $ rectanglePoints pos rot rect detectCollision :: RigidBody -> RigidBody -> Maybe Collision detectCollision b1 b2 = msum $ ((uncurry Collision <$>) . extractMaybe1of2) <$> [(fmap return $ lineIntersection 0.001 x y,lineNormal x) | x <- bodyLines b1,y <- bodyLines b2] bodyLines :: RigidBody -> [Line (V2 Double)] bodyLines b1 = rectangleLines (b1 ^. bodyPosition) (b1 ^. bodyRotation) (b1 ^. bodyShape) -- bodyPoints :: RigidBody -> [V2 Double] -- bodyPoints b1 = rectanglePoints (b1 ^. bodyPosition) (b1 ^. bodyRotation) (b1 ^. bodyShape) bodyPoints :: IndexPreservingGetter RigidBody [V2 Double] bodyPoints = to $ \b1 -> rectanglePoints (b1 ^. bodyPosition) (b1 ^. bodyRotation) (b1 ^. bodyShape) screenWidth :: Int screenWidth = 640 screenHeight :: Int screenHeight = 480 data ConsoleMessage = ConsoleMessage { _conMesText :: String , _conMesStart :: TimeTicks } deriving Show $(makeLenses ''ConsoleMessage) data GameStateData = GameStateData { _renderer :: SDLT.Renderer , _font :: TTFFont , _ticks :: TimeTicks , _prevDelta :: TimeDelta , _bodies :: [RigidBody] , _timeMultiplier :: Double , _contactPointSum :: Int , _consoleMessages :: [ConsoleMessage] } $(makeLenses ''GameStateData) type GameState a = StateT GameStateData IO a data TextPosition = LeftTop | LeftBottom | RightTop | RightBottom trimConsoleMessages :: GameState () trimConsoleMessages = do t <- use ticks consoleMessages %= filter (\cm -> t `tickDelta` view conMesStart cm < fromSeconds 0.5) return () textSize :: String -> GameState (V2 Int) textSize s = do f <- use font sizes <- mapM (sizeText f) (lines s) return $ V2 (maximum . map (view _x) $ sizes) (sum . map (view _y) $ sizes) createAndRenderTextRelative :: String -> Color -> TextPosition -> GameState () createAndRenderTextRelative [] _ _ = return () createAndRenderTextRelative text color position = do (V2 width height) <- textSize text let realPosition = case position of LeftTop -> V2 0 0 LeftBottom -> V2 0 (screenHeight - height) RightTop -> V2 (screenWidth - width) 0 RightBottom -> V2 (screenWidth - width) (screenHeight - height) createAndRenderText text color (fromIntegral <$> realPosition) feedbackFold :: Monad m => (a -> b -> m b) -> [a] -> b -> m () feedbackFold _ [] _ = return () feedbackFold f (x:xs) s = f x s >>= feedbackFold f xs createAndRenderText :: String -> Color -> V2 Double -> GameState () createAndRenderText text color position = feedbackFold (createAndRenderSingleLine color) (lines text) (toIntPoint position) createAndRenderSingleLine :: Color -> String -> V2 Int -> GameState (V2 Int) createAndRenderSingleLine _ [] _ = do f <- use font h <- lift $ SDLTtf.getFontHeight f return $ V2 0 h createAndRenderSingleLine color text position = do f <- use font rend <- use renderer texture <- createFontTexture rend f text color size <- sizeText f text lift $ SDLR.renderCopy rend texture Nothing (Just $ SDLRect.Rect (position ^. _x) (position ^. _y) (size ^. _x) (size ^. _y)) destroyTexture texture return (V2 0 ((position + size) ^. _y)) drawBody :: RigidBody -> GameState () drawBody b = do r <- use renderer lift $ mapM_ (drawLine r) ((\(Line x y) -> (floor <$> x,floor <$> y)) <$> bodyLines b) satIntersectsBodies :: RigidBody -> RigidBody -> Maybe (V2 Double) satIntersectsBodies a b = case satIntersects (bodyLines a) (bodyLines b) of Nothing -> Nothing Just p -> Just $ if ((a ^. bodyPosition) - (b ^. bodyPosition)) `dot` p < 0 then p else negate p findSupportPoints :: V2 Double -> [V2 Double] -> [V2 Double] findSupportPoints n vs = let dots = (`dot` n) <$> vs mindot = minimum dots in take 2 . map (view _2) . filter (\(d,_) -> d < mindot + 0.001) $ zip dots vs drawPoint :: V2 Double -> GameState () drawPoint p = do r <- use renderer let o = 3 ls = [ (p + V2 (-o) (-o),p + V2 o (-o)) , (p + V2 o (-o),p + V2 o o) , (p + V2 o o,p + V2 (-o) o) , (p + V2 (-o) o,p + V2 (-o) (-o))] lift $ mapM_ (drawLine r) $ over (traverse . each) toIntPoint ls updateTimeMultiplier :: [Event] -> Double -> Double updateTimeMultiplier es oldTimeMultiplier | any (`isKeydownEvent` LeftControl) es = max 0 $ oldTimeMultiplier - 0.1 | any (`isKeydownEvent` LeftShift) es = oldTimeMultiplier + 0.1 | otherwise = oldTimeMultiplier sdlSetRenderDrawColor :: Color -> GameState () sdlSetRenderDrawColor (Color r g b a) = use renderer >>= \rend -> lift $ SDLR.setRenderDrawColor rend r g b a sdlRenderClear :: GameState () sdlRenderClear = use renderer >>= \rend -> lift $ SDLR.renderClear rend sdlRenderPresent :: GameState () sdlRenderPresent = use renderer >>= \rend -> lift $ SDLR.renderPresent rend data SimulationStep = SimulationStep { _simStepCollPoints :: [V2 Double] , _simStepBodies :: [RigidBody] } $(makeLenses ''SimulationStep) mainLoop :: GameState () mainLoop = do events <- unfoldM (lift pollEvent) oldTicks <- use ticks newTicks <- lift getTicks ticks .= newTicks let delta' = newTicks `tickDelta` oldTicks oldDelta <- use prevDelta oldtm <- use timeMultiplier timeMultiplier %= updateTimeMultiplier events newtm <- use timeMultiplier when (newtm /= oldtm) (consoleMessages %= ([ConsoleMessage ("time changed to " <> show newtm) newTicks] ++)) let delta = fromSeconds $ newtm * toSeconds delta' let (iterations,newDelta) = splitDelta (oldDelta + delta) prevDelta .= newDelta sdlSetRenderDrawColor colorsBlack sdlRenderClear sdlSetRenderDrawColor colorsWhite oldBodies <- use bodies mapM_ drawBody oldBodies mapM_ (lift . print) oldBodies let simulationResult = iterate (simulationStep maxDelta . view simStepBodies) (SimulationStep [] oldBodies) bodies .= view simStepBodies (simulationResult !! iterations) let points = concatMap (view simStepCollPoints) (take (iterations+1) simulationResult) sdlSetRenderDrawColor colorsRed mapM_ drawPoint points contactPointSum += length points cpsum <- use contactPointSum createAndRenderTextRelative ("cps: " <> show cpsum) colorsWhite LeftTop cms <- use consoleMessages createAndRenderTextRelative (unlines . map (view conMesText) $ cms) colorsWhite LeftBottom trimConsoleMessages sdlRenderPresent unless (any isQuitEvent events) mainLoop maxDelta :: TimeDelta maxDelta = fromSeconds 0.01 splitDelta :: TimeDelta -> (Int,TimeDelta) splitDelta n = let iterations = floor $ toSeconds n / toSeconds maxDelta in (iterations,n - fromIntegral iterations * maxDelta) updateBody :: TimeDelta -> RigidBody -> RigidBody updateBody ds b | isJust (b ^. bodyMass) = let d = toSeconds ds la = ((b ^. bodyLinearForce) ^/ fromJust (b ^. bodyMass)) lv = (b ^. bodyLinearVelocity) + la ^* d p = (b ^. bodyPosition) + lv ^* d in b { _bodyLinearVelocity = lv , _bodyPosition = p , _bodyRotation = (b ^. bodyRotation) + d * (b ^. bodyAngularVelocity) } | otherwise = b unorderedPairs :: forall b. [b] -> [(b, b)] unorderedPairs input = let ts = tails input in concat $ zipWith zip (map (cycle . take 1) ts) (drop 1 ts) generateCollisionData :: RigidBody -> RigidBody -> Maybe Collision generateCollisionData a b = satIntersectsBodies a b >>= helper -- where helper n = case findContactPoints (reverse (a ^. bodyPoints)) (reverse (b ^. bodyPoints)) ((-1) *^ n) of where helper n = case findContactPoints (a ^. bodyPoints) (b ^. bodyPoints) n of [] -> Nothing xs -> Just $ Collision xs n --generateCollisionData a b = (\n -> Collision (findContactPoints (a ^. bodyPoints) (b ^. bodyPoints) n) n) <$> satIntersectsBodies a b toV3 :: V2 a -> a -> V3 a toV3 (V2 x y) = V3 x y angularFunction :: V2 Double -> RigidBody -> RigidBody -> V2 Double -> Double -> Double -> (Double, Double) angularFunction cp a b n nom denomb = let angularvf body v = jam * recip (fromJust $ body ^. bodyInertia) * (v `cross` n3) ^. _z jamdf body v = ((v `cross` n3) & _z *~ recip (fromJust $ body ^. bodyInertia)) `cross` v ra = toV3 (cp - a ^. bodyPosition) 0 rb = toV3 (cp - b ^. bodyPosition) 0 jamd1 = jamdf a ra jamd2 = jamdf b rb jamd = denomb + (jamd1 + jamd2) `dot` n3 jam = nom / jamd n3 = toV3 n 0 in (angularvf a ra,angularvf b rb) processCollision :: (Ixed c, IxValue c ~ RigidBody) => ((Index c, RigidBody), (Index c, RigidBody), Collision) -> c -> c processCollision ((ixa,a),(ixb,b),colldata) = let e = 1.0 cps = colldata ^. collContactPoints n = colldata ^. collNormal va = a ^. bodyLinearVelocity vb = b ^. bodyLinearVelocity vab = va - vb ma = fromJust (a ^. bodyMass) mb = fromJust (b ^. bodyMass) nom = ((-1) * (1+e) * (vab `dot` n)) denomb = (n `dot` n) * (recip ma + recip mb) imp = nom / denomb (angularvas,angularvbs) = unzip . map (\cp -> angularFunction cp a b n nom denomb) $ cps newa = a & bodyLinearVelocity +~ (imp / fromJust (a ^. bodyMass)) *^ n & bodyAngularVelocity +~ sum angularvas newb = b & bodyLinearVelocity -~ (imp / fromJust (b ^. bodyMass)) *^ n & bodyAngularVelocity -~ sum angularvbs in (ix ixa .~ newa) . (ix ixb .~ newb) simulationStepSimple :: TimeDelta -> [RigidBody] -> [RigidBody] simulationStepSimple d = map (updateBody d) simulationStep :: TimeDelta -> [RigidBody] -> SimulationStep simulationStep d bs = let stepResult = map (updateBody d) bs collisionResults = mapMaybe (extractMaybe3of3 . (\(l@(_,bl),r@(_,br)) -> (l,r,generateCollisionData bl br))) (unorderedPairs (zip ([0..] :: [Int]) stepResult)) in SimulationStep (concatMap (view (_3 . collContactPoints)) collisionResults) (foldMap Endo (map processCollision collisionResults) `appEndo` stepResult) mediaDir :: FilePath mediaDir = "media" initialBodies :: [RigidBody] initialBodies = [ RigidBody { _bodyPosition = V2 100 100 , _bodyRotation = 0 , _bodyLinearVelocity = V2 10 0 , _bodyAngularVelocity = 0 , _bodyLinearForce = V2 100 0 , _bodyTorque = V2 0 0 , _bodyMass = Just 10 , _bodyShape = Rectangle 100 100 }, RigidBody { _bodyPosition = V2 300 150 , _bodyRotation = 0.5 , _bodyLinearVelocity = V2 0 0 , _bodyAngularVelocity = 0 , _bodyLinearForce = V2 (-100) 0 , _bodyTorque = V2 0 0 , _bodyMass = Just 1 , _bodyShape = Rectangle 100 100 } ] initialGameState :: SDLT.Renderer -> TTFFont -> TimeTicks -> GameStateData initialGameState rend stdFont currentTicks = GameStateData rend stdFont currentTicks (fromSeconds 0) initialBodies 1 0 [] firstCpTest = let [cp1,cp2] = findContactPoints [V2 8 4,V2 14 4,V2 14 9,V2 8 14] [V2 4 2,V2 12 2,V2 12 5,V2 4 5] (V2 0 (-1)) in if cp1 `distance` V2 12 5 > 0.1 || cp2 `distance` V2 8 5 > 0.1 then putStrLn ("Error in test 1: " <> show cp1 <> ", " <> show cp2) >> return False else return True secondCpTest = let [cp1] = findContactPoints (reverse [V2 2 8,V2 5 11,V2 9 7,V2 6 4]) [V2 4 2,V2 4 5,V2 12 5,V2 12 2] (V2 0 (-1)) in if cp1 `distance` V2 6 4 > 0.1 then putStrLn ("Error in test 2: " <> show cp1) >> return False else return True thirdCpTest = let [cp1,cp2] = findContactPoints (reverse [V2 9 4,V2 10 8,V2 14 7,V2 13 3]) [V2 4 2,V2 4 5,V2 12 5,V2 12 2] (V2 (-0.19) (-0.98)) in if cp1 `distance` V2 12 5 > 0.1 || cp2 `distance` V2 9.28 5 > 0.1 then putStrLn ("Error in test 3: " <> show cp1 <> ", " <> show cp2) >> return False else return True gcTest = let Just gd = generateCollisionData testBody1 testBody2 testBody1 = RigidBody { _bodyPosition = V2 271.6679159090139 96.937339727378 , _bodyRotation = 8.327353346932248e-2 , _bodyLinearVelocity = V2 55.54508644587681 (-2.0502524606742365) , _bodyAngularVelocity = 7.142699621333083e-2 , _bodyLinearForce = V2 100 0 , _bodyTorque = V2 0 0 , _bodyMass = Just 10 , _bodyShape = Rectangle 100 100 } testBody2 = RigidBody { _bodyPosition = V2 365.9708409098729 180.626602726224 , _bodyRotation = -0.127302834111011 , _bodyLinearVelocity = V2 49.549135541237824 20.502524606742373 , _bodyAngularVelocity = -0.36039209074250184 , _bodyLinearForce = V2 100 0 , _bodyTorque = V2 0 0 , _bodyMass = Just 10 , _bodyShape = Rectangle 100 100 } in if ((gd ^. collContactPoints) !! 0) `distance` (V2 310.02748096777106 137.37916952622425) > 0.1 || ((gd ^. collContactPoints) !! 1) `distance` (V2 311.7008164411722 150.4526123847951) > 0.1 then putStrLn ("Error in gcTest: " <> show ((gd ^. collContactPoints) !! 0) <> ", " <> show ((gd ^. collContactPoints) !! 1)) >> return False else return True gcTest2 = let Just gd = generateCollisionData testBody1 testBody2 testBody1 = RigidBody { _bodyPosition = V2 211.95905202966665 99.27362428995211 , _bodyRotation = -2.049046059942099e-2 , _bodyLinearVelocity = V2 45.52994180413638 (-1.6701725940347658) , _bodyAngularVelocity = -4.715452921640557e-2 , _bodyLinearForce = V2 100 0 , _bodyTorque = V2 0 0 , _bodyMass = Just 10 , _bodyShape = Rectangle 100 100 } testBody2 = RigidBody { _bodyPosition = V2 313.3194797033412 157.26375710047827 , _bodyRotation = 0.6790267257789174 , _bodyLinearVelocity = V2 30.700581958640683 16.70172594034766 , _bodyAngularVelocity = 0.4124546372446798 , _bodyLinearForce = V2 100 0 , _bodyTorque = V2 0 0 , _bodyMass = Just 10 , _bodyShape = Rectangle 100 100 } in if ((gd ^. collContactPoints) !! 0) `distance` (V2 262.9730072614697 148.23867684386641) > 0.1 then putStrLn ("Error in gcTest: " <> show ((gd ^. collContactPoints) !! 0)) >> return False else return True unitTests :: IO Bool -- unitTests = and <$> sequence [gcTest] unitTests = and <$> sequence [firstCpTest,secondCpTest,thirdCpTest,gcTest,gcTest2] main :: IO () main = do -- testResult <- unitTests -- when testResult $ putStrLn "Tests passed" -- unless testResult $ putStrLn "Tests failed" print $ rectangleLines (V2 150 150) (-1.57) (Rectangle 50 50) {- putStrLn "OLD (12,5) (8,5)" print $ findContactPoints [V2 8 4,V2 14 4,V2 14 9,V2 8 14] [V2 4 2,V2 12 2,V2 12 5,V2 4 5] (V2 0 (-1)) putStrLn "NEW (6,4)" print $ findContactPoints (reverse [V2 2 8,V2 5 11,V2 9 7,V2 6 4]) [V2 4 2,V2 4 5,V2 12 5,V2 12 2] (V2 0 (-1)) putStrLn "NEW 2 (12,5) (9.28,5)" print $ findContactPoints (reverse [V2 9 4,V2 10 8,V2 14 7,V2 13 3]) [V2 4 2,V2 4 5,V2 12 5,V2 12 2] (V2 (-0.19) (-0.98))-} -- print $ generateCollisionData testBody1 testBody2 withFontInit $ withImgInit $ withWindow "racie 0.0.1.1" $ \window -> do currentTicks <- getTicks stdFont <- SDLTtf.openFont (mediaDir </> "font.ttf") 15 withRenderer window screenWidth screenHeight $ \rend -> void $ runStateT mainLoop (initialGameState rend stdFont currentTicks)
pmiddend/physie
src/Physie/Main.hs
mit
23,261
0
18
7,680
7,424
3,938
3,486
405
4
{-# LANGUAGE FlexibleContexts #-} module ProjectEuler.Problem68 ( problem ) where import Control.Monad import Control.Monad.State import Data.Function import Data.List import Petbox import ProjectEuler.Types problem :: Problem problem = pureProblem 68 Solved result {- 5-gon encoding: - the outer ring is a1 a2 a3 a4 a5 - the inner ring is b1 b2 b3 b4 b5 the number-encoding is the string concatenation of: a1 b1 b2; a2 b2 b3; a3 b3 b4; a4 b4 b5; a5 b5 b1 -} pickOne :: [a] -> [ [a] ] pickOne xs = map (take l) . take l . iterate tail $ cycle xs where l = length xs pickOne' :: StateT [a] [] a pickOne' = do (x:xs) <- (lift . pickOne) =<< get put xs return x solutions :: StateT [Int] [] [Int] solutions = do outer@[a1,a2,a3,a4,a5] <- replicateM 5 pickOne' guard $ 10 `elem` outer b1 <- pickOne' b2 <- pickOne' let correctSum = guard . (== a1 + b1 + b2) b3 <- pickOne' correctSum $ a2 + b2 + b3 b4 <- pickOne' correctSum $ a3 + b3 + b4 b5 <- pickOne' correctSum $ a4 + b4 + b5 correctSum $ a5 + b5 + b1 return $ encodeResult [[a1,b1,b2] ,[a2,b2,b3] ,[a3,b3,b4] ,[a4,b4,b5] ,[a5,b5,b1] ] where -- clockwise, lowest external node encodeResult arms = head [ concat enc | enc@(firstArm:restArms) <- pickOne arms , all ((> head firstArm) . head) restArms ] result :: Int result = snd . maximumBy (compare `on` snd) . map (keepInput concatInt) $ evalStateT solutions [1..10] where concatInt :: [Int] -> Int concatInt = read . concatMap show
Javran/Project-Euler
src/ProjectEuler/Problem68.hs
mit
1,817
0
14
646
585
311
274
52
1
module Notations where test :: Int -> Int -> Int test x y = let q | x == 2 && y == -1 = x | y == 0 = -1 | otherwise = quot x y in q * 2 {- -- The goal of this test is to add edits to -- transform the above into something like this: Require Import Coq.ZArith.BinInt. Open Scope bool_scope. Open Scope Z_scope. Definition test(x y: Z) := let q := if (x =? 2) && (y =? -1) then x else if (y =? 0) then -1 else x / y in q * 2. -- The closest I can get so far is Definition test : Z -> Z -> Z := fun x y => let q := if andb (eqb x #2) (eqb y (GHC.Num.negate #1)) : bool then x else if eqb y #0 : bool then GHC.Num.negate #1 else quot x y in mul q #2. -- We need to still get rid of the -- GHC.Num.fromInteger and GHC.Num.negate -- and provide a way to specify notations in the edit file -}
antalsz/hs-to-coq
examples/tests/Notations.hs
mit
893
0
14
294
92
45
47
7
1
module Main where import Control.Applicative import qualified Data.ByteString.Char8 as BC import qualified Data.ByteString.Lazy as L -- import qualified Data.Attoparsec.ByteString.Char8 as P import qualified Data.ByteString.Builder as B import Data.Maybe import Data.Monoid import qualified Data.Map.Strict as Map import qualified Data.Set as Set import qualified Data.Traversable as T import qualified Data.Foldable as F import Text.Printf (printf) import System.Process.Exts import System.Environment -- import FileEntry import FileInfo ------------------------------------------------------------------------ compareContainers :: [Entry] -> [Entry] -> IO () -- (Set.Set (ByteString, ByteString), Set.Set (ByteString, ByteString)) compareContainers c1 c2 = let helper :: Entry -> (ByteString, Entry) helper e = (fromJust . e_checkSum $ e, e) shelper e = (fromJust . e_checkSum $ e, last . BC.split '/' . e_path $ e) importer = Map.fromList . map helper . filter (not . needsChecksum) simporter = Set.fromList . map shelper . filter (not . needsChecksum) m1 = importer c1 m2 = importer c2 s1 = simporter c1 s2 = simporter c2 common = s1 `Set.intersection` s2 sz1 = Set.size s1 sz2 = Set.size s2 szc = Set.size common sA' = Set.map snd $ s1 `Set.difference` common sB' = Set.map snd $ s2 `Set.difference` common sC' = sA' `Set.intersection` sB' in do printf " common: %9d\n" szc printf "unique to A: %9d\n" (sz1 - szc) printf "unique to B: %9d\n" (sz2 - szc) printf "different content, same name in A, B: %d\n" (Set.size sC') mapM_ print . Set.toList $ sC' -- return (s1, s2) compareDirectories :: FilePath -> FilePath -> IO () compareDirectories indexFile1 indexFile2 = do rs1 <- readState' indexFile1 rs2 <- readState' indexFile2 _ <- compareContainers rs1 rs2 return () main :: IO () main = do [i1, i2] <- getArgs compareDirectories i1 i2
mjansen/disk-info
compare-directories.hs
mit
2,092
0
14
526
586
317
269
49
1
{-# LANGUAGE Trustworthy #-} module MIO.Random ( Read(..) , Write(..) , module Control.Monad.Random , module Control.Monad.Trans.Class ) where import qualified System.Random as R import MIO.MIO import MIO.Privileges () import Control.Monad.Random import Control.Monad.Trans.Class class (Monad m) => Write m where getMIORandom :: (R.StdGen -> (a, R.StdGen)) -> m a getMIOGen :: m R.StdGen setMIOGen :: R.StdGen -> m () newMIOGen :: m R.StdGen instance Write (Change s) where getMIORandom a = Change $! \_ -> R.getStdRandom a getMIOGen = Change $! \_ -> R.getStdGen setMIOGen a = Change $! \_ -> R.setStdGen a newMIOGen = Change $! \_ -> R.newStdGen
RTS2013/RTS
server/src/MIO/Random.hs
mit
659
0
11
110
245
140
105
21
0
{-# LANGUAGE CPP #-} {- | Module : Language.Scheme.FFI Copyright : Justin Ethier Licence : MIT (see LICENSE in the distribution) Maintainer : github.com/justinethier Stability : experimental Portability : non-portable (GHC API) This module contains the foreign function interface. -} module Language.Scheme.FFI (evalfuncLoadFFI) where import Language.Scheme.Types import Language.Scheme.Variables import Control.Monad.Error import qualified GHC import qualified GHC.Paths (libdir) import qualified DynFlags import qualified Unsafe.Coerce (unsafeCoerce) -- |Load a Haskell function into husk using the GHC API. evalfuncLoadFFI :: [LispVal] -> IOThrowsError LispVal {- - |Load a Haskell function into husk using the foreign function inteface (FFI) - - Based on example code from: - - http://stackoverflow.com/questions/5521129/importing-a-known-function-from-an-already-compiled-binary-using-ghcs-api-or-hi - and - http://www.bluishcoder.co.nz/2008/11/dynamic-compilation-and-loading-of.html - - - TODO: pass a list of functions to import. Need to make sure this is done in an efficient way - (IE, result as a list that can be processed) -} evalfuncLoadFFI [(Continuation env _ _ _ _), String targetSrcFile, String moduleName, String externalFuncName, String internalFuncName] = do result <- liftIO $ defaultRunGhc $ do dynflags <- GHC.getSessionDynFlags _ <- GHC.setSessionDynFlags dynflags -- let m = GHC.mkModule (GHC.thisPackage dynflags) (GHC.mkModuleName "Test") -- {- TODO: migrate duplicate code into helper functions to drive everything FUTURE: should be able to load multiple functions in one shot (?). -} -- target <- GHC.guessTarget targetSrcFile Nothing GHC.addTarget target r <- GHC.load GHC.LoadAllTargets case r of GHC.Failed -> error "Compilation failed" GHC.Succeeded -> do m <- GHC.findModule (GHC.mkModuleName moduleName) Nothing #if __GLASGOW_HASKELL__ < 700 GHC.setContext [] [m] #elif __GLASGOW_HASKELL__ == 702 -- Fix from dflemstr: -- http://stackoverflow.com/questions/9198140/ghc-api-how-to-dynamically-load-haskell-code-from-a-compiled-module-using-ghc GHC.setContext [] -- import qualified Module [ (GHC.simpleImportDecl . GHC.mkModuleName $ moduleName) {GHC.ideclQualified = True} ] #elif __GLASGOW_HASKELL__ >= 704 GHC.setContext -- import qualified Module [ GHC.IIDecl $ (GHC.simpleImportDecl . GHC.mkModuleName $ moduleName) {GHC.ideclQualified = True} ] #else GHC.setContext [] [(m, Nothing)] #endif fetched <- GHC.compileExpr (moduleName ++ "." ++ externalFuncName) return (Unsafe.Coerce.unsafeCoerce fetched :: [LispVal] -> IOThrowsError LispVal) defineVar env internalFuncName (IOFunc result) -- >>= continueEval env cont -- Overload that loads code from a compiled module evalfuncLoadFFI [(Continuation env _ _ _ _), String moduleName, String externalFuncName, String internalFuncName] = do result <- liftIO $ defaultRunGhc $ do dynflags <- GHC.getSessionDynFlags _ <- GHC.setSessionDynFlags dynflags m <- GHC.findModule (GHC.mkModuleName moduleName) Nothing #if __GLASGOW_HASKELL__ < 700 GHC.setContext [] [m] #elif __GLASGOW_HASKELL__ == 702 -- Fix from dflemstr: -- http://stackoverflow.com/questions/9198140/ghc-api-how-to-dynamically-load-haskell-code-from-a-compiled-module-using-ghc GHC.setContext [] -- import qualified Module [ (GHC.simpleImportDecl . GHC.mkModuleName $ moduleName) {GHC.ideclQualified = True} ] #elif __GLASGOW_HASKELL__ >= 704 GHC.setContext -- import qualified Module [ GHC.IIDecl $ (GHC.simpleImportDecl . GHC.mkModuleName $ moduleName) {GHC.ideclQualified = True} ] #else GHC.setContext [] [(m, Nothing)] #endif fetched <- GHC.compileExpr $ moduleName ++ "." ++ externalFuncName return (Unsafe.Coerce.unsafeCoerce fetched :: [LispVal] -> IOThrowsError LispVal) defineVar env internalFuncName (IOFunc result) -- >>= continueEval env cont evalfuncLoadFFI _ = throwError $ NumArgs (Just 3) [] defaultRunGhc :: GHC.Ghc a -> IO a defaultRunGhc = #if __GLASGOW_HASKELL__ <= 700 -- Old syntax for GHC 7.0.x and lower GHC.defaultErrorHandler DynFlags.defaultDynFlags . GHC.runGhc (Just GHC.Paths.libdir) #elif __GLASGOW_HASKELL__ < 706 -- New syntax in GHC 7.2 GHC.defaultErrorHandler DynFlags.defaultLogAction . GHC.runGhc (Just GHC.Paths.libdir) #else -- New syntax in GHC 7.6 GHC.defaultErrorHandler DynFlags.defaultFatalMessager DynFlags.defaultFlushOut . GHC.runGhc (Just GHC.Paths.libdir) #endif
justinethier/husk-scheme
hs-src/Language/Scheme/FFI.hs
mit
4,932
0
20
1,091
600
307
293
41
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGFECompositeElement (pattern SVG_FECOMPOSITE_OPERATOR_UNKNOWN, pattern SVG_FECOMPOSITE_OPERATOR_OVER, pattern SVG_FECOMPOSITE_OPERATOR_IN, pattern SVG_FECOMPOSITE_OPERATOR_OUT, pattern SVG_FECOMPOSITE_OPERATOR_ATOP, pattern SVG_FECOMPOSITE_OPERATOR_XOR, pattern SVG_FECOMPOSITE_OPERATOR_ARITHMETIC, js_getIn1, getIn1, js_getIn2, getIn2, js_getOperator, getOperator, js_getK1, getK1, js_getK2, getK2, js_getK3, getK3, js_getK4, getK4, SVGFECompositeElement, castToSVGFECompositeElement, gTypeSVGFECompositeElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums pattern SVG_FECOMPOSITE_OPERATOR_UNKNOWN = 0 pattern SVG_FECOMPOSITE_OPERATOR_OVER = 1 pattern SVG_FECOMPOSITE_OPERATOR_IN = 2 pattern SVG_FECOMPOSITE_OPERATOR_OUT = 3 pattern SVG_FECOMPOSITE_OPERATOR_ATOP = 4 pattern SVG_FECOMPOSITE_OPERATOR_XOR = 5 pattern SVG_FECOMPOSITE_OPERATOR_ARITHMETIC = 6 foreign import javascript unsafe "$1[\"in1\"]" js_getIn1 :: JSRef SVGFECompositeElement -> IO (JSRef SVGAnimatedString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFECompositeElement.in1 Mozilla SVGFECompositeElement.in1 documentation> getIn1 :: (MonadIO m) => SVGFECompositeElement -> m (Maybe SVGAnimatedString) getIn1 self = liftIO ((js_getIn1 (unSVGFECompositeElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"in2\"]" js_getIn2 :: JSRef SVGFECompositeElement -> IO (JSRef SVGAnimatedString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFECompositeElement.in2 Mozilla SVGFECompositeElement.in2 documentation> getIn2 :: (MonadIO m) => SVGFECompositeElement -> m (Maybe SVGAnimatedString) getIn2 self = liftIO ((js_getIn2 (unSVGFECompositeElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"operator\"]" js_getOperator :: JSRef SVGFECompositeElement -> IO (JSRef SVGAnimatedEnumeration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFECompositeElement.operator Mozilla SVGFECompositeElement.operator documentation> getOperator :: (MonadIO m) => SVGFECompositeElement -> m (Maybe SVGAnimatedEnumeration) getOperator self = liftIO ((js_getOperator (unSVGFECompositeElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"k1\"]" js_getK1 :: JSRef SVGFECompositeElement -> IO (JSRef SVGAnimatedNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFECompositeElement.k1 Mozilla SVGFECompositeElement.k1 documentation> getK1 :: (MonadIO m) => SVGFECompositeElement -> m (Maybe SVGAnimatedNumber) getK1 self = liftIO ((js_getK1 (unSVGFECompositeElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"k2\"]" js_getK2 :: JSRef SVGFECompositeElement -> IO (JSRef SVGAnimatedNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFECompositeElement.k2 Mozilla SVGFECompositeElement.k2 documentation> getK2 :: (MonadIO m) => SVGFECompositeElement -> m (Maybe SVGAnimatedNumber) getK2 self = liftIO ((js_getK2 (unSVGFECompositeElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"k3\"]" js_getK3 :: JSRef SVGFECompositeElement -> IO (JSRef SVGAnimatedNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFECompositeElement.k3 Mozilla SVGFECompositeElement.k3 documentation> getK3 :: (MonadIO m) => SVGFECompositeElement -> m (Maybe SVGAnimatedNumber) getK3 self = liftIO ((js_getK3 (unSVGFECompositeElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"k4\"]" js_getK4 :: JSRef SVGFECompositeElement -> IO (JSRef SVGAnimatedNumber) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGFECompositeElement.k4 Mozilla SVGFECompositeElement.k4 documentation> getK4 :: (MonadIO m) => SVGFECompositeElement -> m (Maybe SVGAnimatedNumber) getK4 self = liftIO ((js_getK4 (unSVGFECompositeElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGFECompositeElement.hs
mit
4,803
42
11
664
1,032
581
451
78
1
import qualified Data.Vector.Unboxed as V import Data.Int (Int8) import Data.Bits (xor) import Data.Char (digitToInt, intToDigit) initialState :: String initialState = "11100010111110100" diskLength1 :: Int diskLength1 = 272 diskLength2 :: Int diskLength2 = 35651584 -- given a string it returns an equivalent dragon curve makeDragonCurve :: String -> V.Vector Int8 makeDragonCurve = V.fromList . map (fromIntegral . digitToInt) -- given a dragon curve it expands it one step dragonCurve :: V.Vector Int8 -> V.Vector Int8 dragonCurve vec = V.generate (2 * len + 1) helper where len = V.length vec helper p | p < len = vec `V.unsafeIndex` p | p == len = 0 | otherwise = 1 `xor` vec `V.unsafeIndex` (2 * len - p) -- computes the checksum in O(1) space checksum :: V.Vector Int8 -> Int -> String checksum vec len = let -- computes the size of the final output (after all reductions) and -- how many levels of reductions are needed computeLevels :: Int -> Int -> (Int, Int) computeLevels size level | odd size = (size, level) | otherwise = computeLevels (size `quot` 2) (level + 1) (size_final, levels) = computeLevels len 0 -- first argument is the reduction level and second is the position -- if reduction level is 0 it reads directly from the dragon curve -- otherwise it reads positions 2 * p and 2 * p - 1 from the lower -- reduction level and returns 1 if the values are equal, 0 otherwise helper :: Int -> Int -> Int8 helper 0 p = vec `V.unsafeIndex` p helper n p = let b1 = helper (n - 1) (2 * p) b2 = helper (n - 1) (2 * p + 1) in b1 `xor` b2 `xor` 1 in -- for every character of the output compute the value of the highest -- reduction level and convert it to char map (intToDigit . fromIntegral . helper levels) [0..size_final - 1] main :: IO () main = do -- all curves let curves = iterate dragonCurve (makeDragonCurve initialState) -- first curve that fills the first disk let d1 = head . filter ((>= diskLength1) . V.length) $ curves putStrLn $ checksum d1 diskLength1 -- first curve that fills the second disk let d2 = head . filter ((>= diskLength2) . V.length) $ curves putStrLn $ checksum d2 diskLength2
bno1/adventofcode_2016
d16/main.hs
mit
2,420
2
16
690
689
351
338
40
2