code
stringlengths
5
1.03M
repo_name
stringlengths
5
90
path
stringlengths
4
158
license
stringclasses
15 values
size
int64
5
1.03M
n_ast_errors
int64
0
53.9k
ast_max_depth
int64
2
4.17k
n_whitespaces
int64
0
365k
n_ast_nodes
int64
3
317k
n_ast_terminals
int64
1
171k
n_ast_nonterminals
int64
1
146k
loc
int64
-1
37.3k
cycloplexity
int64
-1
1.31k
{-# LANGUAGE CPP, RecordWildCards, GADTs, ScopedTypeVariables, RankNTypes #-} module Main (main) where import GHCi.Run import GHCi.TH import GHCi.Message import GHCi.Signals import GHCi.Utils import Control.DeepSeq import Control.Exception import Control.Monad import Data.Binary import Data.IORef import System.Environment import System.Exit import Text.Printf dieWithUsage :: IO a dieWithUsage = do prog <- getProgName die $ prog ++ ": " ++ msg where #ifdef WINDOWS msg = "usage: iserv <write-handle> <read-handle> [-v]" #else msg = "usage: iserv <write-fd> <read-fd> [-v]" #endif main :: IO () main = do args <- getArgs (wfd1, rfd2, rest) <- case args of arg0:arg1:rest -> do let wfd1 = read arg0 rfd2 = read arg1 return (wfd1, rfd2, rest) _ -> dieWithUsage verbose <- case rest of ["-v"] -> return True [] -> return False _ -> dieWithUsage when verbose $ do printf "GHC iserv starting (in: %d; out: %d)\n" (fromIntegral rfd2 :: Int) (fromIntegral wfd1 :: Int) inh <- getGhcHandle rfd2 outh <- getGhcHandle wfd1 installSignalHandlers lo_ref <- newIORef Nothing let pipe = Pipe{pipeRead = inh, pipeWrite = outh, pipeLeftovers = lo_ref} uninterruptibleMask $ serv verbose pipe -- we cannot allow any async exceptions while communicating, because -- we will lose sync in the protocol, hence uninterruptibleMask. serv :: Bool -> Pipe -> (forall a .IO a -> IO a) -> IO () serv verbose pipe@Pipe{..} restore = loop where loop = do Msg msg <- readPipe pipe getMessage discardCtrlC when verbose $ putStrLn ("iserv: " ++ show msg) case msg of Shutdown -> return () RunTH st q ty loc -> wrapRunTH $ runTH pipe st q ty loc RunModFinalizers st qrefs -> wrapRunTH $ runModFinalizerRefs pipe st qrefs _other -> run msg >>= reply reply :: forall a. (Binary a, Show a) => a -> IO () reply r = do when verbose $ putStrLn ("iserv: return: " ++ show r) writePipe pipe (put r) loop wrapRunTH :: forall a. (Binary a, Show a) => IO a -> IO () wrapRunTH io = do r <- try io case r of Left e | Just (GHCiQException _ err) <- fromException e -> do when verbose $ putStrLn "iserv: QFail" writePipe pipe (putMessage (QFail err)) loop | otherwise -> do when verbose $ putStrLn "iserv: QException" str <- showException e writePipe pipe (putMessage (QException str)) loop Right a -> do when verbose $ putStrLn "iserv: QDone" writePipe pipe (putMessage QDone) reply a -- carefully when showing an exception, there might be other exceptions -- lurking inside it. If so, we return the inner exception instead. showException :: SomeException -> IO String showException e0 = do r <- try $ evaluate (force (show (e0::SomeException))) case r of Left e -> showException e Right str -> return str -- throw away any pending ^C exceptions while we're not running -- interpreted code. GHC will also get the ^C, and either ignore it -- (if this is GHCi), or tell us to quit with a Shutdown message. discardCtrlC = do r <- try $ restore $ return () case r of Left UserInterrupt -> return () >> discardCtrlC Left e -> throwIO e _ -> return ()
GaloisInc/halvm-ghc
iserv/src/Main.hs
bsd-3-clause
3,420
0
19
934
1,034
498
536
89
8
{-# LANGUAGE DataKinds #-} {-# LANGUAGE RecordWildCards #-} module Ivory.Tower.HAL.Bus.Sched ( Task, task, schedule ) where import Control.Monad (forM) import Ivory.Language import Ivory.Stdlib import Ivory.Tower import Ivory.Tower.HAL.Bus.Interface import Ivory.Tower.HAL.Bus.Sched.Internal -- | Multiplex a request/response bus across any number of tasks that -- need to share it. Tasks may submit requests at any time, but only one -- task's request will be submitted to the bus at a time. When that -- request's response arrives, it is forwarded to the appropriate task -- and the next waiting task's request is sent. -- -- If multiple tasks have outstanding requests simultaneously, then this -- component will choose the highest-priority task first. Earlier tasks -- in the list given to 'schedule' are given higher priority. schedule :: (IvoryArea req, IvoryZero req, IvoryArea res, IvoryZero res, IvoryArea ready, IvoryZero ready) => String -> [Task req res] -> ChanOutput ready -> BackpressureTransmit req res -> Tower e () schedule name tasks ready (BackpressureTransmit reqChan resChan) = do let named nm = name ++ "_scheduler_" ++ nm monitor (name ++ "_scheduler") $ do -- Task IDs are either an index into the list of tasks, or one of -- two special values: 'no_task' or 'not_ready_task'. let no_task = 0 let min_task = 1 let max_task = length tasks let not_ready_task = maxBound response_task <- stateInit (named "response_task") $ ival not_ready_task -- Queue up to 1 request per task, which can arrive in any order. states <- forM (zip (map fromIntegral [min_task..max_task]) tasks) $ \ (taskId, taskBase@Task { .. }) -> do taskPending <- state $ (named $ taskName ++ "_pending") taskLastReq <- state $ (named $ taskName ++ "_last_req") handler taskReq (named taskName) $ do sendReq <- emitter reqChan 1 callback $ \ req -> do was_pending <- deref taskPending assert $ iNot was_pending refCopy taskLastReq req store taskPending true current_task <- deref response_task when (current_task ==? no_task) $ do store response_task taskId emit sendReq $ constRef taskLastReq return TaskState { .. } let do_schedule sendReq = do conds <- forM states $ \ TaskState { .. } -> do pend <- deref taskPending return $ (pend ==>) $ do emit sendReq $ constRef taskLastReq store response_task taskId cond_ (conds ++ [true ==> store response_task no_task]) handler ready (named "ready") $ do sendReq <- emitter reqChan 1 callback $ const $ do_schedule sendReq handler resChan (named "response") $ do sendReq <- emitter reqChan 1 emitters <- forM states $ \ st -> do e <- emitter (taskRes $ taskBase st) 1 return (st, e) callback $ \ res -> do current_task <- deref response_task assert $ current_task >=? fromIntegral min_task assert $ current_task <=? fromIntegral max_task cond_ $ do (TaskState { .. }, e) <- emitters return $ (current_task ==? taskId ==>) $ do was_pending <- deref taskPending assert was_pending store taskPending false emit e res do_schedule sendReq
GaloisInc/tower
tower-hal/src/Ivory/Tower/HAL/Bus/Sched.hs
bsd-3-clause
3,430
0
26
932
884
426
458
66
1
--------------------------------------------------------- ------ Module : Network.LifeRaft.Raft ---- Copyright : (c) 2015 Yahoo, Inc. ---- License : BSD3 ---- Maintainer : Dennis J. McWherter, Jr. ([email protected]) ---- Stability : Experimental ---- Portability : non-portable ---- ---- Hlint configuration for build process ---- ----------------------------------------------------------- module Main (main) where import Language.Haskell.HLint (hlint) import System.Exit (exitFailure, exitSuccess) arguments :: [String] arguments = [ "app" , "src" --, "test" -- Eventually... ] main :: IO () main = do hints <- hlint arguments if null hints then exitSuccess else exitFailure
DeathByTape/LifeRaft
test/HLint.hs
bsd-3-clause
931
0
8
332
102
63
39
11
2
-- | -- Copyright : (c) Sam Truzjan 2013 -- License : BSD3 -- Maintainer : [email protected] -- Stability : stable -- Portability : portable -- -- Efficient encoding and decoding of base32 encoded bytestring -- according to RFC 4648. <http://tools.ietf.org/html/rfc4648> -- -- This module recommended to be imported as -- @import Data.ByteString.Base32 as Base32@ to avoid name clashes -- with @Data.Binary@ or @Data.ByteString.Base64@ modules. -- {-# LANGUAGE BangPatterns #-} module Data.ByteString.Base32 ( Base32 , encode , decode , decodeLenient ) where import Data.ByteString as BS import Data.ByteString.Base32.Internal import Data.List as L -- | Base32 encoded bytestring. type Base32 = ByteString encW5 :: Word5 -> Word8 encW5 !x | x <= 25 = 65 + x | otherwise = 24 + x {-# INLINE encW5 #-} encTable :: EncTable encTable = BS.pack $ L.map encW5 [0..31] -- | Encode an arbitrary bytestring into (upper case) base32 form. encode :: ByteString -> Base32 encode = unpack5 encTable decW5 :: Word8 -> Word5 decW5 !x | x < 50 {- c2w '2' -} = invIx | x <= 55 {- c2w '7' -} = x - 24 {- c2w '2' - 26 -} | x < 65 {- c2w 'A' -} = invIx | x <= 90 {- c2w 'Z' -} = x - 65 {- c2w 'A' -} | x < 97 {- c2w 'a' -} = invIx | x <= 122 {- c2w 'z' -} = x - 97 {- c2w 'a' -} | otherwise = invIx {-# INLINE decW5 #-} decTable :: ByteString decTable = BS.pack $ L.map decW5 [minBound .. maxBound] -- | Decode a base32 encoded bytestring. This functions is -- case-insensitive and do not require correct padding. decode :: Base32 -> Either String ByteString decode = pack5 decTable -- | The same as 'decode' but with additional leniency: decodeLenient -- will skip non-alphabet characters. decodeLenient :: Base32 -> Either String ByteString decodeLenient = pack5Lenient decTable
pxqr/base32-bytestring
src/Data/ByteString/Base32.hs
bsd-3-clause
1,868
0
8
425
357
201
156
35
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 \section[TcBinds]{TcBinds} -} {-# LANGUAGE CPP, RankNTypes, ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} module TcBinds ( tcLocalBinds, tcTopBinds, tcRecSelBinds, tcHsBootSigs, tcPolyCheck, tcVectDecls, addTypecheckedBinds, chooseInferredQuantifiers, badBootDeclErr ) where import GhcPrelude import {-# SOURCE #-} TcMatches ( tcGRHSsPat, tcMatchesFun ) import {-# SOURCE #-} TcExpr ( tcMonoExpr ) import {-# SOURCE #-} TcPatSyn ( tcInferPatSynDecl, tcCheckPatSynDecl , tcPatSynBuilderBind ) import CoreSyn (Tickish (..)) import CostCentre (mkUserCC) import DynFlags import FastString import HsSyn import HscTypes( isHsBootOrSig ) import TcSigs import TcRnMonad import TcEnv import TcUnify import TcSimplify import TcEvidence import TcHsType import TcPat import TcMType import FamInstEnv( normaliseType ) import FamInst( tcGetFamInstEnvs ) import TyCon import TcType import Type( mkStrLitTy, tidyOpenType, splitTyConApp_maybe) import TysPrim import TysWiredIn( mkBoxedTupleTy ) import Id import Var import VarSet import VarEnv( TidyEnv ) import Module import Name import NameSet import NameEnv import SrcLoc import Bag import ListSetOps import ErrUtils import Digraph import Maybes import Util import BasicTypes import Outputable import PrelNames( ipClassName ) import TcValidity (checkValidType) import Unique (getUnique) import UniqFM import UniqSet import qualified GHC.LanguageExtensions as LangExt import ConLike import Control.Monad import Data.List.NonEmpty ( NonEmpty(..) ) #include "HsVersions.h" {- ********************************************************************* * * A useful helper function * * ********************************************************************* -} addTypecheckedBinds :: TcGblEnv -> [LHsBinds GhcTc] -> TcGblEnv addTypecheckedBinds tcg_env binds | isHsBootOrSig (tcg_src tcg_env) = tcg_env -- Do not add the code for record-selector bindings -- when compiling hs-boot files | otherwise = tcg_env { tcg_binds = foldr unionBags (tcg_binds tcg_env) binds } {- ************************************************************************ * * \subsection{Type-checking bindings} * * ************************************************************************ @tcBindsAndThen@ typechecks a @HsBinds@. The "and then" part is because it needs to know something about the {\em usage} of the things bound, so that it can create specialisations of them. So @tcBindsAndThen@ takes a function which, given an extended environment, E, typechecks the scope of the bindings returning a typechecked thing and (most important) an LIE. It is this LIE which is then used as the basis for specialising the things bound. @tcBindsAndThen@ also takes a "combiner" which glues together the bindings and the "thing" to make a new "thing". The real work is done by @tcBindWithSigsAndThen@. Recursive and non-recursive binds are handled in essentially the same way: because of uniques there are no scoping issues left. The only difference is that non-recursive bindings can bind primitive values. Even for non-recursive binding groups we add typings for each binder to the LVE for the following reason. When each individual binding is checked the type of its LHS is unified with that of its RHS; and type-checking the LHS of course requires that the binder is in scope. At the top-level the LIE is sure to contain nothing but constant dictionaries, which we resolve at the module level. Note [Polymorphic recursion] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ The game plan for polymorphic recursion in the code above is * Bind any variable for which we have a type signature to an Id with a polymorphic type. Then when type-checking the RHSs we'll make a full polymorphic call. This fine, but if you aren't a bit careful you end up with a horrendous amount of partial application and (worse) a huge space leak. For example: f :: Eq a => [a] -> [a] f xs = ...f... If we don't take care, after typechecking we get f = /\a -> \d::Eq a -> let f' = f a d in \ys:[a] -> ...f'... Notice the the stupid construction of (f a d), which is of course identical to the function we're executing. In this case, the polymorphic recursion isn't being used (but that's a very common case). This can lead to a massive space leak, from the following top-level defn (post-typechecking) ff :: [Int] -> [Int] ff = f Int dEqInt Now (f dEqInt) evaluates to a lambda that has f' as a free variable; but f' is another thunk which evaluates to the same thing... and you end up with a chain of identical values all hung onto by the CAF ff. ff = f Int dEqInt = let f' = f Int dEqInt in \ys. ...f'... = let f' = let f' = f Int dEqInt in \ys. ...f'... in \ys. ...f'... Etc. NOTE: a bit of arity anaysis would push the (f a d) inside the (\ys...), which would make the space leak go away in this case Solution: when typechecking the RHSs we always have in hand the *monomorphic* Ids for each binding. So we just need to make sure that if (Method f a d) shows up in the constraints emerging from (...f...) we just use the monomorphic Id. We achieve this by adding monomorphic Ids to the "givens" when simplifying constraints. That's what the "lies_avail" is doing. Then we get f = /\a -> \d::Eq a -> letrec fm = \ys:[a] -> ...fm... in fm -} tcTopBinds :: [(RecFlag, LHsBinds GhcRn)] -> [LSig GhcRn] -> TcM (TcGblEnv, TcLclEnv) -- The TcGblEnv contains the new tcg_binds and tcg_spects -- The TcLclEnv has an extended type envt for the new bindings tcTopBinds binds sigs = do { -- Pattern synonym bindings populate the global environment (binds', (tcg_env, tcl_env)) <- tcValBinds TopLevel binds sigs $ do { gbl <- getGblEnv ; lcl <- getLclEnv ; return (gbl, lcl) } ; specs <- tcImpPrags sigs -- SPECIALISE prags for imported Ids ; complete_matches <- setEnvs (tcg_env, tcl_env) $ tcCompleteSigs sigs ; traceTc "complete_matches" (ppr binds $$ ppr sigs) ; traceTc "complete_matches" (ppr complete_matches) ; let { tcg_env' = tcg_env { tcg_imp_specs = specs ++ tcg_imp_specs tcg_env , tcg_complete_matches = complete_matches ++ tcg_complete_matches tcg_env } `addTypecheckedBinds` map snd binds' } ; return (tcg_env', tcl_env) } -- The top level bindings are flattened into a giant -- implicitly-mutually-recursive LHsBinds -- Note [Typechecking Complete Matches] -- Much like when a user bundled a pattern synonym, the result types of -- all the constructors in the match pragma must be consistent. -- -- If we allowed pragmas with inconsistent types then it would be -- impossible to ever match every constructor in the list and so -- the pragma would be useless. -- This is only used in `tcCompleteSig`. We fold over all the conlikes, -- this accumulator keeps track of the first `ConLike` with a concrete -- return type. After fixing the return type, all other constructors with -- a fixed return type must agree with this. -- -- The fields of `Fixed` cache the first conlike and its return type so -- that that we can compare all the other conlikes to it. The conlike is -- stored for error messages. -- -- `Nothing` in the case that the type is fixed by a type signature data CompleteSigType = AcceptAny | Fixed (Maybe ConLike) TyCon tcCompleteSigs :: [LSig GhcRn] -> TcM [CompleteMatch] tcCompleteSigs sigs = let doOne :: Sig GhcRn -> TcM (Maybe CompleteMatch) doOne c@(CompleteMatchSig _ lns mtc) = fmap Just $ do addErrCtxt (text "In" <+> ppr c) $ case mtc of Nothing -> infer_complete_match Just tc -> check_complete_match tc where checkCLTypes acc = foldM checkCLType (acc, []) (unLoc lns) infer_complete_match = do (res, cls) <- checkCLTypes AcceptAny case res of AcceptAny -> failWithTc ambiguousError Fixed _ tc -> return $ mkMatch cls tc check_complete_match tc_name = do ty_con <- tcLookupLocatedTyCon tc_name (_, cls) <- checkCLTypes (Fixed Nothing ty_con) return $ mkMatch cls ty_con mkMatch :: [ConLike] -> TyCon -> CompleteMatch mkMatch cls ty_con = CompleteMatch { completeMatchConLikes = map conLikeName cls, completeMatchTyCon = tyConName ty_con } doOne _ = return Nothing ambiguousError :: SDoc ambiguousError = text "A type signature must be provided for a set of polymorphic" <+> text "pattern synonyms." -- See note [Typechecking Complete Matches] checkCLType :: (CompleteSigType, [ConLike]) -> Located Name -> TcM (CompleteSigType, [ConLike]) checkCLType (cst, cs) n = do cl <- addLocM tcLookupConLike n let (_,_,_,_,_,_, res_ty) = conLikeFullSig cl res_ty_con = fst <$> splitTyConApp_maybe res_ty case (cst, res_ty_con) of (AcceptAny, Nothing) -> return (AcceptAny, cl:cs) (AcceptAny, Just tc) -> return (Fixed (Just cl) tc, cl:cs) (Fixed mfcl tc, Nothing) -> return (Fixed mfcl tc, cl:cs) (Fixed mfcl tc, Just tc') -> if tc == tc' then return (Fixed mfcl tc, cl:cs) else case mfcl of Nothing -> addErrCtxt (text "In" <+> ppr cl) $ failWithTc typeSigErrMsg Just cl -> failWithTc (errMsg cl) where typeSigErrMsg :: SDoc typeSigErrMsg = text "Couldn't match expected type" <+> quotes (ppr tc) <+> text "with" <+> quotes (ppr tc') errMsg :: ConLike -> SDoc errMsg fcl = text "Cannot form a group of complete patterns from patterns" <+> quotes (ppr fcl) <+> text "and" <+> quotes (ppr cl) <+> text "as they match different type constructors" <+> parens (quotes (ppr tc) <+> text "resp." <+> quotes (ppr tc')) in mapMaybeM (addLocM doOne) sigs tcRecSelBinds :: HsValBinds GhcRn -> TcM TcGblEnv tcRecSelBinds (ValBindsOut binds sigs) = tcExtendGlobalValEnv [sel_id | L _ (IdSig sel_id) <- sigs] $ do { (rec_sel_binds, tcg_env) <- discardWarnings $ tcValBinds TopLevel binds sigs getGblEnv ; let tcg_env' = tcg_env `addTypecheckedBinds` map snd rec_sel_binds ; return tcg_env' } tcRecSelBinds (ValBindsIn {}) = panic "tcRecSelBinds" tcHsBootSigs :: [(RecFlag, LHsBinds GhcRn)] -> [LSig GhcRn] -> TcM [Id] -- A hs-boot file has only one BindGroup, and it only has type -- signatures in it. The renamer checked all this tcHsBootSigs binds sigs = do { checkTc (null binds) badBootDeclErr ; concat <$> mapM (addLocM tc_boot_sig) (filter isTypeLSig sigs) } where tc_boot_sig (TypeSig lnames hs_ty) = mapM f lnames where f (L _ name) = do { sigma_ty <- tcHsSigWcType (FunSigCtxt name False) hs_ty ; return (mkVanillaGlobal name sigma_ty) } -- Notice that we make GlobalIds, not LocalIds tc_boot_sig s = pprPanic "tcHsBootSigs/tc_boot_sig" (ppr s) badBootDeclErr :: MsgDoc badBootDeclErr = text "Illegal declarations in an hs-boot file" ------------------------ tcLocalBinds :: HsLocalBinds GhcRn -> TcM thing -> TcM (HsLocalBinds GhcTcId, thing) tcLocalBinds EmptyLocalBinds thing_inside = do { thing <- thing_inside ; return (EmptyLocalBinds, thing) } tcLocalBinds (HsValBinds (ValBindsOut binds sigs)) thing_inside = do { (binds', thing) <- tcValBinds NotTopLevel binds sigs thing_inside ; return (HsValBinds (ValBindsOut binds' sigs), thing) } tcLocalBinds (HsValBinds (ValBindsIn {})) _ = panic "tcLocalBinds" tcLocalBinds (HsIPBinds (IPBinds ip_binds _)) thing_inside = do { ipClass <- tcLookupClass ipClassName ; (given_ips, ip_binds') <- mapAndUnzipM (wrapLocSndM (tc_ip_bind ipClass)) ip_binds -- If the binding binds ?x = E, we must now -- discharge any ?x constraints in expr_lie -- See Note [Implicit parameter untouchables] ; (ev_binds, result) <- checkConstraints (IPSkol ips) [] given_ips thing_inside ; return (HsIPBinds (IPBinds ip_binds' ev_binds), result) } where ips = [ip | L _ (IPBind (Left (L _ ip)) _) <- ip_binds] -- I wonder if we should do these one at at time -- Consider ?x = 4 -- ?y = ?x + 1 tc_ip_bind ipClass (IPBind (Left (L _ ip)) expr) = do { ty <- newOpenFlexiTyVarTy ; let p = mkStrLitTy $ hsIPNameFS ip ; ip_id <- newDict ipClass [ p, ty ] ; expr' <- tcMonoExpr expr (mkCheckExpType ty) ; let d = toDict ipClass p ty `fmap` expr' ; return (ip_id, (IPBind (Right ip_id) d)) } tc_ip_bind _ (IPBind (Right {}) _) = panic "tc_ip_bind" -- Coerces a `t` into a dictionry for `IP "x" t`. -- co : t -> IP "x" t toDict ipClass x ty = mkHsWrap $ mkWpCastR $ wrapIP $ mkClassPred ipClass [x,ty] {- Note [Implicit parameter untouchables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We add the type variables in the types of the implicit parameters as untouchables, not so much because we really must not unify them, but rather because we otherwise end up with constraints like this Num alpha, Implic { wanted = alpha ~ Int } The constraint solver solves alpha~Int by unification, but then doesn't float that solved constraint out (it's not an unsolved wanted). Result disaster: the (Num alpha) is again solved, this time by defaulting. No no no. However [Oct 10] this is all handled automatically by the untouchable-range idea. -} tcValBinds :: TopLevelFlag -> [(RecFlag, LHsBinds GhcRn)] -> [LSig GhcRn] -> TcM thing -> TcM ([(RecFlag, LHsBinds GhcTcId)], thing) tcValBinds top_lvl binds sigs thing_inside = do { let patsyns = getPatSynBinds binds -- Typecheck the signature ; (poly_ids, sig_fn) <- tcAddPatSynPlaceholders patsyns $ tcTySigs sigs ; let prag_fn = mkPragEnv sigs (foldr (unionBags . snd) emptyBag binds) -- Extend the envt right away with all the Ids -- declared with complete type signatures -- Do not extend the TcBinderStack; instead -- we extend it on a per-rhs basis in tcExtendForRhs ; tcExtendSigIds top_lvl poly_ids $ do { (binds', (extra_binds', thing)) <- tcBindGroups top_lvl sig_fn prag_fn binds $ do { thing <- thing_inside -- See Note [Pattern synonym builders don't yield dependencies] -- in RnBinds ; patsyn_builders <- mapM tcPatSynBuilderBind patsyns ; let extra_binds = [ (NonRecursive, builder) | builder <- patsyn_builders ] ; return (extra_binds, thing) } ; return (binds' ++ extra_binds', thing) }} ------------------------ tcBindGroups :: TopLevelFlag -> TcSigFun -> TcPragEnv -> [(RecFlag, LHsBinds GhcRn)] -> TcM thing -> TcM ([(RecFlag, LHsBinds GhcTcId)], thing) -- Typecheck a whole lot of value bindings, -- one strongly-connected component at a time -- Here a "strongly connected component" has the strightforward -- meaning of a group of bindings that mention each other, -- ignoring type signatures (that part comes later) tcBindGroups _ _ _ [] thing_inside = do { thing <- thing_inside ; return ([], thing) } tcBindGroups top_lvl sig_fn prag_fn (group : groups) thing_inside = do { -- See Note [Closed binder groups] type_env <- getLclTypeEnv ; let closed = isClosedBndrGroup type_env (snd group) ; (group', (groups', thing)) <- tc_group top_lvl sig_fn prag_fn group closed $ tcBindGroups top_lvl sig_fn prag_fn groups thing_inside ; return (group' ++ groups', thing) } -- Note [Closed binder groups] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- -- A mutually recursive group is "closed" if all of the free variables of -- the bindings are closed. For example -- -- > h = \x -> let f = ...g... -- > g = ....f...x... -- > in ... -- -- Here @g@ is not closed because it mentions @x@; and hence neither is @f@ -- closed. -- -- So we need to compute closed-ness on each strongly connected components, -- before we sub-divide it based on what type signatures it has. -- ------------------------ tc_group :: forall thing. TopLevelFlag -> TcSigFun -> TcPragEnv -> (RecFlag, LHsBinds GhcRn) -> IsGroupClosed -> TcM thing -> TcM ([(RecFlag, LHsBinds GhcTcId)], thing) -- Typecheck one strongly-connected component of the original program. -- We get a list of groups back, because there may -- be specialisations etc as well tc_group top_lvl sig_fn prag_fn (NonRecursive, binds) closed thing_inside -- A single non-recursive binding -- We want to keep non-recursive things non-recursive -- so that we desugar unlifted bindings correctly = do { let bind = case bagToList binds of [bind] -> bind [] -> panic "tc_group: empty list of binds" _ -> panic "tc_group: NonRecursive binds is not a singleton bag" ; (bind', thing) <- tc_single top_lvl sig_fn prag_fn bind closed thing_inside ; return ( [(NonRecursive, bind')], thing) } tc_group top_lvl sig_fn prag_fn (Recursive, binds) closed thing_inside = -- To maximise polymorphism, we do a new -- strongly-connected-component analysis, this time omitting -- any references to variables with type signatures. -- (This used to be optional, but isn't now.) -- See Note [Polymorphic recursion] in HsBinds. do { traceTc "tc_group rec" (pprLHsBinds binds) ; when hasPatSyn $ recursivePatSynErr binds ; (binds1, thing) <- go sccs ; return ([(Recursive, binds1)], thing) } -- Rec them all together where hasPatSyn = anyBag (isPatSyn . unLoc) binds isPatSyn PatSynBind{} = True isPatSyn _ = False sccs :: [SCC (LHsBind GhcRn)] sccs = stronglyConnCompFromEdgedVerticesUniq (mkEdges sig_fn binds) go :: [SCC (LHsBind GhcRn)] -> TcM (LHsBinds GhcTcId, thing) go (scc:sccs) = do { (binds1, ids1) <- tc_scc scc ; (binds2, thing) <- tcExtendLetEnv top_lvl sig_fn closed ids1 $ go sccs ; return (binds1 `unionBags` binds2, thing) } go [] = do { thing <- thing_inside; return (emptyBag, thing) } tc_scc (AcyclicSCC bind) = tc_sub_group NonRecursive [bind] tc_scc (CyclicSCC binds) = tc_sub_group Recursive binds tc_sub_group rec_tc binds = tcPolyBinds sig_fn prag_fn Recursive rec_tc closed binds recursivePatSynErr :: OutputableBndrId name => LHsBinds name -> TcM a recursivePatSynErr binds = failWithTc $ hang (text "Recursive pattern synonym definition with following bindings:") 2 (vcat $ map pprLBind . bagToList $ binds) where pprLoc loc = parens (text "defined at" <+> ppr loc) pprLBind (L loc bind) = pprWithCommas ppr (collectHsBindBinders bind) <+> pprLoc loc tc_single :: forall thing. TopLevelFlag -> TcSigFun -> TcPragEnv -> LHsBind GhcRn -> IsGroupClosed -> TcM thing -> TcM (LHsBinds GhcTcId, thing) tc_single _top_lvl sig_fn _prag_fn (L _ (PatSynBind psb@PSB{ psb_id = L _ name })) _ thing_inside = do { (aux_binds, tcg_env) <- tc_pat_syn_decl ; thing <- setGblEnv tcg_env thing_inside ; return (aux_binds, thing) } where tc_pat_syn_decl :: TcM (LHsBinds GhcTcId, TcGblEnv) tc_pat_syn_decl = case sig_fn name of Nothing -> tcInferPatSynDecl psb Just (TcPatSynSig tpsi) -> tcCheckPatSynDecl psb tpsi Just _ -> panic "tc_single" tc_single top_lvl sig_fn prag_fn lbind closed thing_inside = do { (binds1, ids) <- tcPolyBinds sig_fn prag_fn NonRecursive NonRecursive closed [lbind] ; thing <- tcExtendLetEnv top_lvl sig_fn closed ids thing_inside ; return (binds1, thing) } ------------------------ type BKey = Int -- Just number off the bindings mkEdges :: TcSigFun -> LHsBinds GhcRn -> [Node BKey (LHsBind GhcRn)] -- See Note [Polymorphic recursion] in HsBinds. mkEdges sig_fn binds = [ DigraphNode bind key [key | n <- nonDetEltsUniqSet (bind_fvs (unLoc bind)), Just key <- [lookupNameEnv key_map n], no_sig n ] | (bind, key) <- keyd_binds ] -- It's OK to use nonDetEltsUFM here as stronglyConnCompFromEdgedVertices -- is still deterministic even if the edges are in nondeterministic order -- as explained in Note [Deterministic SCC] in Digraph. where no_sig :: Name -> Bool no_sig n = not (hasCompleteSig sig_fn n) keyd_binds = bagToList binds `zip` [0::BKey ..] key_map :: NameEnv BKey -- Which binding it comes from key_map = mkNameEnv [(bndr, key) | (L _ bind, key) <- keyd_binds , bndr <- collectHsBindBinders bind ] ------------------------ tcPolyBinds :: TcSigFun -> TcPragEnv -> RecFlag -- Whether the group is really recursive -> RecFlag -- Whether it's recursive after breaking -- dependencies based on type signatures -> IsGroupClosed -- Whether the group is closed -> [LHsBind GhcRn] -- None are PatSynBind -> TcM (LHsBinds GhcTcId, [TcId]) -- Typechecks a single bunch of values bindings all together, -- and generalises them. The bunch may be only part of a recursive -- group, because we use type signatures to maximise polymorphism -- -- Returns a list because the input may be a single non-recursive binding, -- in which case the dependency order of the resulting bindings is -- important. -- -- Knows nothing about the scope of the bindings -- None of the bindings are pattern synonyms tcPolyBinds sig_fn prag_fn rec_group rec_tc closed bind_list = setSrcSpan loc $ recoverM (recoveryCode binder_names sig_fn) $ do -- Set up main recover; take advantage of any type sigs { traceTc "------------------------------------------------" Outputable.empty ; traceTc "Bindings for {" (ppr binder_names) ; dflags <- getDynFlags ; let plan = decideGeneralisationPlan dflags bind_list closed sig_fn ; traceTc "Generalisation plan" (ppr plan) ; result@(_, poly_ids) <- case plan of NoGen -> tcPolyNoGen rec_tc prag_fn sig_fn bind_list InferGen mn -> tcPolyInfer rec_tc prag_fn sig_fn mn bind_list CheckGen lbind sig -> tcPolyCheck prag_fn sig lbind ; traceTc "} End of bindings for" (vcat [ ppr binder_names, ppr rec_group , vcat [ppr id <+> ppr (idType id) | id <- poly_ids] ]) ; return result } where binder_names = collectHsBindListBinders bind_list loc = foldr1 combineSrcSpans (map getLoc bind_list) -- The mbinds have been dependency analysed and -- may no longer be adjacent; so find the narrowest -- span that includes them all -------------- -- If typechecking the binds fails, then return with each -- signature-less binder given type (forall a.a), to minimise -- subsequent error messages recoveryCode :: [Name] -> TcSigFun -> TcM (LHsBinds GhcTcId, [Id]) recoveryCode binder_names sig_fn = do { traceTc "tcBindsWithSigs: error recovery" (ppr binder_names) ; let poly_ids = map mk_dummy binder_names ; return (emptyBag, poly_ids) } where mk_dummy name | Just sig <- sig_fn name , Just poly_id <- completeSigPolyId_maybe sig = poly_id | otherwise = mkLocalId name forall_a_a forall_a_a :: TcType forall_a_a = mkSpecForAllTys [runtimeRep1TyVar, openAlphaTyVar] openAlphaTy {- ********************************************************************* * * tcPolyNoGen * * ********************************************************************* -} tcPolyNoGen -- No generalisation whatsoever :: RecFlag -- Whether it's recursive after breaking -- dependencies based on type signatures -> TcPragEnv -> TcSigFun -> [LHsBind GhcRn] -> TcM (LHsBinds GhcTcId, [TcId]) tcPolyNoGen rec_tc prag_fn tc_sig_fn bind_list = do { (binds', mono_infos) <- tcMonoBinds rec_tc tc_sig_fn (LetGblBndr prag_fn) bind_list ; mono_ids' <- mapM tc_mono_info mono_infos ; return (binds', mono_ids') } where tc_mono_info (MBI { mbi_poly_name = name, mbi_mono_id = mono_id }) = do { _specs <- tcSpecPrags mono_id (lookupPragEnv prag_fn name) ; return mono_id } -- NB: tcPrags generates error messages for -- specialisation pragmas for non-overloaded sigs -- Indeed that is why we call it here! -- So we can safely ignore _specs {- ********************************************************************* * * tcPolyCheck * * ********************************************************************* -} tcPolyCheck :: TcPragEnv -> TcIdSigInfo -- Must be a complete signature -> LHsBind GhcRn -- Must be a FunBind -> TcM (LHsBinds GhcTcId, [TcId]) -- There is just one binding, -- it is a Funbind -- it has a complete type signature, tcPolyCheck prag_fn (CompleteSig { sig_bndr = poly_id , sig_ctxt = ctxt , sig_loc = sig_loc }) (L loc (FunBind { fun_id = L nm_loc name , fun_matches = matches })) = setSrcSpan sig_loc $ do { traceTc "tcPolyCheck" (ppr poly_id $$ ppr sig_loc) ; (tv_prs, theta, tau) <- tcInstType tcInstSkolTyVars poly_id -- See Note [Instantiate sig with fresh variables] ; mono_name <- newNameAt (nameOccName name) nm_loc ; ev_vars <- newEvVars theta ; let mono_id = mkLocalId mono_name tau skol_info = SigSkol ctxt (idType poly_id) tv_prs skol_tvs = map snd tv_prs ; (ev_binds, (co_fn, matches')) <- checkConstraints skol_info skol_tvs ev_vars $ tcExtendBinderStack [TcIdBndr mono_id NotTopLevel] $ tcExtendTyVarEnv2 tv_prs $ setSrcSpan loc $ tcMatchesFun (L nm_loc mono_name) matches (mkCheckExpType tau) ; let prag_sigs = lookupPragEnv prag_fn name ; spec_prags <- tcSpecPrags poly_id prag_sigs ; poly_id <- addInlinePrags poly_id prag_sigs ; mod <- getModule ; let bind' = FunBind { fun_id = L nm_loc mono_id , fun_matches = matches' , fun_co_fn = co_fn , bind_fvs = placeHolderNamesTc , fun_tick = funBindTicks nm_loc mono_id mod prag_sigs } export = ABE { abe_wrap = idHsWrapper , abe_poly = poly_id , abe_mono = mono_id , abe_prags = SpecPrags spec_prags } abs_bind = L loc $ AbsBinds { abs_tvs = skol_tvs , abs_ev_vars = ev_vars , abs_ev_binds = [ev_binds] , abs_exports = [export] , abs_binds = unitBag (L loc bind') , abs_sig = True } ; return (unitBag abs_bind, [poly_id]) } tcPolyCheck _prag_fn sig bind = pprPanic "tcPolyCheck" (ppr sig $$ ppr bind) funBindTicks :: SrcSpan -> TcId -> Module -> [LSig GhcRn] -> [Tickish TcId] funBindTicks loc fun_id mod sigs | (mb_cc_str : _) <- [ cc_name | L _ (SCCFunSig _ _ cc_name) <- sigs ] -- this can only be a singleton list, as duplicate pragmas are rejected -- by the renamer , let cc_str | Just cc_str <- mb_cc_str = sl_fs $ unLoc cc_str | otherwise = getOccFS (Var.varName fun_id) cc_name = moduleNameFS (moduleName mod) `appendFS` consFS '.' cc_str cc = mkUserCC cc_name mod loc (getUnique fun_id) = [ProfNote cc True True] | otherwise = [] {- Note [Instantiate sig with fresh variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It's vital to instantiate a type signature with fresh variables. For example: type T = forall a. [a] -> [a] f :: T; f = g where { g :: T; g = <rhs> } We must not use the same 'a' from the defn of T at both places!! (Instantiation is only necessary because of type synonyms. Otherwise, it's all cool; each signature has distinct type variables from the renamer.) -} {- ********************************************************************* * * tcPolyInfer * * ********************************************************************* -} tcPolyInfer :: RecFlag -- Whether it's recursive after breaking -- dependencies based on type signatures -> TcPragEnv -> TcSigFun -> Bool -- True <=> apply the monomorphism restriction -> [LHsBind GhcRn] -> TcM (LHsBinds GhcTcId, [TcId]) tcPolyInfer rec_tc prag_fn tc_sig_fn mono bind_list = do { (tclvl, wanted, (binds', mono_infos)) <- pushLevelAndCaptureConstraints $ tcMonoBinds rec_tc tc_sig_fn LetLclBndr bind_list ; let name_taus = [ (mbi_poly_name info, idType (mbi_mono_id info)) | info <- mono_infos ] sigs = [ sig | MBI { mbi_sig = Just sig } <- mono_infos ] infer_mode = if mono then ApplyMR else NoRestrictions ; mapM_ (checkOverloadedSig mono) sigs ; traceTc "simplifyInfer call" (ppr tclvl $$ ppr name_taus $$ ppr wanted) ; (qtvs, givens, ev_binds, insoluble) <- simplifyInfer tclvl infer_mode sigs name_taus wanted ; let inferred_theta = map evVarPred givens ; exports <- checkNoErrs $ mapM (mkExport prag_fn insoluble qtvs inferred_theta) mono_infos ; loc <- getSrcSpanM ; let poly_ids = map abe_poly exports abs_bind = L loc $ AbsBinds { abs_tvs = qtvs , abs_ev_vars = givens, abs_ev_binds = [ev_binds] , abs_exports = exports, abs_binds = binds' , abs_sig = False } ; traceTc "Binding:" (ppr (poly_ids `zip` map idType poly_ids)) ; return (unitBag abs_bind, poly_ids) } -- poly_ids are guaranteed zonked by mkExport -------------- mkExport :: TcPragEnv -> Bool -- True <=> there was an insoluble type error -- when typechecking the bindings -> [TyVar] -> TcThetaType -- Both already zonked -> MonoBindInfo -> TcM (ABExport GhcTc) -- Only called for generalisation plan InferGen, not by CheckGen or NoGen -- -- mkExport generates exports with -- zonked type variables, -- zonked poly_ids -- The former is just because no further unifications will change -- the quantified type variables, so we can fix their final form -- right now. -- The latter is needed because the poly_ids are used to extend the -- type environment; see the invariant on TcEnv.tcExtendIdEnv -- Pre-condition: the qtvs and theta are already zonked mkExport prag_fn insoluble qtvs theta mono_info@(MBI { mbi_poly_name = poly_name , mbi_sig = mb_sig , mbi_mono_id = mono_id }) = do { mono_ty <- zonkTcType (idType mono_id) ; poly_id <- mkInferredPolyId insoluble qtvs theta poly_name mb_sig mono_ty -- NB: poly_id has a zonked type ; poly_id <- addInlinePrags poly_id prag_sigs ; spec_prags <- tcSpecPrags poly_id prag_sigs -- tcPrags requires a zonked poly_id -- See Note [Impedance matching] -- NB: we have already done checkValidType, including an ambiguity check, -- on the type; either when we checked the sig or in mkInferredPolyId ; let poly_ty = idType poly_id sel_poly_ty = mkInfSigmaTy qtvs theta mono_ty -- This type is just going into tcSubType, -- so Inferred vs. Specified doesn't matter ; wrap <- if sel_poly_ty `eqType` poly_ty -- NB: eqType ignores visibility then return idHsWrapper -- Fast path; also avoids complaint when we infer -- an ambiguous type and have AllowAmbiguousType -- e..g infer x :: forall a. F a -> Int else addErrCtxtM (mk_impedance_match_msg mono_info sel_poly_ty poly_ty) $ tcSubType_NC sig_ctxt sel_poly_ty poly_ty ; warn_missing_sigs <- woptM Opt_WarnMissingLocalSignatures ; when warn_missing_sigs $ localSigWarn Opt_WarnMissingLocalSignatures poly_id mb_sig ; return (ABE { abe_wrap = wrap -- abe_wrap :: idType poly_id ~ (forall qtvs. theta => mono_ty) , abe_poly = poly_id , abe_mono = mono_id , abe_prags = SpecPrags spec_prags }) } where prag_sigs = lookupPragEnv prag_fn poly_name sig_ctxt = InfSigCtxt poly_name mkInferredPolyId :: Bool -- True <=> there was an insoluble error when -- checking the binding group for this Id -> [TyVar] -> TcThetaType -> Name -> Maybe TcIdSigInst -> TcType -> TcM TcId mkInferredPolyId insoluble qtvs inferred_theta poly_name mb_sig_inst mono_ty | Just (TISI { sig_inst_sig = sig }) <- mb_sig_inst , CompleteSig { sig_bndr = poly_id } <- sig = return poly_id | otherwise -- Either no type sig or partial type sig = checkNoErrs $ -- The checkNoErrs ensures that if the type is ambiguous -- we don't carry on to the impedance matching, and generate -- a duplicate ambiguity error. There is a similar -- checkNoErrs for complete type signatures too. do { fam_envs <- tcGetFamInstEnvs ; let (_co, mono_ty') = normaliseType fam_envs Nominal mono_ty -- Unification may not have normalised the type, -- (see Note [Lazy flattening] in TcFlatten) so do it -- here to make it as uncomplicated as possible. -- Example: f :: [F Int] -> Bool -- should be rewritten to f :: [Char] -> Bool, if possible -- -- We can discard the coercion _co, because we'll reconstruct -- it in the call to tcSubType below ; (binders, theta') <- chooseInferredQuantifiers inferred_theta (tyCoVarsOfType mono_ty') qtvs mb_sig_inst ; let inferred_poly_ty = mkForAllTys binders (mkPhiTy theta' mono_ty') ; traceTc "mkInferredPolyId" (vcat [ppr poly_name, ppr qtvs, ppr theta' , ppr inferred_poly_ty]) ; unless insoluble $ addErrCtxtM (mk_inf_msg poly_name inferred_poly_ty) $ checkValidType (InfSigCtxt poly_name) inferred_poly_ty -- See Note [Validity of inferred types] -- If we found an insoluble error in the function definition, don't -- do this check; otherwise (Trac #14000) we may report an ambiguity -- error for a rather bogus type. ; return (mkLocalIdOrCoVar poly_name inferred_poly_ty) } chooseInferredQuantifiers :: TcThetaType -- inferred -> TcTyVarSet -- tvs free in tau type -> [TcTyVar] -- inferred quantified tvs -> Maybe TcIdSigInst -> TcM ([TyVarBinder], TcThetaType) chooseInferredQuantifiers inferred_theta tau_tvs qtvs Nothing = -- No type signature (partial or complete) for this binder, do { let free_tvs = closeOverKinds (growThetaTyVars inferred_theta tau_tvs) -- Include kind variables! Trac #7916 my_theta = pickCapturedPreds free_tvs inferred_theta binders = [ mkTyVarBinder Inferred tv | tv <- qtvs , tv `elemVarSet` free_tvs ] ; return (binders, my_theta) } chooseInferredQuantifiers inferred_theta tau_tvs qtvs (Just (TISI { sig_inst_sig = sig -- Always PartialSig , sig_inst_wcx = wcx , sig_inst_theta = annotated_theta , sig_inst_skols = annotated_tvs })) = -- Choose quantifiers for a partial type signature do { psig_qtvs <- mk_psig_qtvs annotated_tvs ; annotated_theta <- zonkTcTypes annotated_theta ; (free_tvs, my_theta) <- choose_psig_context psig_qtvs annotated_theta wcx ; return (mk_final_qtvs psig_qtvs free_tvs, my_theta) } where mk_final_qtvs psig_qtvs free_tvs = [ mkTyVarBinder vis tv | tv <- qtvs -- Pulling from qtvs maintains original order , tv `elemVarSet` keep_me , let vis | tv `elemVarSet` psig_qtvs = Specified | otherwise = Inferred ] where keep_me = free_tvs `unionVarSet` psig_qtvs mk_psig_qtvs :: [(Name,TcTyVar)] -> TcM TcTyVarSet mk_psig_qtvs annotated_tvs = do { let (sig_tv_names, sig_tvs) = unzip annotated_tvs ; psig_qtvs <- mapM zonkTcTyVarToTyVar sig_tvs -- Report an error if the quantified variables of the -- partial signature have been unified together -- See Note [Quantified variables in partial type signatures] ; let bad_sig_tvs = findDupsEq eq (sig_tv_names `zip` psig_qtvs) eq (_,tv1) (_,tv2) = tv1 == tv2 ; mapM_ (report_sig_tv_err sig) bad_sig_tvs ; return (mkVarSet psig_qtvs) } report_sig_tv_err (PartialSig { psig_name = fn_name, psig_hs_ty = hs_ty }) ((n1,_) :| (n2,_) : _) = addErrTc (hang (text "Couldn't match" <+> quotes (ppr n1) <+> text "with" <+> quotes (ppr n2)) 2 (hang (text "both bound by the partial type signature:") 2 (ppr fn_name <+> dcolon <+> ppr hs_ty))) report_sig_tv_err sig _ = pprPanic "report_sig_tv_err" (ppr sig) -- Can't happen; by now we know it's a partial sig choose_psig_context :: VarSet -> TcThetaType -> Maybe TcTyVar -> TcM (VarSet, TcThetaType) choose_psig_context _ annotated_theta Nothing = do { let free_tvs = closeOverKinds (tyCoVarsOfTypes annotated_theta `unionVarSet` tau_tvs) ; return (free_tvs, annotated_theta) } choose_psig_context psig_qtvs annotated_theta (Just wc_var) = do { let free_tvs = closeOverKinds (growThetaTyVars inferred_theta seed_tvs) -- growThetaVars just like the no-type-sig case -- Omitting this caused #12844 seed_tvs = tyCoVarsOfTypes annotated_theta -- These are put there `unionVarSet` tau_tvs -- by the user ; let keep_me = psig_qtvs `unionVarSet` free_tvs my_theta = pickCapturedPreds keep_me inferred_theta -- Fill in the extra-constraints wildcard hole with inferred_theta, -- so that the Hole constraint we have already emitted -- (in tcHsPartialSigType) can report what filled it in. -- NB: my_theta already includes all the annotated constraints ; let inferred_diff = [ pred | pred <- my_theta , all (not . (`eqType` pred)) annotated_theta ] ; ctuple <- mk_ctuple inferred_diff ; writeMetaTyVar wc_var ctuple ; traceTc "completeTheta" $ vcat [ ppr sig , ppr annotated_theta, ppr inferred_theta , ppr inferred_diff ] ; return (free_tvs, my_theta) } mk_ctuple preds = return (mkBoxedTupleTy preds) -- Hack alert! See TcHsType: -- Note [Extra-constraint holes in partial type signatures] mk_impedance_match_msg :: MonoBindInfo -> TcType -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc) -- This is a rare but rather awkward error messages mk_impedance_match_msg (MBI { mbi_poly_name = name, mbi_sig = mb_sig }) inf_ty sig_ty tidy_env = do { (tidy_env1, inf_ty) <- zonkTidyTcType tidy_env inf_ty ; (tidy_env2, sig_ty) <- zonkTidyTcType tidy_env1 sig_ty ; let msg = vcat [ text "When checking that the inferred type" , nest 2 $ ppr name <+> dcolon <+> ppr inf_ty , text "is as general as its" <+> what <+> text "signature" , nest 2 $ ppr name <+> dcolon <+> ppr sig_ty ] ; return (tidy_env2, msg) } where what = case mb_sig of Nothing -> text "inferred" Just sig | isPartialSig sig -> text "(partial)" | otherwise -> empty mk_inf_msg :: Name -> TcType -> TidyEnv -> TcM (TidyEnv, SDoc) mk_inf_msg poly_name poly_ty tidy_env = do { (tidy_env1, poly_ty) <- zonkTidyTcType tidy_env poly_ty ; let msg = vcat [ text "When checking the inferred type" , nest 2 $ ppr poly_name <+> dcolon <+> ppr poly_ty ] ; return (tidy_env1, msg) } -- | Warn the user about polymorphic local binders that lack type signatures. localSigWarn :: WarningFlag -> Id -> Maybe TcIdSigInst -> TcM () localSigWarn flag id mb_sig | Just _ <- mb_sig = return () | not (isSigmaTy (idType id)) = return () | otherwise = warnMissingSignatures flag msg id where msg = text "Polymorphic local binding with no type signature:" warnMissingSignatures :: WarningFlag -> SDoc -> Id -> TcM () warnMissingSignatures flag msg id = do { env0 <- tcInitTidyEnv ; let (env1, tidy_ty) = tidyOpenType env0 (idType id) ; addWarnTcM (Reason flag) (env1, mk_msg tidy_ty) } where mk_msg ty = sep [ msg, nest 2 $ pprPrefixName (idName id) <+> dcolon <+> ppr ty ] checkOverloadedSig :: Bool -> TcIdSigInst -> TcM () -- Example: -- f :: Eq a => a -> a -- K f = e -- The MR applies, but the signature is overloaded, and it's -- best to complain about this directly -- c.f Trac #11339 checkOverloadedSig monomorphism_restriction_applies sig | not (null (sig_inst_theta sig)) , monomorphism_restriction_applies , let orig_sig = sig_inst_sig sig = setSrcSpan (sig_loc orig_sig) $ failWith $ hang (text "Overloaded signature conflicts with monomorphism restriction") 2 (ppr orig_sig) | otherwise = return () {- Note [Partial type signatures and generalisation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If /any/ of the signatures in the gropu is a partial type signature f :: _ -> Int then we *always* use the InferGen plan, and hence tcPolyInfer. We do this even for a local binding with -XMonoLocalBinds, when we normally use NoGen. Reasons: * The TcSigInfo for 'f' has a unification variable for the '_', whose TcLevel is one level deeper than the current level. (See pushTcLevelM in tcTySig.) But NoGen doesn't increase the TcLevel like InferGen, so we lose the level invariant. * The signature might be f :: forall a. _ -> a so it really is polymorphic. It's not clear what it would mean to use NoGen on this, and indeed the ASSERT in tcLhs, in the (Just sig) case, checks that if there is a signature then we are using LetLclBndr, and hence a nested AbsBinds with increased TcLevel It might be possible to fix these difficulties somehow, but there doesn't seem much point. Indeed, adding a partial type signature is a way to get per-binding inferred generalisation. We apply the MR if /all/ of the partial signatures lack a context. In particular (Trac #11016): f2 :: (?loc :: Int) => _ f2 = ?loc It's stupid to apply the MR here. This test includes an extra-constraints wildcard; that is, we don't apply the MR if you write f3 :: _ => blah Note [Quantified variables in partial type signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f :: forall a. a -> a -> _ f x y = g x y g :: forall b. b -> b -> _ g x y = [x, y] Here, 'f' and 'g' are mutually recursive, and we end up unifyin 'a' and 'b' together, which is fine. So we bind 'a' and 'b' to SigTvs, which can then unify with each other. But now consider: f :: forall a b. a -> b -> _ f x y = [x, y] We want to get an error from this, because 'a' and 'b' get unified. So we make a test, one per parital signature, to check that the explicitly-quantified type variables have not been unified together. Trac #14449 showed this up. Note [Validity of inferred types] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We need to check inferred type for validity, in case it uses language extensions that are not turned on. The principle is that if the user simply adds the inferred type to the program source, it'll compile fine. See #8883. Examples that might fail: - the type might be ambiguous - an inferred theta that requires type equalities e.g. (F a ~ G b) or multi-parameter type classes - an inferred type that includes unboxed tuples Note [Impedance matching] ~~~~~~~~~~~~~~~~~~~~~~~~~ Consider f 0 x = x f n x = g [] (not x) g [] y = f 10 y g _ y = f 9 y After typechecking we'll get f_mono_ty :: a -> Bool -> Bool g_mono_ty :: [b] -> Bool -> Bool with constraints (Eq a, Num a) Note that f is polymorphic in 'a' and g in 'b'; and these are not linked. The types we really want for f and g are f :: forall a. (Eq a, Num a) => a -> Bool -> Bool g :: forall b. [b] -> Bool -> Bool We can get these by "impedance matching": tuple :: forall a b. (Eq a, Num a) => (a -> Bool -> Bool, [b] -> Bool -> Bool) tuple a b d1 d1 = let ...bind f_mono, g_mono in (f_mono, g_mono) f a d1 d2 = case tuple a Any d1 d2 of (f, g) -> f g b = case tuple Integer b dEqInteger dNumInteger of (f,g) -> g Suppose the shared quantified tyvars are qtvs and constraints theta. Then we want to check that forall qtvs. theta => f_mono_ty is more polymorphic than f's polytype and the proof is the impedance matcher. Notice that the impedance matcher may do defaulting. See Trac #7173. It also cleverly does an ambiguity check; for example, rejecting f :: F a -> F a where F is a non-injective type function. -} {- ********************************************************************* * * Vectorisation * * ********************************************************************* -} tcVectDecls :: [LVectDecl GhcRn] -> TcM ([LVectDecl GhcTcId]) tcVectDecls decls = do { decls' <- mapM (wrapLocM tcVect) decls ; let ids = [lvectDeclName decl | decl <- decls', not $ lvectInstDecl decl] dups = findDupsEq (==) ids ; mapM_ reportVectDups dups ; traceTcConstraints "End of tcVectDecls" ; return decls' } where reportVectDups (first :| (_second:_more)) = addErrAt (getSrcSpan first) $ text "Duplicate vectorisation declarations for" <+> ppr first reportVectDups _ = return () -------------- tcVect :: VectDecl GhcRn -> TcM (VectDecl GhcTcId) -- FIXME: We can't typecheck the expression of a vectorisation declaration against the vectorised -- type of the original definition as this requires internals of the vectoriser not available -- during type checking. Instead, constrain the rhs of a vectorisation declaration to be a single -- identifier (this is checked in 'rnHsVectDecl'). Fix this by enabling the use of 'vectType' -- from the vectoriser here. tcVect (HsVect s name rhs) = addErrCtxt (vectCtxt name) $ do { var <- wrapLocM tcLookupId name ; let L rhs_loc (HsVar (L lv rhs_var_name)) = rhs ; rhs_id <- tcLookupId rhs_var_name ; return $ HsVect s var (L rhs_loc (HsVar (L lv rhs_id))) } tcVect (HsNoVect s name) = addErrCtxt (vectCtxt name) $ do { var <- wrapLocM tcLookupId name ; return $ HsNoVect s var } tcVect (HsVectTypeIn _ isScalar lname rhs_name) = addErrCtxt (vectCtxt lname) $ do { tycon <- tcLookupLocatedTyCon lname ; checkTc ( not isScalar -- either we have a non-SCALAR declaration || isJust rhs_name -- or we explicitly provide a vectorised type || tyConArity tycon == 0 -- otherwise the type constructor must be nullary ) scalarTyConMustBeNullary ; rhs_tycon <- fmapMaybeM (tcLookupTyCon . unLoc) rhs_name ; return $ HsVectTypeOut isScalar tycon rhs_tycon } tcVect (HsVectTypeOut _ _ _) = panic "TcBinds.tcVect: Unexpected 'HsVectTypeOut'" tcVect (HsVectClassIn _ lname) = addErrCtxt (vectCtxt lname) $ do { cls <- tcLookupLocatedClass lname ; return $ HsVectClassOut cls } tcVect (HsVectClassOut _) = panic "TcBinds.tcVect: Unexpected 'HsVectClassOut'" tcVect (HsVectInstIn linstTy) = addErrCtxt (vectCtxt linstTy) $ do { (cls, tys) <- tcHsVectInst linstTy ; inst <- tcLookupInstance cls tys ; return $ HsVectInstOut inst } tcVect (HsVectInstOut _) = panic "TcBinds.tcVect: Unexpected 'HsVectInstOut'" vectCtxt :: Outputable thing => thing -> SDoc vectCtxt thing = text "When checking the vectorisation declaration for" <+> ppr thing scalarTyConMustBeNullary :: MsgDoc scalarTyConMustBeNullary = text "VECTORISE SCALAR type constructor must be nullary" {- Note [SPECIALISE pragmas] ~~~~~~~~~~~~~~~~~~~~~~~~~ There is no point in a SPECIALISE pragma for a non-overloaded function: reverse :: [a] -> [a] {-# SPECIALISE reverse :: [Int] -> [Int] #-} But SPECIALISE INLINE *can* make sense for GADTS: data Arr e where ArrInt :: !Int -> ByteArray# -> Arr Int ArrPair :: !Int -> Arr e1 -> Arr e2 -> Arr (e1, e2) (!:) :: Arr e -> Int -> e {-# SPECIALISE INLINE (!:) :: Arr Int -> Int -> Int #-} {-# SPECIALISE INLINE (!:) :: Arr (a, b) -> Int -> (a, b) #-} (ArrInt _ ba) !: (I# i) = I# (indexIntArray# ba i) (ArrPair _ a1 a2) !: i = (a1 !: i, a2 !: i) When (!:) is specialised it becomes non-recursive, and can usefully be inlined. Scary! So we only warn for SPECIALISE *without* INLINE for a non-overloaded function. ************************************************************************ * * tcMonoBinds * * ************************************************************************ @tcMonoBinds@ deals with a perhaps-recursive group of HsBinds. The signatures have been dealt with already. -} data MonoBindInfo = MBI { mbi_poly_name :: Name , mbi_sig :: Maybe TcIdSigInst , mbi_mono_id :: TcId } tcMonoBinds :: RecFlag -- Whether the binding is recursive for typechecking purposes -- i.e. the binders are mentioned in their RHSs, and -- we are not rescued by a type signature -> TcSigFun -> LetBndrSpec -> [LHsBind GhcRn] -> TcM (LHsBinds GhcTcId, [MonoBindInfo]) tcMonoBinds is_rec sig_fn no_gen [ L b_loc (FunBind { fun_id = L nm_loc name, fun_matches = matches, bind_fvs = fvs })] -- Single function binding, | NonRecursive <- is_rec -- ...binder isn't mentioned in RHS , Nothing <- sig_fn name -- ...with no type signature = -- Note [Single function non-recursive binding special-case] -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -- In this very special case we infer the type of the -- right hand side first (it may have a higher-rank type) -- and *then* make the monomorphic Id for the LHS -- e.g. f = \(x::forall a. a->a) -> <body> -- We want to infer a higher-rank type for f setSrcSpan b_loc $ do { ((co_fn, matches'), rhs_ty) <- tcInferInst $ \ exp_ty -> -- tcInferInst: see TcUnify, -- Note [Deep instantiation of InferResult] tcExtendBinderStack [TcIdBndr_ExpType name exp_ty NotTopLevel] $ -- We extend the error context even for a non-recursive -- function so that in type error messages we show the -- type of the thing whose rhs we are type checking tcMatchesFun (L nm_loc name) matches exp_ty ; mono_id <- newLetBndr no_gen name rhs_ty ; return (unitBag $ L b_loc $ FunBind { fun_id = L nm_loc mono_id, fun_matches = matches', bind_fvs = fvs, fun_co_fn = co_fn, fun_tick = [] }, [MBI { mbi_poly_name = name , mbi_sig = Nothing , mbi_mono_id = mono_id }]) } tcMonoBinds _ sig_fn no_gen binds = do { tc_binds <- mapM (wrapLocM (tcLhs sig_fn no_gen)) binds -- Bring the monomorphic Ids, into scope for the RHSs ; let mono_infos = getMonoBindInfo tc_binds rhs_id_env = [ (name, mono_id) | MBI { mbi_poly_name = name , mbi_sig = mb_sig , mbi_mono_id = mono_id } <- mono_infos , case mb_sig of Just sig -> isPartialSig sig Nothing -> True ] -- A monomorphic binding for each term variable that lacks -- a complete type sig. (Ones with a sig are already in scope.) ; traceTc "tcMonoBinds" $ vcat [ ppr n <+> ppr id <+> ppr (idType id) | (n,id) <- rhs_id_env] ; binds' <- tcExtendRecIds rhs_id_env $ mapM (wrapLocM tcRhs) tc_binds ; return (listToBag binds', mono_infos) } ------------------------ -- tcLhs typechecks the LHS of the bindings, to construct the environment in which -- we typecheck the RHSs. Basically what we are doing is this: for each binder: -- if there's a signature for it, use the instantiated signature type -- otherwise invent a type variable -- You see that quite directly in the FunBind case. -- -- But there's a complication for pattern bindings: -- data T = MkT (forall a. a->a) -- MkT f = e -- Here we can guess a type variable for the entire LHS (which will be refined to T) -- but we want to get (f::forall a. a->a) as the RHS environment. -- The simplest way to do this is to typecheck the pattern, and then look up the -- bound mono-ids. Then we want to retain the typechecked pattern to avoid re-doing -- it; hence the TcMonoBind data type in which the LHS is done but the RHS isn't data TcMonoBind -- Half completed; LHS done, RHS not done = TcFunBind MonoBindInfo SrcSpan (MatchGroup GhcRn (LHsExpr GhcRn)) | TcPatBind [MonoBindInfo] (LPat GhcTcId) (GRHSs GhcRn (LHsExpr GhcRn)) TcSigmaType tcLhs :: TcSigFun -> LetBndrSpec -> HsBind GhcRn -> TcM TcMonoBind -- Only called with plan InferGen (LetBndrSpec = LetLclBndr) -- or NoGen (LetBndrSpec = LetGblBndr) -- CheckGen is used only for functions with a complete type signature, -- and tcPolyCheck doesn't use tcMonoBinds at all tcLhs sig_fn no_gen (FunBind { fun_id = L nm_loc name, fun_matches = matches }) | Just (TcIdSig sig) <- sig_fn name = -- There is a type signature. -- It must be partial; if complete we'd be in tcPolyCheck! -- e.g. f :: _ -> _ -- f x = ...g... -- Just g = ...f... -- Hence always typechecked with InferGen do { mono_info <- tcLhsSigId no_gen (name, sig) ; return (TcFunBind mono_info nm_loc matches) } | otherwise -- No type signature = do { mono_ty <- newOpenFlexiTyVarTy ; mono_id <- newLetBndr no_gen name mono_ty ; let mono_info = MBI { mbi_poly_name = name , mbi_sig = Nothing , mbi_mono_id = mono_id } ; return (TcFunBind mono_info nm_loc matches) } tcLhs sig_fn no_gen (PatBind { pat_lhs = pat, pat_rhs = grhss }) = -- See Note [Typechecking pattern bindings] do { sig_mbis <- mapM (tcLhsSigId no_gen) sig_names ; let inst_sig_fun = lookupNameEnv $ mkNameEnv $ [ (mbi_poly_name mbi, mbi_mono_id mbi) | mbi <- sig_mbis ] -- See Note [Existentials in pattern bindings] ; ((pat', nosig_mbis), pat_ty) <- addErrCtxt (patMonoBindsCtxt pat grhss) $ tcInferNoInst $ \ exp_ty -> tcLetPat inst_sig_fun no_gen pat exp_ty $ mapM lookup_info nosig_names ; let mbis = sig_mbis ++ nosig_mbis ; traceTc "tcLhs" (vcat [ ppr id <+> dcolon <+> ppr (idType id) | mbi <- mbis, let id = mbi_mono_id mbi ] $$ ppr no_gen) ; return (TcPatBind mbis pat' grhss pat_ty) } where bndr_names = collectPatBinders pat (nosig_names, sig_names) = partitionWith find_sig bndr_names find_sig :: Name -> Either Name (Name, TcIdSigInfo) find_sig name = case sig_fn name of Just (TcIdSig sig) -> Right (name, sig) _ -> Left name -- After typechecking the pattern, look up the binder -- names that lack a signature, which the pattern has brought -- into scope. lookup_info :: Name -> TcM MonoBindInfo lookup_info name = do { mono_id <- tcLookupId name ; return (MBI { mbi_poly_name = name , mbi_sig = Nothing , mbi_mono_id = mono_id }) } tcLhs _ _ other_bind = pprPanic "tcLhs" (ppr other_bind) -- AbsBind, VarBind impossible ------------------- tcLhsSigId :: LetBndrSpec -> (Name, TcIdSigInfo) -> TcM MonoBindInfo tcLhsSigId no_gen (name, sig) = do { inst_sig <- tcInstSig sig ; mono_id <- newSigLetBndr no_gen name inst_sig ; return (MBI { mbi_poly_name = name , mbi_sig = Just inst_sig , mbi_mono_id = mono_id }) } ------------ newSigLetBndr :: LetBndrSpec -> Name -> TcIdSigInst -> TcM TcId newSigLetBndr (LetGblBndr prags) name (TISI { sig_inst_sig = id_sig }) | CompleteSig { sig_bndr = poly_id } <- id_sig = addInlinePrags poly_id (lookupPragEnv prags name) newSigLetBndr no_gen name (TISI { sig_inst_tau = tau }) = newLetBndr no_gen name tau ------------------- tcRhs :: TcMonoBind -> TcM (HsBind GhcTcId) tcRhs (TcFunBind info@(MBI { mbi_sig = mb_sig, mbi_mono_id = mono_id }) loc matches) = tcExtendIdBinderStackForRhs [info] $ tcExtendTyVarEnvForRhs mb_sig $ do { traceTc "tcRhs: fun bind" (ppr mono_id $$ ppr (idType mono_id)) ; (co_fn, matches') <- tcMatchesFun (L loc (idName mono_id)) matches (mkCheckExpType $ idType mono_id) ; return ( FunBind { fun_id = L loc mono_id , fun_matches = matches' , fun_co_fn = co_fn , bind_fvs = placeHolderNamesTc , fun_tick = [] } ) } tcRhs (TcPatBind infos pat' grhss pat_ty) = -- When we are doing pattern bindings we *don't* bring any scoped -- type variables into scope unlike function bindings -- Wny not? They are not completely rigid. -- That's why we have the special case for a single FunBind in tcMonoBinds tcExtendIdBinderStackForRhs infos $ do { traceTc "tcRhs: pat bind" (ppr pat' $$ ppr pat_ty) ; grhss' <- addErrCtxt (patMonoBindsCtxt pat' grhss) $ tcGRHSsPat grhss pat_ty ; return ( PatBind { pat_lhs = pat', pat_rhs = grhss' , pat_rhs_ty = pat_ty , bind_fvs = placeHolderNamesTc , pat_ticks = ([],[]) } )} tcExtendTyVarEnvForRhs :: Maybe TcIdSigInst -> TcM a -> TcM a tcExtendTyVarEnvForRhs Nothing thing_inside = thing_inside tcExtendTyVarEnvForRhs (Just sig) thing_inside = tcExtendTyVarEnvFromSig sig thing_inside tcExtendTyVarEnvFromSig :: TcIdSigInst -> TcM a -> TcM a tcExtendTyVarEnvFromSig sig_inst thing_inside | TISI { sig_inst_skols = skol_prs, sig_inst_wcs = wcs } <- sig_inst = tcExtendTyVarEnv2 wcs $ tcExtendTyVarEnv2 skol_prs $ thing_inside tcExtendIdBinderStackForRhs :: [MonoBindInfo] -> TcM a -> TcM a -- Extend the TcBinderStack for the RHS of the binding, with -- the monomorphic Id. That way, if we have, say -- f = \x -> blah -- and something goes wrong in 'blah', we get a "relevant binding" -- looking like f :: alpha -> beta -- This applies if 'f' has a type signature too: -- f :: forall a. [a] -> [a] -- f x = True -- We can't unify True with [a], and a relevant binding is f :: [a] -> [a] -- If we had the *polymorphic* version of f in the TcBinderStack, it -- would not be reported as relevant, because its type is closed tcExtendIdBinderStackForRhs infos thing_inside = tcExtendBinderStack [ TcIdBndr mono_id NotTopLevel | MBI { mbi_mono_id = mono_id } <- infos ] thing_inside -- NotTopLevel: it's a monomorphic binding --------------------- getMonoBindInfo :: [Located TcMonoBind] -> [MonoBindInfo] getMonoBindInfo tc_binds = foldr (get_info . unLoc) [] tc_binds where get_info (TcFunBind info _ _) rest = info : rest get_info (TcPatBind infos _ _ _) rest = infos ++ rest {- Note [Typechecking pattern bindings] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Look at: - typecheck/should_compile/ExPat - Trac #12427, typecheck/should_compile/T12427{a,b} data T where MkT :: Integral a => a -> Int -> T and suppose t :: T. Which of these pattern bindings are ok? E1. let { MkT p _ = t } in <body> E2. let { MkT _ q = t } in <body> E3. let { MkT (toInteger -> r) _ = t } in <body> * (E1) is clearly wrong because the existential 'a' escapes. What type could 'p' possibly have? * (E2) is fine, despite the existential pattern, because q::Int, and nothing escapes. * Even (E3) is fine. The existential pattern binds a dictionary for (Integral a) which the view pattern can use to convert the a-valued field to an Integer, so r :: Integer. An easy way to see all three is to imagine the desugaring. For (E2) it would look like let q = case t of MkT _ q' -> q' in <body> We typecheck pattern bindings as follows. First tcLhs does this: 1. Take each type signature q :: ty, partial or complete, and instantiate it (with tcLhsSigId) to get a MonoBindInfo. This gives us a fresh "mono_id" qm :: instantiate(ty), where qm has a fresh name. Any fresh unification variables in instantiate(ty) born here, not deep under implications as would happen if we allocated them when we encountered q during tcPat. 2. Build a little environment mapping "q" -> "qm" for those Ids with signatures (inst_sig_fun) 3. Invoke tcLetPat to typecheck the pattern. - We pass in the current TcLevel. This is captured by TcPat.tcLetPat, and put into the pc_lvl field of PatCtxt, in PatEnv. - When tcPat finds an existential constructor, it binds fresh type variables and dictionaries as usual, increments the TcLevel, and emits an implication constraint. - When we come to a binder (TcPat.tcPatBndr), it looks it up in the little environment (the pc_sig_fn field of PatCtxt). Success => There was a type signature, so just use it, checking compatibility with the expected type. Failure => No type sigature. Infer case: (happens only outside any constructor pattern) use a unification variable at the outer level pc_lvl Check case: use promoteTcType to promote the type to the outer level pc_lvl. This is the place where we emit a constraint that'll blow up if existential capture takes place Result: the type of the binder is always at pc_lvl. This is crucial. 4. Throughout, when we are making up an Id for the pattern-bound variables (newLetBndr), we have two cases: - If we are generalising (generalisation plan is InferGen or CheckGen), then the let_bndr_spec will be LetLclBndr. In that case we want to bind a cloned, local version of the variable, with the type given by the pattern context, *not* by the signature (even if there is one; see Trac #7268). The mkExport part of the generalisation step will do the checking and impedance matching against the signature. - If for some some reason we are not generalising (plan = NoGen), the LetBndrSpec will be LetGblBndr. In that case we must bind the global version of the Id, and do so with precisely the type given in the signature. (Then we unify with the type from the pattern context type.) And that's it! The implication constraints check for the skolem escape. It's quite simple and neat, and more expressive than before e.g. GHC 8.0 rejects (E2) and (E3). Example for (E1), starting at level 1. We generate p :: beta:1, with constraints (forall:3 a. Integral a => a ~ beta) The (a~beta) can't float (because of the 'a'), nor be solved (because beta is untouchable.) Example for (E2), we generate q :: beta:1, with constraint (forall:3 a. Integral a => Int ~ beta) The beta is untoucable, but floats out of the constraint and can be solved absolutely fine. ************************************************************************ * * Generalisation * * ********************************************************************* -} data GeneralisationPlan = NoGen -- No generalisation, no AbsBinds | InferGen -- Implicit generalisation; there is an AbsBinds Bool -- True <=> apply the MR; generalise only unconstrained type vars | CheckGen (LHsBind GhcRn) TcIdSigInfo -- One FunBind with a signature -- Explicit generalisation -- A consequence of the no-AbsBinds choice (NoGen) is that there is -- no "polymorphic Id" and "monmomorphic Id"; there is just the one instance Outputable GeneralisationPlan where ppr NoGen = text "NoGen" ppr (InferGen b) = text "InferGen" <+> ppr b ppr (CheckGen _ s) = text "CheckGen" <+> ppr s decideGeneralisationPlan :: DynFlags -> [LHsBind GhcRn] -> IsGroupClosed -> TcSigFun -> GeneralisationPlan decideGeneralisationPlan dflags lbinds closed sig_fn | has_partial_sigs = InferGen (and partial_sig_mrs) | Just (bind, sig) <- one_funbind_with_sig = CheckGen bind sig | do_not_generalise closed = NoGen | otherwise = InferGen mono_restriction where binds = map unLoc lbinds partial_sig_mrs :: [Bool] -- One for each partial signature (so empty => no partial sigs) -- The Bool is True if the signature has no constraint context -- so we should apply the MR -- See Note [Partial type signatures and generalisation] partial_sig_mrs = [ null theta | TcIdSig (PartialSig { psig_hs_ty = hs_ty }) <- mapMaybe sig_fn (collectHsBindListBinders lbinds) , let (_, L _ theta, _) = splitLHsSigmaTy (hsSigWcType hs_ty) ] has_partial_sigs = not (null partial_sig_mrs) mono_restriction = xopt LangExt.MonomorphismRestriction dflags && any restricted binds do_not_generalise (IsGroupClosed _ True) = False -- The 'True' means that all of the group's -- free vars have ClosedTypeId=True; so we can ignore -- -XMonoLocalBinds, and generalise anyway do_not_generalise _ = xopt LangExt.MonoLocalBinds dflags -- With OutsideIn, all nested bindings are monomorphic -- except a single function binding with a signature one_funbind_with_sig | [lbind@(L _ (FunBind { fun_id = v }))] <- lbinds , Just (TcIdSig sig) <- sig_fn (unLoc v) = Just (lbind, sig) | otherwise = Nothing -- The Haskell 98 monomorphism restriction restricted (PatBind {}) = True restricted (VarBind { var_id = v }) = no_sig v restricted (FunBind { fun_id = v, fun_matches = m }) = restricted_match m && no_sig (unLoc v) restricted b = pprPanic "isRestrictedGroup/unrestricted" (ppr b) restricted_match mg = matchGroupArity mg == 0 -- No args => like a pattern binding -- Some args => a function binding no_sig n = not (hasCompleteSig sig_fn n) isClosedBndrGroup :: TcTypeEnv -> Bag (LHsBind GhcRn) -> IsGroupClosed isClosedBndrGroup type_env binds = IsGroupClosed fv_env type_closed where type_closed = allUFM (nameSetAll is_closed_type_id) fv_env fv_env :: NameEnv NameSet fv_env = mkNameEnv $ concatMap (bindFvs . unLoc) binds bindFvs :: HsBindLR GhcRn idR -> [(Name, NameSet)] bindFvs (FunBind { fun_id = L _ f, bind_fvs = fvs }) = let open_fvs = filterNameSet (not . is_closed) fvs in [(f, open_fvs)] bindFvs (PatBind { pat_lhs = pat, bind_fvs = fvs }) = let open_fvs = filterNameSet (not . is_closed) fvs in [(b, open_fvs) | b <- collectPatBinders pat] bindFvs _ = [] is_closed :: Name -> ClosedTypeId is_closed name | Just thing <- lookupNameEnv type_env name = case thing of AGlobal {} -> True ATcId { tct_info = ClosedLet } -> True _ -> False | otherwise = True -- The free-var set for a top level binding mentions is_closed_type_id :: Name -> Bool -- We're already removed Global and ClosedLet Ids is_closed_type_id name | Just thing <- lookupNameEnv type_env name = case thing of ATcId { tct_info = NonClosedLet _ cl } -> cl ATcId { tct_info = NotLetBound } -> False ATyVar {} -> False -- In-scope type variables are not closed! _ -> pprPanic "is_closed_id" (ppr name) | otherwise = True -- The free-var set for a top level binding mentions -- imported things too, so that we can report unused imports -- These won't be in the local type env. -- Ditto class method etc from the current module {- ********************************************************************* * * Error contexts and messages * * ********************************************************************* -} -- This one is called on LHS, when pat and grhss are both Name -- and on RHS, when pat is TcId and grhss is still Name patMonoBindsCtxt :: (SourceTextX p, OutputableBndrId p, Outputable body) => LPat p -> GRHSs GhcRn body -> SDoc patMonoBindsCtxt pat grhss = hang (text "In a pattern binding:") 2 (pprPatBind pat grhss)
ezyang/ghc
compiler/typecheck/TcBinds.hs
bsd-3-clause
75,334
0
23
23,550
12,321
6,466
5,855
877
9
module Spring13.Week1.HanoiTower (hanoi) where type Peg = String type Move = (Peg, Peg) hanoi :: Integer -> Peg -> Peg -> Peg -> [Move] hanoi n a b c | n > 0 = (hanoi (n-1) a c b) ++ [(a, b)] ++ (hanoi (n-1) c b a) | otherwise = []
bibaijin/cis194
src/Spring13/Week1/HanoiTower.hs
bsd-3-clause
242
0
11
62
144
79
65
8
1
------------------------------------------------------------------------------- {- LANGUAGE CPP #-} #define DO_TRACE 0 #define USE_POST_ORDER_IDS 0 #define SHOW_PAT_NODE_ATTRS 0 #define WARN_IGNORED_SUBPATTERNS 1 #define NEVER_IGNORE_SUBPATTERNS 0 -- Formerly DEBUG_WITH_DEEPSEQ_GENERICS. -- Now also needed to force issuance of all compilePat warnings -- (so not strictly a debugging flag anymore). -- [Except it didn't work...] --- #define NFDATA_INSTANCE_PATTERN 0 -- now a .cabal flag #define DO_DERIVE_DATA_AND_TYPEABLE 0 #define DO_DERIVE_ONLY_TYPEABLE 1 #if DO_DERIVE_ONLY_TYPEABLE && DO_DERIVE_DATA_AND_TYPEABLE #undef DO_DERIVE_ONLY_TYPEABLE #warning DO_DERIVE_ONLY_TYPEABLE forced 0, due to DO_DERIVE_DATA_AND_TYPEABLE being 1. #define DO_DERIVE_ONLY_TYPEABLE 0 #endif -- Now specified via --flag=[-]USE_WWW_DEEPSEQ --- #define USE_WW_DEEPSEQ 1 ------------------------------------------------------------------------------- -- Good idea: Let * be followed by an integer N. -- This shall have the semantics that, when that node -- is matched in the pattern, instead of rnf it is forcen N'd. -- There may be fusion possible (which is worth trying here -- for practise, even if this lib is not used much): -- -- forcep p1 . forcep p2 = forcep (unionPat [p1,p2]) -- -- This holds if pattern doesn't contain #, or any (type-)constrained -- subpatterns -- the latter might work out, if exclude # from them too, -- but I'm not sure. With #, we lose even monotonicity, let alone -- the above law. -- -- For the above to hold, remember, the union must have exactly -- the "forcing potential" of the LHS -- no more, no less. ------------------------------------------------------------------------------- #if DO_DERIVE_DATA_AND_TYPEABLE {-# LANGUAGE DeriveDataTypeable #-} #endif -- XXX Only needed for something in Blah.hs. -- Check into it, and see if can't get rid of the need -- for Typeable instances in here! #if DO_DERIVE_ONLY_TYPEABLE {-# LANGUAGE DeriveDataTypeable #-} #endif -- Prefer to hand-write the NFData instance, so that can -- use it with HASKELL98_FRAGMENT. #if 0 #if NFDATA_INSTANCE_PATTERN -- For testing only (controlling trace interleaving): {-# LANGUAGE DeriveGeneric #-} #endif #endif {- LANGUAGE DeriveFunctor #-} ------------------------------------------------------------------------------- -- | -- Module : Control.DeepSeq.Bounded.Pattern -- Copyright : Andrew G. Seniuk 2014-2015 -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Andrew Seniuk <[email protected]> -- Stability : provisional -- Portability : portable -- ------------------------------------------------------------------------------- module Control.DeepSeq.Bounded.Pattern ( -- * Pattern datatype Pattern , PatNode(..) , PatNodeAttrs(..) -- * Pattern DSL -- | __Grammar__ -- -- @ -- /pat/ /->/ /[/ /modifiers/ /]/ /pat'/ -- /pat'/ /->/ __.__ /|/ __!__ /|/ __*__ /[/ /decimalint/ /]/ /|/ __(__ /{/ /pat/ /}/ __)__ -- /modifiers/ /->/ zero or one of each of the eight /modifier/, in any order -- /modifier/ /->/ __=__ /|/ __+__ /|/ __^__ /|/ __\/__ /|/ __%__ -- /|/ __:__ /typename/ /{/ __;__ /typename/ /}/ __:__ -- /|/ __@__ /decimalint/ -- /|/ __>__ /permutation/ -- /typename/ /->/ string containing neither __:__ (unless /escaped/) nor __;__ -- /escaped/ /->/ __\\\\:__ -- /decimalint/ /->/ digit string not beginning with zero -- /permutation/ /->/ of an initial part of the lowercase alphabet, /e.g./ __cdba__ -- @ -- -- Here is the grammar in a more <http://fremissant.net/deepseq-bounded/grammar.html#new-grammar vivid rendering>. -- (Haddock makes it tricky to distinguish between metasyntax and concrete syntax.) -- -- Optional whitespace can go between any two tokens (basically, -- anyplace there is space shown in the grammar above). -- -- Semicolons never need escaping, because they're already illegal -- as part of any Haskell type name. -- -- The semantics are given formally in the 'PatNode' and 'PatNodeAttrs' -- documentation, as well as informally in the examples below and from -- the project <http://www.fremissant.net/deepseq-bounded homepage>. -- -- __Examples__ -- -- @\"__(...)__\"@ will match any ternary constructor. -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(!!!)__\" expr@ will force evaluation of @expr@ to a depth of two, -- provided the head of @expr@ is a ternary constructor; otherwise it behaves -- as @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__.__\" expr@ (/i.e./ do nothing). -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(...)__\" expr@ will force it to only a depth of one. That is, -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(...)__\" expr = -- <http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> -- \"__!__\" expr@ when the head of @expr@ -- is a ternary constructor; otherwise it won't perform any evaluation. -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__*__\" expr = <http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:NFData rnf> expr@. -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(***)__\" expr@ will <http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:NFData rnf> (deep) any ternary constructor, but -- will not touch any constructor of other arity. -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(.(*.).)__\" expr@ will match any ternary constructor, then -- match the second subexpression constructor if it is binary, and -- if matching got this far, then the left sub-subexpression -- will be forced (<http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:NFData rnf>), but not the right. -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(!:T:*.)__\" expr@ will unwrap (shallow 'seq') the first -- subexpression of @expr@, and the third subexpression won't be touched. -- As for the second subexpression, if its type is @T@ it will be -- completely evaluated (<http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:NFData rnf>), but otherwise it won't be touched. -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(=**)__\" expr@ will spark the /parallel/ complete evaluation of -- the two components of any pair. (Whether the computations actually -- run in parallel depends on resource availability, and the discretion -- of the RTS, as usual.) -- -- @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataP.html#t:NFDataP rnfp> \"__(>ba(+*+*)=*)__\" expr@ matches a binary constructor, whose first parameter is also a binary constructor. This identifies three main AST branches -- serendipitously symbolised by asterisks -- making up the expression: which branches we'll call __A__, __B__ and __C__. So this example will perform <http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:NFData rnf>, but in a controlled manner: __A__ and __B__ are forced in parallel with __C__, and furthermore, __B__ is forced before __A__. A traceline will be printed at the beginning of the forcing of __B__ and then another traceline will be printed at the beginning of the forcing of __A__. Note that \"__(=>ba(+*+*)*)__\" would be a legal equivalent. -- -- I make no claims as to the usefulness of the examples, they are here just to explain the semantics of the DSL. -- -- __Details__ -- -- The present pattern parser ignores any subpatterns of all -- pattern nodes except 'WR' and 'TR', optionally emitting a warning. -- /(XXX In 0.6.0.0, I'm not sure the warning is still possible.)/ -- Hence, only 'WR' and 'TR' patterns are potentially recursive. -- -- When specifying the list of subpatterns with 'WR' and 'TR', -- in order for the match to succeed, the number of subpatterns must -- be equal to the arity of the constructor the pattern node is -- matching against. (No other pattern node types accept subpatterns.) -- -- Additionally, in the case of 'TR', matching (and consequent recursion) will only -- succeed if the term node has constructor name which is listed in the constraints. -- -- It would be possible to have 'TR' nodes interpret the constraint -- as type name rather than constructor name, but this would require /sum patterns/ -- (maybe for version 0.7). The problem is, no single 'WR' node -- can match multiple constructors of differing arity. This has the -- feel of an excellent application for SOP generics!... -- -- (As contrasted with 'TR' nodes,) 'TI', 'TN' and 'TW' nodes interpret -- type constraint strings as type names (not constructor names). -- A moment's reflection will show you why it must be so. -- -- Finally, if you're trying to name a constructor with __:__ in its name, -- you must escape the colon with a backslash thus __\\\\:__ because -- the unescaped colon is used as (opening and) closing character for -- lists of type and constructor names. {--} -- Old interjection: -- I regret that Haddock cannot offer better markup for distinguishing -- the metasyntax. The bold is not bold enough. The alternation symbol, -- although \/|\/ in the document comment, does not show as slanted for me. -- Had no luck using color, also Unicode support seems pretty sketchy. -- Embedding an image is possible via data URL, but this has been known -- to crash Haddock except for very small images. {--} -- I'm still not sure if I try accepting a double-colon close here? -- (Checking...) -- /|/ /(/ __.__ /|/ __*__ /[/ /decimalint/ /]/ /)/ __::__ /typename/ /{/ __;__ /typename/ /}/ __:__ /[/ __:__ /]/ #if 0 -- These are now in Compile (but may move them back once sort out some stuff) , compilePat , showPat #endif , isWI , isWR , isWS , isWN , isWW , isTI , isTR , isTN , isTW , emptyPatNodeAttrs -- , emptySparkPatNodeAttrs , getPatNodeAttrs , setPatNodeAttrs #if USE_PING_PATNODE , setPatNodePingParentTID #endif , showPerm , showPatRaw , showPatNodeRaw , setPatternPatNodeUniqueIDs -- , patternShapeOK -- useful for defining instances of NFDataP -- * Why depend on whole containers package, when we only want a rose tree , Rose(..) -- * Preferred to have this in Seqable, but had cyclical dependency issues , SeqNode(..) ) where ------------------------------------------------------------------------------- #if DO_DERIVE_DATA_AND_TYPEABLE import Data.Data ( Data ) import Data.Typeable ( Typeable ) #elif DO_DERIVE_ONLY_TYPEABLE import Data.Typeable ( Typeable ) #endif #if USE_WW_DEEPSEQ import Control.DeepSeq ( NFData ) #endif import Control.Concurrent ( ThreadId ) import Data.List ( intercalate ) import Data.Char ( isDigit ) import Data.Maybe ( isNothing, fromJust ) import Data.Maybe ( isJust ) import Debug.Trace ( trace ) #if USE_WW_DEEPSEQ -- The only uses of force in this module are for debugging purposes -- (including trying to get messages to be displayed in a timely -- manner, although that problem has not been completely solved). import Control.DeepSeq ( force ) #endif -- (Hand write this NFData instance for greater portability.) #if NFDATA_INSTANCE_PATTERN -- for helping trace debugging #if 1 import Control.DeepSeq #else import qualified Control.DeepSeq.Generics as DSG import qualified GHC.Generics as GHC ( Generic ) #endif #endif import Data.Char ( ord ) import Data.Char ( chr ) import Control.Monad.State as ST -- Can't do it here, due to cyclical imports. (Surely this -- could be handled better by the tools...). #if 0 #if OVERLOADED_STRINGS import GHC.Exts( IsString(..) ) import Control.DeepSeq.Bounded.Compile ( compilePat ) #endif #endif ------------------------------------------------------------------------------- #if DO_TRACE mytrace = trace #else mytrace _ = id #endif ------------------------------------------------------------------------------- data Rose a = Node a [ Rose a ] -- (Hand write this NFData instance for greater portability.) #if 0 && NFDATA_INSTANCE_PATTERN #if DO_DERIVE_DATA_AND_TYPEABLE deriving (Show, Eq, GHC.Generic, Data, Typeable) -- deriving (Show, Eq, Functor, GHC.Generic, Data, Typeable) #elif DO_DERIVE_ONLY_TYPEABLE deriving (Show, Eq, GHC.Generic, Typeable) #else deriving (Show, Eq, GHC.Generic) #endif #else #if DO_DERIVE_DATA_AND_TYPEABLE deriving (Show, Eq, Data, Typeable) #elif DO_DERIVE_ONLY_TYPEABLE deriving (Show, Eq, Typeable) #else deriving (Show, Eq) #endif #endif type Pattern = Rose PatNode instance NFData a => NFData (Rose a) where rnf (Node x chs) = rnf x `seq` rnf chs instance Functor Rose where fmap f (Node x chs) = Node (f x) (map (fmap f) chs) -- (Hand write this NFData instance for greater portability.) #if 0 #if NFDATA_INSTANCE_PATTERN instance NFData a => NFData (Rose a) where rnf = DSG.genericRnf #endif #endif -- (See note at import of IsString; this instance is in Compile.hs.) #if 0 #if OVERLOADED_STRINGS instance IsString (Rose PatNode) where --instance IsString Pattern where fromString = compilePat -- aahhhh..... (20150204) #endif #endif ------------------------------------------------------------------------------- -- XXX -- -- A major design decision needs to be made [does it?...]: -- Is PatNode to remain a SUM ( ctor1 | ctor2 | ... ) or should -- it be refactored to be a PRODUCT, i.e. a new field called -- patNodeKind :: PatNodeKind, and all the fields of PatNodeAttrs -- are lifted up to be siblings of patNodeKind in a single -- top-level product (and PatNodeAttrs identifier elided). -- -- The SUM has the advantage of convenient pattern-matching, -- whereas the PRODUCT ... well, since we're using record syntax -- (not yet in PatNode though!...), we CAN (I just discovered!) -- do plain H98 pattern matching on multi-parameter constructors, -- projecting out JUST any one value into a fresh pattern variable. -- -- So in light of that, the refactoring to product has a lot to -- recommend it -- however, will there not be a runtime penalty -- of an extra wrapper or selector application or something?... -- -- Am I missing anything crucial?... -- -- If PatNode became a newtype, we pay only a compile-time price, right?... -- -- Reading: -- -- newtype Age = Age { unAge :: Int } -- brings into scope both a constructor and a de-constructor: -- Age :: Int -> Age -- unAge :: Age -> Int -- -- Thanks! I was just trying to remember this. -- So incidentally, newtypes allow record syntax but only for -- SINGLE PARAMETER constructor. (So newtypes will be of little -- use if we adopted the product design above.) ------------------------------------------------------------------------------- -- XXX be truly banished from the code via build flags (USE_PAR_PATNODE etc.). -- - if use cpp (not cpphs) to preprocess, that will appear as 0 or 1 in -- the documentation... -- | These attributes can be mixed freely. Certain combinations may -- seem unuseful, but nothing is prohibited by design. -- -- While this may seem bloated, most of these capabilities can -- be truly banished from the code via build flags (__use_par_patnode__, etc.). -- -- In the concrete pattern syntax, all attributes are represented -- as prefix modifiers (prefixing the -- @\'.\'@, @\'!\'@, @\'(\'@ or @\'*\'@ -- pattern node designator). -- Prefix modifiers may be given in any order. -- -- / NOTE: The 'depth' field in 'PatNodeAttrs' is not really an attribute, / -- / it is logically a (mandatory) extra parameter to 'WN' and 'TN' / -- / nodes (and only those). (Whereas attributes are all optional / -- / and node-type-agnostic.) The 'depth' is stored here as a / -- / convenient hack only! Explanation becomes necessary since / -- / Haddock makes it visible no matter what, I mention this, in case / -- / of confusion, because the 'depth' is always __post__fix, not prefix. / -- {--} -- XXX Is there any particular reason these fields should be marked strict? -- Should they be explicitly unboxed as well? (Performance has been adequate -- for the purposes so far...). data PatNodeAttrs = PatNodeAttrs { uniqueID :: !Int -- ^ Optional for convenience; set up with 'setPatternPatNodeUniqueIDs'. Beware that this function is not called automatically (or if it happens to be at the moment, this behaviour shouldn't be relied upon). For example, if you were to call <http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-PatUtil.html#v:growPat growPat>, the added nodes would all have \"uniqueID\" of 0. , depth :: !Int -- ^ (__*__/n/) &#8195; Depth of forcing for 'WN' and 'TN' nodes (/n/ is decimal integer depth). /(This is not an attribute, it's a displaced mandatory parameter, specific to these two node types.)/ , doConstrainType :: !Bool -- ^ (__:__) &#8195; Constrain pattern to match only types named in 'typeConstraints'. /__XXX__ This should be considered experimental still in 0.6. This and the "NFDataPDyn" aspects lost attention to/ <http://hackage.haskell.org/package/seqaid seqaid>. , typeConstraints :: ![String] -- ^ The list of type rep strings used in the type constraint (when 'doConstrainType' is 'True'). , doDelay :: !Bool -- ^ (__@__) &#8195; Delay (current thread) for 'delayus' microseconds. /__XXX__ Still buggy?/ , delayus :: !Int -- ^ Microseconds of delay (when 'doDelay' is 'True'). #if USE_PAR_PATNODE , doSpark :: !Bool -- ^ (__=__) &#8195; Spark matching for parallel evaluation. #endif #if USE_PSEQ_PATNODE , doPseq :: !Bool -- ^ (__>__/perm/) &#8195; Sequence child subpattern matching, according to the permutation in 'pseqPerm'. , pseqPerm :: Maybe [Int] -- ^ Lowercase alphabetic sequence is used in the concrete pattern syntax. @__>cdba(wxyz)__@ will cause subpattern matching recursion on a quaternary constructor, with the subpattern computations sequenced @__y__@ then @__z__@ then @__x__@ then @__w__@ (order corresponds to @__cdba__@). {-[XXX Until it really is, better not leave it saying so!] It is a runtime error (with a message), tested during matching, if this is a Just value and the list is not compatibly sized with the subpatterns. Sequencing syntax therefore would only work with 'WR' and 'TR' nodes, so we trap for the other cases and give a suitable error message.-} #endif #if USE_TRACE_PATNODE , doTrace :: !Bool -- ^ (__+__) &#8195; Output a traceline to stderr. #endif #if USE_PING_PATNODE , doPing :: !Bool -- ^ (__^__) &#8195; Raise informative (asynchronous? support is not strong for it, <http://hackage.haskell.org/package/base/docs/Control-Exception.html#v:throwTo throwTo> blocks...) exception /en passant/, for benefit of upstream. The exception is thrown in a new thread, so that the pattern matching continues; for a terminating version, see 'doDie'. , pingParentTID :: Maybe ThreadId -- ^ Needed as argument for 'throwTo' call. #endif #if USE_DIE_PATNODE , doDie :: !Bool -- ^ (__/__) &#8195; Kill (just this) thread. #endif #if USE_TIMING_PATNODE , doTiming :: !Bool -- ^ (__%__) &#8195; Note time passed since pattern-matched parent node. /__XXX__ Work in progress./ , timestamp :: !Int -- XXX for now , parent_timestamp :: !Int , delta_timestamp :: !Int #endif } -- (Hand write this NFData instance for greater portability.) #if 0 && NFDATA_INSTANCE_PATTERN #if DO_DERIVE_DATA_AND_TYPEABLE deriving ( Show, Eq, Typeable, Data, GHC.Generic ) #elif DO_DERIVE_ONLY_TYPEABLE deriving ( Show, Eq, Typeable, GHC.Generic ) #else deriving ( Show, Eq, GHC.Generic ) #endif #else #if DO_DERIVE_DATA_AND_TYPEABLE deriving ( Show, Eq, Typeable ) -- Data apparently not needed #elif DO_DERIVE_ONLY_TYPEABLE deriving ( Show, Eq, Typeable ) #else deriving ( Show, Eq ) #endif #endif #if NFDATA_INSTANCE_PATTERN -- (Hand write this NFData instance for greater portability.) --instance NFData PatNodeAttrs where rnf = DSG.genericRnf instance NFData PatNodeAttrs where rnf (PatNodeAttrs uniqueID depth doConstrainType typeConstraints doDelay delayus #if USE_PAR_PATNODE doSpark #endif #if USE_PSEQ_PATNODE doPseq pseqPerm #endif #if USE_TRACE_PATNODE doTrace #endif #if USE_PING_PATNODE doPing pingParentTID #endif #if USE_DIE_PATNODE doDie #endif #if USE_TIMING_PATNODE doTiming timestamp parent_timestamp delta_timestamp #endif ) = uniqueID `seq` rnf depth `seq` rnf doConstrainType `seq` rnf typeConstraints `seq` rnf doDelay `seq` rnf delayus #if USE_PAR_PATNODE `seq` rnf doSpark #endif #if USE_PSEQ_PATNODE `seq` rnf doPseq `seq` rnf pseqPerm #endif #if USE_TRACE_PATNODE `seq` rnf doTrace #endif #if USE_PING_PATNODE `seq` rnf doPing `seq` rnf pingParentTID #endif #if USE_DIE_PATNODE `seq` rnf doDie #endif #if USE_TIMING_PATNODE `seq` rnf doTiming `seq` rnf timestamp `seq` rnf parent_timestamp `seq` rnf delta_timestamp #endif #endif emptyPatNodeAttrs :: PatNodeAttrs emptyPatNodeAttrs = PatNodeAttrs { uniqueID = 0 , depth = 0 , doConstrainType = False , typeConstraints = [] , doDelay = False , delayus = 0 #if USE_PAR_PATNODE , doSpark = False #endif #if USE_PSEQ_PATNODE , doPseq = False , pseqPerm = Nothing #endif #if USE_TRACE_PATNODE , doTrace = False #endif #if USE_PING_PATNODE , doPing = False , pingParentTID = Nothing #endif #if USE_DIE_PATNODE , doDie = False #endif #if USE_TIMING_PATNODE , doTiming = False , timestamp = 0 -- Int for now , parent_timestamp = 0 , delta_timestamp = 0 #endif } -- (later: seems unused so commenting out) --emptySparkPatNodeAttrs :: PatNodeAttrs --emptySparkPatNodeAttrs = emptyPatNodeAttrs { doSpark = True } getPatNodeAttrs :: PatNode -> PatNodeAttrs getPatNodeAttrs pas = case pas of WI as -> as WS as -> as WR as -> as WN as -> as #if USE_WW_DEEPSEQ WW as -> as #endif TI as -> as -- TS as -> as TR as -> as TN as -> as #if USE_WW_DEEPSEQ TW as -> as #endif _ -> error $ "getPatNodeAttrs: unexpected PatNode: " ++ show pas setPatNodeAttrs :: PatNode -> PatNodeAttrs -> PatNode setPatNodeAttrs pas as' = case pas of WI _ -> WI as' WS _ -> WS as' WR _ -> WR as' WN _ -> WN as' #if USE_WW_DEEPSEQ WW _ -> WW as' #endif TI _ -> TI as' -- TS _ -> TS as' TR _ -> TR as' TN _ -> TN as' #if USE_WW_DEEPSEQ TW _ -> TW as' #endif _ -> error $ "setPatNodeAttrs: unexpected PatNode: " ++ show pas #if USE_PING_PATNODE setPatNodePingParentTID :: ThreadId -> PatNode -> PatNode setPatNodePingParentTID tid pn = pn' where pn' = let as' = (getPatNodeAttrs pn) { pingParentTID = Just tid } in setPatNodeAttrs pn as' #endif showPerm :: Maybe [Int] -> String showPerm Nothing = "" showPerm (Just lst) = showPerm' lst showPerm' [] = "" showPerm' (i:is) = (chr (i + ord 'a')) : showPerm' is -- Refer to http://stackoverflow.com/questions/12658443/how-to-decorate-a-tree-in-haskell/12658639 (among other SO questions) for good info and options. -- I've opted to remain H98 here, folloiwng Luis Casillas' answer. setPatternPatNodeUniqueIDs :: Int -> Pattern -> Pattern setPatternPatNodeUniqueIDs n pat #if USE_POST_ORDER_IDS = ST.evalState (mapRoseM step pat) n #else = ST.evalState (mapRoseM' step pat) n #endif where #if 1 step :: PatNode -> ST.State Int PatNode step pn = do tag <- postIncrement let as = getPatNodeAttrs pn let as' = as { uniqueID = tag } let pn' = setPatNodeAttrs pn as' return pn' #else step :: Pattern -> ST.State Int Pattern step p = do tag <- postIncrement let Node pn cs = p let p' = Node (pn { uniqueID = tag }) cs return p' -- return (p, tag) #endif #if 1 -- This is from Luis Casillas' answer. #if 0 -- This function is not part of the solution, but it will help you -- understand mapRoseM below. mapRose :: (a -> b) -> Rose a -> Rose b mapRose fn (Node a subtrees) = let subtrees' = map (mapRose fn) subtrees a' = fn a in Node a' subtrees' -- Normally you'd write that function like this: mapRose' fn (Node a subtrees) = Node (fn a) $ map (mapRose' fn) subtrees #endif -- But I wrote it out the long way to bring out the similarity to the -- following, which extracts the structure of the tagStep definition from -- the first solution above. mapRoseM :: Monad m => (a -> m b) -> Rose a -> m (Rose b) mapRoseM action (Node a subtrees) = do subtrees' <- mapM (mapRoseM action) subtrees a' <- action a return $ Node a' subtrees' -- That whole business with getting the state and putting the successor -- in as the replacement can be abstracted out. This action is like a -- post-increment operator. postIncrement :: Enum s => ST.State s s postIncrement = do val <- ST.get ST.put (succ val) return val #if 0 -- Now tag can be easily written in terms of those. tag init tree = evalState (mapRoseM step tree) init where step a = do tag <- postIncrement return (a, tag) #endif -- You can make mapRoseM process the local value -- before the subtrees if you want: mapRoseM' action (Node a subtrees) = do a' <- action a subtrees' <- mapM (mapRoseM' action) subtrees return $ Node a' subtrees' #if 0 -- And using Control.Monad you can turn this into a one-liner: mapRoseM action (Node a subtrees) = -- Apply the Rose constructor to the results of the two actions liftM2 Node (action a) (mapM (mapRoseM action) subtrees) -- Or in children-first order: mapRoseM' action (Node a subtrees) = liftM2 (flip Node ) (mapM (mapRoseM action) subtrees) (action a) #endif #endif ------------------------------------------------------------------------------- -- XXX Is there any particular reason these fields should be marked strict? -- | Only 'WR' and 'TR' allow for explicit recursion. -- -- All other 'PatNode' values are in leaf position when they occur. -- -- Concrete syntax for @W*@ and @T*@ nodes are identical. A @T*@ node -- is simply a @W*@ node bearing a type constraint attribute. -- Please refer to the __Grammar__ further down this page for more details, -- and links to even more information. -- -- /Notes:/ -- -- /I've kept the @T*@ types broken out as separate constructors, although they could be handled as special cases of @W*@ types in a way analogous to 'doSpark' ('PatNodeAttrs'). These were not \"absorbed\" because the semantics seems icky, and it's still not clear which @W*@ types even make sense with a type constraint.../ -- -- /I tried parametrising this, but it messed up my Show instance and seemed to be pulling me away from Haskell 98, so reverted. It looks a bit ugly in the Haddock unfortunately, with the redundant column of @PatNodeAttrs@. The @T*@ nodes will be absorbed by 'PatNodeAttrs' in version 0.7, and it won't look so bad./ data PatNode = -- PatNodeAttrs was strict, but changed it b/c had problems using TN{} -- form in some places (though not, apparantly, in all places)... WI !PatNodeAttrs -- ^ (/__I__nsulate/, __.__ ) &#8195; Don't even unwrap the constructor of this node. | WR !PatNodeAttrs -- ^ (/__R__ecurse/, __(__...__)__ ) &#8195; Continue pattern matching descendants, provided that arity is compatible (else the match fails). Interior nodes of a pattern are always @WR@, /i.e./ @WR@ is the only @PatNode@ offering explicit recursion. The rest (@?S@, @?N@, and @?W@) are implicitly recursive, but control is only as powerful as "NFDataN". | WS !PatNodeAttrs -- ^ (/__S__top/, __!__ ) &#8195; Stop recursing (nothing more forced down this branch). This is equivalent to 'WN' at a 'depth' of 1. /'WS' is somewhat vestigial, and may be removed in 0.7./ | WN !PatNodeAttrs -- ^ (/__N__ (depth)/, __*__n ) &#8195; @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataN.html#t:NFDataN rnfn> n@ the branch under this node. #if USE_WW_DEEPSEQ | WW !PatNodeAttrs -- ^ (/__W__/ild, __*__ ) &#8195; Fully force (<http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:NFData rnf>) the whole branch under this node. /Note that this is/ not /achievable as a limiting case of 'WN', so the existence of 'WW' is formally justifiable in a way that 'WS' is not. Having said that, for all practical purposes, a 'WN' with 'depth' @= maxBound::Int@ could be used for 'WW'.../ #endif {--} -- XXX It's still unclear whether TI should allow subpatterns; -- the alternative is for TI, when type doesn't match, to behave -- as "." (no subpatterns); but since I say "otherwise behave as TR", -- and TR says "continue pattern matching descendants", this seems to -- say that subpatterns should be permitted. Certainly it's no problem -- to permit subpatterns in this case, but WI should still ignore -- subpatterns since it will always be # regardless of node type. -- (Subpatterns ought to be "safely redundant" in this case, but whether -- they are depends on implementation and needs to be tested if allow -- WI subpatterns to survive past the parser/compiler!) -- And this all applies to TW and TN too, right? Yes. -- It seems clear that TI, TW and TN should all allow subpatterns. -- And that WI, WW and WN should elide them and issue a warning. -- But, none of my present woes seem to be connected with this... -- Nonetheless, it's important to pin down the semantics. -- XXX Jan. '15: Soon these T* nodes will disappear, and the corresponding -- PatNodeAttrs attributes will be used, as did for the P* (now doSpark) nodes. | TI !PatNodeAttrs -- ^ Don't even unwrap the constructor of this node, if it's type is in the list; otherwise behave as 'WW'. (Note this behaviour is the complement of 'TW' behaviour.) | TR !PatNodeAttrs -- ^ Match any of the types in the list (and continue pattern matching descendants); behave as 'WI' for nodes of type not in the list. --- | TS !PatNodeAttrs -- (never existed) | TN !PatNodeAttrs -- ^ @<http://hackage.haskell.org/package/deepseq-bounded-0.8.0.0/docs/Control-DeepSeq-Bounded-NFDataN.html#t:NFDataN rnfn> n@ the branch under this node, if the node type matches any of the types in the list; otherwise behave as 'WI'. #if USE_WW_DEEPSEQ | TW !PatNodeAttrs -- ^ Fully force (<http://hackage.haskell.org/package/deepseq/docs/Control-DeepSeq.html#t:NFData rnf>) the whole branch under this node, if the node type matches any of the types in the list; otherwise behave as 'WI'. (Note this behaviour is the complement of 'TI' behaviour.) #endif | XX -- ^ Dummy node type reserved for internal use. -- (Hand write this NFData instance for greater portability.) #if 0 && NFDATA_INSTANCE_PATTERN #if DO_DERIVE_DATA_AND_TYPEABLE deriving ( Eq, Typeable, Data, GHC.Generic ) #elif DO_DERIVE_ONLY_TYPEABLE deriving ( Eq, Typeable, GHC.Generic ) #else deriving ( Eq, GHC.Generic ) #endif #else #if DO_DERIVE_DATA_AND_TYPEABLE deriving ( Eq, Typeable ) -- Data apparently not needed #elif DO_DERIVE_ONLY_TYPEABLE deriving ( Eq, Typeable ) #else deriving ( Eq ) #endif #endif #if NFDATA_INSTANCE_PATTERN -- (Hand write this NFData instance for greater portability.) --instance NFData PatNode where rnf = DSG.genericRnf instance NFData PatNode where rnf pas = rnf as where as = getPatNodeAttrs pas #if 0 rnf WI = True ; isWI _ = False rnf WR = True ; isWR _ = False rnf WS = True ; isWS _ = False rnf WN = True ; isWN _ = False #if USE_WW_DEEPSEQ rnf WW = True ; isWW _ = False #endif rnf TI = True ; isTI _ = False rnf TR = True ; isTR _ = False rnf TN as = True ; isTN _ = False #if USE_WW_DEEPSEQ rnf TW as = True ; isTW _ = False #endif #endif #endif isWI WI{} = True ; isWI _ = False isWR WR{} = True ; isWR _ = False isWS WS{} = True ; isWS _ = False isWN WN{} = True ; isWN _ = False #if USE_WW_DEEPSEQ isWW WW{} = True ; isWW _ = False #endif isTI TI{} = True ; isTI _ = False isTR TR{} = True ; isTR _ = False isTN TN{} = True ; isTN _ = False #if USE_WW_DEEPSEQ isTW TW{} = True ; isTW _ = False #endif instance Show PatNode where #if SHOW_PAT_NODE_ATTRS show (WI as) = "WI " ++ show as show (WR as) = "WR " ++ show as show (WS as) = "WS " ++ show as show (WN as) = "WN " ++ show as #if USE_WW_DEEPSEQ show (WW as) = "WW " ++ show as #endif show (TI as) = "TI " ++ show as show (TR as) = "TR " ++ show as show (TN as) = "TN " ++ show as #if USE_WW_DEEPSEQ show (TW as) = "TW " ++ show as #endif #else show pas | WI{} <- pas = s1++"WI"++s2 | WR{} <- pas = s1++"WR"++s2 | WS{} <- pas = s1++"WS"++s2 | WN{} <- pas = s1++"WN"++s2' #if USE_WW_DEEPSEQ | WW{} <- pas = s1++"WW"++s2 #endif | TI{} <- pas = s1++"TI"++s2'' | TR{} <- pas = s1++"TR"++s2'' | TN{} <- pas = s1++"TN"++s2''' #if USE_WW_DEEPSEQ | TW{} <- pas = s1++"TW"++s2'' #endif where as = getPatNodeAttrs pas s1 = "" ++ (if doDelay as then "@" ++ (show $ delayus as) else "") #if USE_PAR_PATNODE ++ (if doSpark as then "=" else "") #endif #if USE_PSEQ_PATNODE ++ (if doPseq as then ">" ++ (showPerm $ pseqPerm as) else "") #endif #if USE_TRACE_PATNODE ++ (if doTrace as then "+" else "") #endif #if USE_PING_PATNODE ++ (if doPing as then "^" else "") #endif #if USE_DIE_PATNODE ++ (if doDie as then "/" else "") #endif #if USE_TIMING_PATNODE ++ (if doTiming as then "%" else "") #endif s2 = "" s2' = " " ++ show (depth as) s2'' = " (" ++ intercalate ";" (typeConstraints as) ++ ")" s2''' = s2' ++ s2'' #if 0 doubleBackslashes :: String -> String doubleBackslashes ('\\':t) = '\\':'\\':doubleBackslashes t doubleBackslashes (h:t) = h:doubleBackslashes t doubleBackslashes [] = [] #endif #endif showPatRaw :: Pattern -> String showPatRaw (Node pn cs) = showPatNodeRaw pn ++ "\n[" ++ intercalate "," (map showPatRaw cs) ++ "]" showPatNodeRaw :: PatNode -> String showPatNodeRaw (WI as) = "WI "++show as showPatNodeRaw (WR as) = "WR "++show as showPatNodeRaw (WS as) = "WS "++show as showPatNodeRaw (WN as) = "WN "++show as #if USE_WW_DEEPSEQ showPatNodeRaw (WW as) = "WW "++show as #endif showPatNodeRaw (TI as) = "TI "++show as showPatNodeRaw (TR as) = "TR "++show as showPatNodeRaw (TN as) = "TN "++show as #if USE_WW_DEEPSEQ showPatNodeRaw (TW as) = "TW "++show as #endif ------------------------------------------------------------------------------- #if 0 patternShapeOK :: Data a => Pattern -> a -> Bool patternShapeOK pat x = S.shapeOf pat == S.shapeOf x #endif ------------------------------------------------------------------------------- -- Note that Ord is derived, so the order that the constructors -- are listed matters! (This only affects GHC rules, SFAIK.) -- (This data type is here, to avoid cyclical imports which -- GHC pretty much is useless with.) -------- -- On the one hand, we want to keep this lightweight -- it can in -- principle be a single bit (Insulate/Propagate), as originally planned! -- But the Spark thing was too useful; and Print and Error would -- also be useful. But they're more orthogonal. -------- -- Later: Went with PatNodeAttrs for Pattern, but for Seqable -- we really prefer to keep it swift and simple for a while yet. #if 0 type Spark = Bool type PrintPeriod = Int type ErrorMsg = String data SeqNode = Insulate Spark PrintPeriod | Conduct Spark PrintPeriod | Force Spark PrintPeriod | Error ErrorMsg deriving ( Eq, Ord ) #else -- Later: Maybe "Insulate" is too strong a word. If going to "Insulate", -- then "external demand" (like demand generated by natural program -- evaluation) should also be repulsed (probably throwing an Error). -- "Conduct" would then permit these external demands to propagate, -- but will not cause any additional forcing. -- Then "Propagate" (which we can call "Force" now?) would carry -- the artificial forcing demands. -- So yeah, pretty much the above scheme, but try to get it happening -- for natural demand. -- If we can print trace info for every node, we can trace natural demand. -- And use that info, dynamically, to configure the harness. In a sense -- it seems silly to do that, since that's what the RTS is already doing, -- but it's an important special case. If the natural demand pattern -- is constant (over a window), then (within that window) we can -- safely manipulate the harness so long as its artificial forcing -- doesn't extend beyond those natural bounds. Why would you want -- to do this? I'm not sure, but it has theoretical interest at least. -- Because, for one thing, you are no longer at risk of changing -- the semantics by introducing new bottoms. And so if the demand -- pattern is BIG, we could use the seqharn to parallelise it etc? -- Just the natural demand that is... I hope so. That's the ticket. data SeqNode = Insulate --- | Conduct | Propagate -- XXX if include Conduct, then rename Propagate to Force #if USE_PAR_SEQABLE | Spark #endif -- These would break the Ord; and besides, they're sort of orthogonal -- (as is Spark) --- | Print Int --- | Error String deriving ( Eq, Ord ) -- deriving ( Eq, Ord, Show ) #endif -------------------------------------------------------------------------------
phunehehe/deepseq-bounded
src/Control/DeepSeq/Bounded/Pattern.hs
bsd-3-clause
40,005
44
23
8,987
3,517
2,192
1,325
172
8
{-# LANGUAGE OverloadedStrings #-} module Main where import Control.Monad (forM_) import Data.List.Split (splitOn) import System.Directory (getDirectoryContents) import System.Environment (getArgs) import Data.List (groupBy, sortBy, isSuffixOf) type Pt = Int type Pid = String type Sid = String data Result = Result { pt :: Pt , pid :: Pid , sid :: Sid , filename :: FilePath } deriving (Show) key :: Result -> String key r = pid r ++ sid r instance Eq Result where x == y = pt x == pt y instance Ord Result where x <= y = pt x <= pt y main = do (dir:_) <- getArgs files <- getDirectoryContents dir let rs = map toResult $ filter (isSuffixOf ".json") files let fs = map (filename.maximum) $ groupBy hash $ sortBy hash' rs forM_ fs $ \f -> putStrLn (dir ++ "/" ++ f) where hash x y = key x == key y hash' x y = compare (key x) (key y) toResult :: FilePath -> Result toResult fn = Result pt' pid sid fn where pt' :: Pt pt' = read $ take (length pt - 2) pt (pt:pid:sid:_) = splitOn "-" fn
msakai/icfpc2015
tools/highscores.hs
bsd-3-clause
1,120
0
14
326
455
235
220
35
1
module EFA.Flow.Sequence where import qualified EFA.Flow.Topology as FlowTopo import qualified EFA.Flow.Storage as Storage import qualified EFA.Flow.SequenceState.Index as Idx import qualified EFA.Signal.Sequence as Sequ import Data.Map (Map) import Prelude hiding (sequence) type Storages node storageLabel boundaryLabel carryLabel = Map node (Storage.Graph Idx.Section storageLabel carryLabel, Map Idx.Boundary boundaryLabel) type Sequence node edge sectionLabel nodeLabel flowLabel = Sequ.Map (FlowTopo.Section node edge sectionLabel nodeLabel flowLabel) data Graph node edge sectionLabel nodeLabel storageLabel boundaryLabel flowLabel carryLabel = Graph { storages :: Storages node storageLabel boundaryLabel carryLabel, sequence :: Sequence node edge sectionLabel nodeLabel flowLabel } deriving (Eq)
energyflowanalysis/efa-2.1
src/EFA/Flow/Sequence.hs
bsd-3-clause
914
0
9
201
190
121
69
24
0
{-# LANGUAGE OverloadedStrings, NamedFieldPuns #-} module Distribution.Server.Features.Search.PkgSearch ( PkgSearchEngine, initialPkgSearchEngine, defaultSearchRankParameters, PkgDocField(..), PkgDocFeatures, ) where import Distribution.Server.Features.Search.SearchEngine import Distribution.Server.Features.Search.ExtractNameTerms import Distribution.Server.Features.Search.ExtractDescriptionTerms import Data.Ix import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import NLP.Snowball import Distribution.Package import Distribution.PackageDescription import Distribution.Text (display) import Data.Text (unpack) type PkgSearchEngine = SearchEngine (PackageDescription, DownloadCount) PackageName PkgDocField PkgDocFeatures type DownloadCount = Int data PkgDocField = NameField | SynopsisField | DescriptionField deriving (Eq, Ord, Enum, Bounded, Ix, Show) data PkgDocFeatures = Downloads deriving (Eq, Ord, Enum, Bounded, Ix, Show) initialPkgSearchEngine :: PkgSearchEngine initialPkgSearchEngine = initSearchEngine pkgSearchConfig defaultSearchRankParameters pkgSearchConfig :: SearchConfig (PackageDescription, DownloadCount) PackageName PkgDocField PkgDocFeatures pkgSearchConfig = SearchConfig { documentKey = packageName . fst, extractDocumentTerms = extractTokens . fst, transformQueryTerm = normaliseQueryToken, documentFeatureValue = getFeatureValue, makeKey = mkPackageName . unpack } where extractTokens :: PackageDescription -> PkgDocField -> [Text] extractTokens pkg NameField = concatMap (extraStems computerStems) $ extractPackageNameTerms (display $ packageName pkg) extractTokens pkg SynopsisField = extractSynopsisTerms computerStems stopWords (synopsis pkg) extractTokens pkg DescriptionField = extractDescriptionTerms computerStems stopWords (description pkg) normaliseQueryToken :: Text -> PkgDocField -> Text normaliseQueryToken tok = let tokFold = T.toCaseFold tok -- we don't need to use extraStems here because the index is inflated by it already. tokStem = stem English tokFold in \field -> case field of NameField -> tokFold SynopsisField -> tokStem DescriptionField -> tokStem getFeatureValue (_pkg, downloadcount) Downloads = fromIntegral downloadcount defaultSearchRankParameters :: SearchRankParameters PkgDocField PkgDocFeatures defaultSearchRankParameters = SearchRankParameters { paramK1, paramB, paramFieldWeights, paramFeatureWeights, paramFeatureFunctions, paramResultsetSoftLimit = 400, paramResultsetHardLimit = 800 } where paramK1 :: Float paramK1 = 1.5 paramB :: PkgDocField -> Float paramB NameField = 0.9 paramB SynopsisField = 0.5 paramB DescriptionField = 0.5 paramFieldWeights :: PkgDocField -> Float paramFieldWeights NameField = 20 paramFieldWeights SynopsisField = 5 paramFieldWeights DescriptionField = 1 paramFeatureWeights :: PkgDocFeatures -> Float paramFeatureWeights Downloads = 0.5 paramFeatureFunctions :: PkgDocFeatures -> FeatureFunction paramFeatureFunctions Downloads = LogarithmicFunction 1 stopWords :: Set Term stopWords = Set.fromList ["haskell","library","simple","using","interface","functions", "implementation","package","support","'s","based","for","a","and","the", "to","of","with","in","an","on","from","that","as","into","by","is", "some","which","or","like","your","other","can","at","over","be","it", "within","their","this","but","are","get","one","all","you","so","only", "now","how","where","when","up","has","been","about","them","then","see", "no","do","than","should","out","off","much","if","i","have","also"] -- Extra stems that tend to occur with software packages computerStems :: [Text] computerStems = map T.pack ["ql","db","ml","gl"] {- ------------------- -- Main experiment -- main :: IO () main = do pkgsFile <- readFile "pkgs2" let pkgs :: [PackageDescription] pkgs = map read (lines pkgsFile) -- print "reading file" -- evaluate (length mostFreq + length pkgs) -- print "done" stopWordsFile <- T.readFile "stopwords.txt" let stopWords = Set.fromList (T.lines stopWordsFile) print "forcing pkgs..." evaluate (foldl' (\a p -> seq p a) () pkgs `seq` Set.size stopWords) let config = pkgSearchConfig stopWords searchengine = insertDocs pkgs $ initSearchEngine config print "constructing index..." printTiming "done" $ evaluate searchengine print ("search engine invariant", invariant searchengine) -- print [ avgFieldLength ctx s | s <- [minBound..maxBound] ] -- print $ take 100 $ sortBy (flip compare) $ map Set.size $ Map.elems (termMap searchindex) -- T.putStr $ T.unlines $ Map.keys (termMap searchindex) -- let SearchEngine{searchIndex=SearchIndex{termMap, termIdMap, docKeyMap, docIdMap}} = searchengine -- print (Map.size termMap, IntMap.size termIdMap, Map.size docKeyMap, IntMap.size docIdMap) let loop = do putStr "search term> " hFlush stdout t <- getLine unless (null t) $ do let terms = stems English . map (T.toCaseFold . T.pack) $ words t putStrLn "Ranked results:" let rankedResults = query searchengine terms putStr $ unlines [ {-show rank ++ ": " ++ -}display pkgname | ({-rank, -}pkgname) <- take 10 rankedResults ] loop return () loop printTiming msg action = do t <- getCurrentTime action t' <- getCurrentTime print (msg ++ ". time: " ++ show (diffUTCTime t' t)) -}
edsko/hackage-server
Distribution/Server/Features/Search/PkgSearch.hs
bsd-3-clause
6,198
0
12
1,536
935
550
385
94
5
----------------------------------------------------------------------------- -- | Separate module for HTTP actions, using a proxy server if one exists ----------------------------------------------------------------------------- module Distribution.Client.HttpUtils ( DownloadResult(..), downloadURI, getHTTP, cabalBrowse, proxy, isOldHackageURI ) where import Network.HTTP ( Request (..), Response (..), RequestMethod (..) , Header(..), HeaderName(..), lookupHeader ) import Network.HTTP.Proxy ( Proxy(..), fetchProxy) import Network.URI ( URI (..), URIAuth (..) ) import Network.Browser ( BrowserAction, browse, setAllowBasicAuth, setAuthorityGen , setOutHandler, setErrHandler, setProxy, request) import Network.Stream ( Result, ConnError(..) ) import Control.Monad ( liftM ) import qualified Data.ByteString.Lazy.Char8 as ByteString import Data.ByteString.Lazy (ByteString) import qualified Paths_epm (version) import Distribution.Verbosity (Verbosity) import Distribution.Simple.Utils ( die, info, warn, debug, notice , copyFileVerbose, writeFileAtomic ) import Distribution.System ( buildOS, buildArch ) import Distribution.Text ( display ) import Data.Char ( isSpace ) import qualified System.FilePath.Posix as FilePath.Posix ( splitDirectories ) import System.FilePath ( (<.>) ) import System.Directory ( doesFileExist ) data DownloadResult = FileAlreadyInCache | FileDownloaded FilePath deriving (Eq) -- Trim trim :: String -> String trim = f . f where f = reverse . dropWhile isSpace -- |Get the local proxy settings --TODO: print info message when we're using a proxy based on verbosity proxy :: Verbosity -> IO Proxy proxy _verbosity = do p <- fetchProxy True -- Handle empty proxy strings return $ case p of Proxy uri auth -> let uri' = trim uri in if uri' == "" then NoProxy else Proxy uri' auth _ -> p mkRequest :: URI -> Maybe String -- ^ Optional etag to be set in the If-None-Match HTTP header. -> Request ByteString mkRequest uri etag = Request{ rqURI = uri , rqMethod = GET , rqHeaders = Header HdrUserAgent userAgent : ifNoneMatchHdr , rqBody = ByteString.empty } where userAgent = concat [ "epm/", display Paths_epm.version , " (", display buildOS, "; ", display buildArch, ")" ] ifNoneMatchHdr = maybe [] (\t -> [Header HdrIfNoneMatch t]) etag -- |Carry out a GET request, using the local proxy settings getHTTP :: Verbosity -> URI -> Maybe String -- ^ Optional etag to check if we already have the latest file. -> IO (Result (Response ByteString)) getHTTP verbosity uri etag = liftM (\(_, resp) -> Right resp) $ cabalBrowse verbosity Nothing (request (mkRequest uri etag)) cabalBrowse :: Verbosity -> Maybe (String, String) -> BrowserAction s a -> IO a cabalBrowse verbosity auth act = do p <- proxy verbosity browse $ do setProxy p setErrHandler (warn verbosity . ("http error: "++)) setOutHandler (debug verbosity) setAllowBasicAuth False setAuthorityGen (\_ _ -> return auth) act downloadURI :: Verbosity -> URI -- ^ What to download -> FilePath -- ^ Where to put it -> IO DownloadResult downloadURI verbosity uri path | uriScheme uri == "file:" = do copyFileVerbose verbosity (uriPath uri) path return (FileDownloaded path) -- Can we store the hash of the file so we can safely return path when the -- hash matches to avoid unnecessary computation? downloadURI verbosity uri path = do let etagPath = path <.> "etag" targetExists <- doesFileExist path etagPathExists <- doesFileExist etagPath -- In rare cases the target file doesn't exist, but the etag does. etag <- if targetExists && etagPathExists then liftM Just $ readFile etagPath else return Nothing result <- getHTTP verbosity uri etag let result' = case result of Left err -> Left err Right rsp -> case rspCode rsp of (2,0,0) -> Right rsp (3,0,4) -> Right rsp (a,b,c) -> Left err where err = ErrorMisc $ "Error HTTP code: " ++ concatMap show [a,b,c] -- Only write the etag if we get a 200 response code. -- A 304 still sends us an etag header. case result' of Left _ -> return () Right rsp -> case rspCode rsp of (2,0,0) -> case lookupHeader HdrETag (rspHeaders rsp) of Nothing -> return () Just newEtag -> writeFile etagPath newEtag (_,_,_) -> return () case result' of Left err -> die $ "Failed to download " ++ show uri ++ " : " ++ show err Right rsp -> case rspCode rsp of (2,0,0) -> do info verbosity ("Downloaded to " ++ path) writeFileAtomic path $ rspBody rsp return (FileDownloaded path) (3,0,4) -> do notice verbosity "Skipping download: Local and remote files match." return FileAlreadyInCache (_,_,_) -> return (FileDownloaded path) --FIXME: check the content-length header matches the body length. --TODO: stream the download into the file rather than buffering the whole -- thing in memory. -- Utility function for legacy support. isOldHackageURI :: URI -> Bool isOldHackageURI uri = case uriAuthority uri of Just (URIAuth {uriRegName = "hackage.haskell.org"}) -> FilePath.Posix.splitDirectories (uriPath uri) == ["/","packages","archive"] _ -> False
typelead/epm
epm/Distribution/Client/HttpUtils.hs
bsd-3-clause
5,840
0
20
1,639
1,471
786
685
126
11
{-# LANGUAGE OverloadedStrings #-} module Network.Sock.Types.Server ( Server(..) , ServerSettings(..) , ServerState(..) , ServerEnvironment(..) ) where ------------------------------------------------------------------------------ import Control.Monad.Trans.State.Strict (StateT) import Control.Concurrent.MVar.Lifted (MVar) ------------------------------------------------------------------------------ import qualified Data.HashMap.Strict as HM (HashMap) import qualified Data.Text as TS (Text) import qualified Data.Conduit as C (ResourceT) ------------------------------------------------------------------------------ import Network.Sock.Types.Application import Network.Sock.Types.Session ------------------------------------------------------------------------------ -- | Server monad. -- TODO: Wrap in newtype. type Server = StateT ServerState (C.ResourceT IO) -- | Sever state. data ServerState = ServerState { serverSettings :: ServerSettings , serverEnvironment :: ServerEnvironment , serverApplicationRouter :: [TS.Text] -> Maybe (Application (C.ResourceT IO)) } -- | Server settings. data ServerSettings = ServerSettings { settingsSockVersion :: TS.Text } -- | Server environment. newtype ServerEnvironment = ServerEnvironment { environmentSessions :: MVar (HM.HashMap SessionID Session) }
Palmik/wai-sockjs
src/Network/Sock/Types/Server.hs
bsd-3-clause
1,402
0
15
218
242
157
85
22
0
{-# LANGUAGE OverloadedStrings , PatternGuards , TypeOperators , DataKinds , GADTs , KindSignatures , FlexibleContexts , RankNTypes , CPP #-} module Main where import Language.Hakaru.Pretty.Concrete import Language.Hakaru.Syntax.TypeCheck import Language.Hakaru.Syntax.IClasses import Language.Hakaru.Syntax.ABT import Language.Hakaru.Syntax.AST as AST import Language.Hakaru.Types.Sing import Language.Hakaru.Types.DataKind import Language.Hakaru.Disintegrate import Language.Hakaru.Evaluation.ConstantPropagation import Language.Hakaru.Command #if __GLASGOW_HASKELL__ < 710 import Control.Applicative (Applicative(..), (<$>)) #endif import Data.Monoid import Control.Monad (when) import qualified Data.Text as T import qualified Data.Text.IO as IO import System.IO (stderr) import Options.Applicative as O data Options = Options { total :: Bool , index :: Int , program :: String } options :: Parser Options options = Options <$> switch ( long "total" <> short 't' <> help "Whether to show the total number of disintegrations" ) <*> option auto ( long "index" <> short 'i' <> metavar "INDEX" <> value 0 <> help "The index of the desired result in the list of disintegrations (default: 0)" ) <*> strArgument ( metavar "PROGRAM" <> help "File containing program to disintegrate" ) parseOpts :: IO Options parseOpts = execParser $ info (helper <*> options) $ fullDesc <> progDesc "Disintegrate a Hakaru program" <> header "disintegrate: symbolic conditioning of probabilistic programs" main :: IO () main = do args <- parseOpts case args of Options t i file -> do prog <- readFromFile file runDisintegrate prog t i runDisintegrate :: T.Text -> Bool -> Int -> IO () runDisintegrate prog showTotal i = case parseAndInfer prog of Left err -> IO.hPutStrLn stderr err Right typedAST -> go Nil1 typedAST where go :: List1 Variable (xs :: [Hakaru]) -> TypedAST (TrivialABT AST.Term) -> IO () go xs (TypedAST typ ast) = case typ of SMeasure (SData (STyCon sym `STyApp` _ `STyApp` _) _) | Just Refl <- jmEq1 sym sSymbol_Pair -> case disintegrate ast of [] -> IO.hPutStrLn stderr "No disintegration found" rs -> when showTotal (IO.hPutStrLn stderr.T.pack $ "Number of disintegrations: " ++ show (length rs)) >> lams xs (print.pretty.constantPropagation) (rs Prelude.!! i) SFun _ b -> caseVarSyn ast putErrorMsg $ \t -> case t of Lam_ :$ body :* End -> caseBind body $ \x e -> go (append1 xs (Cons1 x Nil1)) (TypedAST b e) _ -> putErrorMsg ast _ -> putErrorMsg ast putErrorMsg :: (Show a) => a -> IO () putErrorMsg a = IO.hPutStrLn stderr . T.pack $ "Can only disintegrate (functions over) measures over pairs" -- ++ "\nGiven\n" ++ show a -- | Use a list of variables to wrap lambdas around a given term lams :: (ABT AST.Term abt) => List1 Variable (xs :: [Hakaru]) -> (forall a. abt '[] a -> IO ()) -> abt '[] a -> IO () lams Nil1 k = k lams (Cons1 x xs) k = lams xs (k . lam_ x)
zachsully/hakaru
commands/Disintegrate.hs
bsd-3-clause
3,930
1
21
1,515
944
493
451
93
6
----------------------------------------------------------------------------- -- | -- Module : Network.HTTP.Headers -- Copyright : (c) Warrick Gray 2002, Bjorn Bringert 2003-2005, 2007 Robin Bate Boerop, 2008- Sigbjorn Finne -- License : BSD -- -- Maintainer : Sigbjorn Finne <[email protected]> -- Stability : experimental -- Portability : non-portable (not tested) -- -- This module provides the data types for representing HTTP headers, and -- operations for looking up header values and working with sequences of -- header values in 'Request's and 'Response's. To avoid having to provide -- separate set of operations for doing so, we introduce a type class 'HasHeaders' -- to facilitate writing such processing using overloading instead. -- ----------------------------------------------------------------------------- module Network.HTTP.Headers ( HasHeaders(..) -- type class , Header(..) , mkHeader -- :: HeaderName -> String -> Header , hdrName -- :: Header -> HeaderName , hdrValue -- :: Header -> String , HeaderName(..) , insertHeader -- :: HasHeaders a => HeaderName -> String -> a -> a , insertHeaderIfMissing -- :: HasHeaders a => HeaderName -> String -> a -> a , insertHeaders -- :: HasHeaders a => [Header] -> a -> a , retrieveHeaders -- :: HasHeaders a => HeaderName -> a -> [Header] , replaceHeader -- :: HasHeaders a => HeaderName -> String -> a -> a , findHeader -- :: HasHeaders a => HeaderName -> a -> Maybe String , lookupHeader -- :: HeaderName -> [Header] -> Maybe String , parseHeader -- :: parseHeader :: String -> Result Header , parseHeaders -- :: [String] -> Result [Header] , headerMap -- :: [(String, HeaderName)] , HeaderSetter ) where import Data.Char (toLower) import Network.Stream (Result, failParse) import Network.HTTP.Utils ( trim, split, crlf ) -- | The @Header@ data type pairs header names & values. data Header = Header HeaderName String hdrName :: Header -> HeaderName hdrName (Header h _) = h hdrValue :: Header -> String hdrValue (Header _ v) = v -- | Header constructor as a function, hiding above rep. mkHeader :: HeaderName -> String -> Header mkHeader = Header instance Show Header where show (Header key value) = shows key (':':' ':value ++ crlf) -- | HTTP @HeaderName@ type, a Haskell data constructor for each -- specification-defined header, prefixed with @Hdr@ and CamelCased, -- (i.e., eliding the @-@ in the process.) Should you require using -- a custom header, there's the @HdrCustom@ constructor which takes -- a @String@ argument. -- -- Encoding HTTP header names differently, as Strings perhaps, is an -- equally fine choice..no decidedly clear winner, but let's stick -- with data constructors here. -- data HeaderName -- Generic Headers -- = HdrCacheControl | HdrConnection | HdrDate | HdrPragma | HdrTransferEncoding | HdrUpgrade | HdrVia -- Request Headers -- | HdrAccept | HdrAcceptCharset | HdrAcceptEncoding | HdrAcceptLanguage | HdrAuthorization | HdrCookie | HdrExpect | HdrFrom | HdrHost | HdrIfModifiedSince | HdrIfMatch | HdrIfNoneMatch | HdrIfRange | HdrIfUnmodifiedSince | HdrMaxForwards | HdrProxyAuthorization | HdrRange | HdrReferer | HdrUserAgent -- Response Headers | HdrAge | HdrLocation | HdrProxyAuthenticate | HdrPublic | HdrRetryAfter | HdrServer | HdrSetCookie | HdrTE | HdrTrailer | HdrVary | HdrWarning | HdrWWWAuthenticate -- Entity Headers | HdrAllow | HdrContentBase | HdrContentEncoding | HdrContentLanguage | HdrContentLength | HdrContentLocation | HdrContentMD5 | HdrContentRange | HdrContentType | HdrETag | HdrExpires | HdrLastModified -- | MIME entity headers (for sub-parts) | HdrContentTransferEncoding -- | Allows for unrecognised or experimental headers. | HdrCustom String -- not in header map below. deriving(Eq) -- | @headerMap@ is a straight assoc list for translating between header names -- and values. headerMap :: [ (String,HeaderName) ] headerMap = [ p "Cache-Control" HdrCacheControl , p "Connection" HdrConnection , p "Date" HdrDate , p "Pragma" HdrPragma , p "Transfer-Encoding" HdrTransferEncoding , p "Upgrade" HdrUpgrade , p "Via" HdrVia , p "Accept" HdrAccept , p "Accept-Charset" HdrAcceptCharset , p "Accept-Encoding" HdrAcceptEncoding , p "Accept-Language" HdrAcceptLanguage , p "Authorization" HdrAuthorization , p "Cookie" HdrCookie , p "Expect" HdrExpect , p "From" HdrFrom , p "Host" HdrHost , p "If-Modified-Since" HdrIfModifiedSince , p "If-Match" HdrIfMatch , p "If-None-Match" HdrIfNoneMatch , p "If-Range" HdrIfRange , p "If-Unmodified-Since" HdrIfUnmodifiedSince , p "Max-Forwards" HdrMaxForwards , p "Proxy-Authorization" HdrProxyAuthorization , p "Range" HdrRange , p "Referer" HdrReferer , p "User-Agent" HdrUserAgent , p "Age" HdrAge , p "Location" HdrLocation , p "Proxy-Authenticate" HdrProxyAuthenticate , p "Public" HdrPublic , p "Retry-After" HdrRetryAfter , p "Server" HdrServer , p "Set-Cookie" HdrSetCookie , p "TE" HdrTE , p "Trailer" HdrTrailer , p "Vary" HdrVary , p "Warning" HdrWarning , p "WWW-Authenticate" HdrWWWAuthenticate , p "Allow" HdrAllow , p "Content-Base" HdrContentBase , p "Content-Encoding" HdrContentEncoding , p "Content-Language" HdrContentLanguage , p "Content-Length" HdrContentLength , p "Content-Location" HdrContentLocation , p "Content-MD5" HdrContentMD5 , p "Content-Range" HdrContentRange , p "Content-Type" HdrContentType , p "ETag" HdrETag , p "Expires" HdrExpires , p "Last-Modified" HdrLastModified , p "Content-Transfer-Encoding" HdrContentTransferEncoding ] where p a b = (a,b) instance Show HeaderName where show (HdrCustom s) = s show x = case filter ((==x).snd) headerMap of [] -> error "headerMap incomplete" (h:_) -> fst h -- | @HasHeaders@ is a type class for types containing HTTP headers, allowing -- you to write overloaded header manipulation functions -- for both 'Request' and 'Response' data types, for instance. class HasHeaders x where getHeaders :: x -> [Header] setHeaders :: x -> [Header] -> x -- Header manipulation functions type HeaderSetter a = HeaderName -> String -> a -> a -- | @insertHeader hdr val x@ inserts a header with the given header name -- and value. Does not check for existing headers with same name, allowing -- duplicates to be introduce (use 'replaceHeader' if you want to avoid this.) insertHeader :: HasHeaders a => HeaderSetter a insertHeader name value x = setHeaders x newHeaders where newHeaders = (Header name value) : getHeaders x -- | @insertHeaderIfMissing hdr val x@ adds the new header only if no previous -- header with name @hdr@ exists in @x@. insertHeaderIfMissing :: HasHeaders a => HeaderSetter a insertHeaderIfMissing name value x = setHeaders x (newHeaders $ getHeaders x) where newHeaders list@(h@(Header n _): rest) | n == name = list | otherwise = h : newHeaders rest newHeaders [] = [Header name value] -- | @replaceHeader hdr val o@ replaces the header @hdr@ with the -- value @val@, dropping any existing replaceHeader :: HasHeaders a => HeaderSetter a replaceHeader name value h = setHeaders h newHeaders where newHeaders = Header name value : [ x | x@(Header n _) <- getHeaders h, name /= n ] -- | @insertHeaders hdrs x@ appends multiple headers to @x@'s existing -- set. insertHeaders :: HasHeaders a => [Header] -> a -> a insertHeaders hdrs x = setHeaders x (getHeaders x ++ hdrs) -- | @retrieveHeaders hdrNm x@ gets a list of headers with 'HeaderName' @hdrNm@. retrieveHeaders :: HasHeaders a => HeaderName -> a -> [Header] retrieveHeaders name x = filter matchname (getHeaders x) where matchname (Header n _) = n == name -- | @findHeader hdrNm x@ looks up @hdrNm@ in @x@, returning the first -- header that matches, if any. findHeader :: HasHeaders a => HeaderName -> a -> Maybe String findHeader n x = lookupHeader n (getHeaders x) -- | @lookupHeader hdr hdrs@ locates the first header matching @hdr@ in the -- list @hdrs@. lookupHeader :: HeaderName -> [Header] -> Maybe String lookupHeader _ [] = Nothing lookupHeader v (Header n s:t) | v == n = Just s | otherwise = lookupHeader v t -- | @parseHeader headerNameAndValueString@ tries to unscramble a -- @header: value@ pairing and returning it as a 'Header'. parseHeader :: String -> Result Header parseHeader str = case split ':' str of Nothing -> failParse ("Unable to parse header: " ++ str) Just (k,v) -> return $ Header (fn k) (trim $ drop 1 v) where fn k = case map snd $ filter (match k . fst) headerMap of [] -> (HdrCustom k) (h:_) -> h match :: String -> String -> Bool match s1 s2 = map toLower s1 == map toLower s2 -- | @parseHeaders hdrs@ takes a sequence of strings holding header -- information and parses them into a set of headers (preserving their -- order in the input argument.) Handles header values split up over -- multiple lines. parseHeaders :: [String] -> Result [Header] parseHeaders = catRslts [] . map (parseHeader . clean) . joinExtended "" where -- Joins consecutive lines where the second line -- begins with ' ' or '\t'. joinExtended old [] = [old] joinExtended old (h : t) | isLineExtension h = joinExtended (old ++ ' ' : tail h) t | otherwise = old : joinExtended h t isLineExtension (x:_) = x == ' ' || x == '\t' isLineExtension _ = False clean [] = [] clean (h:t) | h `elem` "\t\r\n" = ' ' : clean t | otherwise = h : clean t -- tolerant of errors? should parse -- errors here be reported or ignored? -- currently ignored. catRslts :: [a] -> [Result a] -> Result [a] catRslts list (h:t) = case h of Left _ -> catRslts list t Right v -> catRslts (v:list) t catRslts list [] = Right $ reverse list
astro/HTTPbis
Network/HTTP/Headers.hs
bsd-3-clause
10,933
15
14
2,999
2,023
1,109
914
200
6
module GraphVizGenSpec where import TestPrograms import Test.Hspec import Data.CFG (progToCfg, writeVizCfg) import Data.Cmm.Parser (parse, program) main :: IO () main = hspec spec spec :: Spec spec = it "generates graphviz file" $ generateGviz generateGviz :: IO () generateGviz = mapM_ fun testPrograms where fun (nm, prog) = either (error "did not parse") (\p -> writeVizCfg (progToCfg p) nm) $ parse program nm prog
adamschoenemann/asa-analysis
test/GraphVizGenSpec.hs
bsd-3-clause
448
0
13
93
151
82
69
13
1
{- Data/Singletons/TH/Promote/Monad.hs (c) Richard Eisenberg 2014 [email protected] This file defines the PrM monad and its operations, for use during promotion. The PrM monad allows reading from a PrEnv environment and writing to a list of DDec, and is wrapped around a Q. -} module Data.Singletons.TH.Promote.Monad ( PrM, promoteM, promoteM_, promoteMDecs, VarPromotions, allLocals, emitDecs, emitDecsM, lambdaBind, LetBind, letBind, lookupVarE, forallBind, allBoundKindVars ) where import Control.Monad.Reader import Control.Monad.Writer import Language.Haskell.TH.Syntax hiding ( lift ) import Language.Haskell.TH.Desugar import qualified Language.Haskell.TH.Desugar.OMap.Strict as OMap import Language.Haskell.TH.Desugar.OMap.Strict (OMap) import qualified Language.Haskell.TH.Desugar.OSet as OSet import Language.Haskell.TH.Desugar.OSet (OSet) import Data.Singletons.TH.Options import Data.Singletons.TH.Syntax type LetExpansions = OMap Name DType -- from **term-level** name -- environment during promotion data PrEnv = PrEnv { pr_options :: Options , pr_lambda_bound :: OMap Name Name , pr_let_bound :: LetExpansions , pr_forall_bound :: OSet Name -- See Note [Explicitly binding kind variables] , pr_local_decls :: [Dec] } emptyPrEnv :: PrEnv emptyPrEnv = PrEnv { pr_options = defaultOptions , pr_lambda_bound = OMap.empty , pr_let_bound = OMap.empty , pr_forall_bound = OSet.empty , pr_local_decls = [] } -- the promotion monad newtype PrM a = PrM (ReaderT PrEnv (WriterT [DDec] Q) a) deriving ( Functor, Applicative, Monad, Quasi , MonadReader PrEnv, MonadWriter [DDec] , MonadFail, MonadIO ) instance DsMonad PrM where localDeclarations = asks pr_local_decls instance OptionsMonad PrM where getOptions = asks pr_options -- return *type-level* names allLocals :: MonadReader PrEnv m => m [Name] allLocals = do lambdas <- asks (OMap.assocs . pr_lambda_bound) lets <- asks pr_let_bound -- filter out shadowed variables! return [ typeName | (termName, typeName) <- lambdas , case OMap.lookup termName lets of Just (DVarT typeName') | typeName' == typeName -> True _ -> False ] emitDecs :: MonadWriter [DDec] m => [DDec] -> m () emitDecs = tell emitDecsM :: MonadWriter [DDec] m => m [DDec] -> m () emitDecsM action = do decs <- action emitDecs decs -- when lambda-binding variables, we still need to add the variables -- to the let-expansion, because of shadowing. ugh. lambdaBind :: VarPromotions -> PrM a -> PrM a lambdaBind binds = local add_binds where add_binds env@(PrEnv { pr_lambda_bound = lambdas , pr_let_bound = lets }) = let new_lets = OMap.fromList [ (tmN, DVarT tyN) | (tmN, tyN) <- binds ] in env { pr_lambda_bound = OMap.fromList binds `OMap.union` lambdas , pr_let_bound = new_lets `OMap.union` lets } type LetBind = (Name, DType) letBind :: [LetBind] -> PrM a -> PrM a letBind binds = local add_binds where add_binds env@(PrEnv { pr_let_bound = lets }) = env { pr_let_bound = OMap.fromList binds `OMap.union` lets } lookupVarE :: Name -> PrM DType lookupVarE n = do opts <- getOptions lets <- asks pr_let_bound case OMap.lookup n lets of Just ty -> return ty Nothing -> return $ DConT $ defunctionalizedName0 opts n -- Add to the set of bound kind variables currently in scope. -- See Note [Explicitly binding kind variables] forallBind :: OSet Name -> PrM a -> PrM a forallBind kvs1 = local (\env@(PrEnv { pr_forall_bound = kvs2 }) -> env { pr_forall_bound = kvs1 `OSet.union` kvs2 }) -- Look up the set of bound kind variables currently in scope. -- See Note [Explicitly binding kind variables] allBoundKindVars :: PrM (OSet Name) allBoundKindVars = asks pr_forall_bound promoteM :: OptionsMonad q => [Dec] -> PrM a -> q (a, [DDec]) promoteM locals (PrM rdr) = do opts <- getOptions other_locals <- localDeclarations let wr = runReaderT rdr (emptyPrEnv { pr_options = opts , pr_local_decls = other_locals ++ locals }) q = runWriterT wr runQ q promoteM_ :: OptionsMonad q => [Dec] -> PrM () -> q [DDec] promoteM_ locals thing = do ((), decs) <- promoteM locals thing return decs -- promoteM specialized to [DDec] promoteMDecs :: OptionsMonad q => [Dec] -> PrM [DDec] -> q [DDec] promoteMDecs locals thing = do (decs1, decs2) <- promoteM locals thing return $ decs1 ++ decs2 {- Note [Explicitly binding kind variables] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We want to ensure that when we single type signatures for functions and data constructors, we should explicitly quantify every kind variable bound by a forall. For example, if we were to single the identity function: identity :: forall a. a -> a identity x = x We want the final result to be: sIdentity :: forall a (x :: a). Sing x -> Sing (Identity x :: a) sIdentity sX = sX Accomplishing this takes a bit of care during promotion. When promoting a function, we determine what set of kind variables are currently bound at that point and store them in an ALetDecEnv (as lde_bound_kvs), which in turn is singled. Then, during singling, we extract every kind variable in a singled type signature, subtract the lde_bound_kvs, and explicitly bind the variables that remain. For a top-level function like identity, lde_bound_kvs is the empty set. But consider this more complicated example: f :: forall a. a -> a f = g where g :: a -> a g x = x When singling, we would eventually end up in this spot: sF :: forall a (x :: a). Sing a -> Sing (F a :: a) sF = sG where sG :: _ sG x = x We must make sure /not/ to fill in the following type for _: sF :: forall a (x :: a). Sing a -> Sing (F a :: a) sF = sG where sG :: forall a (y :: a). Sing a -> Sing (G a :: a) sG x = x This would be incorrect, as the `a` bound by sF /must/ be the same one used in sG, as per the scoping of the original `f` function. Thus, we ensure that the bound variables from `f` are put into lde_bound_kvs when promoting `g` so that we subtract out `a` and are left with the correct result: sF :: forall a (x :: a). Sing a -> Sing (F a :: a) sF = sG where sG :: forall (y :: a). Sing a -> Sing (G a :: a) sG x = x -}
goldfirere/singletons
singletons-th/src/Data/Singletons/TH/Promote/Monad.hs
bsd-3-clause
6,561
0
16
1,586
1,255
687
568
-1
-1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP #-} module TcValidity ( Rank, UserTypeCtxt(..), checkValidType, checkValidMonoType, expectedKindInCtxt, checkValidTheta, checkValidFamPats, checkValidInstance, validDerivPred, checkInstTermination, ClsInfo, checkValidCoAxiom, checkValidCoAxBranch, checkValidTyFamEqn, checkConsistentFamInst, arityErr, badATErr ) where #include "HsVersions.h" -- friends: import TcUnify ( tcSubType_NC ) import TcSimplify ( simplifyAmbiguityCheck ) import TypeRep import TcType import TcMType import TysWiredIn ( coercibleClass, eqTyCon ) import PrelNames import Type import Unify( tcMatchTyX ) import Kind import CoAxiom import Class import TyCon -- others: import Coercion ( pprCoAxBranch ) import HsSyn -- HsType import TcRnMonad -- TcType, amongst others import FunDeps import FamInstEnv ( isDominatedBy, injectiveBranches, InjectivityCheckResult(..) ) import FamInst ( makeInjectivityErrors ) import Name import VarEnv import VarSet import ErrUtils import DynFlags import Util import ListSetOps import SrcLoc import Outputable import FastString import Control.Monad import Data.Maybe import Data.List ( (\\) ) {- ************************************************************************ * * Checking for ambiguity * * ************************************************************************ Note [The ambiguity check for type signatures] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ checkAmbiguity is a check on *user-supplied type signatures*. It is *purely* there to report functions that cannot possibly be called. So for example we want to reject: f :: C a => Int The idea is there can be no legal calls to 'f' because every call will give rise to an ambiguous constraint. We could soundly omit the ambiguity check on type signatures entirely, at the expense of delaying ambiguity errors to call sites. Indeed, the flag -XAllowAmbiguousTypes switches off the ambiguity check. What about things like this: class D a b | a -> b where .. h :: D Int b => Int The Int may well fix 'b' at the call site, so that signature should not be rejected. Moreover, using *visible* fundeps is too conservative. Consider class X a b where ... class D a b | a -> b where ... instance D a b => X [a] b where... h :: X a b => a -> a Here h's type looks ambiguous in 'b', but here's a legal call: ...(h [True])... That gives rise to a (X [Bool] beta) constraint, and using the instance means we need (D Bool beta) and that fixes 'beta' via D's fundep! Behind all these special cases there is a simple guiding principle. Consider f :: <type> f = ...blah... g :: <type> g = f You would think that the definition of g would surely typecheck! After all f has exactly the same type, and g=f. But in fact f's type is instantiated and the instantiated constraints are solved against the originals, so in the case an ambiguous type it won't work. Consider our earlier example f :: C a => Int. Then in g's definition, we'll instantiate to (C alpha) and try to deduce (C alpha) from (C a), and fail. So in fact we use this as our *definition* of ambiguity. We use a very similar test for *inferred* types, to ensure that they are unambiguous. See Note [Impedence matching] in TcBinds. This test is very conveniently implemented by calling tcSubType <type> <type> This neatly takes account of the functional dependecy stuff above, and implicit parameter (see Note [Implicit parameters and ambiguity]). And this is what checkAmbiguity does. What about this, though? g :: C [a] => Int Is every call to 'g' ambiguous? After all, we might have intance C [a] where ... at the call site. So maybe that type is ok! Indeed even f's quintessentially ambiguous type might, just possibly be callable: with -XFlexibleInstances we could have instance C a where ... and now a call could be legal after all! Well, we'll reject this unless the instance is available *here*. Note [When to call checkAmbiguity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We call checkAmbiguity (a) on user-specified type signatures (b) in checkValidType Conncerning (b), you might wonder about nested foralls. What about f :: forall b. (forall a. Eq a => b) -> b The nested forall is ambiguous. Originally we called checkAmbiguity in the forall case of check_type, but that had two bad consequences: * We got two error messages about (Eq b) in a nested forall like this: g :: forall a. Eq a => forall b. Eq b => a -> a * If we try to check for ambiguity of an nested forall like (forall a. Eq a => b), the implication constraint doesn't bind all the skolems, which results in "No skolem info" in error messages (see Trac #10432). To avoid this, we call checkAmbiguity once, at the top, in checkValidType. (I'm still a bit worried about unbound skolems when the type mentions in-scope type variables.) In fact, because of the co/contra-variance implemented in tcSubType, this *does* catch function f above. too. Concerning (a) the ambiguity check is only used for *user* types, not for types coming from inteface files. The latter can legitimately have ambiguous types. Example class S a where s :: a -> (Int,Int) instance S Char where s _ = (1,1) f:: S a => [a] -> Int -> (Int,Int) f (_::[a]) x = (a*x,b) where (a,b) = s (undefined::a) Here the worker for f gets the type fw :: forall a. S a => Int -> (# Int, Int #) Note [Implicit parameters and ambiguity] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Only a *class* predicate can give rise to ambiguity An *implicit parameter* cannot. For example: foo :: (?x :: [a]) => Int foo = length ?x is fine. The call site will supply a particular 'x' Furthermore, the type variables fixed by an implicit parameter propagate to the others. E.g. foo :: (Show a, ?x::[a]) => Int foo = show (?x++?x) The type of foo looks ambiguous. But it isn't, because at a call site we might have let ?x = 5::Int in foo and all is well. In effect, implicit parameters are, well, parameters, so we can take their type variables into account as part of the "tau-tvs" stuff. This is done in the function 'FunDeps.grow'. -} checkAmbiguity :: UserTypeCtxt -> Type -> TcM () checkAmbiguity ctxt ty | GhciCtxt <- ctxt -- Allow ambiguous types in GHCi's :kind command = return () -- E.g. type family T a :: * -- T :: forall k. k -> * -- Then :k T should work in GHCi, not complain that -- (T k) is ambiguous! | InfSigCtxt {} <- ctxt -- See Note [Validity of inferred types] in TcBinds = return () | otherwise = do { traceTc "Ambiguity check for" (ppr ty) ; let free_tkvs = varSetElemsKvsFirst (closeOverKinds (tyVarsOfType ty)) ; (subst, _tvs) <- tcInstSkolTyVars free_tkvs ; let ty' = substTy subst ty -- The type might have free TyVars, esp when the ambiguity check -- happens during a call to checkValidType, -- so we skolemise them as TcTyVars. -- Tiresome; but the type inference engine expects TcTyVars -- NB: The free tyvar might be (a::k), so k is also free -- and we must skolemise it as well. Hence closeOverKinds. -- (Trac #9222) -- Solve the constraints eagerly because an ambiguous type -- can cause a cascade of further errors. Since the free -- tyvars are skolemised, we can safely use tcSimplifyTop ; (_wrap, wanted) <- addErrCtxtM (mk_msg ty') $ captureConstraints $ tcSubType_NC ctxt ty' ty' ; whenNoErrs $ -- only run the simplifier if we have a clean -- environment. Otherwise we might trip. -- example: indexed-types/should_fail/BadSock -- fails in DEBUG mode without this simplifyAmbiguityCheck ty wanted ; traceTc "Done ambiguity check for" (ppr ty) } where mk_msg ty tidy_env = do { allow_ambiguous <- xoptM Opt_AllowAmbiguousTypes ; (tidy_env', tidy_ty) <- zonkTidyTcType tidy_env ty ; return (tidy_env', mk_msg tidy_ty $$ ppWhen (not allow_ambiguous) ambig_msg) } where mk_msg ty = pprSigCtxt ctxt (ptext (sLit "the ambiguity check for")) (ppr ty) ambig_msg = ptext (sLit "To defer the ambiguity check to use sites, enable AllowAmbiguousTypes") checkUserTypeError :: Type -> TcM () checkUserTypeError = check where check ty | Just (_,msg) <- isUserErrorTy ty = failWithTc (pprUserTypeErrorTy msg) | Just (_,ts) <- splitTyConApp_maybe ty = mapM_ check ts | Just (t1,t2) <- splitAppTy_maybe ty = check t1 >> check t2 | otherwise = return () {- ************************************************************************ * * Checking validity of a user-defined type * * ************************************************************************ When dealing with a user-written type, we first translate it from an HsType to a Type, performing kind checking, and then check various things that should be true about it. We don't want to perform these checks at the same time as the initial translation because (a) they are unnecessary for interface-file types and (b) when checking a mutually recursive group of type and class decls, we can't "look" at the tycons/classes yet. Also, the checks are rather diverse, and used to really mess up the other code. One thing we check for is 'rank'. Rank 0: monotypes (no foralls) Rank 1: foralls at the front only, Rank 0 inside Rank 2: foralls at the front, Rank 1 on left of fn arrow, basic ::= tyvar | T basic ... basic r2 ::= forall tvs. cxt => r2a r2a ::= r1 -> r2a | basic r1 ::= forall tvs. cxt => r0 r0 ::= r0 -> r0 | basic Another thing is to check that type synonyms are saturated. This might not necessarily show up in kind checking. type A i = i data T k = MkT (k Int) f :: T A -- BAD! -} checkValidType :: UserTypeCtxt -> Type -> TcM () -- Checks that the type is valid for the given context -- Not used for instance decls; checkValidInstance instead checkValidType ctxt ty = do { traceTc "checkValidType" (ppr ty <+> text "::" <+> ppr (typeKind ty)) ; rankn_flag <- xoptM Opt_RankNTypes ; let gen_rank :: Rank -> Rank gen_rank r | rankn_flag = ArbitraryRank | otherwise = r rank1 = gen_rank r1 rank0 = gen_rank r0 r0 = rankZeroMonoType r1 = LimitedRank True r0 rank = case ctxt of DefaultDeclCtxt-> MustBeMonoType ResSigCtxt -> MustBeMonoType PatSigCtxt -> rank0 RuleSigCtxt _ -> rank1 TySynCtxt _ -> rank0 ExprSigCtxt -> rank1 FunSigCtxt {} -> rank1 InfSigCtxt _ -> ArbitraryRank -- Inferred type ConArgCtxt _ -> rank1 -- We are given the type of the entire -- constructor, hence rank 1 ForSigCtxt _ -> rank1 SpecInstCtxt -> rank1 ThBrackCtxt -> rank1 GhciCtxt -> ArbitraryRank _ -> panic "checkValidType" -- Can't happen; not used for *user* sigs -- Check the internal validity of the type itself ; check_type ctxt rank ty -- Check that the thing has kind Type, and is lifted if necessary. -- Do this *after* check_type, because we can't usefully take -- the kind of an ill-formed type such as (a~Int) ; check_kind ctxt ty ; checkUserTypeError ty -- Check for ambiguous types. See Note [When to call checkAmbiguity] -- NB: this will happen even for monotypes, but that should be cheap; -- and there may be nested foralls for the subtype test to examine ; checkAmbiguity ctxt ty ; traceTc "checkValidType done" (ppr ty <+> text "::" <+> ppr (typeKind ty)) } checkValidMonoType :: Type -> TcM () checkValidMonoType ty = check_mono_type SigmaCtxt MustBeMonoType ty check_kind :: UserTypeCtxt -> TcType -> TcM () -- Check that the type's kind is acceptable for the context check_kind ctxt ty | TySynCtxt {} <- ctxt , returnsConstraintKind actual_kind = do { ck <- xoptM Opt_ConstraintKinds ; if ck then when (isConstraintKind actual_kind) (do { dflags <- getDynFlags ; check_pred_ty dflags ctxt ty }) else addErrTc (constraintSynErr actual_kind) } | Just k <- expectedKindInCtxt ctxt = checkTc (tcIsSubKind actual_kind k) (kindErr actual_kind) | otherwise = return () -- Any kind will do where actual_kind = typeKind ty -- Depending on the context, we might accept any kind (for instance, in a TH -- splice), or only certain kinds (like in type signatures). expectedKindInCtxt :: UserTypeCtxt -> Maybe Kind expectedKindInCtxt (TySynCtxt _) = Nothing -- Any kind will do expectedKindInCtxt ThBrackCtxt = Nothing expectedKindInCtxt GhciCtxt = Nothing -- The types in a 'default' decl can have varying kinds -- See Note [Extended defaults]" in TcEnv expectedKindInCtxt DefaultDeclCtxt = Nothing expectedKindInCtxt (ForSigCtxt _) = Just liftedTypeKind expectedKindInCtxt InstDeclCtxt = Just constraintKind expectedKindInCtxt SpecInstCtxt = Just constraintKind expectedKindInCtxt _ = Just openTypeKind {- Note [Higher rank types] ~~~~~~~~~~~~~~~~~~~~~~~~ Technically Int -> forall a. a->a is still a rank-1 type, but it's not Haskell 98 (Trac #5957). So the validity checker allow a forall after an arrow only if we allow it before -- that is, with Rank2Types or RankNTypes -} data Rank = ArbitraryRank -- Any rank ok | LimitedRank -- Note [Higher rank types] Bool -- Forall ok at top Rank -- Use for function arguments | MonoType SDoc -- Monotype, with a suggestion of how it could be a polytype | MustBeMonoType -- Monotype regardless of flags rankZeroMonoType, tyConArgMonoType, synArgMonoType :: Rank rankZeroMonoType = MonoType (ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types")) tyConArgMonoType = MonoType (ptext (sLit "GHC doesn't yet support impredicative polymorphism")) synArgMonoType = MonoType (ptext (sLit "Perhaps you intended to use LiberalTypeSynonyms")) funArgResRank :: Rank -> (Rank, Rank) -- Function argument and result funArgResRank (LimitedRank _ arg_rank) = (arg_rank, LimitedRank (forAllAllowed arg_rank) arg_rank) funArgResRank other_rank = (other_rank, other_rank) forAllAllowed :: Rank -> Bool forAllAllowed ArbitraryRank = True forAllAllowed (LimitedRank forall_ok _) = forall_ok forAllAllowed _ = False ---------------------------------------- check_mono_type :: UserTypeCtxt -> Rank -> KindOrType -> TcM () -- No foralls anywhere -- No unlifted types of any kind check_mono_type ctxt rank ty | isKind ty = return () -- IA0_NOTE: Do we need to check kinds? | otherwise = do { check_type ctxt rank ty ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) } check_type :: UserTypeCtxt -> Rank -> Type -> TcM () -- The args say what the *type context* requires, independent -- of *flag* settings. You test the flag settings at usage sites. -- -- Rank is allowed rank for function args -- Rank 0 means no for-alls anywhere check_type ctxt rank ty | not (null tvs && null theta) = do { checkTc (forAllAllowed rank) (forAllTyErr rank ty) -- Reject e.g. (Maybe (?x::Int => Int)), -- with a decent error message ; check_valid_theta SigmaCtxt theta -- Allow type T = ?x::Int => Int -> Int -- but not type T = ?x::Int ; check_type ctxt rank tau } -- Allow foralls to right of arrow where (tvs, theta, tau) = tcSplitSigmaTy ty check_type _ _ (TyVarTy _) = return () check_type ctxt rank (FunTy arg_ty res_ty) = do { check_type ctxt arg_rank arg_ty ; check_type ctxt res_rank res_ty } where (arg_rank, res_rank) = funArgResRank rank check_type ctxt rank (AppTy ty1 ty2) = do { check_arg_type ctxt rank ty1 ; check_arg_type ctxt rank ty2 } check_type ctxt rank ty@(TyConApp tc tys) | isTypeSynonymTyCon tc || isTypeFamilyTyCon tc = check_syn_tc_app ctxt rank ty tc tys | isUnboxedTupleTyCon tc = check_ubx_tuple ctxt ty tys | otherwise = mapM_ (check_arg_type ctxt rank) tys check_type _ _ (LitTy {}) = return () check_type _ _ ty = pprPanic "check_type" (ppr ty) ---------------------------------------- check_syn_tc_app :: UserTypeCtxt -> Rank -> KindOrType -> TyCon -> [KindOrType] -> TcM () -- Used for type synonyms and type synonym families, -- which must be saturated, -- but not data families, which need not be saturated check_syn_tc_app ctxt rank ty tc tys | tc_arity <= length tys -- Saturated -- Check that the synonym has enough args -- This applies equally to open and closed synonyms -- It's OK to have an *over-applied* type synonym -- data Tree a b = ... -- type Foo a = Tree [a] -- f :: Foo a b -> ... = do { -- See Note [Liberal type synonyms] ; liberal <- xoptM Opt_LiberalTypeSynonyms ; if not liberal || isTypeFamilyTyCon tc then -- For H98 and synonym families, do check the type args mapM_ check_arg tys else -- In the liberal case (only for closed syns), expand then check case tcView ty of Just ty' -> check_type ctxt rank ty' Nothing -> pprPanic "check_tau_type" (ppr ty) } | GhciCtxt <- ctxt -- Accept under-saturated type synonyms in -- GHCi :kind commands; see Trac #7586 = mapM_ check_arg tys | otherwise = failWithTc (tyConArityErr tc tys) where tc_arity = tyConArity tc check_arg | isTypeFamilyTyCon tc = check_arg_type ctxt rank | otherwise = check_mono_type ctxt synArgMonoType ---------------------------------------- check_ubx_tuple :: UserTypeCtxt -> KindOrType -> [KindOrType] -> TcM () check_ubx_tuple ctxt ty tys = do { ub_tuples_allowed <- xoptM Opt_UnboxedTuples ; checkTc ub_tuples_allowed (ubxArgTyErr ty) ; impred <- xoptM Opt_ImpredicativeTypes ; let rank' = if impred then ArbitraryRank else tyConArgMonoType -- c.f. check_arg_type -- However, args are allowed to be unlifted, or -- more unboxed tuples, so can't use check_arg_ty ; mapM_ (check_type ctxt rank') tys } ---------------------------------------- check_arg_type :: UserTypeCtxt -> Rank -> KindOrType -> TcM () -- The sort of type that can instantiate a type variable, -- or be the argument of a type constructor. -- Not an unboxed tuple, but now *can* be a forall (since impredicativity) -- Other unboxed types are very occasionally allowed as type -- arguments depending on the kind of the type constructor -- -- For example, we want to reject things like: -- -- instance Ord a => Ord (forall s. T s a) -- and -- g :: T s (forall b.b) -- -- NB: unboxed tuples can have polymorphic or unboxed args. -- This happens in the workers for functions returning -- product types with polymorphic components. -- But not in user code. -- Anyway, they are dealt with by a special case in check_tau_type check_arg_type ctxt rank ty | isKind ty = return () -- IA0_NOTE: Do we need to check a kind? | otherwise = do { impred <- xoptM Opt_ImpredicativeTypes ; let rank' = case rank of -- Predictive => must be monotype MustBeMonoType -> MustBeMonoType -- Monotype, regardless _other | impred -> ArbitraryRank | otherwise -> tyConArgMonoType -- Make sure that MustBeMonoType is propagated, -- so that we don't suggest -XImpredicativeTypes in -- (Ord (forall a.a)) => a -> a -- and so that if it Must be a monotype, we check that it is! ; check_type ctxt rank' ty ; checkTc (not (isUnLiftedType ty)) (unliftedArgErr ty) } -- NB the isUnLiftedType test also checks for -- T State# -- where there is an illegal partial application of State# (which has -- kind * -> #); see Note [The kind invariant] in TypeRep ---------------------------------------- forAllTyErr :: Rank -> Type -> SDoc forAllTyErr rank ty = vcat [ hang (ptext (sLit "Illegal polymorphic or qualified type:")) 2 (ppr ty) , suggestion ] where suggestion = case rank of LimitedRank {} -> ptext (sLit "Perhaps you intended to use RankNTypes or Rank2Types") MonoType d -> d _ -> Outputable.empty -- Polytype is always illegal unliftedArgErr, ubxArgTyErr :: Type -> SDoc unliftedArgErr ty = sep [ptext (sLit "Illegal unlifted type:"), ppr ty] ubxArgTyErr ty = sep [ptext (sLit "Illegal unboxed tuple type as function argument:"), ppr ty] kindErr :: Kind -> SDoc kindErr kind = sep [ptext (sLit "Expecting an ordinary type, but found a type of kind"), ppr kind] {- Note [Liberal type synonyms] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If -XLiberalTypeSynonyms is on, expand closed type synonyms *before* doing validity checking. This allows us to instantiate a synonym defn with a for-all type, or with a partially-applied type synonym. e.g. type T a b = a type S m = m () f :: S (T Int) Here, T is partially applied, so it's illegal in H98. But if you expand S first, then T we get just f :: Int which is fine. IMPORTANT: suppose T is a type synonym. Then we must do validity checking on an appliation (T ty1 ty2) *either* before expansion (i.e. check ty1, ty2) *or* after expansion (i.e. expand T ty1 ty2, and then check) BUT NOT BOTH If we do both, we get exponential behaviour!! data TIACons1 i r c = c i ::: r c type TIACons2 t x = TIACons1 t (TIACons1 t x) type TIACons3 t x = TIACons2 t (TIACons1 t x) type TIACons4 t x = TIACons2 t (TIACons2 t x) type TIACons7 t x = TIACons4 t (TIACons3 t x) ************************************************************************ * * \subsection{Checking a theta or source type} * * ************************************************************************ Note [Implicit parameters in instance decls] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Implicit parameters _only_ allowed in type signatures; not in instance decls, superclasses etc. The reason for not allowing implicit params in instances is a bit subtle. If we allowed instance (?x::Int, Eq a) => Foo [a] where ... then when we saw (e :: (?x::Int) => t) it would be unclear how to discharge all the potential uses of the ?x in e. For example, a constraint Foo [Int] might come out of e, and applying the instance decl would show up two uses of ?x. Trac #8912. -} checkValidTheta :: UserTypeCtxt -> ThetaType -> TcM () checkValidTheta ctxt theta = addErrCtxt (checkThetaCtxt ctxt theta) (check_valid_theta ctxt theta) ------------------------- check_valid_theta :: UserTypeCtxt -> [PredType] -> TcM () check_valid_theta _ [] = return () check_valid_theta ctxt theta = do { dflags <- getDynFlags ; warnTc (wopt Opt_WarnDuplicateConstraints dflags && notNull dups) (dupPredWarn dups) ; traceTc "check_valid_theta" (ppr theta) ; mapM_ (check_pred_ty dflags ctxt) theta } where (_,dups) = removeDups cmpPred theta ------------------------- check_pred_ty :: DynFlags -> UserTypeCtxt -> PredType -> TcM () -- Check the validity of a predicate in a signature -- Do not look through any type synonyms; any constraint kinded -- type synonyms have been checked at their definition site -- C.f. Trac #9838 check_pred_ty dflags ctxt pred = do { checkValidMonoType pred ; check_pred_help False dflags ctxt pred } check_pred_help :: Bool -- True <=> under a type synonym -> DynFlags -> UserTypeCtxt -> PredType -> TcM () check_pred_help under_syn dflags ctxt pred | Just pred' <- coreView pred -- Switch on under_syn when going under a -- synonym (Trac #9838, yuk) = check_pred_help True dflags ctxt pred' | otherwise = case splitTyConApp_maybe pred of Just (tc, tys) | isTupleTyCon tc -> check_tuple_pred under_syn dflags ctxt pred tys | Just cls <- tyConClass_maybe tc -> check_class_pred dflags ctxt pred cls tys -- Includes Coercible | tc `hasKey` eqTyConKey -> check_eq_pred dflags pred tys _ -> check_irred_pred under_syn dflags ctxt pred check_eq_pred :: DynFlags -> PredType -> [TcType] -> TcM () check_eq_pred dflags pred tys = -- Equational constraints are valid in all contexts if type -- families are permitted do { checkTc (length tys == 3) (tyConArityErr eqTyCon tys) ; checkTc (xopt Opt_TypeFamilies dflags || xopt Opt_GADTs dflags) (eqPredTyErr pred) } check_tuple_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> [PredType] -> TcM () check_tuple_pred under_syn dflags ctxt pred ts = do { -- See Note [ConstraintKinds in predicates] checkTc (under_syn || xopt Opt_ConstraintKinds dflags) (predTupleErr pred) ; mapM_ (check_pred_help under_syn dflags ctxt) ts } -- This case will not normally be executed because without -- -XConstraintKinds tuple types are only kind-checked as * check_irred_pred :: Bool -> DynFlags -> UserTypeCtxt -> PredType -> TcM () check_irred_pred under_syn dflags ctxt pred -- The predicate looks like (X t1 t2) or (x t1 t2) :: Constraint -- where X is a type function = do { -- If it looks like (x t1 t2), require ConstraintKinds -- see Note [ConstraintKinds in predicates] -- But (X t1 t2) is always ok because we just require ConstraintKinds -- at the definition site (Trac #9838) failIfTc (not under_syn && not (xopt Opt_ConstraintKinds dflags) && hasTyVarHead pred) (predIrredErr pred) -- Make sure it is OK to have an irred pred in this context -- See Note [Irreducible predicates in superclasses] ; failIfTc (is_superclass ctxt && not (xopt Opt_UndecidableInstances dflags) && has_tyfun_head pred) (predSuperClassErr pred) } where is_superclass ctxt = case ctxt of { ClassSCCtxt _ -> True; _ -> False } has_tyfun_head ty = case tcSplitTyConApp_maybe ty of Just (tc, _) -> isTypeFamilyTyCon tc Nothing -> False {- Note [ConstraintKinds in predicates] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Don't check for -XConstraintKinds under a type synonym, because that was done at the type synonym definition site; see Trac #9838 e.g. module A where type C a = (Eq a, Ix a) -- Needs -XConstraintKinds module B where import A f :: C a => a -> a -- Does *not* need -XConstraintKinds Note [Irreducible predicates in superclasses] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Allowing type-family calls in class superclasses is somewhat dangerous because we can write: type family Fooish x :: * -> Constraint type instance Fooish () = Foo class Fooish () a => Foo a where This will cause the constraint simplifier to loop because every time we canonicalise a (Foo a) class constraint we add a (Fooish () a) constraint which will be immediately solved to add+canonicalise another (Foo a) constraint. -} ------------------------- check_class_pred :: DynFlags -> UserTypeCtxt -> PredType -> Class -> [TcType] -> TcM () check_class_pred dflags ctxt pred cls tys | isIPClass cls = do { check_arity ; checkTc (okIPCtxt ctxt) (badIPPred pred) } | otherwise = do { check_arity ; checkTc arg_tys_ok (predTyVarErr pred) } where check_arity = checkTc (classArity cls == length tys) (tyConArityErr (classTyCon cls) tys) flexible_contexts = xopt Opt_FlexibleContexts dflags undecidable_ok = xopt Opt_UndecidableInstances dflags arg_tys_ok = case ctxt of SpecInstCtxt -> True -- {-# SPECIALISE instance Eq (T Int) #-} is fine InstDeclCtxt -> checkValidClsArgs (flexible_contexts || undecidable_ok) tys -- Further checks on head and theta -- in checkInstTermination _ -> checkValidClsArgs flexible_contexts tys ------------------------- okIPCtxt :: UserTypeCtxt -> Bool -- See Note [Implicit parameters in instance decls] okIPCtxt (FunSigCtxt {}) = True okIPCtxt (InfSigCtxt {}) = True okIPCtxt ExprSigCtxt = True okIPCtxt PatSigCtxt = True okIPCtxt ResSigCtxt = True okIPCtxt GenSigCtxt = True okIPCtxt (ConArgCtxt {}) = True okIPCtxt (ForSigCtxt {}) = True -- ?? okIPCtxt ThBrackCtxt = True okIPCtxt GhciCtxt = True okIPCtxt SigmaCtxt = True okIPCtxt (DataTyCtxt {}) = True okIPCtxt (PatSynCtxt {}) = True okIPCtxt (ClassSCCtxt {}) = False okIPCtxt (InstDeclCtxt {}) = False okIPCtxt (SpecInstCtxt {}) = False okIPCtxt (TySynCtxt {}) = False okIPCtxt (RuleSigCtxt {}) = False okIPCtxt DefaultDeclCtxt = False badIPPred :: PredType -> SDoc badIPPred pred = ptext (sLit "Illegal implicit parameter") <+> quotes (ppr pred) {- Note [Kind polymorphic type classes] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MultiParam check: class C f where... -- C :: forall k. k -> Constraint instance C Maybe where... The dictionary gets type [C * Maybe] even if it's not a MultiParam type class. Flexibility check: class C f where... -- C :: forall k. k -> Constraint data D a = D a instance C D where The dictionary gets type [C * (D *)]. IA0_TODO it should be generalized actually. -} checkThetaCtxt :: UserTypeCtxt -> ThetaType -> SDoc checkThetaCtxt ctxt theta = vcat [ptext (sLit "In the context:") <+> pprTheta theta, ptext (sLit "While checking") <+> pprUserTypeCtxt ctxt ] eqPredTyErr, predTyVarErr, predTupleErr, predIrredErr, predSuperClassErr :: PredType -> SDoc eqPredTyErr pred = vcat [ ptext (sLit "Illegal equational constraint") <+> pprType pred , parens (ptext (sLit "Use GADTs or TypeFamilies to permit this")) ] predTyVarErr pred = vcat [ hang (ptext (sLit "Non type-variable argument")) 2 (ptext (sLit "in the constraint:") <+> pprType pred) , parens (ptext (sLit "Use FlexibleContexts to permit this")) ] predTupleErr pred = hang (ptext (sLit "Illegal tuple constraint:") <+> pprType pred) 2 (parens constraintKindsMsg) predIrredErr pred = hang (ptext (sLit "Illegal constraint:") <+> pprType pred) 2 (parens constraintKindsMsg) predSuperClassErr pred = hang (ptext (sLit "Illegal constraint") <+> quotes (pprType pred) <+> ptext (sLit "in a superclass context")) 2 (parens undecidableMsg) constraintSynErr :: Type -> SDoc constraintSynErr kind = hang (ptext (sLit "Illegal constraint synonym of kind:") <+> quotes (ppr kind)) 2 (parens constraintKindsMsg) dupPredWarn :: [[PredType]] -> SDoc dupPredWarn dups = ptext (sLit "Duplicate constraint(s):") <+> pprWithCommas pprType (map head dups) tyConArityErr :: TyCon -> [TcType] -> SDoc -- For type-constructor arity errors, be careful to report -- the number of /type/ arguments required and supplied, -- ignoring the /kind/ arguments, which the user does not see. -- (e.g. Trac #10516) tyConArityErr tc tks = arityErr (tyConFlavour tc) (tyConName tc) tc_type_arity tc_type_args where tvs = tyConTyVars tc kbs :: [Bool] -- True for a Type arg, false for a Kind arg kbs = map isTypeVar tvs -- tc_type_arity = number of *type* args expected -- tc_type_args = number of *type* args encountered tc_type_arity = count id kbs tc_type_args = count (id . fst) (kbs `zip` tks) arityErr :: Outputable a => String -> a -> Int -> Int -> SDoc arityErr what name n m = hsep [ ptext (sLit "The") <+> text what, quotes (ppr name), ptext (sLit "should have"), n_arguments <> comma, text "but has been given", if m==0 then text "none" else int m] where n_arguments | n == 0 = ptext (sLit "no arguments") | n == 1 = ptext (sLit "1 argument") | True = hsep [int n, ptext (sLit "arguments")] {- ************************************************************************ * * \subsection{Checking for a decent instance head type} * * ************************************************************************ @checkValidInstHead@ checks the type {\em and} its syntactic constraints: it must normally look like: @instance Foo (Tycon a b c ...) ...@ The exceptions to this syntactic checking: (1)~if the @GlasgowExts@ flag is on, or (2)~the instance is imported (they must have been compiled elsewhere). In these cases, we let them go through anyway. We can also have instances for functions: @instance Foo (a -> b) ...@. -} checkValidInstHead :: UserTypeCtxt -> Class -> [Type] -> TcM () checkValidInstHead ctxt clas cls_args = do { dflags <- getDynFlags ; checkTc (clas `notElem` abstractClasses) (instTypeErr clas cls_args abstract_class_msg) -- Check language restrictions; -- but not for SPECIALISE isntance pragmas ; let ty_args = dropWhile isKind cls_args ; unless spec_inst_prag $ do { checkTc (xopt Opt_TypeSynonymInstances dflags || all tcInstHeadTyNotSynonym ty_args) (instTypeErr clas cls_args head_type_synonym_msg) ; checkTc (xopt Opt_FlexibleInstances dflags || all tcInstHeadTyAppAllTyVars ty_args) (instTypeErr clas cls_args head_type_args_tyvars_msg) ; checkTc (xopt Opt_MultiParamTypeClasses dflags || length ty_args == 1 || -- Only count type arguments (xopt Opt_NullaryTypeClasses dflags && null ty_args)) (instTypeErr clas cls_args head_one_type_msg) } -- May not contain type family applications ; mapM_ checkTyFamFreeness ty_args ; mapM_ checkValidMonoType ty_args -- For now, I only allow tau-types (not polytypes) in -- the head of an instance decl. -- E.g. instance C (forall a. a->a) is rejected -- One could imagine generalising that, but I'm not sure -- what all the consequences might be } where spec_inst_prag = case ctxt of { SpecInstCtxt -> True; _ -> False } head_type_synonym_msg = parens ( text "All instance types must be of the form (T t1 ... tn)" $$ text "where T is not a synonym." $$ text "Use TypeSynonymInstances if you want to disable this.") head_type_args_tyvars_msg = parens (vcat [ text "All instance types must be of the form (T a1 ... an)", text "where a1 ... an are *distinct type variables*,", text "and each type variable appears at most once in the instance head.", text "Use FlexibleInstances if you want to disable this."]) head_one_type_msg = parens ( text "Only one type can be given in an instance head." $$ text "Use MultiParamTypeClasses if you want to allow more, or zero.") abstract_class_msg = text "The class is abstract, manual instances are not permitted." abstractClasses :: [ Class ] abstractClasses = [ coercibleClass ] -- See Note [Coercible Instances] instTypeErr :: Class -> [Type] -> SDoc -> SDoc instTypeErr cls tys msg = hang (hang (ptext (sLit "Illegal instance declaration for")) 2 (quotes (pprClassPred cls tys))) 2 msg {- Note [Valid 'deriving' predicate] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ validDerivPred checks for OK 'deriving' context. See Note [Exotic derived instance contexts] in TcDeriv. However the predicate is here because it uses sizeTypes, fvTypes. It checks for three things * No repeated variables (hasNoDups fvs) * No type constructors. This is done by comparing sizeTypes tys == length (fvTypes tys) sizeTypes counts variables and constructors; fvTypes returns variables. So if they are the same, there must be no constructors. But there might be applications thus (f (g x)). * Also check for a bizarre corner case, when the derived instance decl would look like instance C a b => D (T a) where ... Note that 'b' isn't a parameter of T. This gives rise to all sorts of problems; in particular, it's hard to compare solutions for equality when finding the fixpoint, and that means the inferContext loop does not converge. See Trac #5287. -} validDerivPred :: TyVarSet -> PredType -> Bool -- See Note [Valid 'deriving' predicate] validDerivPred tv_set pred = case classifyPredType pred of ClassPred _ tys -> check_tys tys EqPred {} -> False -- reject equality constraints _ -> True -- Non-class predicates are ok where check_tys tys = hasNoDups fvs && sizeTypes tys == fromIntegral (length fvs) && all (`elemVarSet` tv_set) fvs where fvs = fvTypes tys {- ************************************************************************ * * \subsection{Checking instance for termination} * * ************************************************************************ -} checkValidInstance :: UserTypeCtxt -> LHsType Name -> Type -> TcM ([TyVar], ThetaType, Class, [Type]) checkValidInstance ctxt hs_type ty | Just (clas,inst_tys) <- getClassPredTys_maybe tau , inst_tys `lengthIs` classArity clas = do { setSrcSpan head_loc (checkValidInstHead ctxt clas inst_tys) ; checkValidTheta ctxt theta -- The Termination and Coverate Conditions -- Check that instance inference will terminate (if we care) -- For Haskell 98 this will already have been done by checkValidTheta, -- but as we may be using other extensions we need to check. -- -- Note that the Termination Condition is *more conservative* than -- the checkAmbiguity test we do on other type signatures -- e.g. Bar a => Bar Int is ambiguous, but it also fails -- the termination condition, because 'a' appears more often -- in the constraint than in the head ; undecidable_ok <- xoptM Opt_UndecidableInstances ; if undecidable_ok then checkAmbiguity ctxt ty else checkInstTermination inst_tys theta ; case (checkInstCoverage undecidable_ok clas theta inst_tys) of IsValid -> return () -- Check succeeded NotValid msg -> addErrTc (instTypeErr clas inst_tys msg) ; return (tvs, theta, clas, inst_tys) } | otherwise = failWithTc (ptext (sLit "Malformed instance head:") <+> ppr tau) where (tvs, theta, tau) = tcSplitSigmaTy ty -- The location of the "head" of the instance head_loc = case hs_type of L _ (HsForAllTy _ _ _ _ (L loc _)) -> loc L loc _ -> loc {- Note [Paterson conditions] ~~~~~~~~~~~~~~~~~~~~~~~~~~ Termination test: the so-called "Paterson conditions" (see Section 5 of "Understanding functional dependencies via Constraint Handling Rules, JFP Jan 2007). We check that each assertion in the context satisfies: (1) no variable has more occurrences in the assertion than in the head, and (2) the assertion has fewer constructors and variables (taken together and counting repetitions) than the head. This is only needed with -fglasgow-exts, as Haskell 98 restrictions (which have already been checked) guarantee termination. The underlying idea is that for any ground substitution, each assertion in the context has fewer type constructors than the head. -} checkInstTermination :: [TcType] -> ThetaType -> TcM () -- See Note [Paterson conditions] checkInstTermination tys theta = check_preds theta where head_fvs = fvTypes tys head_size = sizeTypes tys check_preds :: [PredType] -> TcM () check_preds preds = mapM_ check preds check :: PredType -> TcM () check pred = case classifyPredType pred of EqPred {} -> return () -- See Trac #4200. IrredPred {} -> check2 pred (sizeType pred) ClassPred cls tys | isIPClass cls -> return () -- You can't get to class predicates from implicit params | isCTupleClass cls -- Look inside tuple predicates; Trac #8359 -> check_preds tys | otherwise -> check2 pred (sizeTypes tys) -- Other ClassPreds check2 pred pred_size | not (null bad_tvs) = addErrTc (noMoreMsg bad_tvs what) | pred_size >= head_size = addErrTc (smallerMsg what) | otherwise = return () where what = ptext (sLit "constraint") <+> quotes (ppr pred) bad_tvs = fvType pred \\ head_fvs smallerMsg :: SDoc -> SDoc smallerMsg what = vcat [ hang (ptext (sLit "The") <+> what) 2 (ptext (sLit "is no smaller than the instance head")) , parens undecidableMsg ] noMoreMsg :: [TcTyVar] -> SDoc -> SDoc noMoreMsg tvs what = vcat [ hang (ptext (sLit "Variable") <> plural tvs <+> quotes (pprWithCommas ppr tvs) <+> occurs <+> ptext (sLit "more often")) 2 (sep [ ptext (sLit "in the") <+> what , ptext (sLit "than in the instance head") ]) , parens undecidableMsg ] where occurs = if isSingleton tvs then ptext (sLit "occurs") else ptext (sLit "occur") undecidableMsg, constraintKindsMsg :: SDoc undecidableMsg = ptext (sLit "Use UndecidableInstances to permit this") constraintKindsMsg = ptext (sLit "Use ConstraintKinds to permit this") {- Note [Associated type instances] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ We allow this: class C a where type T x a instance C Int where type T (S y) Int = y type T Z Int = Char Note that a) The variable 'x' is not bound by the class decl b) 'x' is instantiated to a non-type-variable in the instance c) There are several type instance decls for T in the instance All this is fine. Of course, you can't give any *more* instances for (T ty Int) elsewhere, because it's an *associated* type. Note [Checking consistent instantiation] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ class C a b where type T a x b instance C [p] Int type T [p] y Int = (p,y,y) -- Induces the family instance TyCon -- type TR p y = (p,y,y) So we * Form the mini-envt from the class type variables a,b to the instance decl types [p],Int: [a->[p], b->Int] * Look at the tyvars a,x,b of the type family constructor T (it shares tyvars with the class C) * Apply the mini-evnt to them, and check that the result is consistent with the instance types [p] y Int We do *not* assume (at this point) the the bound variables of the associated type instance decl are the same as for the parent instance decl. So, for example, instance C [p] Int type T [q] y Int = ... would work equally well. Reason: making the *kind* variables line up is much harder. Example (Trac #7282): class Foo (xs :: [k]) where type Bar xs :: * instance Foo '[] where type Bar '[] = Int Here the instance decl really looks like instance Foo k ('[] k) where type Bar k ('[] k) = Int but the k's are not scoped, and hence won't match Uniques. So instead we just match structure, with tcMatchTyX, and check that distinct type variables match 1-1 with distinct type variables. HOWEVER, we *still* make the instance type variables scope over the type instances, to pick up non-obvious kinds. Eg class Foo (a :: k) where type F a instance Foo (b :: k -> k) where type F b = Int Here the instance is kind-indexed and really looks like type F (k->k) (b::k->k) = Int But if the 'b' didn't scope, we would make F's instance too poly-kinded. -} -- | Extra information needed when type-checking associated types. The 'Class' is -- the enclosing class, and the @VarEnv Type@ maps class variables to their -- instance types. type ClsInfo = (Class, VarEnv Type) checkConsistentFamInst :: Maybe ClsInfo -> TyCon -- ^ Family tycon -> [TyVar] -- ^ Type variables of the family instance -> [Type] -- ^ Type patterns from instance -> TcM () -- See Note [Checking consistent instantiation] checkConsistentFamInst Nothing _ _ _ = return () checkConsistentFamInst (Just (clas, mini_env)) fam_tc at_tvs at_tys = do { -- Check that the associated type indeed comes from this class checkTc (Just clas == tyConAssoc_maybe fam_tc) (badATErr (className clas) (tyConName fam_tc)) -- See Note [Checking consistent instantiation] in TcTyClsDecls -- Check right to left, so that we spot type variable -- inconsistencies before (more confusing) kind variables ; discardResult $ foldrM check_arg emptyTvSubst $ tyConTyVars fam_tc `zip` at_tys } where at_tv_set = mkVarSet at_tvs check_arg :: (TyVar, Type) -> TvSubst -> TcM TvSubst check_arg (fam_tc_tv, at_ty) subst | Just inst_ty <- lookupVarEnv mini_env fam_tc_tv = case tcMatchTyX at_tv_set subst at_ty inst_ty of Just subst | all_distinct subst -> return subst _ -> failWithTc $ wrongATArgErr at_ty inst_ty -- No need to instantiate here, because the axiom -- uses the same type variables as the assocated class | otherwise = return subst -- Allow non-type-variable instantiation -- See Note [Associated type instances] all_distinct :: TvSubst -> Bool -- True if all the variables mapped the substitution -- map to *distinct* type *variables* all_distinct subst = go [] at_tvs where go _ [] = True go acc (tv:tvs) = case lookupTyVar subst tv of Nothing -> go acc tvs Just ty | Just tv' <- tcGetTyVar_maybe ty , tv' `notElem` acc -> go (tv' : acc) tvs _other -> False badATErr :: Name -> Name -> SDoc badATErr clas op = hsep [ptext (sLit "Class"), quotes (ppr clas), ptext (sLit "does not have an associated type"), quotes (ppr op)] wrongATArgErr :: Type -> Type -> SDoc wrongATArgErr ty instTy = sep [ ptext (sLit "Type indexes must match class instance head") , ptext (sLit "Found") <+> quotes (ppr ty) <+> ptext (sLit "but expected") <+> quotes (ppr instTy) ] {- ************************************************************************ * * Checking type instance well-formedness and termination * * ************************************************************************ -} checkValidCoAxiom :: CoAxiom Branched -> TcM () checkValidCoAxiom ax@(CoAxiom { co_ax_tc = fam_tc, co_ax_branches = branches }) = do { mapM_ (checkValidCoAxBranch Nothing fam_tc) branch_list ; foldlM_ check_branch_compat [] branch_list } where branch_list = fromBranches branches injectivity = familyTyConInjectivityInfo fam_tc check_branch_compat :: [CoAxBranch] -- previous branches in reverse order -> CoAxBranch -- current branch -> TcM [CoAxBranch]-- current branch : previous branches -- Check for -- (a) this banch is dominated by previous ones -- (b) failure of injectivity check_branch_compat prev_branches cur_branch | cur_branch `isDominatedBy` prev_branches = do { addWarnAt (coAxBranchSpan cur_branch) $ inaccessibleCoAxBranch ax cur_branch ; return prev_branches } | otherwise = do { check_injectivity prev_branches cur_branch ; return (cur_branch : prev_branches) } -- Injectivity check: check whether a new (CoAxBranch) can extend -- already checked equations without violating injectivity -- annotation supplied by the user. -- See Note [Verifying injectivity annotation] in FamInstEnv check_injectivity prev_branches cur_branch | Injective inj <- injectivity = do { let conflicts = fst $ foldl (gather_conflicts inj prev_branches cur_branch) ([], 0) prev_branches ; mapM_ (\(err, span) -> setSrcSpan span $ addErr err) (makeInjectivityErrors ax cur_branch inj conflicts) } | otherwise = return () gather_conflicts inj prev_branches cur_branch (acc, n) branch -- n is 0-based index of branch in prev_branches = case injectiveBranches inj cur_branch branch of InjectivityUnified ax1 ax2 | ax1 `isDominatedBy` (replace_br prev_branches n ax2) -> (acc, n + 1) | otherwise -> (branch : acc, n + 1) InjectivityAccepted -> (acc, n + 1) -- Replace n-th element in the list. Assumes 0-based indexing. replace_br :: [CoAxBranch] -> Int -> CoAxBranch -> [CoAxBranch] replace_br brs n br = take n brs ++ [br] ++ drop (n+1) brs -- Check that a "type instance" is well-formed (which includes decidability -- unless -XUndecidableInstances is given). -- checkValidCoAxBranch :: Maybe ClsInfo -> TyCon -> CoAxBranch -> TcM () checkValidCoAxBranch mb_clsinfo fam_tc (CoAxBranch { cab_tvs = tvs, cab_lhs = typats , cab_rhs = rhs, cab_loc = loc }) = checkValidTyFamEqn mb_clsinfo fam_tc tvs typats rhs loc -- | Do validity checks on a type family equation, including consistency -- with any enclosing class instance head, termination, and lack of -- polytypes. checkValidTyFamEqn :: Maybe ClsInfo -> TyCon -- ^ of the type family -> [TyVar] -- ^ bound tyvars in the equation -> [Type] -- ^ type patterns -> Type -- ^ rhs -> SrcSpan -> TcM () checkValidTyFamEqn mb_clsinfo fam_tc tvs typats rhs loc = setSrcSpan loc $ do { checkValidFamPats fam_tc tvs typats -- The argument patterns, and RHS, are all boxed tau types -- E.g Reject type family F (a :: k1) :: k2 -- type instance F (forall a. a->a) = ... -- type instance F Int# = ... -- type instance F Int = forall a. a->a -- type instance F Int = Int# -- See Trac #9357 ; mapM_ checkValidMonoType typats ; checkValidMonoType rhs -- We have a decidable instance unless otherwise permitted ; undecidable_ok <- xoptM Opt_UndecidableInstances ; unless undecidable_ok $ mapM_ addErrTc (checkFamInstRhs typats (tcTyFamInsts rhs)) -- Check that type patterns match the class instance head ; checkConsistentFamInst mb_clsinfo fam_tc tvs typats } -- Make sure that each type family application is -- (1) strictly smaller than the lhs, -- (2) mentions no type variable more often than the lhs, and -- (3) does not contain any further type family instances. -- checkFamInstRhs :: [Type] -- lhs -> [(TyCon, [Type])] -- type family instances -> [MsgDoc] checkFamInstRhs lhsTys famInsts = mapMaybe check famInsts where size = sizeTypes lhsTys fvs = fvTypes lhsTys check (tc, tys) | not (all isTyFamFree tys) = Just (nestedMsg what) | not (null bad_tvs) = Just (noMoreMsg bad_tvs what) | size <= sizeTypes tys = Just (smallerMsg what) | otherwise = Nothing where what = ptext (sLit "type family application") <+> quotes (pprType (TyConApp tc tys)) bad_tvs = fvTypes tys \\ fvs checkValidFamPats :: TyCon -> [TyVar] -> [Type] -> TcM () -- Patterns in a 'type instance' or 'data instance' decl should -- a) contain no type family applications -- (vanilla synonyms are fine, though) -- b) properly bind all their free type variables -- e.g. we disallow (Trac #7536) -- type T a = Int -- type instance F (T a) = a -- c) Have the right number of patterns checkValidFamPats fam_tc tvs ty_pats = ASSERT2( length ty_pats == tyConArity fam_tc , ppr ty_pats $$ ppr fam_tc $$ ppr (tyConArity fam_tc) ) -- A family instance must have exactly the same number of type -- parameters as the family declaration. You can't write -- type family F a :: * -> * -- type instance F Int y = y -- because then the type (F Int) would be like (\y.y) -- But this is checked at the time the axiom is created do { mapM_ checkTyFamFreeness ty_pats ; let unbound_tvs = filterOut (`elemVarSet` exactTyVarsOfTypes ty_pats) tvs ; checkTc (null unbound_tvs) (famPatErr fam_tc unbound_tvs ty_pats) } -- Ensure that no type family instances occur in a type. checkTyFamFreeness :: Type -> TcM () checkTyFamFreeness ty = checkTc (isTyFamFree ty) $ tyFamInstIllegalErr ty -- Check that a type does not contain any type family applications. -- isTyFamFree :: Type -> Bool isTyFamFree = null . tcTyFamInsts -- Error messages inaccessibleCoAxBranch :: CoAxiom br -> CoAxBranch -> SDoc inaccessibleCoAxBranch fi_ax cur_branch = ptext (sLit "Type family instance equation is overlapped:") $$ nest 2 (pprCoAxBranch fi_ax cur_branch) tyFamInstIllegalErr :: Type -> SDoc tyFamInstIllegalErr ty = hang (ptext (sLit "Illegal type synonym family application in instance") <> colon) 2 $ ppr ty nestedMsg :: SDoc -> SDoc nestedMsg what = sep [ ptext (sLit "Illegal nested") <+> what , parens undecidableMsg ] famPatErr :: TyCon -> [TyVar] -> [Type] -> SDoc famPatErr fam_tc tvs pats = hang (ptext (sLit "Family instance purports to bind type variable") <> plural tvs <+> pprQuotedList tvs) 2 (hang (ptext (sLit "but the real LHS (expanding synonyms) is:")) 2 (pprTypeApp fam_tc (map expandTypeSynonyms pats) <+> ptext (sLit "= ..."))) {- ************************************************************************ * * \subsection{Auxiliary functions} * * ************************************************************************ -} -- Free variables of a type, retaining repetitions, and expanding synonyms -- Ignore kinds altogether: rightly or wrongly, we only check for -- excessive occurrences of *type* variables. -- e.g. type instance Demote {T k} a = T (Demote {k} (Any {k})) -- -- c.f. sizeType, which is often called side by side with fvType fvType, fv_type :: Type -> [TyVar] fvType ty | isKind ty = [] | otherwise = fv_type ty fv_type ty | Just exp_ty <- tcView ty = fv_type exp_ty fv_type (TyVarTy tv) = [tv] fv_type (TyConApp _ tys) = fvTypes tys fv_type (LitTy {}) = [] fv_type (FunTy arg res) = fv_type arg ++ fv_type res fv_type (AppTy fun arg) = fv_type fun ++ fv_type arg fv_type (ForAllTy tyvar ty) = filter (/= tyvar) (fv_type ty) fvTypes :: [Type] -> [TyVar] fvTypes tys = concat (map fvType tys)
elieux/ghc
compiler/typecheck/TcValidity.hs
bsd-3-clause
58,004
4
16
16,419
8,751
4,478
4,273
-1
-1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE UndecidableInstances #-} module AI.Network.FeedForwardNetwork ( FeedForwardNetwork(..) , emptyFeedForwardNetwork , isEmptyFeedForwardNetwork , addFeedForwardNetworks , loadFeedForwardNetwork , saveFeedForwardNetwork , apply ) where import AI.Layer import AI.Network import AI.Neuron import Data.Binary (Binary (..), decode, encode) import qualified Data.ByteString.Lazy as B import Data.Monoid (Monoid (..)) import Numeric.LinearAlgebra import Numeric.LinearAlgebra.Data (cmap) import System.IO import System.Random -- | Networks are constructed front to back. Start by adding an input layer, -- then each hidden layer, and finally an output layer. data FeedForwardNetwork = FeedForwardNetwork { layers :: [Layer] } deriving Show -- | We gain the ability to combine two networks of the same proportions -- by abstracting a network as a monoid. This is useful in backpropagation -- for batch training instance Monoid FeedForwardNetwork where mempty = emptyFeedForwardNetwork mappend = addFeedForwardNetworks -- | A tuple of (input, expected output) type TrainingData = (Vector Double, Vector Double) -- | Our Unit, an empty network with no layers emptyFeedForwardNetwork :: FeedForwardNetwork emptyFeedForwardNetwork = FeedForwardNetwork [] -- | A boolean to check if the network is the unit network or not isEmptyFeedForwardNetwork :: FeedForwardNetwork -> Bool isEmptyFeedForwardNetwork n = null $ layers n -- | A function to combine two networks addFeedForwardNetworks :: FeedForwardNetwork -> FeedForwardNetwork -> FeedForwardNetwork addFeedForwardNetworks n1 n2 | isEmptyFeedForwardNetwork n1 = n2 | isEmptyFeedForwardNetwork n2 = n1 | otherwise = FeedForwardNetwork $ zipWith combineLayers (layers n1) (layers n2) where combineLayers l1 l2 = Layer (weightMatrix l1 + weightMatrix l2) (biasVector l1 + biasVector l2) (neuron l1) instance Network FeedForwardNetwork where type Parameters FeedForwardNetwork g = [LayerDefinition g] -- | Predict folds over each layer of the network using the input vector as the -- first value of the accumulator. It operates on whatever network you pass in. predict input network = foldl apply input (layers network) -- | The createNetwork function takes in a random transform used for weight -- initialization, a source of entropy, and a list of layer definitions, -- and returns a network with the weights initialized per the random transform. createNetwork t g (layerDef : layerDef' : otherLayerDefs) = FeedForwardNetwork (layer : layers restOfNetwork) where layer = createLayer t g' layerDef layerDef' restOfNetwork = createNetwork t g'' (layerDef' : otherLayerDefs) (g', g'') = split g createNetwork _ _ _ = emptyFeedForwardNetwork -- | A function used in the fold in predict that applies the activation -- function and pushes the input through a layer of the network. apply :: Vector Double -> Layer -> Vector Double apply vector layer = cmap sigma (weights #> vector + bias) where sigma = activation (neuron layer) weights = weightMatrix layer bias = biasVector layer -- | Given a filename and a network, we want to save the weights and biases -- of the network to the file for later use. saveFeedForwardNetwork :: (Binary Layer) => FilePath -> FeedForwardNetwork -> IO () saveFeedForwardNetwork file n = B.writeFile file (encode (layers n)) -- | Given a filename, and a list of layer definitions, we want to reexpand -- the data back into a network. loadFeedForwardNetwork :: (Binary Layer, RandomGen g) => FilePath -> [LayerDefinition g] -> IO FeedForwardNetwork loadFeedForwardNetwork file defs = B.readFile file >>= \sls -> return . FeedForwardNetwork $ zipWith (curry showableToLayer) (decode sls) defs
jbarrow/LambdaNet
AI/Network/FeedForwardNetwork.hs
mit
4,007
0
10
821
731
396
335
59
1
main :: [()] main = [() | Nothing <- []]
roberth/uu-helium
test/staticwarnings/Generator6.hs
gpl-3.0
42
0
8
11
31
17
14
2
1
{-# LANGUAGE OverloadedStrings #-} module Ldap.Client.ModifySpec (spec) where import Test.Hspec import qualified Ldap.Asn1.Type as Ldap.Type import Ldap.Client as Ldap import SpecHelper (locally, charizard, pikachu, raichu) spec :: Spec spec = do let go l f = Ldap.search l (Dn "o=localhost") (Ldap.typesOnly True) f [] context "delete" $ do it "can land ‘charizard’" $ do res <- locally $ \l -> do [x] <- go l (Attr "cn" := "charizard") lookupAttr (Attr "type") x `shouldBe` Just ["fire", "flying"] Ldap.modify l charizard [Attr "type" `Delete` ["flying"]] [y] <- go l (Attr "cn" := "charizard") lookupAttr (Attr "type") y `shouldBe` Just ["fire"] res `shouldBe` Right () it "tries to remove ‘pikachu’'s password, unsuccessfully" $ do res <- locally $ \l -> Ldap.modify l pikachu [Attr "password" `Delete` []] res `shouldBe` Left (ResponseError (ResponseErrorCode (Ldap.Type.ModifyRequest (Ldap.Type.LdapDn (Ldap.Type.LdapString "cn=pikachu,o=localhost")) [( Ldap.Type.Delete , Ldap.Type.PartialAttribute (Ldap.Type.AttributeDescription (Ldap.Type.LdapString "password")) [] )]) UnwillingToPerform (Dn "o=localhost") "cannot delete password")) context "add" $ it "can feed ‘charizard’" $ do res <- locally $ \l -> do [x] <- go l (Attr "cn" := "charizard") lookupAttr (Attr "type") x `shouldBe` Just ["fire", "flying"] Ldap.modify l charizard [Attr "type" `Add` ["fed"]] [y] <- go l (Attr "cn" := "charizard") lookupAttr (Attr "type") y `shouldBe` Just ["fire", "flying", "fed"] res `shouldBe` Right () context "replace" $ it "can put ‘charizard’ to sleep" $ do res <- locally $ \l -> do [x] <- go l (Attr "cn" := "charizard") lookupAttr (Attr "type") x `shouldBe` Just ["fire", "flying"] Ldap.modify l charizard [Attr "type" `Replace` ["sleeping"]] [y] <- go l (Attr "cn" := "charizard") lookupAttr (Attr "type") y `shouldBe` Just ["sleeping"] res `shouldBe` Right () context "modify dn" $ it "evolves ‘pikachu’ into ‘raichu’" $ do res <- locally $ \l -> do [] <- go l (Attr "cn" := "raichu") Ldap.modifyDn l pikachu (RelativeDn "cn=raichu") False Nothing Ldap.modify l raichu [Attr "evolution" `Replace` ["1"]] [res] <- go l (Attr "cn" := "raichu") res `shouldBe` SearchEntry raichu [ (Attr "cn", ["raichu"]) , (Attr "evolution", ["1"]) , (Attr "type", ["electric"]) , (Attr "password", ["i-choose-you"]) ] res `shouldBe` Right () lookupAttr :: Attr -> SearchEntry -> Maybe [AttrValue] lookupAttr a (SearchEntry _ as) = lookup a as
VictorDenisov/ldap-client
test/Ldap/Client/ModifySpec.hs
bsd-2-clause
3,231
0
28
1,132
1,067
545
522
66
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TemplateHaskell #-} module Stack.Init ( findCabalFiles , initProject , InitOpts (..) , SnapPref (..) , Method (..) , makeConcreteResolver ) where import Control.Exception (assert) import Control.Exception.Enclosed (handleIO, catchAny) import Control.Monad (liftM, when) import Control.Monad.Catch (MonadMask, throwM, MonadThrow) import Control.Monad.IO.Class import Control.Monad.Logger import Control.Monad.Reader (MonadReader, asks) import Control.Monad.Trans.Control (MonadBaseControl) import qualified Data.IntMap as IntMap import Data.List (isSuffixOf,sort) import Data.List.Extra (nubOrd) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (mapMaybe) import Data.Monoid import Data.Set (Set) import qualified Data.Set as Set import qualified Data.Text as T import qualified Data.Yaml as Yaml import qualified Distribution.PackageDescription as C import Network.HTTP.Client.Conduit (HasHttpManager) import Path import Path.Find import Path.IO import Stack.BuildPlan import Stack.Constants import Stack.Package import Stack.Solver import Stack.Types import System.Directory (getDirectoryContents) findCabalFiles :: MonadIO m => Bool -> Path Abs Dir -> m [Path Abs File] findCabalFiles recurse dir = liftIO $ findFiles dir isCabal (\subdir -> recurse && not (isIgnored subdir)) where isCabal path = ".cabal" `isSuffixOf` toFilePath path isIgnored path = toFilePath (dirname path) `Set.member` ignoredDirs -- | Special directories that we don't want to traverse for .cabal files ignoredDirs :: Set FilePath ignoredDirs = Set.fromList [ ".git" , "dist" , ".stack-work" ] -- | Generate stack.yaml initProject :: (MonadIO m, MonadMask m, MonadReader env m, HasConfig env, HasHttpManager env, HasGHCVariant env, MonadLogger m, MonadBaseControl IO m) => Path Abs Dir -> InitOpts -> m () initProject currDir initOpts = do let dest = currDir </> stackDotYaml dest' = toFilePath dest exists <- fileExists dest when (not (forceOverwrite initOpts) && exists) $ error ("Refusing to overwrite existing stack.yaml, " <> "please delete before running stack init " <> "or if you are sure use \"--force\"") cabalfps <- findCabalFiles (includeSubDirs initOpts) currDir $logInfo $ "Writing default config file to: " <> T.pack dest' $logInfo $ "Basing on cabal files:" mapM_ (\path -> $logInfo $ "- " <> T.pack (toFilePath path)) cabalfps $logInfo "" when (null cabalfps) $ error "In order to init, you should have an existing .cabal file. Please try \"stack new\" instead" (warnings,gpds) <- fmap unzip (mapM readPackageUnresolved cabalfps) sequence_ (zipWith (mapM_ . printCabalFileWarning) cabalfps warnings) (r, flags, extraDeps) <- getDefaultResolver cabalfps gpds initOpts let p = Project { projectPackages = pkgs , projectExtraDeps = extraDeps , projectFlags = flags , projectResolver = r } pkgs = map toPkg cabalfps toPkg fp = PackageEntry { peValidWanted = Nothing , peExtraDepMaybe = Nothing , peLocation = PLFilePath $ case stripDir currDir $ parent fp of Nothing | currDir == parent fp -> "." | otherwise -> assert False $ toFilePath $ parent fp Just rel -> toFilePath rel , peSubdirs = [] } $logInfo $ "Selected resolver: " <> resolverName r liftIO $ Yaml.encodeFile dest' p $logInfo $ "Wrote project config to: " <> T.pack dest' getSnapshots' :: (MonadIO m, MonadMask m, MonadReader env m, HasConfig env, HasHttpManager env, MonadLogger m, MonadBaseControl IO m) => m (Maybe Snapshots) getSnapshots' = liftM Just getSnapshots `catchAny` \e -> do $logError $ "Unable to download snapshot list, and therefore could " <> "not generate a stack.yaml file automatically" $logError $ "This sometimes happens due to missing Certificate Authorities " <> "on your system. For more information, see:" $logError "" $logError " https://github.com/commercialhaskell/stack/issues/234" $logError "" $logError "You can try again, or create your stack.yaml file by hand. See:" $logError "" $logError " https://github.com/commercialhaskell/stack/wiki/stack.yaml" $logError "" $logError $ "Exception was: " <> T.pack (show e) return Nothing -- | Get the default resolver value getDefaultResolver :: (MonadIO m, MonadMask m, MonadReader env m, HasConfig env, HasHttpManager env, HasGHCVariant env, MonadLogger m, MonadBaseControl IO m) => [Path Abs File] -- ^ cabal files -> [C.GenericPackageDescription] -- ^ cabal descriptions -> InitOpts -> m (Resolver, Map PackageName (Map FlagName Bool), Map PackageName Version) getDefaultResolver cabalfps gpds initOpts = case ioMethod initOpts of MethodSnapshot snapPref -> do msnapshots <- getSnapshots' names <- case msnapshots of Nothing -> return [] Just snapshots -> getRecommendedSnapshots snapshots snapPref mpair <- findBuildPlan gpds names case mpair of Just (snap, flags) -> return (ResolverSnapshot snap, flags, Map.empty) Nothing -> throwM $ NoMatchingSnapshot names MethodResolver aresolver -> do resolver <- makeConcreteResolver aresolver mpair <- case resolver of ResolverSnapshot name -> findBuildPlan gpds [name] ResolverCompiler _ -> return Nothing ResolverCustom _ _ -> return Nothing case mpair of Just (snap, flags) -> return (ResolverSnapshot snap, flags, Map.empty) Nothing -> return (resolver, Map.empty, Map.empty) MethodSolver -> do (compilerVersion, extraDeps) <- cabalSolver Ghc (map parent cabalfps) Map.empty [] return ( ResolverCompiler compilerVersion , Map.filter (not . Map.null) $ fmap snd extraDeps , fmap fst extraDeps ) getRecommendedSnapshots :: (MonadIO m, MonadMask m, MonadReader env m, HasConfig env, HasHttpManager env, HasGHCVariant env, MonadLogger m, MonadBaseControl IO m) => Snapshots -> SnapPref -> m [SnapName] getRecommendedSnapshots snapshots pref = do -- Get the most recent LTS and Nightly in the snapshots directory and -- prefer them over anything else, since odds are high that something -- already exists for them. existing <- liftM (reverse . sort . mapMaybe (parseSnapName . T.pack)) $ snapshotsDir >>= liftIO . handleIO (const $ return []) . getDirectoryContents . toFilePath let isLTS LTS{} = True isLTS Nightly{} = False isNightly Nightly{} = True isNightly LTS{} = False names = nubOrd $ concat [ take 2 $ filter isLTS existing , take 2 $ filter isNightly existing , map (uncurry LTS) (take 2 $ reverse $ IntMap.toList $ snapshotsLts snapshots) , [Nightly $ snapshotsNightly snapshots] ] namesLTS = filter isLTS names namesNightly = filter isNightly names case pref of PrefNone -> return names PrefLTS -> return $ namesLTS ++ namesNightly PrefNightly -> return $ namesNightly ++ namesLTS data InitOpts = InitOpts { ioMethod :: !Method -- ^ Preferred snapshots , forceOverwrite :: Bool -- ^ Overwrite existing files , includeSubDirs :: Bool -- ^ If True, include all .cabal files found in any sub directories } data SnapPref = PrefNone | PrefLTS | PrefNightly -- | Method of initializing data Method = MethodSnapshot SnapPref | MethodResolver AbstractResolver | MethodSolver -- | Turn an 'AbstractResolver' into a 'Resolver'. makeConcreteResolver :: (MonadIO m, MonadReader env m, HasConfig env, MonadThrow m, HasHttpManager env, MonadLogger m) => AbstractResolver -> m Resolver makeConcreteResolver (ARResolver r) = return r makeConcreteResolver ar = do snapshots <- getSnapshots r <- case ar of ARResolver r -> assert False $ return r ARGlobal -> do stackRoot <- asks $ configStackRoot . getConfig let fp = implicitGlobalDir stackRoot </> stackDotYaml (ProjectAndConfigMonoid project _, _warnings) <- liftIO (Yaml.decodeFileEither $ toFilePath fp) >>= either throwM return return $ projectResolver project ARLatestNightly -> return $ ResolverSnapshot $ Nightly $ snapshotsNightly snapshots ARLatestLTSMajor x -> case IntMap.lookup x $ snapshotsLts snapshots of Nothing -> error $ "No LTS release found with major version " ++ show x Just y -> return $ ResolverSnapshot $ LTS x y ARLatestLTS | IntMap.null $ snapshotsLts snapshots -> error $ "No LTS releases found" | otherwise -> let (x, y) = IntMap.findMax $ snapshotsLts snapshots in return $ ResolverSnapshot $ LTS x y $logInfo $ "Selected resolver: " <> resolverName r return r
sinelaw/stack
src/Stack/Init.hs
bsd-3-clause
10,510
0
20
3,523
2,457
1,241
1,216
207
8
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ExtendedDefaultRules #-} module Main (main) where import Database.MongoDB (Action, Document, Document, Value, access, close, connect, delete, exclude, find, host, insertMany, insert_, master, project, rest, select, sort, (=:)) import Control.Monad.Trans (liftIO) import System.Environment (getArgs) import Prelude import System.IO data Command = Insert { getTag :: String, getData :: String } | Delete { getTag :: String } | Update { getTag :: String } | Find { getTag :: String } | FindAll | Illegal deriving Show main :: IO () main = do args <- getArgs database (argsToCommand args) database :: Command -> IO () database command = do pipe <- connect (host "127.0.0.1") e <- access pipe master "todohaskell" (runTodo command) close pipe -- コマンドラインの命令を振り分けます argsToCommand :: [String] -> Command argsToCommand [] = FindAll argsToCommand (x:[]) = Find x argsToCommand (x:(y:[])) = if x == "fin" then Delete y else Insert x y argsToCommand _ = Illegal runTodo :: Command -> Action IO () runTodo FindAll = do findAllTodo >>= printDocs "All Todo" runTodo (Find tag) = do (findTodo tag) >>= printDocs ("Tag:" ++ tag) runTodo (Insert tag mes) = do insertTodo tag mes runTodo (Delete tag) = do deleteTodo tag liftIO $ (putStrLn $ "delete Tag:" ++ tag) deleteTodo :: String -> Action IO () deleteTodo tag = delete (select ["tag" =: tag] "list") insertTodo :: String -> String -> Action IO () insertTodo tag mes = insert_ "list" ["tag" =: tag, "message" =: mes] findAllTodo :: Action IO [Document] findAllTodo = rest =<< find (select [] "list") findTodo :: String -> Action IO [Document] findTodo tag = rest =<< find (select ["tag" =: tag] "list") printDocs :: String -> [Document] -> Action IO () printDocs title docs = liftIO $ putStrLn title >> mapM_ (print . exclude ["_id"]) docs
tagia0212/haskell-mongod-todo
src/Main.hs
bsd-3-clause
2,220
0
10
660
732
388
344
54
2
{-# OPTIONS_GHC -fno-implicit-prelude -#include "HsBase.h" #-} ----------------------------------------------------------------------------- -- | -- Module : Foreign.C.Error -- Copyright : (c) The FFI task force 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- C-specific Marshalling support: Handling of C \"errno\" error codes. -- ----------------------------------------------------------------------------- module Foreign.C.Error ( -- * Haskell representations of @errno@ values Errno(..), -- instance: Eq -- ** Common @errno@ symbols -- | Different operating systems and\/or C libraries often support -- different values of @errno@. This module defines the common values, -- but due to the open definition of 'Errno' users may add definitions -- which are not predefined. eOK, e2BIG, eACCES, eADDRINUSE, eADDRNOTAVAIL, eADV, eAFNOSUPPORT, eAGAIN, eALREADY, eBADF, eBADMSG, eBADRPC, eBUSY, eCHILD, eCOMM, eCONNABORTED, eCONNREFUSED, eCONNRESET, eDEADLK, eDESTADDRREQ, eDIRTY, eDOM, eDQUOT, eEXIST, eFAULT, eFBIG, eFTYPE, eHOSTDOWN, eHOSTUNREACH, eIDRM, eILSEQ, eINPROGRESS, eINTR, eINVAL, eIO, eISCONN, eISDIR, eLOOP, eMFILE, eMLINK, eMSGSIZE, eMULTIHOP, eNAMETOOLONG, eNETDOWN, eNETRESET, eNETUNREACH, eNFILE, eNOBUFS, eNODATA, eNODEV, eNOENT, eNOEXEC, eNOLCK, eNOLINK, eNOMEM, eNOMSG, eNONET, eNOPROTOOPT, eNOSPC, eNOSR, eNOSTR, eNOSYS, eNOTBLK, eNOTCONN, eNOTDIR, eNOTEMPTY, eNOTSOCK, eNOTTY, eNXIO, eOPNOTSUPP, ePERM, ePFNOSUPPORT, ePIPE, ePROCLIM, ePROCUNAVAIL, ePROGMISMATCH, ePROGUNAVAIL, ePROTO, ePROTONOSUPPORT, ePROTOTYPE, eRANGE, eREMCHG, eREMOTE, eROFS, eRPCMISMATCH, eRREMOTE, eSHUTDOWN, eSOCKTNOSUPPORT, eSPIPE, eSRCH, eSRMNT, eSTALE, eTIME, eTIMEDOUT, eTOOMANYREFS, eTXTBSY, eUSERS, eWOULDBLOCK, eXDEV, -- ** 'Errno' functions -- :: Errno isValidErrno, -- :: Errno -> Bool -- access to the current thread's "errno" value -- getErrno, -- :: IO Errno resetErrno, -- :: IO () -- conversion of an "errno" value into IO error -- errnoToIOError, -- :: String -- location -- -> Errno -- errno -- -> Maybe Handle -- handle -- -> Maybe String -- filename -- -> IOError -- throw current "errno" value -- throwErrno, -- :: String -> IO a -- ** Guards for IO operations that may fail throwErrnoIf, -- :: (a -> Bool) -> String -> IO a -> IO a throwErrnoIf_, -- :: (a -> Bool) -> String -> IO a -> IO () throwErrnoIfRetry, -- :: (a -> Bool) -> String -> IO a -> IO a throwErrnoIfRetry_, -- :: (a -> Bool) -> String -> IO a -> IO () throwErrnoIfMinus1, -- :: Num a -- => String -> IO a -> IO a throwErrnoIfMinus1_, -- :: Num a -- => String -> IO a -> IO () throwErrnoIfMinus1Retry, -- :: Num a -- => String -> IO a -> IO a throwErrnoIfMinus1Retry_, -- :: Num a -- => String -> IO a -> IO () throwErrnoIfNull, -- :: String -> IO (Ptr a) -> IO (Ptr a) throwErrnoIfNullRetry,-- :: String -> IO (Ptr a) -> IO (Ptr a) throwErrnoIfRetryMayBlock, throwErrnoIfRetryMayBlock_, throwErrnoIfMinus1RetryMayBlock, throwErrnoIfMinus1RetryMayBlock_, throwErrnoIfNullRetryMayBlock ) where -- this is were we get the CONST_XXX definitions from that configure -- calculated for us -- #ifndef __NHC__ #include "HsBaseConfig.h" #endif -- system dependent imports -- ------------------------ -- GHC allows us to get at the guts inside IO errors/exceptions -- #if __GLASGOW_HASKELL__ import GHC.IOBase (IOException(..), IOErrorType(..)) #endif /* __GLASGOW_HASKELL__ */ -- regular imports -- --------------- import Foreign.Storable import Foreign.Ptr import Foreign.C.Types import Foreign.C.String import Foreign.Marshal.Error ( void ) import Data.Maybe #if __GLASGOW_HASKELL__ import GHC.IOBase import GHC.Num import GHC.Base #else import System.IO ( Handle ) import System.IO.Error ( IOError, ioError ) import System.IO.Unsafe ( unsafePerformIO ) #endif #ifdef __HUGS__ {-# CFILES cbits/PrelIOUtils.c #-} #endif -- "errno" type -- ------------ -- | Haskell representation for @errno@ values. -- The implementation is deliberately exposed, to allow users to add -- their own definitions of 'Errno' values. newtype Errno = Errno CInt instance Eq Errno where errno1@(Errno no1) == errno2@(Errno no2) | isValidErrno errno1 && isValidErrno errno2 = no1 == no2 | otherwise = False -- common "errno" symbols -- eOK, e2BIG, eACCES, eADDRINUSE, eADDRNOTAVAIL, eADV, eAFNOSUPPORT, eAGAIN, eALREADY, eBADF, eBADMSG, eBADRPC, eBUSY, eCHILD, eCOMM, eCONNABORTED, eCONNREFUSED, eCONNRESET, eDEADLK, eDESTADDRREQ, eDIRTY, eDOM, eDQUOT, eEXIST, eFAULT, eFBIG, eFTYPE, eHOSTDOWN, eHOSTUNREACH, eIDRM, eILSEQ, eINPROGRESS, eINTR, eINVAL, eIO, eISCONN, eISDIR, eLOOP, eMFILE, eMLINK, eMSGSIZE, eMULTIHOP, eNAMETOOLONG, eNETDOWN, eNETRESET, eNETUNREACH, eNFILE, eNOBUFS, eNODATA, eNODEV, eNOENT, eNOEXEC, eNOLCK, eNOLINK, eNOMEM, eNOMSG, eNONET, eNOPROTOOPT, eNOSPC, eNOSR, eNOSTR, eNOSYS, eNOTBLK, eNOTCONN, eNOTDIR, eNOTEMPTY, eNOTSOCK, eNOTTY, eNXIO, eOPNOTSUPP, ePERM, ePFNOSUPPORT, ePIPE, ePROCLIM, ePROCUNAVAIL, ePROGMISMATCH, ePROGUNAVAIL, ePROTO, ePROTONOSUPPORT, ePROTOTYPE, eRANGE, eREMCHG, eREMOTE, eROFS, eRPCMISMATCH, eRREMOTE, eSHUTDOWN, eSOCKTNOSUPPORT, eSPIPE, eSRCH, eSRMNT, eSTALE, eTIME, eTIMEDOUT, eTOOMANYREFS, eTXTBSY, eUSERS, eWOULDBLOCK, eXDEV :: Errno -- -- the cCONST_XXX identifiers are cpp symbols whose value is computed by -- configure -- eOK = Errno 0 #ifdef __NHC__ #include "Errno.hs" #else e2BIG = Errno (CONST_E2BIG) eACCES = Errno (CONST_EACCES) eADDRINUSE = Errno (CONST_EADDRINUSE) eADDRNOTAVAIL = Errno (CONST_EADDRNOTAVAIL) eADV = Errno (CONST_EADV) eAFNOSUPPORT = Errno (CONST_EAFNOSUPPORT) eAGAIN = Errno (CONST_EAGAIN) eALREADY = Errno (CONST_EALREADY) eBADF = Errno (CONST_EBADF) eBADMSG = Errno (CONST_EBADMSG) eBADRPC = Errno (CONST_EBADRPC) eBUSY = Errno (CONST_EBUSY) eCHILD = Errno (CONST_ECHILD) eCOMM = Errno (CONST_ECOMM) eCONNABORTED = Errno (CONST_ECONNABORTED) eCONNREFUSED = Errno (CONST_ECONNREFUSED) eCONNRESET = Errno (CONST_ECONNRESET) eDEADLK = Errno (CONST_EDEADLK) eDESTADDRREQ = Errno (CONST_EDESTADDRREQ) eDIRTY = Errno (CONST_EDIRTY) eDOM = Errno (CONST_EDOM) eDQUOT = Errno (CONST_EDQUOT) eEXIST = Errno (CONST_EEXIST) eFAULT = Errno (CONST_EFAULT) eFBIG = Errno (CONST_EFBIG) eFTYPE = Errno (CONST_EFTYPE) eHOSTDOWN = Errno (CONST_EHOSTDOWN) eHOSTUNREACH = Errno (CONST_EHOSTUNREACH) eIDRM = Errno (CONST_EIDRM) eILSEQ = Errno (CONST_EILSEQ) eINPROGRESS = Errno (CONST_EINPROGRESS) eINTR = Errno (CONST_EINTR) eINVAL = Errno (CONST_EINVAL) eIO = Errno (CONST_EIO) eISCONN = Errno (CONST_EISCONN) eISDIR = Errno (CONST_EISDIR) eLOOP = Errno (CONST_ELOOP) eMFILE = Errno (CONST_EMFILE) eMLINK = Errno (CONST_EMLINK) eMSGSIZE = Errno (CONST_EMSGSIZE) eMULTIHOP = Errno (CONST_EMULTIHOP) eNAMETOOLONG = Errno (CONST_ENAMETOOLONG) eNETDOWN = Errno (CONST_ENETDOWN) eNETRESET = Errno (CONST_ENETRESET) eNETUNREACH = Errno (CONST_ENETUNREACH) eNFILE = Errno (CONST_ENFILE) eNOBUFS = Errno (CONST_ENOBUFS) eNODATA = Errno (CONST_ENODATA) eNODEV = Errno (CONST_ENODEV) eNOENT = Errno (CONST_ENOENT) eNOEXEC = Errno (CONST_ENOEXEC) eNOLCK = Errno (CONST_ENOLCK) eNOLINK = Errno (CONST_ENOLINK) eNOMEM = Errno (CONST_ENOMEM) eNOMSG = Errno (CONST_ENOMSG) eNONET = Errno (CONST_ENONET) eNOPROTOOPT = Errno (CONST_ENOPROTOOPT) eNOSPC = Errno (CONST_ENOSPC) eNOSR = Errno (CONST_ENOSR) eNOSTR = Errno (CONST_ENOSTR) eNOSYS = Errno (CONST_ENOSYS) eNOTBLK = Errno (CONST_ENOTBLK) eNOTCONN = Errno (CONST_ENOTCONN) eNOTDIR = Errno (CONST_ENOTDIR) eNOTEMPTY = Errno (CONST_ENOTEMPTY) eNOTSOCK = Errno (CONST_ENOTSOCK) eNOTTY = Errno (CONST_ENOTTY) eNXIO = Errno (CONST_ENXIO) eOPNOTSUPP = Errno (CONST_EOPNOTSUPP) ePERM = Errno (CONST_EPERM) ePFNOSUPPORT = Errno (CONST_EPFNOSUPPORT) ePIPE = Errno (CONST_EPIPE) ePROCLIM = Errno (CONST_EPROCLIM) ePROCUNAVAIL = Errno (CONST_EPROCUNAVAIL) ePROGMISMATCH = Errno (CONST_EPROGMISMATCH) ePROGUNAVAIL = Errno (CONST_EPROGUNAVAIL) ePROTO = Errno (CONST_EPROTO) ePROTONOSUPPORT = Errno (CONST_EPROTONOSUPPORT) ePROTOTYPE = Errno (CONST_EPROTOTYPE) eRANGE = Errno (CONST_ERANGE) eREMCHG = Errno (CONST_EREMCHG) eREMOTE = Errno (CONST_EREMOTE) eROFS = Errno (CONST_EROFS) eRPCMISMATCH = Errno (CONST_ERPCMISMATCH) eRREMOTE = Errno (CONST_ERREMOTE) eSHUTDOWN = Errno (CONST_ESHUTDOWN) eSOCKTNOSUPPORT = Errno (CONST_ESOCKTNOSUPPORT) eSPIPE = Errno (CONST_ESPIPE) eSRCH = Errno (CONST_ESRCH) eSRMNT = Errno (CONST_ESRMNT) eSTALE = Errno (CONST_ESTALE) eTIME = Errno (CONST_ETIME) eTIMEDOUT = Errno (CONST_ETIMEDOUT) eTOOMANYREFS = Errno (CONST_ETOOMANYREFS) eTXTBSY = Errno (CONST_ETXTBSY) eUSERS = Errno (CONST_EUSERS) eWOULDBLOCK = Errno (CONST_EWOULDBLOCK) eXDEV = Errno (CONST_EXDEV) #endif -- | Yield 'True' if the given 'Errno' value is valid on the system. -- This implies that the 'Eq' instance of 'Errno' is also system dependent -- as it is only defined for valid values of 'Errno'. -- isValidErrno :: Errno -> Bool -- -- the configure script sets all invalid "errno"s to -1 -- isValidErrno (Errno errno) = errno /= -1 -- access to the current thread's "errno" value -- -------------------------------------------- -- | Get the current value of @errno@ in the current thread. -- getErrno :: IO Errno -- We must call a C function to get the value of errno in general. On -- threaded systems, errno is hidden behind a C macro so that each OS -- thread gets its own copy. #ifdef __NHC__ getErrno = do e <- peek _errno; return (Errno e) foreign import ccall unsafe "errno.h &errno" _errno :: Ptr CInt #else getErrno = do e <- get_errno; return (Errno e) foreign import ccall unsafe "HsBase.h __hscore_get_errno" get_errno :: IO CInt #endif -- | Reset the current thread\'s @errno@ value to 'eOK'. -- resetErrno :: IO () -- Again, setting errno has to be done via a C function. #ifdef __NHC__ resetErrno = poke _errno 0 #else resetErrno = set_errno 0 foreign import ccall unsafe "HsBase.h __hscore_set_errno" set_errno :: CInt -> IO () #endif -- throw current "errno" value -- --------------------------- -- | Throw an 'IOError' corresponding to the current value of 'getErrno'. -- throwErrno :: String -- ^ textual description of the error location -> IO a throwErrno loc = do errno <- getErrno ioError (errnoToIOError loc errno Nothing Nothing) -- guards for IO operations that may fail -- -------------------------------------- -- | Throw an 'IOError' corresponding to the current value of 'getErrno' -- if the result value of the 'IO' action meets the given predicate. -- throwErrnoIf :: (a -> Bool) -- ^ predicate to apply to the result value -- of the 'IO' operation -> String -- ^ textual description of the location -> IO a -- ^ the 'IO' operation to be executed -> IO a throwErrnoIf pred loc f = do res <- f if pred res then throwErrno loc else return res -- | as 'throwErrnoIf', but discards the result of the 'IO' action after -- error handling. -- throwErrnoIf_ :: (a -> Bool) -> String -> IO a -> IO () throwErrnoIf_ pred loc f = void $ throwErrnoIf pred loc f -- | as 'throwErrnoIf', but retry the 'IO' action when it yields the -- error code 'eINTR' - this amounts to the standard retry loop for -- interrupted POSIX system calls. -- throwErrnoIfRetry :: (a -> Bool) -> String -> IO a -> IO a throwErrnoIfRetry pred loc f = do res <- f if pred res then do err <- getErrno if err == eINTR then throwErrnoIfRetry pred loc f else throwErrno loc else return res -- | as 'throwErrnoIfRetry', but checks for operations that would block and -- executes an alternative action before retrying in that case. -- throwErrnoIfRetryMayBlock :: (a -> Bool) -- ^ predicate to apply to the result value -- of the 'IO' operation -> String -- ^ textual description of the location -> IO a -- ^ the 'IO' operation to be executed -> IO b -- ^ action to execute before retrying if -- an immediate retry would block -> IO a throwErrnoIfRetryMayBlock pred loc f on_block = do res <- f if pred res then do err <- getErrno if err == eINTR then throwErrnoIfRetryMayBlock pred loc f on_block else if err == eWOULDBLOCK || err == eAGAIN then do on_block; throwErrnoIfRetryMayBlock pred loc f on_block else throwErrno loc else return res -- | as 'throwErrnoIfRetry', but discards the result. -- throwErrnoIfRetry_ :: (a -> Bool) -> String -> IO a -> IO () throwErrnoIfRetry_ pred loc f = void $ throwErrnoIfRetry pred loc f -- | as 'throwErrnoIfRetryMayBlock', but discards the result. -- throwErrnoIfRetryMayBlock_ :: (a -> Bool) -> String -> IO a -> IO b -> IO () throwErrnoIfRetryMayBlock_ pred loc f on_block = void $ throwErrnoIfRetryMayBlock pred loc f on_block -- | Throw an 'IOError' corresponding to the current value of 'getErrno' -- if the 'IO' action returns a result of @-1@. -- throwErrnoIfMinus1 :: Num a => String -> IO a -> IO a throwErrnoIfMinus1 = throwErrnoIf (== -1) -- | as 'throwErrnoIfMinus1', but discards the result. -- throwErrnoIfMinus1_ :: Num a => String -> IO a -> IO () throwErrnoIfMinus1_ = throwErrnoIf_ (== -1) -- | Throw an 'IOError' corresponding to the current value of 'getErrno' -- if the 'IO' action returns a result of @-1@, but retries in case of -- an interrupted operation. -- throwErrnoIfMinus1Retry :: Num a => String -> IO a -> IO a throwErrnoIfMinus1Retry = throwErrnoIfRetry (== -1) -- | as 'throwErrnoIfMinus1', but discards the result. -- throwErrnoIfMinus1Retry_ :: Num a => String -> IO a -> IO () throwErrnoIfMinus1Retry_ = throwErrnoIfRetry_ (== -1) -- | as 'throwErrnoIfMinus1Retry', but checks for operations that would block. -- throwErrnoIfMinus1RetryMayBlock :: Num a => String -> IO a -> IO b -> IO a throwErrnoIfMinus1RetryMayBlock = throwErrnoIfRetryMayBlock (== -1) -- | as 'throwErrnoIfMinus1RetryMayBlock', but discards the result. -- throwErrnoIfMinus1RetryMayBlock_ :: Num a => String -> IO a -> IO b -> IO () throwErrnoIfMinus1RetryMayBlock_ = throwErrnoIfRetryMayBlock_ (== -1) -- | Throw an 'IOError' corresponding to the current value of 'getErrno' -- if the 'IO' action returns 'nullPtr'. -- throwErrnoIfNull :: String -> IO (Ptr a) -> IO (Ptr a) throwErrnoIfNull = throwErrnoIf (== nullPtr) -- | Throw an 'IOError' corresponding to the current value of 'getErrno' -- if the 'IO' action returns 'nullPtr', -- but retry in case of an interrupted operation. -- throwErrnoIfNullRetry :: String -> IO (Ptr a) -> IO (Ptr a) throwErrnoIfNullRetry = throwErrnoIfRetry (== nullPtr) -- | as 'throwErrnoIfNullRetry', but checks for operations that would block. -- throwErrnoIfNullRetryMayBlock :: String -> IO (Ptr a) -> IO b -> IO (Ptr a) throwErrnoIfNullRetryMayBlock = throwErrnoIfRetryMayBlock (== nullPtr) -- conversion of an "errno" value into IO error -- -------------------------------------------- -- | Construct a Haskell 98 I\/O error based on the given 'Errno' value. -- The optional information can be used to improve the accuracy of -- error messages. -- errnoToIOError :: String -- ^ the location where the error occurred -> Errno -- ^ the error number -> Maybe Handle -- ^ optional handle associated with the error -> Maybe String -- ^ optional filename associated with the error -> IOError errnoToIOError loc errno maybeHdl maybeName = unsafePerformIO $ do str <- strerror errno >>= peekCString #if __GLASGOW_HASKELL__ return (IOError maybeHdl errType loc str maybeName) where errType | errno == eOK = OtherError | errno == e2BIG = ResourceExhausted | errno == eACCES = PermissionDenied | errno == eADDRINUSE = ResourceBusy | errno == eADDRNOTAVAIL = UnsupportedOperation | errno == eADV = OtherError | errno == eAFNOSUPPORT = UnsupportedOperation | errno == eAGAIN = ResourceExhausted | errno == eALREADY = AlreadyExists | errno == eBADF = InvalidArgument | errno == eBADMSG = InappropriateType | errno == eBADRPC = OtherError | errno == eBUSY = ResourceBusy | errno == eCHILD = NoSuchThing | errno == eCOMM = ResourceVanished | errno == eCONNABORTED = OtherError | errno == eCONNREFUSED = NoSuchThing | errno == eCONNRESET = ResourceVanished | errno == eDEADLK = ResourceBusy | errno == eDESTADDRREQ = InvalidArgument | errno == eDIRTY = UnsatisfiedConstraints | errno == eDOM = InvalidArgument | errno == eDQUOT = PermissionDenied | errno == eEXIST = AlreadyExists | errno == eFAULT = OtherError | errno == eFBIG = PermissionDenied | errno == eFTYPE = InappropriateType | errno == eHOSTDOWN = NoSuchThing | errno == eHOSTUNREACH = NoSuchThing | errno == eIDRM = ResourceVanished | errno == eILSEQ = InvalidArgument | errno == eINPROGRESS = AlreadyExists | errno == eINTR = Interrupted | errno == eINVAL = InvalidArgument | errno == eIO = HardwareFault | errno == eISCONN = AlreadyExists | errno == eISDIR = InappropriateType | errno == eLOOP = InvalidArgument | errno == eMFILE = ResourceExhausted | errno == eMLINK = ResourceExhausted | errno == eMSGSIZE = ResourceExhausted | errno == eMULTIHOP = UnsupportedOperation | errno == eNAMETOOLONG = InvalidArgument | errno == eNETDOWN = ResourceVanished | errno == eNETRESET = ResourceVanished | errno == eNETUNREACH = NoSuchThing | errno == eNFILE = ResourceExhausted | errno == eNOBUFS = ResourceExhausted | errno == eNODATA = NoSuchThing | errno == eNODEV = UnsupportedOperation | errno == eNOENT = NoSuchThing | errno == eNOEXEC = InvalidArgument | errno == eNOLCK = ResourceExhausted | errno == eNOLINK = ResourceVanished | errno == eNOMEM = ResourceExhausted | errno == eNOMSG = NoSuchThing | errno == eNONET = NoSuchThing | errno == eNOPROTOOPT = UnsupportedOperation | errno == eNOSPC = ResourceExhausted | errno == eNOSR = ResourceExhausted | errno == eNOSTR = InvalidArgument | errno == eNOSYS = UnsupportedOperation | errno == eNOTBLK = InvalidArgument | errno == eNOTCONN = InvalidArgument | errno == eNOTDIR = InappropriateType | errno == eNOTEMPTY = UnsatisfiedConstraints | errno == eNOTSOCK = InvalidArgument | errno == eNOTTY = IllegalOperation | errno == eNXIO = NoSuchThing | errno == eOPNOTSUPP = UnsupportedOperation | errno == ePERM = PermissionDenied | errno == ePFNOSUPPORT = UnsupportedOperation | errno == ePIPE = ResourceVanished | errno == ePROCLIM = PermissionDenied | errno == ePROCUNAVAIL = UnsupportedOperation | errno == ePROGMISMATCH = ProtocolError | errno == ePROGUNAVAIL = UnsupportedOperation | errno == ePROTO = ProtocolError | errno == ePROTONOSUPPORT = ProtocolError | errno == ePROTOTYPE = ProtocolError | errno == eRANGE = UnsupportedOperation | errno == eREMCHG = ResourceVanished | errno == eREMOTE = IllegalOperation | errno == eROFS = PermissionDenied | errno == eRPCMISMATCH = ProtocolError | errno == eRREMOTE = IllegalOperation | errno == eSHUTDOWN = IllegalOperation | errno == eSOCKTNOSUPPORT = UnsupportedOperation | errno == eSPIPE = UnsupportedOperation | errno == eSRCH = NoSuchThing | errno == eSRMNT = UnsatisfiedConstraints | errno == eSTALE = ResourceVanished | errno == eTIME = TimeExpired | errno == eTIMEDOUT = TimeExpired | errno == eTOOMANYREFS = ResourceExhausted | errno == eTXTBSY = ResourceBusy | errno == eUSERS = ResourceExhausted | errno == eWOULDBLOCK = OtherError | errno == eXDEV = UnsupportedOperation | otherwise = OtherError #else return (userError (loc ++ ": " ++ str ++ maybe "" (": "++) maybeName)) #endif foreign import ccall unsafe "string.h" strerror :: Errno -> IO (Ptr CChar)
FranklinChen/hugs98-plus-Sep2006
packages/base/Foreign/C/Error.hs
bsd-3-clause
21,679
384
12
5,399
3,346
2,000
1,346
249
4
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE ScopedTypeVariables #-} import qualified Network.Connection as N import Options.Applicative import qualified Rede.TLSConnect as SP import Rede.Utils (strToInt) import System.X509 (getSystemCertificateStore) import Rede.Subprograms.BasicPing(basicPingProgram) import Rede.Subprograms.BasicConnect(basicConnectProgram) data CmdConfig = CmdConfig { host :: String , port :: Int } deriving Show sample :: Parser CmdConfig sample = CmdConfig <$> strOption ( long "host" <> short 's' <> metavar "HOST" <> help "Target for the Ping" ) <*> ( strToInt <$> strOption ( long "port" <> short 'p' <> help "Port to connect to" )) greet :: CmdConfig -> IO () greet CmdConfig{ host=h, port=p} = do basicConnectProgram h p ctx <- N.initConnectionContext scs <- getSystemCertificateStore con <- N.connectTo ctx $ N.ConnectionParams { N.connectionHostname = h , N.connectionPort = fromInteger $ fromIntegral p , N.connectionUseSecure = Just $ N.TLSSettings ( SP.makeTLSParamsForSpdy (h,p) scs) , N.connectionUseSocks = Nothing } basicPingProgram (N.connectionGet con 4096) (N.connectionPut con) N.connectionClose con return () main :: IO () main = execParser opts >>= greet opts :: ParserInfo CmdConfig opts = info (sample <**> helper) ( fullDesc <> progDesc "Ping a SPDY host" <> header "Let's learn everything there is to learn about that host..." )
alcidesv/ReH
hs-src/main.hs
bsd-3-clause
1,683
0
15
467
423
222
201
47
1
{-# LANGUAGE OverloadedStrings #-} module Data.Streaming.NetworkSpec where import Control.Concurrent.Async (withAsync) import Control.Exception (bracket) import Control.Monad (forever, replicateM_) import Data.Array.Unboxed (elems) import qualified Data.ByteString.Char8 as S8 import Data.Char (toUpper) import Data.Streaming.Network import Network.Socket (sClose) import Test.Hspec import Test.Hspec.QuickCheck spec :: Spec spec = do describe "getUnassignedPort" $ do it "sanity" $ replicateM_ 100000 $ do port <- getUnassignedPort (port `elem` elems unassignedPorts) `shouldBe` True describe "bindRandomPortTCP" $ do modifyMaxSuccess (const 5) $ prop "sanity" $ \content -> bracket (bindRandomPortTCP "*4") (sClose . snd) $ \(port, socket) -> do let server ad = forever $ appRead ad >>= appWrite ad . S8.map toUpper client ad = do appWrite ad bs appRead ad >>= (`shouldBe` S8.map toUpper bs) bs | null content = "hello" | otherwise = S8.pack $ take 1000 content withAsync (runTCPServer (serverSettingsTCPSocket socket) server) $ \_ -> do runTCPClient (clientSettingsTCP port "127.0.0.1") client
phadej/streaming-commons
test/Data/Streaming/NetworkSpec.hs
mit
1,513
0
24
559
388
201
187
32
1
{-# LANGUAGE OverloadedStrings #-} module Main where import AndroidLintSummary.CLI (runCLI) import Paths_android_lint_summary (version) main :: IO () main = runCLI version
VikingDen/android-lint-summary
Main.hs
apache-2.0
199
0
6
48
41
24
17
6
1
{- | Module : $Header$ Copyright : (c) Till Mossakowski, Wiebke Herding, C. Maeder, Uni Bremen 2004 License : GPLv2 or higher, see LICENSE.txt Maintainer : [email protected] Stability : provisional Portability : portable Parser for modal logic extension of CASL -} module Modal.Parse_AS where import CASL.Formula import CASL.OpItem import Common.AS_Annotation import Common.AnnoState import Common.Id import Common.Keywords import Common.Lexer import Common.Token import Modal.AS_Modal import Text.ParserCombinators.Parsec import Data.List modal_reserved_words :: [String] modal_reserved_words = diamondS : termS : rigidS : flexibleS : modalityS : [modalitiesS] modalFormula :: AParser st M_FORMULA modalFormula = do o <- oBracketT m <- modality [] c <- cBracketT f <- primFormula modal_reserved_words return (BoxOrDiamond True m f $ toRange o [] c) <|> do o <- asKey lessS m <- modality [greaterS] -- do not consume matching ">"! c <- asKey greaterS f <- primFormula modal_reserved_words return (BoxOrDiamond False m f $ toRange o [] c) <|> do d <- asKey diamondS f <- primFormula modal_reserved_words let p = tokPos d return (BoxOrDiamond False (Simple_mod $ Token emptyS p) f p) modality :: [String] -> AParser st MODALITY modality ks = do t <- term (ks ++ modal_reserved_words) return $ Term_mod t <|> return (Simple_mod $ mkSimpleId emptyS) instance TermParser M_FORMULA where termParser = aToTermParser modalFormula rigor :: AParser st RIGOR rigor = (asKey rigidS >> return Rigid) <|> (asKey flexibleS >> return Flexible) rigidSigItems :: AParser st M_SIG_ITEM rigidSigItems = do r <- rigor itemList modal_reserved_words opS opItem (Rigid_op_items r) <|> itemList modal_reserved_words predS predItem (Rigid_pred_items r) instance AParsable M_SIG_ITEM where aparser = rigidSigItems mKey :: AParser st Token mKey = asKey modalityS <|> asKey modalitiesS mBasic :: AParser st M_BASIC_ITEM mBasic = do (as, fs, ps) <- mItem simpleId return (Simple_mod_decl as fs ps) <|> do t <- asKey termS (as, fs, ps) <- mItem (sortId modal_reserved_words) return (Term_mod_decl as fs (tokPos t `appRange` ps)) mItem :: AParser st a -> AParser st ([Annoted a], [AnModFORM], Range) mItem pr = do c <- mKey (as, cs) <- separatedBy (annoParser pr) anSemiOrComma let ps = catRange $ c : cs do o <- oBraceT (fs, q) <- auxItemList (delete diamondS modal_reserved_words) [] (formula modal_reserved_words) (,) p <- cBraceT return (as, fs, ps `appRange` q `appRange` toRange o [] p) <|> return (as, [], ps) instance AParsable M_BASIC_ITEM where aparser = mBasic
mariefarrell/Hets
Modal/Parse_AS.hs
gpl-2.0
2,863
0
14
693
884
438
446
73
1
import Common import Communication.IVC import Control.Concurrent import Control.Exception import Control.Monad import Data.Binary.Put import Hypervisor.Debug import Hypervisor.ErrorCodes import Hypervisor.XenStore main = handle exceptionHandler $ do writeDebugConsole "LEFT: Initializing XenStore.\n" xs <- initXenStore writeDebugConsole "LEFT: Starting rendezvous.\n" outch <- leftSide xs writeDebugConsole "LEFT: Completed rendezvous.\n" forM_ [0..65500] $ \next -> do when (next `mod` 100 == 0) $ do writeDebugConsole $ "LEFT: Sent message " ++ show next ++ "\n" put outch (runPut (putWord16be next)) put outch (runPut (putWord16be next)) put outch (runPut (putWord16be next)) put outch (runPut (putWord16be next)) writeDebugConsole "LEFT: Completed writes. Delaying.\n" threadDelay (2 * 1000 * 1000) writeDebugConsole "LEFT: Done.\n" exceptionHandler :: ErrorCode -> IO () exceptionHandler ec = do writeDebugConsole ("RIGHT: Caught exception: " ++ show ec ++ "\n")
ggkitsas/HaLVM
examples/IVC/ByteStringIVC/Peer1.hs
bsd-3-clause
1,019
0
17
172
304
144
160
28
1
-- Tests created by Jan Stolarek <[email protected]> {-# LANGUAGE BangPatterns, MagicHash #-} module Main where import GHC.Exts main :: IO () main = do -- PrimOps for comparing Char# putStrLn "=== testing gtChar# ===" test "gtChar#" (a# `gtChar#` a# ) -- False test "gtChar#" (b# `gtChar#` a# ) -- True test "gtChar#" (a# `gtChar#` b# ) -- False test "gtChar#" (minC# `gtChar#` minC#) -- False test "gtChar#" (maxC# `gtChar#` maxC#) -- False test "gtChar#" (minC# `gtChar#` maxC#) -- False test "gtChar#" (maxC# `gtChar#` minC#) -- True putStrLn "=== testing geChar# ===" test "geChar#" (a# `geChar#` a# ) -- True test "geChar#" (b# `geChar#` a# ) -- True test "geChar#" (a# `geChar#` b# ) -- False test "geChar#" (minC# `geChar#` minC#) -- True test "geChar#" (maxC# `geChar#` maxC#) -- True test "geChar#" (minC# `geChar#` maxC#) -- False test "geChar#" (maxC# `geChar#` minC#) -- True putStrLn "=== testing ltChar# ===" test "ltChar#" (a# `ltChar#` a# ) -- False test "ltChar#" (b# `ltChar#` a# ) -- False test "ltChar#" (a# `ltChar#` b# ) -- True test "ltChar#" (minC# `ltChar#` minC#) -- False test "ltChar#" (maxC# `ltChar#` maxC#) -- False test "ltChar#" (minC# `ltChar#` maxC#) -- True test "ltChar#" (maxC# `ltChar#` minC#) -- False putStrLn "=== testing leChar# ===" test "leChar#" (a# `leChar#` a# ) -- True test "leChar#" (b# `leChar#` a# ) -- False test "leChar#" (a# `leChar#` b# ) -- True test "leChar#" (minC# `leChar#` minC#) -- True test "leChar#" (maxC# `leChar#` maxC#) -- True test "leChar#" (minC# `leChar#` maxC#) -- True test "leChar#" (maxC# `leChar#` minC#) -- False putStrLn "=== testing eqChar# ===" test "eqChar#" (a# `eqChar#` a# ) -- True test "eqChar#" (b# `eqChar#` a# ) -- False test "eqChar#" (a# `eqChar#` b# ) -- False test "eqChar#" (minC# `eqChar#` minC#) -- True test "eqChar#" (maxC# `eqChar#` maxC#) -- True test "eqChar#" (minC# `eqChar#` maxC#) -- False test "eqChar#" (maxC# `eqChar#` minC#) -- False putStrLn "=== testing neChar# ===" test "neChar#" (a# `neChar#` a# ) -- False test "neChar#" (b# `neChar#` a# ) -- True test "neChar#" (a# `neChar#` b# ) -- True test "neChar#" (minC# `neChar#` minC#) -- False test "neChar#" (maxC# `neChar#` maxC#) -- False test "neChar#" (minC# `neChar#` maxC#) -- True test "neChar#" (maxC# `neChar#` minC#) -- True -- PrimOps for comparing Int# putStrLn "=== testing ># ===" test ">#" (0# ># 0# ) -- False test ">#" (1# ># 0# ) -- True test ">#" (0# ># 1# ) -- False test ">#" (minI# ># minI# ) -- False test ">#" (maxI# ># maxI# ) -- False test ">#" (minI# +# 1# ># minI# ) -- True test ">#" (minI# ># minI# -# 1#) -- False (overflow) test ">#" (maxI# +# 1# ># maxI# ) -- False (overflow) test ">#" (maxI# ># maxI# -# 1#) -- True putStrLn "=== testing <# ===" test "<#" (0# <# 0# ) -- False test "<#" (1# <# 0# ) -- False test "<#" (0# <# 1# ) -- True test "<#" (minI# <# minI# ) -- False test "<#" (maxI# <# maxI# ) -- False test "<#" (minI# <# minI# +# 1#) -- True test "<#" (minI# -# 1# <# minI# ) -- False (overflow) test "<#" (maxI# <# maxI# +# 1#) -- False (overflow) test "<#" (maxI# -# 1# <# maxI# ) -- True putStrLn "=== testing >=# ===" test ">=#" (0# >=# 0# ) -- True test ">=#" (1# >=# 0# ) -- True test ">=#" (0# >=# 1# ) -- False test ">=#" (minI# >=# minI# ) -- True test ">=#" (maxI# >=# maxI# ) -- True test ">=#" (minI# +# 1# >=# minI# ) -- True test ">=#" (minI# >=# minI# -# 1#) -- False (overflow) test ">=#" (maxI# +# 1# >=# maxI# ) -- False (overflow) test ">=#" (maxI# >=# maxI# -# 1#) -- True putStrLn "=== testing <=# ===" test "<=#" (0# <=# 0# ) -- True test "<=#" (1# <=# 0# ) -- False test "<=#" (0# <=# 1# ) -- True test "<=#" (minI# <=# minI# ) -- True test "<=#" (maxI# <=# maxI# ) -- True test "<=#" (minI# <=# minI# +# 1#) -- True test "<=#" (minI# -# 1# <=# minI# ) -- False (overflow) test "<=#" (maxI# <=# maxI# +# 1#) -- False (overflow) test "<=#" (maxI# -# 1# <=# maxI# ) -- True putStrLn "=== testing ==# ===" test "==#" (0# ==# 0# ) -- True test "==#" (1# ==# 0# ) -- False test "==#" (0# ==# 1# ) -- False test "==#" (maxI# ==# maxI# ) -- True test "==#" (maxI# -# 1# ==# maxI# ) -- False test "==#" (minI# ==# minI# ) -- True test "==#" (minI# ==# minI# +# 1#) -- False test "==#" (minI# ==# maxI# +# 1#) -- True (overflow) test "==#" (maxI# +# 1# ==# minI# ) -- True (overflow) test "==#" (maxI# ==# minI# -# 1#) -- True (overflow) test "==#" (minI# -# 1# ==# maxI# ) -- True (overflow) putStrLn "=== testing /=# ===" test "/=#" (0# /=# 0# ) -- False test "/=#" (1# /=# 0# ) -- True test "/=#" (0# /=# 1# ) -- True test "/=#" (maxI# /=# maxI# ) -- False test "/=#" (maxI# -# 1# /=# maxI# ) -- True test "/=#" (minI# /=# minI# ) -- False test "/=#" (minI# /=# minI# +# 1#) -- True test "/=#" (minI# /=# maxI# +# 1#) -- False (overflow) test "/=#" (maxI# +# 1# /=# minI# ) -- False (overflow) test "/=#" (maxI# /=# minI# -# 1#) -- False (overflow) test "/=#" (minI# -# 1# /=# maxI# ) -- False (overflow) -- PrimOps for comparing Word# putStrLn "=== testing gtWord# ===" test "gtWord#" (zeroW# `gtWord#` zeroW# ) -- False test "gtWord#" (oneW# `gtWord#` zeroW# ) -- True test "gtWord#" (zeroW# `gtWord#` oneW# ) -- False test "gtWord#" (minW# `gtWord#` minW# ) -- False test "gtWord#" (maxW# `gtWord#` maxW# ) -- False test "gtWord#" ((minW# `plusWord#` oneW#) `gtWord#` minW# ) -- True test "gtWord#" (minW# `gtWord#` (minW# `minusWord#` oneW#)) -- False (overflow) test "gtWord#" ((maxW# `plusWord#` oneW#) `gtWord#` maxW# ) -- False (overflow) test "gtWord#" (maxW# `gtWord#` (maxW# `minusWord#` oneW#)) -- True putStrLn "=== testing ltWord# ===" test "ltWord#" (zeroW# `ltWord#` zeroW# ) -- False test "ltWord#" (oneW# `ltWord#` zeroW# ) -- False test "ltWord#" (zeroW# `ltWord#` oneW# ) -- True test "ltWord#" (minW# `ltWord#` minW# ) -- False test "ltWord#" (maxW# `ltWord#` maxW# ) -- False test "ltWord#" (minW# `ltWord#` (minW# `plusWord#` oneW#)) -- True test "ltWord#" ((minW# `minusWord#` oneW#) `ltWord#` minW# ) -- False (overflow) test "ltWord#" (maxW# `ltWord#` (maxW# `plusWord#` oneW#)) -- False (overflow) test "ltWord#" ((maxW# `minusWord#` oneW#) `ltWord#` maxW# ) -- True putStrLn "=== testing geWord# ===" test "geWord#" (zeroW# `geWord#` zeroW# ) -- True test "geWord#" (oneW# `geWord#` zeroW# ) -- True test "geWord#" (zeroW# `geWord#` oneW# ) -- False test "geWord#" (minW# `geWord#` minW# ) -- True test "geWord#" (maxW# `geWord#` maxW# ) -- True test "geWord#" ((minW# `plusWord#` oneW#) `geWord#` minW# ) -- True test "geWord#" (minW# `geWord#` (minW# `minusWord#` oneW#)) -- False (overflow) test "geWord#" ((maxW# `plusWord#` oneW#) `geWord#` maxW# ) -- False (overflow) test "geWord#" (maxW# `geWord#` (maxW# `minusWord#` oneW#)) -- True putStrLn "=== testing leWord# ===" test "leWord#" (zeroW# `leWord#` zeroW# ) -- True test "leWord#" (oneW# `leWord#` zeroW# ) -- False test "leWord#" (zeroW# `leWord#` oneW# ) -- True test "leWord#" (minW# `leWord#` minW# ) -- True test "leWord#" (maxW# `leWord#` maxW# ) -- True test "leWord#" (minW# `leWord#` (minW# `plusWord#` oneW#)) -- True test "leWord#" ((minW# `minusWord#` oneW#) `leWord#` minW# ) -- False (overflow) test "leWord#" (maxW# `leWord#` (maxW# `plusWord#` oneW#)) -- False (overflow) test "leWord#" ((maxW# `minusWord#` oneW#) `leWord#` maxW# ) -- True putStrLn "=== testing eqWord# ===" test "eqWord#" (zeroW# `eqWord#` zeroW# ) -- True test "eqWord#" (oneW# `eqWord#` zeroW# ) -- False test "eqWord#" (zeroW# `eqWord#` oneW# ) -- False test "eqWord#" (maxW# `eqWord#` maxW# ) -- True test "eqWord#" ((maxW# `minusWord#` oneW#) `eqWord#` maxW# ) -- False test "eqWord#" (minW# `eqWord#` minW# ) -- True test "eqWord#" (minW# `eqWord#` (minW# `plusWord#` oneW#) ) -- False test "eqWord#" (minW# `eqWord#` (maxW# `plusWord#` oneW#) ) -- True (overflow) test "eqWord#" ((maxW# `plusWord#` oneW#) `eqWord#` minW# ) -- True (overflow) test "eqWord#" (maxW# `eqWord#` (minW# `minusWord#` oneW#)) -- True (overflow) test "eqWord#" ((minW# `minusWord#` oneW#) `eqWord#` maxW# ) -- True (overflow) putStrLn "=== testing neWord# ===" test "neWord#" (zeroW# `neWord#` zeroW# ) -- False test "neWord#" (oneW# `neWord#` zeroW# ) -- True test "neWord#" (zeroW# `neWord#` oneW# ) -- True test "neWord#" (maxW# `neWord#` maxW# ) -- False test "neWord#" ((maxW# `minusWord#` oneW#) `neWord#` maxW# ) -- True test "neWord#" (minW# `neWord#` minW# ) -- False test "neWord#" (minW# `neWord#` (minW# `plusWord#` oneW#) ) -- True test "neWord#" (minW# `neWord#` (maxW# `plusWord#` oneW#) ) -- False (overflow) test "neWord#" ((maxW# `plusWord#` oneW#) `neWord#` minW# ) -- False (overflow) test "neWord#" (maxW# `neWord#` (minW# `minusWord#` oneW#)) -- False (overflow) test "neWord#" ((minW# `minusWord#` oneW#) `neWord#` maxW# ) -- False (overflow) -- PrimOps for comparing Double# putStrLn "=== testing >## ===" test ">##" (0.0## >## 0.0## ) -- False test ">##" (1.0## >## 0.0## ) -- True test ">##" (0.0## >## 1.0## ) -- False test ">##" (0.0## >## nan## ) -- False test ">##" (nan## >## 0.0## ) -- False test ">##" (nan## >## nan## ) -- False test ">##" (infp## >## infp##) -- False test ">##" (infn## >## infn##) -- False test ">##" (infp## >## infn##) -- True test ">##" (infn## >## infp##) -- False test ">##" (infp## >## nan## ) -- False test ">##" (infn## >## nan## ) -- False test ">##" (nan## >## infp##) -- False test ">##" (nan## >## infn##) -- False putStrLn "=== testing <## ===" test "<##" (0.0## <## 0.0## ) -- False test "<##" (1.0## <## 0.0## ) -- False test "<##" (0.0## <## 1.0## ) -- True test "<##" (0.0## <## nan## ) -- False test "<##" (nan## <## 0.0## ) -- False test "<##" (nan## <## nan## ) -- False test "<##" (infp## <## infp##) -- False test "<##" (infn## <## infn##) -- False test "<##" (infp## <## infn##) -- False test "<##" (infn## <## infp##) -- True test "<##" (infp## <## nan## ) -- False test "<##" (infn## <## nan## ) -- False test "<##" (nan## <## infp##) -- False test "<##" (nan## <## infn##) -- False putStrLn "=== testing >=## ===" test ">=##" (0.0## >=## 0.0## ) -- True test ">=##" (1.0## >=## 0.0## ) -- True test ">=##" (0.0## >=## 1.0## ) -- False test ">=##" (0.0## >=## nan## ) -- False test ">=##" (nan## >=## 0.0## ) -- False test ">=##" (nan## >=## nan## ) -- False test ">=##" (infp## >=## infp##) -- True test ">=##" (infn## >=## infn##) -- True test ">=##" (infp## >=## infn##) -- True test ">=##" (infn## >=## infp##) -- False test ">=##" (infp## >=## nan## ) -- False test ">=##" (infn## >=## nan## ) -- False test ">=##" (nan## >=## infp##) -- False test ">=##" (nan## >=## infn##) -- False putStrLn "=== testing <=## ===" test "<=##" (0.0## <=## 0.0## ) -- True test "<=##" (1.0## <=## 0.0## ) -- False test "<=##" (0.0## <=## 1.0## ) -- True test "<=##" (0.0## <=## nan## ) -- False test "<=##" (nan## <=## 0.0## ) -- False test "<=##" (nan## <=## nan## ) -- False test "<=##" (infp## <=## infp##) -- True test "<=##" (infn## <=## infn##) -- True test "<=##" (infp## <=## infn##) -- False test "<=##" (infn## <=## infp##) -- True test "<=##" (infp## <=## nan## ) -- False test "<=##" (infn## <=## nan## ) -- False test "<=##" (nan## <=## infp##) -- False test "<=##" (nan## <=## infn##) -- False putStrLn "=== testing ==## ===" test "==##" (0.0## ==## 0.0## ) -- True test "==##" (1.0## ==## 0.0## ) -- False test "==##" (0.0## ==## 1.0## ) -- False test "==##" (0.0## ==## nan## ) -- False test "==##" (nan## ==## 0.0## ) -- False test "==##" (nan## ==## nan## ) -- False test "==##" (infp## ==## infp##) -- True test "==##" (infn## ==## infn##) -- True test "==##" (infp## ==## infn##) -- False test "==##" (infn## ==## infp##) -- False test "==##" (infp## ==## nan## ) -- False test "==##" (infn## ==## nan## ) -- False test "==##" (nan## ==## infp##) -- False test "==##" (nan## ==## infn##) -- False putStrLn "=== testing /=## ===" test "/=##" (0.0## /=## 0.0## ) -- False test "/=##" (1.0## /=## 0.0## ) -- True test "/=##" (0.0## /=## 1.0## ) -- True test "/=##" (0.0## /=## nan## ) -- True test "/=##" (nan## /=## 0.0## ) -- True test "/=##" (nan## /=## nan## ) -- True test "/=##" (infp## /=## infp##) -- False test "/=##" (infn## /=## infn##) -- False test "/=##" (infp## /=## infn##) -- True test "/=##" (infn## /=## infp##) -- True test "/=##" (infp## /=## nan## ) -- True test "/=##" (infn## /=## nan## ) -- True test "/=##" (nan## /=## infp##) -- True test "/=##" (nan## /=## infn##) -- True -- PrimOps for comparing Float# putStrLn "=== testing gtFloat# ===" test "gtFloat#" (zeroF# `gtFloat#` zeroF#) -- False test "gtFloat#" (oneF# `gtFloat#` zeroF#) -- True test "gtFloat#" (zeroF# `gtFloat#` oneF# ) -- False test "gtFloat#" (zeroF# `gtFloat#` nanF# ) -- False test "gtFloat#" (nanF# `gtFloat#` zeroF#) -- False test "gtFloat#" (nanF# `gtFloat#` nanF# ) -- False test "gtFloat#" (infpF# `gtFloat#` infpF#) -- False test "gtFloat#" (infnF# `gtFloat#` infnF#) -- False test "gtFloat#" (infpF# `gtFloat#` infnF#) -- True test "gtFloat#" (infnF# `gtFloat#` infpF#) -- False test "gtFloat#" (infpF# `gtFloat#` nanF# ) -- False test "gtFloat#" (infnF# `gtFloat#` nanF# ) -- False test "gtFloat#" (nanF# `gtFloat#` infpF#) -- False test "gtFloat#" (nanF# `gtFloat#` infnF#) -- False putStrLn "=== testing ltFloat# ===" test "ltFloat#" (zeroF# `ltFloat#` zeroF#) -- False test "ltFloat#" (oneF# `ltFloat#` zeroF#) -- False test "ltFloat#" (zeroF# `ltFloat#` oneF# ) -- True test "ltFloat#" (zeroF# `ltFloat#` nanF# ) -- False test "ltFloat#" (nanF# `ltFloat#` zeroF#) -- False test "ltFloat#" (nanF# `ltFloat#` nanF# ) -- False test "ltFloat#" (infpF# `ltFloat#` infpF#) -- False test "ltFloat#" (infnF# `ltFloat#` infnF#) -- False test "ltFloat#" (infpF# `ltFloat#` infnF#) -- False test "ltFloat#" (infnF# `ltFloat#` infpF#) -- True test "ltFloat#" (infpF# `ltFloat#` nanF# ) -- False test "ltFloat#" (infnF# `ltFloat#` nanF# ) -- False test "ltFloat#" (nanF# `ltFloat#` infpF#) -- False test "ltFloat#" (nanF# `ltFloat#` infnF#) -- False putStrLn "=== testing geFloat# ===" test "geFloat#" (zeroF# `geFloat#` zeroF#) -- True test "geFloat#" (oneF# `geFloat#` zeroF#) -- True test "geFloat#" (zeroF# `geFloat#` oneF# ) -- False test "geFloat#" (zeroF# `geFloat#` nanF# ) -- False test "geFloat#" (nanF# `geFloat#` zeroF#) -- False test "geFloat#" (nanF# `geFloat#` nanF# ) -- False test "geFloat#" (infpF# `geFloat#` infpF#) -- True test "geFloat#" (infnF# `geFloat#` infnF#) -- True test "geFloat#" (infpF# `geFloat#` infnF#) -- True test "geFloat#" (infnF# `geFloat#` infpF#) -- False test "geFloat#" (infpF# `geFloat#` nanF# ) -- False test "geFloat#" (infnF# `geFloat#` nanF# ) -- False test "geFloat#" (nanF# `geFloat#` infpF#) -- False test "geFloat#" (nanF# `geFloat#` infnF#) -- False putStrLn "=== testing leFloat# ===" test "leFloat#" (zeroF# `leFloat#` zeroF#) -- True test "leFloat#" (oneF# `leFloat#` zeroF#) -- False test "leFloat#" (zeroF# `leFloat#` oneF# ) -- True test "leFloat#" (zeroF# `leFloat#` nanF# ) -- False test "leFloat#" (nanF# `leFloat#` zeroF#) -- False test "leFloat#" (nanF# `leFloat#` nanF# ) -- False test "leFloat#" (infpF# `leFloat#` infpF#) -- True test "leFloat#" (infnF# `leFloat#` infnF#) -- True test "leFloat#" (infpF# `leFloat#` infnF#) -- False test "leFloat#" (infnF# `leFloat#` infpF#) -- True test "leFloat#" (infpF# `leFloat#` nanF# ) -- False test "leFloat#" (infnF# `leFloat#` nanF# ) -- False test "leFloat#" (nanF# `leFloat#` infpF#) -- False test "leFloat#" (nanF# `leFloat#` infnF#) -- False putStrLn "=== testing eqFloat# ===" test "eqFloat#" (zeroF# `eqFloat#` zeroF#) -- True test "eqFloat#" (oneF# `eqFloat#` zeroF#) -- False test "eqFloat#" (zeroF# `eqFloat#` oneF# ) -- False test "eqFloat#" (zeroF# `eqFloat#` nanF# ) -- False test "eqFloat#" (nanF# `eqFloat#` zeroF#) -- False test "eqFloat#" (nanF# `eqFloat#` nanF# ) -- False test "eqFloat#" (infpF# `eqFloat#` infpF#) -- True test "eqFloat#" (infnF# `eqFloat#` infnF#) -- True test "eqFloat#" (infpF# `eqFloat#` infnF#) -- False test "eqFloat#" (infnF# `eqFloat#` infpF#) -- False test "eqFloat#" (infpF# `eqFloat#` nanF# ) -- False test "eqFloat#" (infnF# `eqFloat#` nanF# ) -- False test "eqFloat#" (nanF# `eqFloat#` infpF#) -- False test "eqFloat#" (nanF# `eqFloat#` infnF#) -- False putStrLn "=== testing neFloat# ===" test "neFloat#" (zeroF# `neFloat#` zeroF#) -- False test "neFloat#" (oneF# `neFloat#` zeroF#) -- True test "neFloat#" (zeroF# `neFloat#` oneF# ) -- True test "neFloat#" (zeroF# `neFloat#` nanF# ) -- True test "neFloat#" (nanF# `neFloat#` zeroF#) -- True test "neFloat#" (nanF# `neFloat#` nanF# ) -- True test "neFloat#" (infpF# `neFloat#` infpF#) -- False test "neFloat#" (infnF# `neFloat#` infnF#) -- False test "neFloat#" (infpF# `neFloat#` infnF#) -- True test "neFloat#" (infnF# `neFloat#` infpF#) -- True test "neFloat#" (infpF# `neFloat#` nanF# ) -- True test "neFloat#" (infnF# `neFloat#` nanF# ) -- True test "neFloat#" (nanF# `neFloat#` infpF#) -- True test "neFloat#" (nanF# `neFloat#` infnF#) -- True where -- every integer is compared to 1 representing True. This -- results in printing "True" when the primop should return True -- and printing "False" when it should return False test :: String -> Int# -> IO () test str x = putStrLn $ str ++ " " ++ (show (I# x == 1)) a = 'a' b = 'b' !(C# a#) = a !(C# b#) = b zeroW = 0 :: Word oneW = 1 :: Word !(W# zeroW#) = zeroW !(W# oneW#) = oneW nan = 0.0 / 0.0 :: Double infp = 1.0 / 0.0 :: Double infn = -1.0 / 0.0 :: Double !(D# nan##) = 0.0 / 0.0 !(D# infp##) = 1.0 / 0.0 !(D# infn##) = -1.0 / 0.0 zeroF = 0.0 :: Float oneF = 1.0 :: Float nanF = 0.0 / 0.0 :: Float infpF = 1.0 / 0.0 :: Float infnF = -1.0 / 0.0 :: Float !(F# zeroF#) = 0.0 !(F# oneF#) = 1.0 !(F# nanF#) = 0.0 / 0.0 !(F# infpF#) = 1.0 / 0.0 !(F# infnF#) = -1.0 / 0.0 minC = minBound :: Char maxC = maxBound :: Char !(C# minC#) = minC !(C# maxC#) = maxC minI = minBound :: Int maxI = maxBound :: Int !(I# minI#) = minI !(I# maxI#) = maxI minW = minBound :: Word maxW = maxBound :: Word !(W# minW#) = minW !(W# maxW#) = maxW
urbanslug/ghc
testsuite/tests/primops/should_run/T6135.hs
bsd-3-clause
21,657
200
11
6,743
6,956
3,741
3,215
399
1
module Main where main :: IO () main = do putStrLn "Hello, World!"
StanislavKhalash/cruel-world-hs
app/Main.hs
mit
68
0
7
14
25
13
12
3
1
{-# LANGUAGE DataKinds #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE UndecidableInstances #-} module Main (main) where import Data.Proxy import Data.Typeable import Data.Monoid import Data.Map.Strict (Map) import qualified Data.Vector as Vector import qualified Data.Vector.Storable as Storable import qualified Data.Vector.Unboxed as Unboxed import Data.Semiring import Data.Semiring.Infinite import Data.Semiring.Numeric import Numeric.Natural import Numeric.Sized.WordOfSize import Test.DocTest import Test.Tasty import qualified Test.Tasty.QuickCheck as QC import qualified Test.Tasty.SmallCheck as SC import Test.Semiring import ApproxLog import Fraction import Func import LimitSize import Orphans () import Vectors import Properties type Tup2 a = (a,a) type Tup3 a = (a,a,a) type Tup4 a = (a,a,a,a) type Tup5 a = (a,a,a,a,a) type Tup6 a = (a,a,a,a,a,a) type Tup7 a = (a,a,a,a,a,a,a) type Tup8 a = (a,a,a,a,a,a,a,a) type Tup9 a = (a,a,a,a,a,a,a,a,a) groupType :: Typeable a => Proxy a -> [Proxy a -> TestTree] -> TestTree groupType p = testGroup (show (typeRep p)) . map ($p) typeclassTests :: TestTree typeclassTests = testGroup "typeclass tests" [ storableQCT (Proxy :: Proxy [ PositiveInfinite Int , NegativeInfinite Int , Infinite Int ]) , liftedQCT (Proxy :: Proxy [ PositiveInfinite , NegativeInfinite , Infinite , Add , Mul , Max , Min , Bottleneck , Division , Łukasiewicz , Viterbi , PosFrac , PosInt ])] semiringLawTests :: TestTree semiringLawTests = testGroup "Semiring/StarSemiring Laws" [ semiringLawsSCT (Proxy :: Proxy [ ApproxLog Double , SApproxLog Double , Integer , PositiveInfinite Natural , Int , WordOfSize 2 , Tup2 (WordOfSize 2) , () , Bool , Any , All , Min (PositiveInfinite Integer) , Max (NegativeInfinite Integer) , Division Integer , Viterbi Fraction , Łukasiewicz Fraction ]) , semiringLawsQCT (Proxy :: Proxy [ Matrix V0 V0 Integer , Matrix V1 V1 Integer , Matrix V2 V2 Integer , Matrix V5 V5 Integer , Func Bool Bool , Tup3 (WordOfSize 2) , Tup4 Int , Tup5 Int , Tup6 Int , Tup7 Int , Tup8 Int , Tup9 Int , [Int] , Vector.Vector Int , Storable.Vector Int , Unboxed.Vector Int ]) , starLawsQCT (Proxy :: Proxy [ Tup4 (PositiveInfinite Int) , Tup5 (PositiveInfinite Int) , Tup6 (PositiveInfinite Int) , Tup7 (PositiveInfinite Int) , Tup8 (PositiveInfinite Int) , Tup9 (PositiveInfinite Int) , LimitSize 100 (PositiveInfinite Integer) ]) , starLawsSCT (Proxy :: Proxy [ Tup2 (PositiveInfinite (WordOfSize 2)) , Tup3 (PositiveInfinite (WordOfSize 2)) , () , Bool , Any , All , Min (Infinite Integer) , Max (Infinite Integer) ]) , ordLawsQCT (Proxy :: Proxy '[]) , ordLawsSCT (Proxy :: Proxy [ Integer , PositiveInfinite Natural , Int , () , Bool , Any , All ]) , zeroLawsQCT (Proxy :: Proxy [ Tup3 (WordOfSize 2) , Tup4 Int , Tup5 Int , Tup6 Int , Tup7 Int , Tup8 Int , Tup9 Int ]) , zeroLawsSCT (Proxy :: Proxy [ Integer , PositiveInfinite Natural , Int , WordOfSize 2 , Tup2 (WordOfSize 2) , () , Bool , Any , All , Min (PositiveInfinite Integer) , Max (NegativeInfinite Integer) , Division Integer , Viterbi Fraction , Łukasiewicz Fraction ]) , refListMulQCT (Proxy :: Proxy [ [Int] , Vector.Vector Int , Unboxed.Vector Int , Storable.Vector Int , Unboxed.Vector (NegativeInfinite Int) , Unboxed.Vector (Infinite Int) ]) , groupType (Proxy :: Proxy (Map String Int)) [localOption (QC.QuickCheckMaxSize 10) . semiringLawsQC] , testGroup "Endo Bool" [ QC.testProperty "plusId" (plusId :: UnaryLaws (EndoFunc (Add Bool))) , QC.testProperty "mulId" (mulId :: UnaryLaws (EndoFunc (Add Bool))) , QC.testProperty "annihilateR" (annihilateR :: UnaryLaws (EndoFunc (Add Bool))) , zeroLawsQC (Proxy :: Proxy (EndoFunc (Add Bool))) , QC.testProperty "plusComm" (plusComm :: BinaryLaws (EndoFunc (Add Bool))) , QC.testProperty "plusAssoc" (plusAssoc :: TernaryLaws (EndoFunc (Add Bool))) , QC.testProperty "mulAssoc" (mulAssoc :: TernaryLaws (EndoFunc (Add Bool))) , QC.testProperty "mulDistribR" (mulDistribR :: TernaryLaws (EndoFunc (Add Bool)))] , testGroup "Negative Infinite Integer" [ SC.testProperty "plusId" (plusId :: UnaryLaws (NegativeInfinite Integer)) , SC.testProperty "mulId" (mulId :: UnaryLaws (NegativeInfinite Integer)) , SC.testProperty "annihilateR" (annihilateR :: UnaryLaws (NegativeInfinite Integer)) , zeroLawsSC (Proxy :: Proxy (NegativeInfinite Integer)) , SC.testProperty "plusComm" (plusComm :: BinaryLaws (NegativeInfinite Integer)) , ordLawsSC (Proxy :: Proxy (NegativeInfinite Integer)) , SC.testProperty "plusAssoc" (plusAssoc :: TernaryLaws (NegativeInfinite Integer)) , SC.testProperty "mulAssoc" (mulAssoc :: TernaryLaws (NegativeInfinite Integer)) , SC.testProperty "mulDistribL" (mulDistribL :: TernaryLaws (NegativeInfinite Integer))] , testGroup "Infinite Integer" [ SC.testProperty "plusId" (plusId :: UnaryLaws (Infinite Integer)) , SC.testProperty "mulId" (mulId :: UnaryLaws (Infinite Integer)) , SC.testProperty "annihilateR" (annihilateR :: UnaryLaws (Infinite Integer)) , SC.testProperty "annihilateL" (annihilateL :: UnaryLaws (Infinite Integer)) , zeroLawsSC (Proxy :: Proxy (Infinite Integer)) , SC.testProperty "plusComm" (plusComm :: BinaryLaws (Infinite Integer)) , ordLawsSC (Proxy :: Proxy (Infinite Integer)) , SC.testProperty "plusAssoc" (plusAssoc :: TernaryLaws (Infinite Integer)) , SC.testProperty "mulAssoc" (mulAssoc :: TernaryLaws (Infinite Integer))] ] main :: IO () main = do doctest ["-isrc", "src/"] defaultMain $ testGroup "Tests" [typeclassTests, semiringLawTests]
oisdk/semiring-num
test/Spec.hs
mit
8,833
0
15
3,973
2,057
1,131
926
238
1
{-# LANGUAGE OverloadedStrings #-} module Main (main) where import Control.Monad (void) import Data.String (fromString) import Data.Text (pack) import Options.Applicative import Bot import Vindinium data Cmd = Training Settings (Maybe Int) (Maybe Board) | Arena Settings cmdSettings :: Cmd -> Settings cmdSettings (Training s _ _) = s cmdSettings (Arena s) = s settings :: Parser Settings settings = Settings <$> (Key <$> argument (str >>= (return . pack)) (metavar "KEY")) <*> (fromString <$> strOption (long "url" <> value "http://vindinium.org")) <*> switch (long "browse" <> short 'b' <> help "Open game page in browser") trainingCmd :: Parser Cmd trainingCmd = Training <$> settings <*> optional (option auto (long "turns")) <*> pure Nothing arenaCmd :: Parser Cmd arenaCmd = Arena <$> settings cmd :: Parser Cmd cmd = subparser ( command "training" (info trainingCmd ( progDesc "Run bot in training mode" )) <> command "arena" (info arenaCmd (progDesc "Run bot in arena mode" )) ) runCmd :: Cmd -> IO () runCmd c = do let browse = settingsBrowse $ cmdSettings c void $ runVindinium (cmdSettings c) $ do case c of (Training _ t b) -> playTraining t b browse bot (Arena _) -> playArena browse bot putStrLn "Game finished." main :: IO () main = execParser opts >>= runCmd where opts = info (cmd <**> helper) idm
osa1/vindinium
src/Main.hs
mit
1,511
0
14
413
502
254
248
41
2
import Control.Applicative import Control.Monad import Data.List import Text.Printf import qualified Data.Set as Set main :: IO () main = do tests <- readLn forM_ [1..tests] $ \caseNum -> do n <- readLn let ans = case n of 0 -> Nothing _ -> Just solve where solve = solve' n $ Set.fromList (show n) solve' a s | Set.size s == 10 = a solve' a s = solve' (a+n) (s `Set.union` Set.fromList (show$a+n)) printf "Case #%d: %s\n" (caseNum::Int) (maybe "INSOMNIA" show ans)
marknsikora/codejam
6254486/A.hs
mit
562
1
26
179
234
116
118
17
3
module Paths_harmlang ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName, getSysconfDir ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) import Prelude catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,0,1], versionTags = []} bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath bindir = "/Users/louisrassaby/Library/Haskell/bin" libdir = "/Users/louisrassaby/Library/Haskell/ghc-7.8.3-x86_64/lib/harmlang-0.1.0.1" datadir = "/Users/louisrassaby/Library/Haskell/share/ghc-7.8.3-x86_64/harmlang-0.1.0.1" libexecdir = "/Users/louisrassaby/Library/Haskell/libexec" sysconfdir = "/Users/louisrassaby/Library/Haskell/etc" getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath getBinDir = catchIO (getEnv "harmlang_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "harmlang_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "harmlang_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "harmlang_libexecdir") (\_ -> return libexecdir) getSysconfDir = catchIO (getEnv "harmlang_sysconfdir") (\_ -> return sysconfdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
lrassaby/harmlang
dist/build/autogen/Paths_harmlang.hs
mit
1,420
0
10
182
371
213
158
28
1
module Types where import Data.Ord (comparing) type Problem = ([Server], [VM]) data Server = Server { serverID :: Int , ramCap :: Int -- RAM capacity , cpuCap :: Int -- CPU capacity } deriving (Eq) instance Show Server where show server = "S" ++ show (serverID server) instance Ord Server where compare = comparing serverID data VM = VM { vmID :: Int , jobID :: Int -- The job to which this VM belongs , vmIndex :: Int -- The index of this VM in its job , ramReq :: Int -- RAM requirement , cpuReq :: Int -- CPU requirement , hasAntiCollocation :: Bool } deriving (Eq) instance Show VM where show vm = "VM" ++ show (vmID vm) instance Ord VM where compare = comparing vmID
rodamber/vmc-hs
lib/Types.hs
mit
776
0
9
234
214
125
89
24
0
{-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE RankNTypes #-} module SFold where import Control.Arrow (second) import Control.Category (Category(..)) import Data.Monoid (Monoid(..), (<>)) import Prelude hiding ((.), id) import Data.Profunctor import qualified Control.Foldl as L import Data.Foldable (fold) {-| SFold stands for Stream Fold and is a representation of a fold of a Stream where: to: (a -> x) translates the incoming stream to the accumulator step: (x -> x -> x) is the accumulator step function This busts the usual step function for folds (x -> a -> x) into two (step x a ~ step x (to a). begin: x is the initial accumulator. release: (x -> (x,[b]) takes the accumulator and computes a new accumulator (a remainder say), and an accumulated result of the fold so far (a release). flush: (x -> x) prepare the accumulator for final release (eg on finalization of the stream) -} data SFold a b = forall x. SFold (a -> x) (x -> x -> x) x (x -> (x, [b])) (x -> x) data Pair a b = Pair !a !b instance Functor (SFold a) where fmap f (SFold to step begin release flush) = SFold to step begin (second (fmap f) . release) flush instance Profunctor SFold where lmap f (SFold to step begin release flush) = SFold (to . f) step begin release flush rmap = fmap instance Category SFold where id = SFold (:[]) (<>) [] (\x -> (x, [])) id (SFold to1 step1 begin1 release1 flush1) . (SFold to0 step0 begin0 release0 flush0) = SFold to step begin release flush where flushr = foldr (step1 . to1) begin1 to = second flushr . release0 . to0 step (x0, x1) (x0', x1') = (step0 x0 x0', step1 x1 x1') begin = (begin0, begin1) release (x0, x1) = let (x0', out) = release0 x0 x1' = step1 x1 (flushr out) (x1'', out') = release1 x1' in ((x0', x1''), out') flush (x0, x1) = let x0' = flush0 x0 (x0'', out) = release0 x0' x1' = step1 x1 (flushr out) x1'' = flush1 x1' in (x0'', x1'') instance Semigroup b => Semigroup (SFold a b) where (<>) (SFold toL stepL beginL releaseL flushL) (SFold toR stepR beginR releaseR flushR) = SFold to step begin release flush where to a = Pair (toL a) (toR a) step (Pair xLL xRL) (Pair xLR xRR) = Pair (stepL xLL xLR) (stepR xRL xRR) begin = Pair beginL beginR release (Pair xL xR) = let (xL', bsL) = releaseL xL (xR', bsR) = releaseR xR in (Pair xL' xR', bsL <> bsR) flush (Pair xL xR) = Pair (flushL xL) (flushR xR) instance Monoid b => Monoid (SFold a b) where mempty = SFold (const ()) (\() _ -> ()) () (\() -> ((), [])) (const ()) mappend (SFold toL stepL beginL releaseL flushL) (SFold toR stepR beginR releaseR flushR) = SFold to step begin release flush where to a = Pair (toL a) (toR a) step (Pair xLL xRL) (Pair xLR xRR) = Pair (stepL xLL xLR) (stepR xRL xRR) begin = Pair beginL beginR release (Pair xL xR) = let (xL', bsL) = releaseL xL (xR', bsR) = releaseR xR in (Pair xL' xR', bsL <> bsR) flush (Pair xL xR) = Pair (flushL xL) (flushR xR) instance Applicative (SFold a) where pure b = SFold (const ()) (\() _ -> ()) () (\() -> ((), [b])) (const ()) (SFold toF stepF beginF releaseF flushF) <*> (SFold toA stepA beginA releaseA flushA) = SFold to step begin release flush where to a = Pair (toF a) (toA a) step (Pair xF xA) (Pair aF aA) = Pair (stepF xF aF)(stepA xA aA) begin = Pair beginF beginA release (Pair xF xA) = let (xA', outA) = releaseA xA (xF', outF) = releaseF xF in (Pair xF' xA', outF <*> outA) flush (Pair xF xA) = Pair (flushF xF) (flushA xA) -- pure id <*> (SFold toA stepA beginA releaseA flushA) -- (SFold (const ()) (\() _ -> ()) () (\() -> ((), [id])) (const ())) <*> (SFold toA stepA beginA releaseA flushA) -- SFold (\x -> Pair () (toA x)) (\(Pair () xA) (Pair () aA) -> Pair () (stepA xA aA)) (Pair () beginA) (\(Pair () xA) -> ((Pair () (fst $ releaseA xA)), [id] <*> (snd $ releaseA xA))) (\(Pair () xA) -> Pair () flushA xA) -- x is isomorphic to (Pair () x) -- SFold (\x -> toA x) (\xA aA -> stepA xA aA) beginA (\xA -> (fst $ releaseA xA, [id] <*> (snd $ releaseA xA))) (\xA -> flushA xA) -- lambda removal -- SFold toA stepA beginA (\xA -> (fst $ releaseA xA, [id] <*> (snd $ releaseA xA))) flushA -- [id] <*> is id -- SFold toA stepA beginA (\xA -> (fst $ releaseA xA, (snd $ releaseA xA))) flushA -- \x -> (fst $ f x, snd $ f x) is f -- SFold toA stepA beginA releaseA flushA -- toFoldl :: SFold a b -> L.Fold a [b] toFoldl (SFold to step begin release flush) = L.Fold step' begin done where step' x a = step x (to a) done = snd . release . flush sfold :: (Foldable f) => SFold a b -> f a -> [b] sfold = L.fold . toFoldl
tonyday567/sfold
sfold/src/SFold.hs
mit
4,941
0
14
1,329
1,671
876
795
82
1
----------------------------------------------------------------------------- -- | -- Module : Data.Generics.K.ToK -- Copyright : (c) David Lazar, 2011 -- License : MIT -- -- Maintainer : [email protected] -- Stability : experimental -- Portability : unknown -- -- Convert 'Data' values to K terms. ----------------------------------------------------------------------------- module Data.Generics.K.ToK where import Data.Char (ord) import Data.Generics import Language.K.Core.Syntax import Language.Haskell.Exts.Syntax -- Issue 198 (see below) toK :: (Data a) => a -> K toK = defaultToK `extQ` stringToK stringToK :: String -> K stringToK s = KApp (KString s) [] defaultToK :: (Data a) => a -> K defaultToK a = KApp (toKLabel a) (gmapQ toK a) toKLabel :: (Data a) => a -> KLabel toKLabel = defaultToKLabel `extQ` KInt -- Integer `extQ` KBool -- Bool `extQ` intToKLabel -- Int `extQ` charToKLabel -- Char `extQ` literalToKLabel -- Issue 198 (see below) `extQ` expToKLabel expToKLabel :: Exp -> KLabel expToKLabel (List es) = KLabel [Syntax "ListExp", Hole] expToKLabel e = defaultToKLabel e -- Workaround for Issue 198 in K. literalToKLabel :: Literal -> KLabel literalToKLabel (Int _) = KLabel [Syntax "IntLit", Hole] literalToKLabel (String _) = KLabel [Syntax "StringLit", Hole] literalToKLabel l = defaultToKLabel l intToKLabel :: Int -> KLabel intToKLabel = KInt . fromIntegral charToKLabel :: Char -> KLabel charToKLabel = KInt . fromIntegral . ord defaultToKLabel :: (Data a) => a -> KLabel defaultToKLabel a = KLabel $ Syntax ctor : replicate (glength a) Hole where ctor = showConstr . toConstr $ a
davidlazar/generic-k
src/Data/Generics/K/ToK.hs
mit
1,688
0
10
315
440
249
191
34
1
{-# language PatternGuards #-} {-# language TypeApplications #-} {-# language OverloadedStrings #-} module Unison.Test.MCode where import EasyTest import Control.Concurrent.STM import qualified Data.Map.Strict as Map import Data.Bits (bit) import Data.Word (Word64) import Unison.Util.EnumContainers as EC import Unison.Term (unannotate) import Unison.Symbol (Symbol) import Unison.Reference (Reference(Builtin)) import Unison.Runtime.Pattern import Unison.Runtime.ANF ( superNormalize , lamLift ) import Unison.Runtime.MCode ( Section(..) , Instr(..) , Args(..) , Comb(..) , Combs , Branch(..) , RefNums(..) , emitComb , emitCombs ) import Unison.Runtime.Builtin import Unison.Runtime.Machine ( CCache(..), eval0, baseCCache ) import Unison.Test.Common (tm) dummyRef :: Reference dummyRef = Builtin "dummy" modifyTVarTest :: TVar a -> (a -> a) -> Test () modifyTVarTest v f = io . atomically $ modifyTVar v f testEval0 :: EnumMap Word64 Combs -> Section -> Test () testEval0 env sect = do cc <- io baseCCache modifyTVarTest (combs cc) (env <>) modifyTVarTest (combRefs cc) ((dummyRef <$ env) <>) io $ eval0 cc sect ok builtins :: Reference -> Word64 builtins r | Builtin "todo" <- r = bit 64 | Just i <- Map.lookup r builtinTermNumbering = i | otherwise = error $ "builtins: " ++ show r cenv :: EnumMap Word64 Combs cenv = fmap (emitComb numbering 0 mempty . (0,)) $ numberedTermLookup @Symbol env :: Combs -> EnumMap Word64 Combs env m = mapInsert (bit 24) m . mapInsert (bit 64) (mapSingleton 0 $ Lam 0 1 2 1 asrt) $ cenv asrt :: Section asrt = Ins (Unpack Nothing 0) $ Match 0 $ Test1 1 (Yield ZArgs) (Die "assertion failed") multRec :: String multRec = "let\n\ \ n = 5\n\ \ f acc i = match i with\n\ \ 0 -> acc\n\ \ _ -> f (##Nat.+ acc n) (##Nat.sub i 1)\n\ \ ##todo (##Nat.== (f 0 1000) 5000)" numbering :: RefNums numbering = RN (builtinTypeNumbering Map.!) builtins testEval :: String -> Test () testEval s = testEval0 (env aux) main where Lam 0 0 _ _ main = aux ! 0 aux = emitCombs numbering (bit 24) . superNormalize . fst . lamLift . splitPatterns builtinDataSpec . unannotate $ tm s nested :: String nested = "let\n\ \ x = match 2 with\n\ \ 0 -> ##Nat.+ 0 1\n\ \ m@n -> n\n\ \ ##todo (##Nat.== x 2)" matching'arguments :: String matching'arguments = "let\n\ \ f x y z = y\n\ \ g x = f x\n\ \ blorf = let\n\ \ a = 0\n\ \ b = 1\n\ \ d = 2\n\ \ h = g a b\n\ \ c = 2\n\ \ h c\n\ \ ##todo (##Nat.== blorf 1)" test :: Test () test = scope "mcode" . tests $ [ scope "2=2" $ testEval "##todo (##Nat.== 2 2)" , scope "2=1+1" $ testEval "##todo (##Nat.== 2 (##Nat.+ 1 1))" , scope "2=3-1" $ testEval "##todo (##Nat.== 2 (##Nat.sub 3 1))" , scope "5*5=25" $ testEval "##todo (##Nat.== (##Nat.* 5 5) 25)" , scope "5*1000=5000" $ testEval "##todo (##Nat.== (##Nat.* 5 1000) 5000)" , scope "5*1000=5000 rec" $ testEval multRec , scope "nested" $ testEval nested , scope "matching arguments" $ testEval matching'arguments ]
unisonweb/platform
parser-typechecker/tests/Unison/Test/MCode.hs
mit
3,217
0
15
804
900
476
424
-1
-1
-- Solves the Reverse Polish Notation problem. -- -- RPN form of the following operation: -- 10 - (4 + 3) * 2 -- is: -- 10 4 3 + 2 * - -- You traverse the list of symbols from left to right, whever you encounter a -- number you push it into a stack, when you encounter an operator, pop two -- numbers from the stack, apply the operator to them, then push the result back -- to the stack. module ReversePolish ( solve ) where solve :: String -> Float solve = head . foldl compute [] . words where compute (x:x':xs) "*" = (x*x'):xs compute (x:x':xs) "+" = (x+x'):xs compute (x:x':xs) "-" = (x'-x):xs compute (x:x':xs) "/" = (x'/x):xs compute (x:x':xs) "^" = (x' ** x):xs compute (x:xs) "ln" = (log x):xs compute xs "sum" = [sum xs] compute xs num = (read num) : xs
topliceanu/learn
haskell/ReversePolish.hs
mit
853
0
10
240
273
149
124
12
8
{-# LANGUAGE ScopedTypeVariables #-} module LLVM.Emitter (emitLLVM) where import Data.Word import LLVM.AbcOps import LLVM.Emitter.Bootstrap import LLVM.Lang import LLVM.Passes.AbcT import LLVM.Passes.Branch import LLVM.Passes.LLVMT import LLVM.Util import qualified Abc.Def as Abc import qualified MonadLib as ML {-scopeStack :: D scopeStack = P $ Struct [scopeStack, P I32]-} {- a stack of registers (?) and the register count to make new RTs pushR/popR CONSIDER var f1:Foo = new Foo; var f2:Foo = new Foo; f2.bar(); f1.bar(); VS var f1:Foo = new Foo; var f2:Foo = new Foo; f1.bar(); f2.bar(); -} --type State = ML.StateT ([R], Int) IO type State = ML.StateT [R] IO data AbcTMethod = AbcTMethod { abctCode :: [(Label, [OpCode])] , abctExceptions :: [Abc.Exception] , abctTraits :: [Abc.TraitsInfo] , abctReturnType :: D , abctParamTypes :: [D] , abctMethodName :: String , abctFlags :: Word8 } abcTypeToLLVMType :: String -> D abcTypeToLLVMType "Boolean" = Bool abcTypeToLLVMType "int" = I32 abcTypeToLLVMType "uint" = U32 abcTypeToLLVMType "String" = P I8 abcTypeToLLVMType "void" = Void toAbcTMethod :: ( (Abc.IntIdx -> Abc.S32) , (Abc.UintIdx -> Abc.U32) , (Abc.DoubleIdx -> Double) , (Abc.StringIdx -> String) , (Abc.MultinameIdx -> Maybe String) ) -> ([Abc.OpCode] -> [(Label, [OpCode])]) -> (Abc.MethodSignature, Abc.MethodBody) -> AbcTMethod toAbcTMethod (i, u, d, s, m) c (sig, body) = AbcTMethod { abctCode = c code , abctExceptions = ex , abctTraits = tr , abctReturnType = maybe (P I8) abcTypeToLLVMType $ m rt , abctParamTypes = map (maybe (P I8) abcTypeToLLVMType . m) pts , abctMethodName = map underscore $ s name , abctFlags = flags } where (Abc.MethodSignature rt pts name flags opt pns) = sig (Abc.MethodBody _ _ _ _ _ code ex tr) = body underscore :: Char -> Char underscore '/' = '_' underscore a = a nextR :: D -> State R nextR d = do rs <- ML.get let next = maxT rs ML.set $ next:rs return next where maxT :: [R] -> R maxT [] = RT d 1 maxT rs = case maximum rs of RN _ i -> RT d (i+1) RAS3 _ i -> RT d (i+1) RT _ i -> RT d (i+1) lastR :: State R lastR = lastRs 1 >>= return . head lastRs :: Int -> State [R] lastRs a = ML.get >>= return . take a functionEmitter :: AbcTMethod -> State FunctionDef functionEmitter (AbcTMethod code _ _ ret params name _) = toBlocks code >>= return . FunctionDef Nothing Nothing Nothing ret name params {- TODO - detect local register types and alloca them - detect types being added to know whether to call a function or just add and possibly insert arbitary new codes to keep transform to LLVMOp simple -} toBlocks :: [(Label, [OpCode])] -> State [Block] --toBlocks = mapM toBlock toBlocks ls = mapM toBlock ls where preAlloca :: [Block] -> [Block] preAlloca all@(Block l entryOps:bs) = Block l (preAllocaOps ++ entryOps):bs where ops :: [LLVMOp] ops = concatMap (\(Block _ ops) -> ops) all preAllocaOps :: [LLVMOp] preAllocaOps = undefined toBlock :: (Label, [OpCode]) -> State Block toBlock (l, ops) = toLLVMOps ops >>= return . Block l returnR :: [OpCode] -> [LLVMOp] -> State [LLVMOp] returnR abc llvm = do rest <- toLLVMOps abc return $ llvm ++ rest -- the current goal is to preserve simple rules at the expense of efficiency -- knowing that many of the inefficiencies will be handled by opt. The -- "Combine redundant instructions" pass, for example, is taking care of -- useless load/store operations for the Push* line of abc ops toLLVMOps :: [OpCode] -> State [LLVMOp] toLLVMOps (SetLocal a:ops) = do lt@(RT d _) <- lastR returnR ops [ Comment $ "SetLocal" ++ show a , StoreR lt (RAS3 (P d) a) ] -- TODO need to know what data type this is toLLVMOps (GetLocal a:ops) = do t <- nextR I32 returnR ops [ Comment $ "GetLocal" ++ show a , Load t (RAS3 (P I32) a) ] toLLVMOps (IfGreaterThan t f:ops) = do (t1:t2:[]) <- lastRs 2 i1 <- nextR Bool returnR ops [ Comment $ "IfGreaterThan " ++ show t ++ " " ++ show f -- TODO sign , Icmp i1 UGT t1 t2 , Br $ Conditional i1 t f ] toLLVMOps (PushInt a:ops) = do t1 <- nextR $ P I32 t2 <- nextR I32 returnR ops [ Comment "PushInt" , Alloca t1 , StoreC I32 (fromIntegral a) t1 , Load t2 t1 -- the next instruction is expecting a value ] toLLVMOps (PushByte a:ops) = do t1 <- nextR $ P I32 t2 <- nextR I32 returnR ops [ Comment "PushByte" , Alloca t1 , StoreC I32 (fromIntegral a) t1 , Load t2 t1 -- the next instruction is expecting a value ] toLLVMOps (Jump l:ops) = do returnR ops [ Comment $ "Jump " ++ show l , Br (UnConditional l) ] toLLVMOps (IncrementInt:ops) = do lt <- lastR t <- nextR I32 returnR ops [ Comment "IncrementInt" , LLVM.Lang.AddC t 1 lt ] toLLVMOps (DecrementInt:ops) = do lt <- lastR t <- nextR I32 returnR ops [ Comment "DecrementInt" , Sub t lt 1 ] toLLVMOps (LLVM.AbcOps.Add:ops) = do (t1:t2:[]) <- lastRs 2 t <- nextR I32 returnR ops [ Comment "Add" , LLVM.Lang.Add t t1 t2 ] toLLVMOps (ReturnValue:ops) = do lt <- lastR returnR ops [ Comment "ReturnValue" , Ret lt ] {-toLLVMOps (NewObject args:ops) = do lt <- lastR t <- nextR I32 returnR ops [ Comment "NewObject" , Sub t lt 1 ]-} toLLVMOps _ = return [] --topStatement :: [(Label, [OpCode])] -> State [TopStmt] --topStatement = undefined --topStatement ((l, ops):ts) = return [Block l [Load (R Bool "A") (R Bool "B")]] emitLLVM :: Abc.Abc -> IO [Module] emitLLVM abc@(Abc.Abc ints uints doubles strings nsInfo nsSet multinames methodSigs metadata instances classes scripts methodBodies) = do (fs :: [(FunctionDef, [R])]) <- mapM (\abctM -> ML.runStateT [RN I32 0] $ functionEmitter abctM) llvms return [Module [] $ map (\(f, _) -> FunctionDef_ f) fs] where rms@(ires, ures, dres, sres, mres) = getResolutionMethods abc (llvms :: [AbcTMethod]) = map (toAbcTMethod rms (abcT rms . insertLabels)) $ zip methodSigs methodBodies
phylake/avm3
llvm/emitter.hs
mit
6,636
0
14
1,941
2,092
1,086
1,006
160
4
{-# LANGUAGE CPP #-} {-# LANGUAGE NamedFieldPuns #-} {-# LANGUAGE OverloadedStrings #-} module Antigen ( antigen , AntigenConfig(..) , defaultConfig , ZshPlugin(..) , RepoStorage(..) , SourcingStrategy , defaultZshPlugin , bundle , local , strictSourcingStrategy , antigenSourcingStrategy , filePathsSourcingStrategy ) where #if __GLASGOW_HASKELL__ < 709 import Control.Applicative #endif import Control.Exception (bracket_) import Control.Monad import Data.List (isSuffixOf) import Data.Maybe (fromMaybe) import Data.Monoid ((<>)) import Data.Text (Text) import System.Directory (createDirectoryIfMissing, doesDirectoryExist, getCurrentDirectory, getDirectoryContents, getHomeDirectory, setCurrentDirectory) import System.Environment (lookupEnv) import System.Exit (exitFailure) import System.FilePath (isRelative, normalise, (</>)) import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified System.Process as Proc -- | Configuration of Antigen. data AntigenConfig = AntigenConfig { plugins :: ![ZshPlugin] -- ^ List of plugins to install. , outputDirectory :: FilePath -- ^ Directory to which all generated files will be written. -- -- This may be overridden with the @ANTIGEN_HS_OUT@ environment variable. } -- | Get a default AntigenConfig. defaultConfig :: AntigenConfig defaultConfig = AntigenConfig { plugins = [] , outputDirectory = ".antigen-hs" } -- | Data type representing a zsh plugin data ZshPlugin = ZshPlugin { storage :: RepoStorage -- ^ Where can this plugin be found? -- -- If this is a git repository, it will automatically be checked out in a -- system-determined location. , sourcingStrategy :: SourcingStrategy -- ^ How to determine which scripts to source and in what order? , sourcingLocations :: [FilePath] -- ^ List of paths relative to the plugin root in which @sourcingStrategy@ -- will be executed. , fpathLocations :: [FilePath] -- ^ Paths relative to plugin root which will be added to @fpath@. } -- | The SourcingStrategy is executed inside the plugin's @sourcingLocations@, -- and the paths returned by it are sourced in-order. type SourcingStrategy = IO [FilePath] -- | A location where the plugin may be found. data RepoStorage = -- | The plugin is available in a GitHub repository. -- -- A local copy will be cloned. GitRepository { url :: !Text -- ^ Example: https://github.com/Tarrasch/zsh-functional } | -- | The plugin is available locally. Local { filePath :: !FilePath -- ^ See 'local' } deriving (Show, Eq) -- | Directory where the repositories will be stored. reposDirectory :: AntigenConfig -> FilePath reposDirectory config = outputDirectory config </> "repos" -- | The final output script. -- -- This is automatically sourced by init.zsh. outputFileToSource :: AntigenConfig -> FilePath outputFileToSource config = outputDirectory config </> "antigen-hs.zsh" -- | A default ZshPlugin -- -- The default plugin uses the 'strictSourcingStrategy' inside the plugin -- root, and adds the plugin root to @fpaths@. defaultZshPlugin :: ZshPlugin defaultZshPlugin = ZshPlugin { storage = error "Please specify a plugin storage." , sourcingStrategy = strictSourcingStrategy , sourcingLocations = ["."] , fpathLocations = [""] } -- | Like @antigen bundle@ from antigen. It assumes you want a GitHub -- repository. bundle :: Text -> ZshPlugin bundle repo = defaultZshPlugin { storage = GitRepository $ "https://github.com/" <> repo } -- | A local repository, useful when testing plugins -- -- > local "/home/arash/repos/zsh-snakebite-completion" local :: FilePath -> ZshPlugin local filePath = defaultZshPlugin { storage = Local filePath } -- TODO should resolve path to absolute -- | Get the folder in which the storage will be stored on disk storagePath :: AntigenConfig -> RepoStorage -> FilePath storagePath config storage = case storage of GitRepository repo -> reposDirectory config </> Text.unpack (santitize repo) Local path -> path where santitize = Text.concatMap aux aux ':' = "-COLON-" aux '/' = "-SLASH-" aux c = Text.singleton c -- | Clone the repository if it already doesn't exist. ensurePlugin :: AntigenConfig -> RepoStorage -> IO () ensurePlugin _ (Local path) = do exists <- doesDirectoryExist path unless exists $ die $ "Local plugin " ++ show path ++ " does not exist. " ++ "Make sure that the path is absolute." ensurePlugin config storage@(GitRepository url) = do exists <- doesDirectoryExist path unless exists $ gitClone url path where path = storagePath config storage -- TODO URL should be ByteString? gitClone :: Text -> FilePath -> IO () gitClone url path = Proc.callProcess "git" ["clone", "--recursive", "--", Text.unpack url, path] -- | Convert a relative path to absolute by prepending the current directory. -- -- This is available in directory >= 1.2.3, but GHC 7.8 uses 1.2.1.0. makeAbsolute :: FilePath -> IO FilePath makeAbsolute = (normalise <$>) . absolutize where absolutize path | isRelative path = (</> path) <$> getCurrentDirectory | otherwise = return path withDirectory :: FilePath -> IO a -> IO a withDirectory p io = do old <- getCurrentDirectory bracket_ (setCurrentDirectory p) (setCurrentDirectory old) io -- | Gather scripts to source for each sourcing location of the plugin. findPluginZshs :: AntigenConfig -> ZshPlugin -> IO [FilePath] findPluginZshs config plugin = withDirectory (storagePath config (storage plugin)) $ fmap concat . forM (sourcingLocations plugin) $ \loc -> withDirectory loc $ sourcingStrategy plugin -- | Get full paths to all files in the given directory. listFiles :: FilePath -> IO [FilePath] listFiles p = map (p </>) . filter (`notElem` [".", ".."]) <$> getDirectoryContents p die :: String -> IO a die msg = putStrLn msg >> exitFailure -- | Match for one single *.plugin.zsh file strictSourcingStrategy :: SourcingStrategy strictSourcingStrategy = do directory <- getCurrentDirectory files <- listFiles directory let matches = filter (".plugin.zsh" `isSuffixOf`) files case matches of [file] -> return [file] [] -> die $ "No *.plugin.zsh file in " ++ directory ++ "! " ++ "See antigenSourcingStrategy example in README " ++ "on how to configure this." _ -> die ("Too many *.plugin.zsh files in " ++ directory ++ "!") -- | Find what to source, using the strategy described here: -- -- https://github.com/zsh-users/antigen#notes-on-writing-plugins antigenSourcingStrategy :: SourcingStrategy antigenSourcingStrategy = do files <- getCurrentDirectory >>= listFiles let candidatePatterns = [".plugin.zsh", "init.zsh", ".zsh", ".sh"] filesMatching pat = filter (pat `isSuffixOf`) files filteredResults = map filesMatching candidatePatterns results = filter (not . null) filteredResults case results of (matchedFiles:_) -> return matchedFiles [] -> die $ "No files to source among " ++ show files -- | Source all files in the given order. Currently does no file existence -- check or anything. filePathsSourcingStrategy :: [FilePath] -> SourcingStrategy filePathsSourcingStrategy paths = do cwd <- getCurrentDirectory return $ map (cwd </>) paths getAbsoluteFpaths :: AntigenConfig -> ZshPlugin -> IO [FilePath] getAbsoluteFpaths config plugin = do let path = storagePath config (storage plugin) mapM (makeAbsolute . (path </>)) (fpathLocations plugin) -- | Get the content that will be put in the file to source. fileToSourceContent :: AntigenConfig -> [FilePath] -- ^ List of all the *.plugin.zsh files -> IO Text -- ^ What the file should contain fileToSourceContent config@AntigenConfig{plugins} pluginZshs = do pluginZshsAbs <- mapM makeAbsolute pluginZshs fpaths <- concat <$> mapM (getAbsoluteFpaths config) plugins return $ Text.unlines $ "# THIS FILE IS GENERATED BY antigen-hs!!!!\n" : map (("source " <>) . Text.pack) pluginZshsAbs ++ map (("fpath+=" <>) . Text.pack) fpaths -- | Do an action inside the home directory inHomeDir :: IO a -> IO a inHomeDir io = do home <- getHomeDirectory withDirectory home io -- | The main function that will clone all the repositories and create the -- file to be sourced by the user antigen :: AntigenConfig -> IO () antigen config'@AntigenConfig{plugins} = inHomeDir $ do hsOut <- lookupEnv "ANTIGEN_HS_OUT" let config = config' { outputDirectory = fromMaybe (outputDirectory config') hsOut } createDirectoryIfMissing True (reposDirectory config) mapM_ (ensurePlugin config . storage) plugins pluginZshs <- concat <$> mapM (findPluginZshs config) plugins contents <- fileToSourceContent config pluginZshs Text.writeFile (outputFileToSource config) contents
Tarrasch/antigen-hs
Antigen.hs
mit
9,342
0
15
2,135
1,826
990
836
177
4
-- Generated by protobuf-simple. DO NOT EDIT! module Types.EnumMsg where import Control.Applicative ((<$>)) import Prelude () import qualified Data.ProtoBufInt as PB import qualified Types.Enum newtype EnumMsg = EnumMsg { value :: Types.Enum.Enum } deriving (PB.Show, PB.Eq, PB.Ord) instance PB.Default EnumMsg where defaultVal = EnumMsg { value = PB.defaultVal } instance PB.Mergeable EnumMsg where merge a b = EnumMsg { value = PB.merge (value a) (value b) } instance PB.Required EnumMsg where reqTags _ = PB.fromList [PB.WireTag 1 PB.VarInt] instance PB.WireMessage EnumMsg where fieldToValue (PB.WireTag 1 PB.VarInt) self = (\v -> self{value = PB.merge (value self) v}) <$> PB.getEnum fieldToValue tag self = PB.getUnknown tag self messageToFields self = do PB.putEnum (PB.WireTag 1 PB.VarInt) (value self)
sru-systems/protobuf-simple
test/Types/EnumMsg.hs
mit
856
0
13
160
303
164
139
21
0
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE OverloadedStrings #-} module Shexkell.Text.JSON.NodeConstraint where import Data.Aeson import Data.Aeson.Types import Data.Foldable (asum) import Control.Applicative import Data.Scientific import Data.String import Data.Maybe (fromMaybe) import Shexkell.Data.ShEx import Shexkell.Data.ShapeExpr import Shexkell.Data.Common import Shexkell.Text.JSON.Control import Shexkell.Text.JSON.Common parseNodeConstraint :: ObjectParser ShapeExpr parseNodeConstraint = do assertType "NodeConstraint" shapeId <- valueOpt "id" nodeKind <- valueOpt "nodeKind" dataType <- valueOpt "dataType" xsFacets <- fromMaybe [] <$> valueOpt "xsFacet" values <- valueOpt "values" return NodeConstraint{..} instance FromJSON NodeKind where parseJSON = withText "Node kind" parseKind where parseKind "iri" = return IRIKind parseKind "bnode" = return BNodeKind parseKind "nonliteral" = return NonLiteralKind parseKind "literal" = return LiteralKind parseKind _ = fail "Expeced iri, bnode, nonliteral, or literal" instance FromJSON XsFacet where parseJSON = withObject "XsFacet" $ parseObject $ asum [ XsStringFacet <$> parseStringFacet , XsNumericFacet <$> parseNumericFacet ] instance FromJSON NumericLiteral where parseJSON = withScientific "Numeric literal" parseNumericLiteral where parseNumericLiteral n | isInteger n = NumericInt <$> parseJSON (Number n) | isFloating n = NumericDouble <$> parseJSON (Number n) | otherwise = NumericDecimal <$> parseJSON (Number n) instance FromJSON ValueSetValue where parseJSON value = ObjectValue <$> (parseJSON value :: Parser ObjectValue) <|> withObject "Stem" (parseObject $ do assertType "Stem" Stem <$> valueOf "stem") value <|> withObject "StemRange" (parseObject $ do assertType "StemRange" stemValue <- valueOf "stem" exclusions <- valueOpt "exclusions" return $ StemRange stemValue exclusions) value instance FromJSON ObjectValue where parseJSON text@(String _) = IRIValue <$> parseJSON text parseJSON _ = fail "Expected text" instance FromJSON StemValue where parseJSON (Object o) | null o = return Wildcard | otherwise = fail "Expected empty object (Wildcard)" parseJSON text@(String _) = IRIStem <$> parseJSON text parseStringFacet :: ObjectParser StringFacet parseStringFacet = parseLitStringFacet <|> parsePatternFacet parseLitStringFacet :: ObjectParser StringFacet parseLitStringFacet = asum [ LitStringFacet "length" <$> valueOf "length" , LitStringFacet "minlength" <$> valueOf "minlength" , LitStringFacet "maxlength" <$> valueOf "maxlength" ] parsePatternFacet :: ObjectParser StringFacet parsePatternFacet = do patt <- valueOf "pattern" flags <- valueOf "flags" return $ PatternStringFacet patt flags parseNumericFacet :: ObjectParser NumericFacet parseNumericFacet = asum [ parseWithKey MaxExclusive "maxexclusive" , parseWithKey MaxInclusive "maxinclusive" , parseWithKey MinExclusive "minexclusive" , parseWithKey MinInclusive "mininclusive" , parseWithKey TotalDigits "totaldigits" , parseWithKey FractionDigits "fractiondigits" ] parseWithKey :: FromJSON a => (String -> a -> b) -> String -> ObjectParser b parseWithKey constr key = constr key <$> valueOf (fromString key)
weso/shexkell
src/Shexkell/Text/JSON/NodeConstraint.hs
mit
3,493
0
14
715
866
420
446
83
1
import Control.Arrow import Control.Applicative import qualified Data.Foldable as F import Data.List import Data.List.Split (|>) :: a -> (a -> b) -> b (|>) x y = y x infixl 0 |> main :: IO () main = do _ <- getLine ((lines >>> map readBinary >>> solve >>> map show >>> intercalate "\n") <$> getContents) >>= putStrLn readInts :: String -> [Int] readInts = splitOn " " >>> map read readBinary :: String -> [Bool] readBinary = map charToBool charToBool :: Char -> Bool charToBool '1' = True charToBool _ = False solve :: [[Bool]] -> [Int] solve byRow = [bestOverlap, bestCount] where pairs = byRow |> comb 2 |> map (F.toList >>> toPair) overlaps = pairs |> map ratePair bestOverlap = maximum overlaps bestCount = overlaps |> filter (==bestOverlap) |> length ratePair :: ([Bool], [Bool]) -> Int ratePair (a, b) = zipWith (||) a b |> filter id |> length toPair :: [a] -> (a, a) toPair [a, b] = (a, b) toPair _ = error "list must have length 2" -- http://rosettacode.org/wiki/Combinations#Haskell comb :: Int -> [a] -> [[a]] comb 0 _ = [[]] comb m l = [x:ys | x:xs <- tails l, ys <- comb (m-1) xs]
Dobiasd/HackerRank-solutions
Algorithms/Warmup/ACM_ICPC_Team/Main.hs
mit
1,158
4
15
266
524
277
247
34
1
module Graphics where import Control.Monad import Control.Monad.State import Control.Monad.Reader import Graphics.UI.SDL as SDL import Graphics.UI.SDL.Image as IMG import Graphics.UI.SDL.Rotozoomer as Roto import Constants import Entities import World data Graphics = Graphics { screen :: Surface , background :: Surface , ship_sprite :: Surface , bullet_sprite :: Surface , asteroid_sprite :: Surface } initGfx :: IO (Graphics) initGfx = do SDL.init [InitEverything] screen <- setVideoMode (fromIntegral window_x) (fromIntegral window_y) 32 [SWSurface] setCaption "Celestial Bodies" [] background <- loadBMP "images/background.bmp" ship_sprite <- loadBMP "images/ship.bmp" bullet_sprite <- loadBMP "images/bullet.bmp" asteroid_sprite <- loadBMP "images/asteroid.bmp" return (Graphics { screen = screen , background = background , ship_sprite = ship_sprite , bullet_sprite = bullet_sprite , asteroid_sprite = asteroid_sprite }) draw :: World -> Time -> Graphics -> IO () draw world elapsed_time graphics = do blitSurface (background graphics) Nothing (screen graphics) Nothing mapM_ (\x -> drawAsteroid x graphics) (asteroids world) drawShip (ship world) graphics mapM_ (\x -> drawBullet x graphics) (bullets world) SDL.flip $ screen graphics putStrLn $ (show world) ++ " " ++ (show elapsed_time) drawShip :: Ship -> Graphics -> IO Bool drawShip ship graphics = do rotated_ship <- rotozoom (ship_sprite graphics) ((orientation ship) * (360 / (2 * pi))) 1 True drawEntity ship rotated_ship (screen graphics) drawBullet :: Bullet -> Graphics -> IO Bool drawBullet bullet graphics = do drawEntity bullet (bullet_sprite graphics) (screen graphics) drawAsteroid :: Asteroid -> Graphics -> IO Bool drawAsteroid asteroid graphics = do drawEntity asteroid (asteroid_sprite graphics) (screen graphics) drawEntity :: Entity a => a -> Surface -> Surface -> IO Bool drawEntity entity sprite screen = do let x_pos = (x . position) entity let y_pos = (y. position) entity let offset = Just Rect { rectX = x_pos - ((surfaceGetWidth sprite) `div` 2) , rectY = y_pos - ((surfaceGetHeight sprite) `div` 2) , rectW = 0 , rectH = 0 } blitSurface sprite Nothing screen offset
rdtaylor/CelestialBodies
Graphics.hs
mit
2,293
0
17
448
761
394
367
61
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} module Hearthstone.Card ( Card(..) , pretty ) where import Data.Text (Text) import qualified Data.Text.Lazy as LT import Control.Lens.TH import Hearthstone.CardType (CardType) import Data.Text.Format (format) import Control.Applicative import Control.Lens data Card = Card { _cardName :: !Text , _cardId :: !Text , _cardSet :: !Int , _cardTypeId :: !Int , _cardType :: Maybe CardType } makeLenses ''Card pretty :: Card -> LT.Text pretty c = format "Card\t{}\t{}\t{}\t{}\t{}" $ ( c^.cardName , c^.cardId , c^.cardSet , c^.cardTypeId , c^?cardType.to show )
jb55/hearthstone-cards
src/Hearthstone/Card.hs
mit
673
0
9
136
196
114
82
-1
-1
module LoanCapitalSplit where -- This module delivers solution of proportional capital split. Ie. when capital is split into limited number of amounts where each of -- amounts is always in the same proportion to the capital. -- Can be used in cases where are financed some number of different goods or services that should be amortized separatelly. type CapSplit = [Int] -- List of amounts that are contained in capital. Meaning of each amount is not important here. -- Returns list of capital split after n-th installment. Returned list is one element longer than xs. 1st element contains main part of capital after n-th installment. -- c - initial capital -- cn - capital after n-th installment -- xs - list of amounts that compose initial capital. Amounts musn't sum up to capital. Main past of capital must be missing capitalSplit :: Int -> [Int] -> Int -> [Int] capitalSplit c [] cn = [cn] capitalSplit 0 xs _ = (map (0*) xs) ++ [0] capitalSplit c xs cn = [foldl (-) cn ol] ++ ol where ol = map round (map (fromIntegral cn / fromIntegral c *) (map fromIntegral xs)) -- This function does the same like previous one, with little difference: it doesn't add 1st element to the output list. -- Output list is same long as input xs one. capitalSplit1 :: Int -> [Int] -> Int -> [Int] capitalSplit1 c [] cn = [] capitalSplit1 0 xs _ = map (0*) xs capitalSplit1 c xs cn = map round (map (fromIntegral cn / fromIntegral c *) (map fromIntegral xs))
bartoszw/elca
LoanCapitalSplit.hs
gpl-2.0
1,505
0
12
323
271
149
122
11
1
module Heap where emptyHeap:: (Ord a) => Heap a heapEmpty:: (Ord a) => Heap a -> Bool findHeap :: (Ord a) => Heap a -> a insHeap :: (Ord a) => a -> Heap a -> Heap a delHeap :: (Ord a) => Heap a -> Heap a -- IMPLEMENTATION with Leftist Heap -- adapted from C. Okasaki Purely Functional Data Structures p 197 data (Ord a) => Heap a = EmptyHP | HP a Int (Heap a) (Heap a) deriving (Eq,Show) emptyHeap = EmptyHP heapEmpty EmptyHP = True heapEmpty _ = False findHeap EmptyHP = error "findHeap:empty heap" findHeap (HP x _ a b) = x insHeap x h = merge (HP x 1 EmptyHP EmptyHP) h delHeap EmptyHP = error "delHeap:empty heap" delHeap (HP x _ a b) = merge a b -- auxiliary functions rank :: (Ord a) => Heap a -> Int rank EmptyHP = 0 rank (HP _ r _ _) = r makeHP :: (Ord a) => a -> Heap a -> Heap a -> Heap a makeHP x a b | rank a >= rank b = HP x (rank b + 1) a b | otherwise = HP x (rank a + 1) b a merge ::(Ord a) => Heap a -> Heap a -> Heap a merge h EmptyHP = h merge EmptyHP h = h merge h1@(HP x _ a1 b1) h2@(HP y _ a2 b2) | x <= y = makeHP x a1 (merge b1 h2) | otherwise = makeHP y a2 (merge h1 b2) -- examples of use of auxiliary functions fig5_5a = insHeap 6 (insHeap 1(insHeap 4 (insHeap 8 emptyHeap))) -- HP 1 2 (HP 4 1 (HP 8 1 EmptyHP EmptyHP) EmptyHP) -- (HP 6 1 EmptyHP EmptyHP) fig5_5b = insHeap 7 (insHeap 5 emptyHeap) -- HP 5 1 (HP 7 1 EmptyHP EmptyHP) EmptyHP {- examples of calls and results Heap> merge fig5_5a fig5_5b HP 1 2 (HP 5 2 (HP 7 1 EmptyHP EmptyHP) (HP 6 1 EmptyHP EmptyHP)) (HP 4 1 (HP 8 1 EmptyHP EmptyHP) EmptyHP) -}
collective/ECSpooler
backends/haskell/haskell_libs/Heap.hs
gpl-2.0
1,763
0
11
568
640
322
318
31
1
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances, CPP, OverloadedStrings, GeneralizedNewtypeDeriving #-} {- Copyright (C) 2009-2014 John MacFarlane <[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 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -} {- | Module : Text.Pandoc.Templates Copyright : Copyright (C) 2009-2014 John MacFarlane License : GNU GPL, version 2 or above Maintainer : John MacFarlane <[email protected]> Stability : alpha Portability : portable A simple templating system with variable substitution and conditionals. The following program illustrates its use: > {-# LANGUAGE OverloadedStrings #-} > import Data.Text > import Data.Aeson > import Text.Pandoc.Templates > > data Employee = Employee { firstName :: String > , lastName :: String > , salary :: Maybe Int } > instance ToJSON Employee where > toJSON e = object [ "name" .= object [ "first" .= firstName e > , "last" .= lastName e ] > , "salary" .= salary e ] > > employees :: [Employee] > employees = [ Employee "John" "Doe" Nothing > , Employee "Omar" "Smith" (Just 30000) > , Employee "Sara" "Chen" (Just 60000) ] > > template :: Template > template = either error id $ compileTemplate > "$for(employee)$Hi, $employee.name.first$. $if(employee.salary)$You make $employee.salary$.$else$No salary data.$endif$$sep$\n$endfor$" > > main = putStrLn $ renderTemplate template $ object ["employee" .= employees ] A slot for an interpolated variable is a variable name surrounded by dollar signs. To include a literal @$@ in your template, use @$$@. Variable names must begin with a letter and can contain letters, numbers, @_@, @-@, and @.@. The values of variables are determined by a JSON object that is passed as a parameter to @renderTemplate@. So, for example, @title@ will return the value of the @title@ field, and @employee.salary@ will return the value of the @salary@ field of the object that is the value of the @employee@ field. The value of a variable will be indented to the same level as the variable. A conditional begins with @$if(variable_name)$@ and ends with @$endif$@. It may optionally contain an @$else$@ section. The if section is used if @variable_name@ has a non-null value, otherwise the else section is used. Conditional keywords should not be indented, or unexpected spacing problems may occur. The @$for$@ keyword can be used to iterate over an array. If the value of the associated variable is not an array, a single iteration will be performed on its value. You may optionally specify separators using @$sep$@, as in the example above. -} module Text.Pandoc.Templates ( renderTemplate , renderTemplate' , TemplateTarget(..) , varListToJSON , compileTemplate , Template , getDefaultTemplate ) where import Data.Char (isAlphaNum) import Control.Monad (guard, when) import Data.Aeson (ToJSON(..), Value(..)) import qualified Text.Parsec as P import Text.Parsec.Text (Parser) import Control.Applicative import qualified Data.Text as T import Data.Text (Text) import Data.Text.Encoding (encodeUtf8) import Text.Pandoc.Compat.Monoid ((<>), Monoid(..)) import Data.List (intersperse) import System.FilePath ((</>), (<.>)) import qualified Data.Map as M import qualified Data.HashMap.Strict as H import Data.Foldable (toList) import qualified Control.Exception.Extensible as E (try, IOException) #if MIN_VERSION_blaze_html(0,5,0) import Text.Blaze.Html (Html) import Text.Blaze.Internal (preEscapedText) #else import Text.Blaze (preEscapedText, Html) #endif import Data.ByteString.Lazy (ByteString, fromChunks) import Text.Pandoc.Shared (readDataFileUTF8, ordNub) import Data.Vector ((!?)) -- | Get default template for the specified writer. getDefaultTemplate :: (Maybe FilePath) -- ^ User data directory to search first -> String -- ^ Name of writer -> IO (Either E.IOException String) getDefaultTemplate user writer = do let format = takeWhile (`notElem` "+-") writer -- strip off extensions case format of "native" -> return $ Right "" "json" -> return $ Right "" "docx" -> return $ Right "" "fb2" -> return $ Right "" "odt" -> getDefaultTemplate user "opendocument" "markdown_strict" -> getDefaultTemplate user "markdown" "multimarkdown" -> getDefaultTemplate user "markdown" "markdown_github" -> getDefaultTemplate user "markdown" "markdown_mmd" -> getDefaultTemplate user "markdown" "markdown_phpextra" -> getDefaultTemplate user "markdown" _ -> let fname = "templates" </> "default" <.> format in E.try $ readDataFileUTF8 user fname newtype Template = Template { unTemplate :: Value -> Text } deriving Monoid type Variable = [Text] class TemplateTarget a where toTarget :: Text -> a instance TemplateTarget Text where toTarget = id instance TemplateTarget String where toTarget = T.unpack instance TemplateTarget ByteString where toTarget = fromChunks . (:[]) . encodeUtf8 instance TemplateTarget Html where toTarget = preEscapedText varListToJSON :: [(String, String)] -> Value varListToJSON assoc = toJSON $ M.fromList assoc' where assoc' = [(T.pack k, toVal [T.pack z | (y,z) <- assoc, not (null z), y == k]) | k <- ordNub $ map fst assoc ] toVal [x] = toJSON x toVal [] = Null toVal xs = toJSON xs renderTemplate :: (ToJSON a, TemplateTarget b) => Template -> a -> b renderTemplate (Template f) context = toTarget $ f $ toJSON context compileTemplate :: Text -> Either String Template compileTemplate template = case P.parse (pTemplate <* P.eof) "template" template of Left e -> Left (show e) Right x -> Right x -- | Like 'renderTemplate', but compiles the template first, -- raising an error if compilation fails. renderTemplate' :: (ToJSON a, TemplateTarget b) => String -> a -> b renderTemplate' template = renderTemplate (either error id $ compileTemplate $ T.pack template) var :: Variable -> Template var = Template . resolveVar resolveVar :: Variable -> Value -> Text resolveVar var' val = case multiLookup var' val of Just (Array vec) -> maybe mempty (resolveVar []) $ vec !? 0 Just (String t) -> T.stripEnd t Just (Number n) -> T.pack $ show n Just (Bool True) -> "true" Just (Object _) -> "true" Just _ -> mempty Nothing -> mempty multiLookup :: [Text] -> Value -> Maybe Value multiLookup [] x = Just x multiLookup (v:vs) (Object o) = H.lookup v o >>= multiLookup vs multiLookup _ _ = Nothing lit :: Text -> Template lit = Template . const cond :: Variable -> Template -> Template -> Template cond var' (Template ifyes) (Template ifno) = Template $ \val -> case resolveVar var' val of "" -> ifno val _ -> ifyes val iter :: Variable -> Template -> Template -> Template iter var' template sep = Template $ \val -> unTemplate (case multiLookup var' val of Just (Array vec) -> mconcat $ intersperse sep $ map (setVar template var') $ toList vec Just x -> cond var' (setVar template var' x) mempty Nothing -> mempty) val setVar :: Template -> Variable -> Value -> Template setVar (Template f) var' val = Template $ f . replaceVar var' val replaceVar :: Variable -> Value -> Value -> Value replaceVar [] new _ = new replaceVar (v:vs) new (Object o) = Object $ H.adjust (\x -> replaceVar vs new x) v o replaceVar _ _ old = old --- parsing pTemplate :: Parser Template pTemplate = do sp <- P.option mempty pInitialSpace rest <- mconcat <$> many (pConditional <|> pFor <|> pNewline <|> pVar <|> pLit <|> pEscapedDollar) return $ sp <> rest takeWhile1 :: (Char -> Bool) -> Parser Text takeWhile1 f = T.pack <$> P.many1 (P.satisfy f) pLit :: Parser Template pLit = lit <$> takeWhile1 (\x -> x /='$' && x /= '\n') pNewline :: Parser Template pNewline = do P.char '\n' sp <- P.option mempty pInitialSpace return $ lit "\n" <> sp pInitialSpace :: Parser Template pInitialSpace = do sps <- takeWhile1 (==' ') let indentVar = if T.null sps then id else indent (T.length sps) v <- P.option mempty $ indentVar <$> pVar return $ lit sps <> v pEscapedDollar :: Parser Template pEscapedDollar = lit "$" <$ P.try (P.string "$$") pVar :: Parser Template pVar = var <$> (P.try $ P.char '$' *> pIdent <* P.char '$') pIdent :: Parser [Text] pIdent = do first <- pIdentPart rest <- many (P.char '.' *> pIdentPart) return (first:rest) pIdentPart :: Parser Text pIdentPart = P.try $ do first <- P.letter rest <- T.pack <$> P.many (P.satisfy (\c -> isAlphaNum c || c == '_' || c == '-')) let id' = T.singleton first <> rest guard $ id' `notElem` reservedWords return id' reservedWords :: [Text] reservedWords = ["else","endif","for","endfor","sep"] skipEndline :: Parser () skipEndline = P.try $ P.skipMany (P.satisfy (`elem` " \t")) >> P.char '\n' >> return () pConditional :: Parser Template pConditional = do P.try $ P.string "$if(" id' <- pIdent P.string ")$" -- if newline after the "if", then a newline after "endif" will be swallowed multiline <- P.option False (True <$ skipEndline) ifContents <- pTemplate elseContents <- P.option mempty $ P.try $ do P.string "$else$" when multiline $ P.option () skipEndline pTemplate P.string "$endif$" when multiline $ P.option () skipEndline return $ cond id' ifContents elseContents pFor :: Parser Template pFor = do P.try $ P.string "$for(" id' <- pIdent P.string ")$" -- if newline after the "for", then a newline after "endfor" will be swallowed multiline <- P.option False $ skipEndline >> return True contents <- pTemplate sep <- P.option mempty $ do P.try $ P.string "$sep$" when multiline $ P.option () skipEndline pTemplate P.string "$endfor$" when multiline $ P.option () skipEndline return $ iter id' contents sep indent :: Int -> Template -> Template indent 0 x = x indent ind (Template f) = Template $ \val -> indent' (f val) where indent' t = T.concat $ intersperse ("\n" <> T.replicate ind " ") $ T.lines t
rgaiacs/pandoc
src/Text/Pandoc/Templates.hs
gpl-2.0
11,583
0
19
3,046
2,677
1,365
1,312
197
11
import Language.Dockerfile main :: IO () main = writeFile "./examples/test-dockerfile.dockerfile" $ toDockerfileStr $ do from (tagged "fpco/stack-build" "lts-6.9") add "." "/app/language-dockerfile" workdir "/app/language-dockerfile" run "stack build --test --only-dependencies" cmd "stack test"
beijaflor-io/haskell-language-dockerfile
examples/test-dockerfile.hs
gpl-3.0
327
1
10
62
75
31
44
8
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.Books.CloudLoading.UpdateBook -- 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) -- -- Updates a user-upload volume. -- -- /See:/ <https://code.google.com/apis/books/docs/v1/getting_started.html Books API Reference> for @books.cloudloading.updateBook@. module Network.Google.Resource.Books.CloudLoading.UpdateBook ( -- * REST Resource CloudLoadingUpdateBookResource -- * Creating a Request , cloudLoadingUpdateBook , CloudLoadingUpdateBook -- * Request Lenses , clubXgafv , clubUploadProtocol , clubAccessToken , clubUploadType , clubPayload , clubCallback ) where import Network.Google.Books.Types import Network.Google.Prelude -- | A resource alias for @books.cloudloading.updateBook@ method which the -- 'CloudLoadingUpdateBook' request conforms to. type CloudLoadingUpdateBookResource = "books" :> "v1" :> "cloudloading" :> "updateBook" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] BooksCloudLoadingResource :> Post '[JSON] BooksCloudLoadingResource -- | Updates a user-upload volume. -- -- /See:/ 'cloudLoadingUpdateBook' smart constructor. data CloudLoadingUpdateBook = CloudLoadingUpdateBook' { _clubXgafv :: !(Maybe Xgafv) , _clubUploadProtocol :: !(Maybe Text) , _clubAccessToken :: !(Maybe Text) , _clubUploadType :: !(Maybe Text) , _clubPayload :: !BooksCloudLoadingResource , _clubCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'CloudLoadingUpdateBook' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'clubXgafv' -- -- * 'clubUploadProtocol' -- -- * 'clubAccessToken' -- -- * 'clubUploadType' -- -- * 'clubPayload' -- -- * 'clubCallback' cloudLoadingUpdateBook :: BooksCloudLoadingResource -- ^ 'clubPayload' -> CloudLoadingUpdateBook cloudLoadingUpdateBook pClubPayload_ = CloudLoadingUpdateBook' { _clubXgafv = Nothing , _clubUploadProtocol = Nothing , _clubAccessToken = Nothing , _clubUploadType = Nothing , _clubPayload = pClubPayload_ , _clubCallback = Nothing } -- | V1 error format. clubXgafv :: Lens' CloudLoadingUpdateBook (Maybe Xgafv) clubXgafv = lens _clubXgafv (\ s a -> s{_clubXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). clubUploadProtocol :: Lens' CloudLoadingUpdateBook (Maybe Text) clubUploadProtocol = lens _clubUploadProtocol (\ s a -> s{_clubUploadProtocol = a}) -- | OAuth access token. clubAccessToken :: Lens' CloudLoadingUpdateBook (Maybe Text) clubAccessToken = lens _clubAccessToken (\ s a -> s{_clubAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). clubUploadType :: Lens' CloudLoadingUpdateBook (Maybe Text) clubUploadType = lens _clubUploadType (\ s a -> s{_clubUploadType = a}) -- | Multipart request metadata. clubPayload :: Lens' CloudLoadingUpdateBook BooksCloudLoadingResource clubPayload = lens _clubPayload (\ s a -> s{_clubPayload = a}) -- | JSONP clubCallback :: Lens' CloudLoadingUpdateBook (Maybe Text) clubCallback = lens _clubCallback (\ s a -> s{_clubCallback = a}) instance GoogleRequest CloudLoadingUpdateBook where type Rs CloudLoadingUpdateBook = BooksCloudLoadingResource type Scopes CloudLoadingUpdateBook = '["https://www.googleapis.com/auth/books"] requestClient CloudLoadingUpdateBook'{..} = go _clubXgafv _clubUploadProtocol _clubAccessToken _clubUploadType _clubCallback (Just AltJSON) _clubPayload booksService where go = buildClient (Proxy :: Proxy CloudLoadingUpdateBookResource) mempty
brendanhay/gogol
gogol-books/gen/Network/Google/Resource/Books/CloudLoading/UpdateBook.hs
mpl-2.0
4,884
0
18
1,135
711
414
297
107
1
-- -*-haskell-*- -- GIMP Toolkit (GTK) Widget Separator -- -- Author : Axel Simon -- -- Created: 23 May 2001 -- -- Copyright (C) 1999-2005 Axel Simon -- -- This library is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser General Public -- License as published by the Free Software Foundation; either -- version 2.1 of the License, or (at your option) any later version. -- -- This library is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- Lesser General Public License for more details. -- -- | -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable (depends on GHC) -- -- Base class for 'Graphics.UI.Gtk.Ornaments.HSeparator' and -- 'Graphics.UI.Gtk.Ornaments.VSeparator'. -- module Graphics.UI.Gtk.Abstract.Separator ( -- * Detail -- -- | The 'Separator' widget is an abstract class, used only for deriving the -- subclasses 'Graphics.UI.Gtk.Ornaments.HSeparator' and -- 'Graphics.UI.Gtk.Ornaments.VSeparator'. -- * Class Hierarchy -- | -- @ -- | 'System.Glib.GObject' -- | +----'Graphics.UI.Gtk.Abstract.Object' -- | +----'Graphics.UI.Gtk.Abstract.Widget' -- | +----Separator -- | +----'Graphics.UI.Gtk.Ornaments.HSeparator' -- | +----'Graphics.UI.Gtk.Ornaments.VSeparator' -- @ -- * Types Separator, SeparatorClass, castToSeparator, toSeparator, ) where import Graphics.UI.Gtk.Types (Separator, SeparatorClass, castToSeparator, toSeparator) -- well this widget is very abstract!
thiagoarrais/gtk2hs
gtk/Graphics/UI/Gtk/Abstract/Separator.hs
lgpl-2.1
1,740
0
5
349
89
75
14
7
0
module Main (main) where import SimpleJSON2 main = print (JObject [("foo", JNumber 1), ("bar", JBool False)])
caiorss/Functional-Programming
haskell/rwh/ch05/Main.hs
unlicense
113
0
10
19
50
29
21
3
1
{- Copyright 2020 The CodeWorld Authors. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -}
google/codeworld
codeworld-compiler/test/testcases/empty/source.hs
apache-2.0
610
0
2
115
3
2
1
1
0
module Main where import Prelude hiding ((.)) import Control.Category import Data.Lens.Common import Data.Ord import Lol.Build import Lol.Champs import Lol.Constraints import Lol.FD import Lol.Items import Lol.Stats import Lol.Stats.Types improvesDPS :: Item -> Bool improvesDPS i = let stats = itemStats i in any (> 0) $ map (^$ stats) [csAttackDamage . iCoreStats ,esBonusAttackSpeed . iExtendedStats ,esCriticalChance . iExtendedStats] buildList :: [[Item]] buildList = runFD $ do build <- defaultBuilds head build `satisfies` isBoots mapM_ (flip satisfies $ not . isBoots) (tail build) mapM_ (flip lacksValue Empty) (tail build) mapM_ (flip satisfies improvesDPS) build orderedEx build labelling build createBestBuild :: Build createBestBuild = let bs = map (makeBuild Tryndamere 18) buildList in maximumBy' (comparing $ dps . getL bChampStats) bs main :: IO () main = do putStrLn "What's up?" putStrLn $ show createBestBuild
MostAwesomeDude/lollerskates
Main.hs
bsd-2-clause
1,049
0
12
251
340
176
164
33
1
import System.Environment (getArgs) import System.Directory (getAppUserDataDirectory, createDirectoryIfMissing) import Control.Applicative ((<$>)) import Data.Maybe (catMaybes) import Data.Char (isSpace) import Data.List (isPrefixOf, foldl', sort) import Data.Ord (comparing) import System.Exit (exitWith, ExitCode (ExitSuccess), exitFailure) import System.Cmd (rawSystem) import Network.HTTP (simpleHTTP, getRequest, getResponseBody) import qualified Data.ByteString.Lazy as L import qualified Codec.Archive.Tar as Tar import Control.Exception (throwIO) import qualified Data.Map as Map import Control.Monad (unless) import Data.Maybe (fromMaybe) import qualified Paths_cabal_nirvana import Data.Version (showVersion, parseVersion) import Text.ParserCombinators.ReadP (readP_to_S) currVersion :: String currVersion = showVersion Paths_cabal_nirvana.version indexFile :: IO FilePath indexFile = do dir <- getAppUserDataDirectory "cabal" return $ dir ++ "/packages/hackage.haskell.org/00-index.tar" nirvanaFile :: IO FilePath nirvanaFile = do dir <- getAppUserDataDirectory "cabal-nirvana" createDirectoryIfMissing True dir return $ dir ++ "/default" data Package = Package { name :: String , version :: String } readPackages :: FilePath -> IO [Package] readPackages fp = readFile fp >>= (catMaybes <$>) . mapM parse . lines where parse s | all isSpace s = return Nothing | "--" `isPrefixOf` s = return Nothing parse s = case words s of [a, b] -> return $ Just $ Package a b _ -> error $ "Invalid nirvana line: " ++ show s main :: IO () main = do args <- getArgs case args of [] -> do ec <- rawSystem "cabal" ["update"] unless (ec == ExitSuccess) $ exitWith ec checkVersion fetch Nothing start Nothing ["fetch"] -> fetch Nothing ["fetch", url] -> fetch $ Just url ["start"] -> start Nothing ["start", nfp] -> start $ Just nfp ["test"] -> test Nothing ["test", fp] -> test $ Just fp _ -> do putStrLn "Available commands:" putStrLn " cabal-nirvana" putStrLn " cabal-nirvana fetch [URL]" putStrLn " cabal-nirvana start [package file]" putStrLn " cabal-nirvana test [package file]" beginLine, endLine :: String beginLine = "-- cabal-nirvana begin" endLine = "-- cabal-nirvana end" removeNirvana :: [String] -> [String] removeNirvana [] = [] removeNirvana (x:xs) | x == beginLine = removeNirvana $ drop 1 $ dropWhile (/= endLine) xs | otherwise = x : removeNirvana xs addNirvana :: [Package] -> [String] -> [String] addNirvana ps = (++ ss) where ss = beginLine : foldr (:) [endLine] (map toS ps) toS (Package n v) = concat [ "constraint: " , n , " == " , v ] fetch :: Maybe String -> IO () fetch murl = do str <- simpleHTTP (getRequest url) >>= getResponseBody nirvanaFile >>= flip writeFile str where url = fromMaybe "http://yesodweb.github.com/nirvana" murl checkVersion :: IO () checkVersion = do ifp <- indexFile entries <- Tar.read <$> L.readFile ifp versions <- go id entries case reverse $ sort versions of [] -> return () v:_ | v == Paths_cabal_nirvana.version -> return () | v < Paths_cabal_nirvana.version -> do putStrLn "You appear to be running an unreleased version." putStrLn "If not, please install the latest version from Hackage:" putStrLn " cabal install cabal-nirvana" | otherwise -> do putStrLn "Your version of cabal-nirvana is out-of-date." putStrLn $ "Your version: " ++ showVersion Paths_cabal_nirvana.version putStrLn $ "Latest version: " ++ showVersion v putStrLn "Please update by running:" putStrLn " cabal install cabal-nirvana" exitFailure where go front Tar.Done = return $ front [] go _ (Tar.Fail e) = throwIO e go front (Tar.Next e es) = go front' es where fp = Tar.entryPath e (p, fp') = break (== '/') fp v = takeWhile (/= '/') $ drop 1 fp' front' | p == "cabal-nirvana" = case filter (null . snd) $ readP_to_S parseVersion v of (v', _):_ -> front . (v':) [] -> front | otherwise = front start :: Maybe String -> IO () start mnfp = do nfp <- maybe nirvanaFile return mnfp packages <- readPackages nfp let packMap = Map.fromList $ map (\(Package n v) -> (n, v)) packages start' packMap where start' packMap = do ifp <- indexFile entries <- Tar.read <$> L.readFile ifp go id entries >>= L.writeFile ifp . Tar.write where go front Tar.Done = return $ front [] go _ (Tar.Fail e) = throwIO e go front (Tar.Next e es) = go front' es where fp = Tar.entryPath e (p, fp') = break (== '/') fp v = takeWhile (/= '/') $ drop 1 fp' front' | toRemove p v = front | otherwise = front . (e:) toRemove _ "" = False toRemove p v = case Map.lookup p packMap of Nothing -> False Just v' -> v /= v' test :: Maybe FilePath -> IO () test mfp = do fp <- maybe nirvanaFile return mfp packages <- readPackages fp let ws = map (\(Package n v) -> concat [n, "-", v]) packages putStrLn $ "cabal-dev install " ++ unwords ws ec <- rawSystem "cabal-dev" $ "install" : ws exitWith ec
snoyberg/cabal-nirvana
cabal-nirvana.hs
bsd-2-clause
5,789
16
16
1,782
1,794
903
891
153
8
module Calculus.All -- ( module Calculus.Dipole24 ( module Calculus.Dipole72 -- , module Calculus.Dipole80 , module Calculus.FlipFlop , module Calculus.Opra , module Calculus.Opra1 , module Calculus.Opra2 , module Calculus.Opra3 , module Calculus.Opra4 , module Calculus.Opra8 , module Calculus.Opra10 , module Calculus.Opra16 ) where --import Calculus.Dipole24 import Calculus.Dipole72 --import Calculus.Dipole80 import Calculus.FlipFlop import Calculus.Opra import Calculus.Opra1 import Calculus.Opra2 import Calculus.Opra3 import Calculus.Opra4 import Calculus.Opra8 import Calculus.Opra10 import Calculus.Opra16
spatial-reasoning/zeno
src/Calculus/All.hs
bsd-2-clause
668
0
5
118
122
79
43
21
0
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Admin.Categories where import Admin.Feedback import Application import Control.Applicative import FormUtil import Snap.Core import Snap.Snaplet import Snap.Snaplet.Heist import qualified Data.Map as M import qualified Data.Text.Encoding as DTE import qualified ShopData.Category as Cat handleNewCategory :: AppHandler () handleNewCategory = do name <- getFormByteString "category-name" "" pcid <- getFormInt "new-category-parent-id" 0 let pcidm = if pcid == 0 then Nothing else Just pcid with db $ Cat.addCategory (DTE.decodeUtf8 name) pcidm infoRedirect "/admin/categories" "New Category Added" handleDelCategory :: AppHandler () handleDelCategory = do cid <- getFormInt "del-category-id" 0 ncid <- getFormInt "del-new-category-id" 0 resp ncid cid where resp ncid cid | ncid == 0 = dangerRedirect "/admin/categories" "Refusing to move products to non-existant category" | ncid == cid = dangerRedirect "/admin/categories" "Refusing to move products to category you are deleting!" | otherwise = do with db $ Cat.delCategory cid ncid infoRedirect "/admin/categories" "Category Deleted" moveCategory :: Bool -> AppHandler () moveCategory down = do let key = if down then "category-move-down" else "category-move-up" cid <- getFormInt key 0 if cid == 0 then dangerRedirect "/admin/categories" "Attempted to move missing category" else do mc <- with db $ Cat.getCategory cid case mc of Nothing -> return () Just c -> with db $ Cat.moveCategory c down infoRedirect "/admin/categories" "Category Moved" handleCategories :: AppHandler () handleCategories = method GET handleCategoriesGet <|> method POST handleCategoriesPost where handleCategoriesGet = cRender "admin/_categories" handler p | "category-move-down" `M.member` p = moveCategory True | "category-move-up" `M.member` p = moveCategory False | "new-category" `M.member` p = handleNewCategory | "del-category-id" `M.member` p = handleDelCategory | otherwise = redirect "/admin/categories" handleCategoriesPost = do p <- getParams handler p
rjohnsondev/haskellshop
src/Admin/Categories.hs
bsd-2-clause
2,531
0
15
747
573
279
294
56
4
{-# LANGUAGE PackageImports #-} import "league-famous" Application (getApplicationDev) import Network.Wai.Handler.Warp (runSettings, defaultSettings, settingsPort) import System.Directory (doesFileExist, removeFile) import System.Exit (exitSuccess) import Control.Concurrent (threadDelay, forkIO) import System.Environment (getArgs) main :: IO () main = do args <- getArgs let confName = case args of [arg] -> arg _ -> "Development" putStrLn "Starting devel application" (port, app) <- getApplicationDev (read confName) forkIO $ runSettings defaultSettings { settingsPort = port } app loop loop :: IO () loop = do threadDelay 100000 e <- doesFileExist "dist/devel-terminate" if e then terminateDevel else loop terminateDevel :: IO () terminateDevel = exitSuccess
JerrySun/league-famous
devel.hs
bsd-2-clause
859
2
13
192
240
124
116
27
2
module Bead.View.RequestParams where import Control.Monad (join) import Data.String (IsString(..)) import Bead.Domain.Entities (Username(..)) import Bead.Domain.Relationships import Bead.View.Dictionary (Language, languageCata) import Bead.View.Fay.HookIds import Bead.View.TemplateAndComponentNames -- Request Parameter Name Constants assignmentKeyParamName :: IsString s => s assignmentKeyParamName = fromString $ fieldName assignmentKeyField assessmentKeyParamName :: IsString s => s assessmentKeyParamName = fromString $ fieldName assessmentKeyField submissionKeyParamName :: IsString s => s submissionKeyParamName = fromString $ fieldName submissionKeyField scoreKeyParamName :: IsString s => s scoreKeyParamName = fromString $ fieldName scoreKeyField evaluationKeyParamName :: IsString s => s evaluationKeyParamName = fromString $ fieldName evaluationKeyField languageParamName :: IsString s => s languageParamName = fromString $ fieldName changeLanguageField courseKeyParamName :: IsString s => s courseKeyParamName = fromString $ fieldName courseKeyField groupKeyParamName :: IsString s => s groupKeyParamName = fromString $ fieldName groupKeyField testScriptKeyParamName :: IsString s => s testScriptKeyParamName = fromString $ fieldName testScriptKeyField -- Request Param is a Pair of Strings, which -- are key and value representing a parameter in -- the GET or POST http request newtype ReqParam = ReqParam (String,String) -- Produces a string representing the key value pair -- E.g: ReqParam ("name", "rika") = "name=rika" queryStringParam :: ReqParam -> String queryStringParam (ReqParam (k,v)) = join [k, "=", v] -- Values that can be converted into a request param, -- only the value of the param is calculated class ReqParamValue p where paramValue :: (IsString s) => p -> s -- Values that can be converted into request param, -- the name and the value is also calculated class (ReqParamValue r) => RequestParam r where requestParam :: r -> ReqParam instance ReqParamValue AssignmentKey where paramValue (AssignmentKey a) = fromString a instance RequestParam AssignmentKey where requestParam a = ReqParam (assignmentKeyParamName, paramValue a) instance ReqParamValue AssessmentKey where paramValue (AssessmentKey a) = fromString a instance RequestParam AssessmentKey where requestParam a = ReqParam (assessmentKeyParamName, paramValue a) instance ReqParamValue SubmissionKey where paramValue (SubmissionKey s) = fromString s instance RequestParam SubmissionKey where requestParam s = ReqParam (submissionKeyParamName, paramValue s) instance ReqParamValue ScoreKey where paramValue (ScoreKey s) = fromString s instance RequestParam ScoreKey where requestParam s = ReqParam (scoreKeyParamName, paramValue s) instance ReqParamValue GroupKey where paramValue (GroupKey g) = fromString g instance RequestParam GroupKey where requestParam g = ReqParam (groupKeyParamName, paramValue g) instance ReqParamValue TestScriptKey where paramValue (TestScriptKey t) = fromString t instance RequestParam TestScriptKey where requestParam t = ReqParam (testScriptKeyParamName, paramValue t) instance ReqParamValue CourseKey where paramValue (CourseKey c) = fromString c instance RequestParam CourseKey where requestParam g = ReqParam (courseKeyParamName, paramValue g) instance ReqParamValue EvaluationKey where paramValue (EvaluationKey e) = fromString e instance RequestParam EvaluationKey where requestParam e = ReqParam (evaluationKeyParamName, paramValue e) instance ReqParamValue Username where paramValue (Username u) = fromString u instance RequestParam Username where requestParam u = ReqParam (fieldName usernameField, paramValue u) instance ReqParamValue Language where paramValue = languageCata fromString instance RequestParam Language where requestParam l = ReqParam (languageParamName, paramValue l)
andorp/bead
src/Bead/View/RequestParams.hs
bsd-3-clause
3,896
0
8
544
938
487
451
73
1
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | This module provides a large suite of utilities that resemble Unix -- utilities. -- -- Many of these commands are just existing Haskell commands renamed to match -- their Unix counterparts: -- -- >>> :set -XOverloadedStrings -- >>> cd "/tmp" -- >>> pwd -- FilePath "/tmp" -- -- Some commands are `Shell`s that emit streams of values. `view` prints all -- values in a `Shell` stream: -- -- >>> view (ls "/usr") -- FilePath "/usr/lib" -- FilePath "/usr/src" -- FilePath "/usr/sbin" -- FilePath "/usr/include" -- FilePath "/usr/share" -- FilePath "/usr/games" -- FilePath "/usr/local" -- FilePath "/usr/bin" -- >>> view (find (suffix "Browser.py") "/usr/lib") -- FilePath "/usr/lib/python3.4/idlelib/ClassBrowser.py" -- FilePath "/usr/lib/python3.4/idlelib/RemoteObjectBrowser.py" -- FilePath "/usr/lib/python3.4/idlelib/PathBrowser.py" -- FilePath "/usr/lib/python3.4/idlelib/ObjectBrowser.py" -- -- Use `fold` to reduce the output of a `Shell` stream: -- -- >>> import qualified Control.Foldl as Fold -- >>> fold (ls "/usr") Fold.length -- 8 -- >>> fold (find (suffix "Browser.py") "/usr/lib") Fold.head -- Just (FilePath "/usr/lib/python3.4/idlelib/ClassBrowser.py") -- -- Create files using `output`: -- -- >>> output "foo.txt" ("123" <|> "456" <|> "ABC") -- >>> realpath "foo.txt" -- FilePath "/tmp/foo.txt" -- -- Read in files using `input`: -- -- >>> stdout (input "foo.txt") -- 123 -- 456 -- ABC -- -- Commands like `grep`, `sed` and `find` accept arbitrary `Pattern`s -- -- >>> stdout (grep ("123" <|> "ABC") (input "foo.txt")) -- 123 -- ABC -- >>> let exclaim = fmap (<> "!") (plus digit) -- >>> stdout (sed exclaim (input "foo.txt")) -- 123! -- 456! -- ABC -- -- Note that `grep` and `find` differ from their Unix counterparts by requiring -- that the `Pattern` matches the entire line or file name by default. However, -- you can optionally match the prefix, suffix, or interior of a line: -- -- >>> stdout (grep (has "2") (input "foo.txt")) -- 123 -- >>> stdout (grep (prefix "1") (input "foo.txt")) -- 123 -- >>> stdout (grep (suffix "3") (input "foo.txt")) -- 123 -- -- You can also build up more sophisticated `Shell` programs using `sh` in -- conjunction with @do@ notation: -- -- >{-# LANGUAGE OverloadedStrings #-} -- > -- >import Turtle -- > -- >main = sh example -- > -- >example = do -- > -- Read in file names from "files1.txt" and "files2.txt" -- > file <- fmap fromText (input "files1.txt" <|> input "files2.txt") -- > -- > -- Stream each file to standard output only if the file exists -- > True <- liftIO (testfile file) -- > line <- input file -- > liftIO (echo line) -- -- See "Turtle.Tutorial" for an extended tutorial explaining how to use this -- library in greater detail. module Turtle.Prelude ( -- * IO proc , shell , procStrict , shellStrict , echo , err , readline , arguments #if MIN_VERSION_base(4,7,0) , export , unset #endif #if MIN_VERSION_base(4,6,0) , need #endif , env , cd , pwd , home , realpath , mv , mkdir , mktree , cp , rm , rmdir , rmtree , testfile , testdir , date , datefile , touch , time , hostname , sleep , exit , die , (.&&.) , (.||.) -- * Managed , readonly , writeonly , appendonly , mktemp , mktempdir , fork , wait -- * Shell , inproc , inshell , stdin , input , inhandle , stdout , output , outhandle , append , stderr , strict , ls , lstree , cat , grep , sed , find , yes , limit , limitWhile , cache -- * Folds , countChars , countWords , countLines -- * Permissions , Permissions , chmod , getmod , setmod , readable, nonreadable , writable, nonwritable , executable, nonexecutable , searchable, nonsearchable , ooo,roo,owo,oox,oos,rwo,rox,ros,owx,rwx,rws -- * File size , du , Size , bytes , kilobytes , megabytes , gigabytes , terabytes , kibibytes , mebibytes , gibibytes , tebibytes ) where import Control.Applicative (Alternative(..), (<*), (*>)) import Control.Concurrent.Async (Async, withAsync, wait, concurrently) import Control.Concurrent.MVar (newMVar, modifyMVar_) import Control.Concurrent (threadDelay) import Control.Exception (bracket, throwIO) import Control.Foldl (Fold, FoldM(..), genericLength, handles, list, premap) import qualified Control.Foldl.Text import Control.Monad (liftM, msum, when, unless) import Control.Monad.IO.Class (MonadIO(..)) import Control.Monad.Managed (Managed, managed) #ifdef mingw32_HOST_OS import Data.Bits ((.&.)) #endif import Data.IORef (newIORef, readIORef, writeIORef) import Data.Text (Text, pack, unpack) import Data.Time (NominalDiffTime, UTCTime, getCurrentTime) import Data.Traversable (traverse) import qualified Data.Text as Text import qualified Data.Text.IO as Text import qualified Filesystem import Filesystem.Path.CurrentOS (FilePath, (</>)) import qualified Filesystem.Path.CurrentOS as Filesystem import Network.HostName (getHostName) import System.Clock (Clock(..), TimeSpec(..), getTime) import System.Environment ( getArgs, #if MIN_VERSION_base(4,7,0) setEnv, unsetEnv, #endif #if MIN_VERSION_base(4,6,0) lookupEnv, #endif getEnvironment ) import System.Directory (Permissions) import qualified System.Directory as Directory import System.Exit (ExitCode(..), exitWith) import System.IO (Handle, hClose) import qualified System.IO as IO import System.IO.Temp (withTempDirectory, withTempFile) import qualified System.Process as Process #ifdef mingw32_HOST_OS import qualified System.Win32 as Win32 #else import System.Posix (openDirStream, readDirStream, closeDirStream, touchFile) #endif import Prelude hiding (FilePath) import Turtle.Pattern (Pattern, anyChar, match) import Turtle.Shell import Turtle.Format (format, w, (%)) {-| Run a command using @execvp@, retrieving the exit code The command inherits @stdout@ and @stderr@ for the current process -} proc :: MonadIO io => Text -- ^ Command -> [Text] -- ^ Arguments -> Shell Text -- ^ Lines of standard input -> io ExitCode -- ^ Exit code proc cmd args = system (Process.proc (unpack cmd) (map unpack args)) {-| Run a command line using the shell, retrieving the exit code This command is more powerful than `proc`, but highly vulnerable to code injection if you template the command line with untrusted input The command inherits @stdout@ and @stderr@ for the current process -} shell :: MonadIO io => Text -- ^ Command line -> Shell Text -- ^ Lines of standard input -> io ExitCode -- ^ Exit code shell cmdLine = system (Process.shell (unpack cmdLine)) {-| Run a command using @execvp@, retrieving the exit code and stdout as a non-lazy blob of Text The command inherits @stderr@ for the current process -} procStrict :: MonadIO io => Text -- ^ Command -> [Text] -- ^ Arguments -> Shell Text -- ^ Lines of standard input -> io (ExitCode, Text) -- ^ Exit code and stdout procStrict cmd args = systemStrict (Process.proc (Text.unpack cmd) (map Text.unpack args)) {-| Run a command line using the shell, retrieving the exit code and stdout as a non-lazy blob of Text This command is more powerful than `proc`, but highly vulnerable to code injection if you template the command line with untrusted input The command inherits @stderr@ for the current process -} shellStrict :: MonadIO io => Text -- ^ Command line -> Shell Text -- ^ Lines of standard input -> io (ExitCode, Text) -- ^ Exit code and stdout shellStrict cmdLine = systemStrict (Process.shell (Text.unpack cmdLine)) system :: MonadIO io => Process.CreateProcess -- ^ Command -> Shell Text -- ^ Lines of standard input -> io ExitCode -- ^ Exit code system p s = liftIO (do let p' = p { Process.std_in = Process.CreatePipe , Process.std_out = Process.Inherit , Process.std_err = Process.Inherit } let open = do (Just hIn, Nothing, Nothing, ph) <- Process.createProcess p' return (hIn, ph) -- Prevent double close mvar <- newMVar False let close handle = do modifyMVar_ mvar (\finalized -> do unless finalized (hClose handle) return True ) bracket open (\(hIn, _) -> close hIn) (\(hIn, ph) -> do let feedIn = do sh (do txt <- s liftIO (Text.hPutStrLn hIn txt) ) close hIn withAsync feedIn (\a -> liftIO (Process.waitForProcess ph) <* wait a) ) ) systemStrict :: MonadIO io => Process.CreateProcess -- ^ Command -> Shell Text -- ^ Lines of standard input -> io (ExitCode, Text) -- ^ Exit code and stdout systemStrict p s = liftIO (do let p' = p { Process.std_in = Process.CreatePipe , Process.std_out = Process.CreatePipe , Process.std_err = Process.Inherit } let open = do (Just hIn, Just hOut, Nothing, ph) <- liftIO (Process.createProcess p') return (hIn, hOut, ph) -- Prevent double close mvar <- newMVar False let close handle = do modifyMVar_ mvar (\finalized -> do unless finalized (hClose handle) return True ) bracket open (\(hIn, _, _) -> close hIn) (\(hIn, hOut, ph) -> do let feedIn = do sh (do txt <- s liftIO (Text.hPutStrLn hIn txt) ) close hIn concurrently (withAsync feedIn (\a -> liftIO (Process.waitForProcess ph) <* wait a)) (Text.hGetContents hOut) ) ) {-| Run a command using @execvp@, streaming @stdout@ as lines of `Text` The command inherits @stderr@ for the current process -} inproc :: Text -- ^ Command -> [Text] -- ^ Arguments -> Shell Text -- ^ Lines of standard input -> Shell Text -- ^ Lines of standard output inproc cmd args = stream (Process.proc (unpack cmd) (map unpack args)) {-| Run a command line using the shell, streaming @stdout@ as lines of `Text` This command is more powerful than `inproc`, but highly vulnerable to code injection if you template the command line with untrusted input The command inherits @stderr@ for the current process -} inshell :: Text -- ^ Command line -> Shell Text -- ^ Lines of standard input -> Shell Text -- ^ Lines of standard output inshell cmd = stream (Process.shell (unpack cmd)) stream :: Process.CreateProcess -- ^ Command -> Shell Text -- ^ Lines of standard input -> Shell Text -- ^ Lines of standard output stream p s = do let p' = p { Process.std_in = Process.CreatePipe , Process.std_out = Process.CreatePipe , Process.std_err = Process.Inherit } let open = do (Just hIn, Just hOut, Nothing, ph) <- liftIO (Process.createProcess p') return (hIn, hOut, ph) -- Prevent double close mvar <- liftIO (newMVar False) let close handle = do modifyMVar_ mvar (\finalized -> do unless finalized (hClose handle) return True ) (hIn, hOut, ph) <- using (managed (bracket open (\(hIn, _, _) -> close hIn))) let feedIn = do sh (do txt <- s liftIO (Text.hPutStrLn hIn txt) ) close hIn a <- using (fork feedIn) inhandle hOut <|> (liftIO (Process.waitForProcess ph *> wait a) *> empty) -- | Print to @stdout@ echo :: MonadIO io => Text -> io () echo txt = liftIO (Text.putStrLn txt) -- | Print to @stderr@ err :: MonadIO io => Text -> io () err txt = liftIO (Text.hPutStrLn IO.stderr txt) {-| Read in a line from @stdin@ Returns `Nothing` if at end of input -} readline :: MonadIO io => io (Maybe Text) readline = liftIO (do eof <- IO.isEOF if eof then return Nothing else fmap (Just . pack) getLine ) -- | Get command line arguments in a list arguments :: MonadIO io => io [Text] arguments = liftIO (fmap (map pack) getArgs) #if MIN_VERSION_base(4,7,0) -- | Set or modify an environment variable export :: MonadIO io => Text -> Text -> io () export key val = liftIO (setEnv (unpack key) (unpack val)) -- | Delete an environment variable unset :: MonadIO io => Text -> io () unset key = liftIO (unsetEnv (unpack key)) #endif #if MIN_VERSION_base(4,6,0) -- | Look up an environment variable need :: MonadIO io => Text -> io (Maybe Text) need key = liftIO (fmap (fmap pack) (lookupEnv (unpack key))) #endif -- | Retrieve all environment variables env :: MonadIO io => io [(Text, Text)] env = liftIO (fmap (fmap toTexts) getEnvironment) where toTexts (key, val) = (pack key, pack val) -- | Change the current directory cd :: MonadIO io => FilePath -> io () cd path = liftIO (Filesystem.setWorkingDirectory path) -- | Get the current directory pwd :: MonadIO io => io FilePath pwd = liftIO Filesystem.getWorkingDirectory -- | Get the home directory home :: MonadIO io => io FilePath home = liftIO Filesystem.getHomeDirectory -- | Canonicalize a path realpath :: MonadIO io => FilePath -> io FilePath realpath path = liftIO (Filesystem.canonicalizePath path) #ifdef mingw32_HOST_OS fILE_ATTRIBUTE_REPARSE_POINT :: Win32.FileAttributeOrFlag fILE_ATTRIBUTE_REPARSE_POINT = 1024 reparsePoint :: Win32.FileAttributeOrFlag -> Bool reparsePoint attr = fILE_ATTRIBUTE_REPARSE_POINT .&. attr /= 0 #endif {-| Stream all immediate children of the given directory, excluding @\".\"@ and @\"..\"@ -} ls :: FilePath -> Shell FilePath ls path = Shell (\(FoldM step begin done) -> do x0 <- begin let path' = Filesystem.encodeString path canRead <- fmap Directory.readable (Directory.getPermissions (deslash path')) #ifdef mingw32_HOST_OS reparse <- fmap reparsePoint (Win32.getFileAttributes path') if (canRead && not reparse) then bracket (Win32.findFirstFile (Filesystem.encodeString (path </> "*"))) (\(h, _) -> Win32.findClose h) (\(h, fdat) -> do let loop x = do file' <- Win32.getFindDataFileName fdat let file = Filesystem.decodeString file' x' <- if (file' /= "." && file' /= "..") then step x (path </> file) else return x more <- Win32.findNextFile h fdat if more then loop $! x' else done x' loop $! x0 ) else done x0 ) #else if canRead then bracket (openDirStream path') closeDirStream (\dirp -> do let loop x = do file' <- readDirStream dirp case file' of "" -> done x _ -> do let file = Filesystem.decodeString file' x' <- if (file' /= "." && file' /= "..") then step x (path </> file) else return x loop $! x' loop $! x0 ) else done x0 ) #endif {-| This is used to remove the trailing slash from a path, because `getPermissions` will fail if a path ends with a trailing slash -} deslash :: String -> String deslash [] = [] deslash (c0:cs0) = c0:go cs0 where go [] = [] go ['\\'] = [] go (c:cs) = c:go cs -- | Stream all recursive descendents of the given directory lstree :: FilePath -> Shell FilePath lstree path = do child <- ls path isDir <- liftIO (testdir child) if isDir then return child <|> lstree child else return child -- | Move a file or directory mv :: MonadIO io => FilePath -> FilePath -> io () mv oldPath newPath = liftIO (Filesystem.rename oldPath newPath) {-| Create a directory Fails if the directory is present -} mkdir :: MonadIO io => FilePath -> io () mkdir path = liftIO (Filesystem.createDirectory False path) {-| Create a directory tree (equivalent to @mkdir -p@) Does not fail if the directory is present -} mktree :: MonadIO io => FilePath -> io () mktree path = liftIO (Filesystem.createTree path) -- | Copy a file cp :: MonadIO io => FilePath -> FilePath -> io () cp oldPath newPath = liftIO (Filesystem.copyFile oldPath newPath) -- | Remove a file rm :: MonadIO io => FilePath -> io () rm path = liftIO (Filesystem.removeFile path) -- | Remove a directory rmdir :: MonadIO io => FilePath -> io () rmdir path = liftIO (Filesystem.removeDirectory path) {-| Remove a directory tree (equivalent to @rm -r@) Use at your own risk -} rmtree :: MonadIO io => FilePath -> io () rmtree path = liftIO (Filesystem.removeTree path) -- | Check if a file exists testfile :: MonadIO io => FilePath -> io Bool testfile path = liftIO (Filesystem.isFile path) -- | Check if a directory exists testdir :: MonadIO io => FilePath -> io Bool testdir path = liftIO (Filesystem.isDirectory path) {-| Touch a file, updating the access and modification times to the current time Creates an empty file if it does not exist -} touch :: MonadIO io => FilePath -> io () touch file = do exists <- testfile file liftIO (if exists #ifdef mingw32_HOST_OS then do handle <- Win32.createFile (Filesystem.encodeString file) Win32.gENERIC_WRITE Win32.fILE_SHARE_NONE Nothing Win32.oPEN_EXISTING Win32.fILE_ATTRIBUTE_NORMAL Nothing (creationTime, _, _) <- Win32.getFileTime handle systemTime <- Win32.getSystemTimeAsFileTime Win32.setFileTime handle creationTime systemTime systemTime #else then touchFile (Filesystem.encodeString file) #endif else output file empty ) {-| Update a file or directory's user permissions > chmod rwo "foo.txt" -- chmod u=rw foo.txt > chmod executable "foo.txt" -- chmod u+x foo.txt > chmod nonwritable "foo.txt" -- chmod u-x foo.txt -} chmod :: MonadIO io => (Permissions -> Permissions) -- ^ Permissions update function -> FilePath -- ^ Path -> io Permissions -- ^ Updated permissions chmod modifyPermissions path = liftIO (do let path' = deslash (Filesystem.encodeString path) permissions <- Directory.getPermissions path' let permissions' = modifyPermissions permissions changed = permissions /= permissions' when changed (Directory.setPermissions path' permissions') return permissions' ) -- | Get a file or directory's user permissions getmod :: MonadIO io => FilePath -> io Permissions getmod path = liftIO (do let path' = deslash (Filesystem.encodeString path) Directory.getPermissions path' ) -- | Set a file or directory's user permissions setmod :: MonadIO io => Permissions -> FilePath -> io () setmod permissions path = liftIO (do let path' = deslash (Filesystem.encodeString path) Directory.setPermissions path' permissions ) -- | @+r@ readable :: Permissions -> Permissions readable = Directory.setOwnerReadable True -- | @-r@ nonreadable :: Permissions -> Permissions nonreadable = Directory.setOwnerReadable False -- | @+w@ writable :: Permissions -> Permissions writable = Directory.setOwnerWritable True -- | @-w@ nonwritable :: Permissions -> Permissions nonwritable = Directory.setOwnerWritable False -- | @+x@ executable :: Permissions -> Permissions executable = Directory.setOwnerExecutable True -- | @-x@ nonexecutable :: Permissions -> Permissions nonexecutable = Directory.setOwnerExecutable False -- | @+s@ searchable :: Permissions -> Permissions searchable = Directory.setOwnerSearchable True -- | @-s@ nonsearchable :: Permissions -> Permissions nonsearchable = Directory.setOwnerSearchable False -- | @-r -w -x@ ooo :: Permissions -> Permissions ooo = const Directory.emptyPermissions -- | @+r -w -x@ roo :: Permissions -> Permissions roo = readable . ooo -- | @-r +w -x@ owo :: Permissions -> Permissions owo = writable . ooo -- | @-r -w +x@ oox :: Permissions -> Permissions oox = executable . ooo -- | @-r -w +s@ oos :: Permissions -> Permissions oos = searchable . ooo -- | @+r +w -x@ rwo :: Permissions -> Permissions rwo = readable . writable . ooo -- | @+r -w +x@ rox :: Permissions -> Permissions rox = readable . executable . ooo -- | @+r -w +s@ ros :: Permissions -> Permissions ros = readable . searchable . ooo -- | @-r +w +x@ owx :: Permissions -> Permissions owx = writable . executable . ooo -- | @+r +w +x@ rwx :: Permissions -> Permissions rwx = readable . writable . executable . ooo rws :: Permissions -> Permissions rws = readable . writable . searchable . ooo {-| Time how long a command takes in monotonic wall clock time Returns the duration alongside the return value -} time :: MonadIO io => io a -> io (a, NominalDiffTime) time io = do TimeSpec seconds1 nanoseconds1 <- liftIO (getTime Monotonic) a <- io TimeSpec seconds2 nanoseconds2 <- liftIO (getTime Monotonic) let t = fromIntegral ( seconds2 - seconds1) + fromIntegral (nanoseconds2 - nanoseconds1) / 10^(9::Int) return (a, fromRational t) -- | Get the system's host name hostname :: MonadIO io => io Text hostname = liftIO (fmap Text.pack getHostName) {-| Sleep for the given duration A numeric literal argument is interpreted as seconds. In other words, @(sleep 2.0)@ will sleep for two seconds. -} sleep :: MonadIO io => NominalDiffTime -> io () sleep n = liftIO (threadDelay (truncate (n * 10^(6::Int)))) {-| Exit with the given exit code An exit code of @0@ indicates success -} exit :: MonadIO io => ExitCode -> io a exit code = liftIO (exitWith code) -- | Throw an exception using the provided `Text` message die :: MonadIO io => Text -> io a die txt = liftIO (throwIO (userError (unpack txt))) infixr 2 .&&., .||. {-| Analogous to `&&` in Bash Runs the second command only if the first one returns `ExitSuccess` -} (.&&.) :: Monad m => m ExitCode -> m ExitCode -> m ExitCode cmd1 .&&. cmd2 = do r <- cmd1 case r of ExitSuccess -> cmd2 _ -> return r {-| Analogous to `||` in Bash Run the second command only if the first one returns `ExitFailure` -} (.||.) :: Monad m => m ExitCode -> m ExitCode -> m ExitCode cmd1 .||. cmd2 = do r <- cmd1 case r of ExitFailure _ -> cmd2 _ -> return r {-| Create a temporary directory underneath the given directory Deletes the temporary directory when done -} mktempdir :: FilePath -- ^ Parent directory -> Text -- ^ Directory name template -> Managed FilePath mktempdir parent prefix = do let parent' = Filesystem.encodeString parent let prefix' = unpack prefix dir' <- managed (withTempDirectory parent' prefix') return (Filesystem.decodeString dir') {-| Create a temporary file underneath the given directory Deletes the temporary file when done -} mktemp :: FilePath -- ^ Parent directory -> Text -- ^ File name template -> Managed (FilePath, Handle) mktemp parent prefix = do let parent' = Filesystem.encodeString parent let prefix' = unpack prefix (file', handle) <- managed (\k -> withTempFile parent' prefix' (\file' handle -> k (file', handle)) ) let file = Filesystem.decodeString file' return (file, handle) -- | Fork a thread, acquiring an `Async` value fork :: IO a -> Managed (Async a) fork io = managed (withAsync io) -- | Read lines of `Text` from standard input stdin :: Shell Text stdin = inhandle IO.stdin -- | Read lines of `Text` from a file input :: FilePath -> Shell Text input file = do handle <- using (readonly file) inhandle handle -- | Read lines of `Text` from a `Handle` inhandle :: Handle -> Shell Text inhandle handle = Shell (\(FoldM step begin done) -> do x0 <- begin let loop x = do eof <- IO.hIsEOF handle if eof then done x else do txt <- Text.hGetLine handle x' <- step x txt loop $! x' loop $! x0 ) -- | Stream lines of `Text` to standard output stdout :: MonadIO io => Shell Text -> io () stdout s = sh (do txt <- s liftIO (echo txt) ) -- | Stream lines of `Text` to a file output :: MonadIO io => FilePath -> Shell Text -> io () output file s = sh (do handle <- using (writeonly file) txt <- s liftIO (Text.hPutStrLn handle txt) ) -- | Stream lines of `Text` to a `Handle` outhandle :: MonadIO io => Handle -> Shell Text -> io () outhandle handle s = sh (do txt <- s liftIO (Text.hPutStrLn handle txt) ) -- | Stream lines of `Text` to append to a file append :: MonadIO io => FilePath -> Shell Text -> io () append file s = sh (do handle <- using (appendonly file) txt <- s liftIO (Text.hPutStrLn handle txt) ) -- | Stream lines of `Text` to standard error stderr :: MonadIO io => Shell Text -> io () stderr s = sh (do txt <- s liftIO (err txt) ) -- | Read in a stream's contents strictly strict :: MonadIO io => Shell Text -> io Text strict s = liftM Text.unlines (fold s list) -- | Acquire a `Managed` read-only `Handle` from a `FilePath` readonly :: FilePath -> Managed Handle readonly file = managed (Filesystem.withTextFile file IO.ReadMode) -- | Acquire a `Managed` write-only `Handle` from a `FilePath` writeonly :: FilePath -> Managed Handle writeonly file = managed (Filesystem.withTextFile file IO.WriteMode) -- | Acquire a `Managed` append-only `Handle` from a `FilePath` appendonly :: FilePath -> Managed Handle appendonly file = managed (Filesystem.withTextFile file IO.AppendMode) -- | Combine the output of multiple `Shell`s, in order cat :: [Shell a] -> Shell a cat = msum -- | Keep all lines that match the given `Pattern` grep :: Pattern a -> Shell Text -> Shell Text grep pattern s = do txt <- s _:_ <- return (match pattern txt) return txt {-| Replace all occurrences of a `Pattern` with its `Text` result Warning: Do not use a `Pattern` that matches the empty string, since it will match an infinite number of times -} sed :: Pattern Text -> Shell Text -> Shell Text sed pattern s = do let pattern' = fmap Text.concat (many (pattern <|> fmap Text.singleton anyChar)) txt <- s txt':_ <- return (match pattern' txt) return txt' -- | Search a directory recursively for all files matching the given `Pattern` find :: Pattern a -> FilePath -> Shell FilePath find pattern dir = do path <- lstree dir Right txt <- return (Filesystem.toText path) _:_ <- return (match pattern txt) return path -- | A Stream of @\"y\"@s yes :: Shell Text yes = Shell (\(FoldM step begin _) -> do x0 <- begin let loop x = do x' <- step x "y" loop $! x' loop $! x0 ) -- | Limit a `Shell` to a fixed number of values limit :: Int -> Shell a -> Shell a limit n s = Shell (\(FoldM step begin done) -> do ref <- newIORef 0 -- I feel so dirty let step' x a = do n' <- readIORef ref writeIORef ref (n' + 1) if n' < n then step x a else return x foldIO s (FoldM step' begin done) ) {-| Limit a `Shell` to values that satisfy the predicate This terminates the stream on the first value that does not satisfy the predicate -} limitWhile :: (a -> Bool) -> Shell a -> Shell a limitWhile predicate s = Shell (\(FoldM step begin done) -> do ref <- newIORef True let step' x a = do b <- readIORef ref let b' = b && predicate a writeIORef ref b' if b' then step x a else return x foldIO s (FoldM step' begin done) ) {-| Cache a `Shell`'s output so that repeated runs of the script will reuse the result of previous runs. You must supply a `FilePath` where the cached result will be stored. The stored result is only reused if the `Shell` successfully ran to completion without any exceptions. Note: on some platforms Ctrl-C will flush standard input and signal end of file before killing the program, which may trick the program into \"successfully\" completing. -} cache :: (Read a, Show a) => FilePath -> Shell a -> Shell a cache file s = do let cached = do txt <- input file case reads (Text.unpack txt) of [(ma, "")] -> return ma _ -> die (format ("cache: Invalid data stored in "%w) file) exists <- testfile file mas <- fold (if exists then cached else empty) list case [ () | Nothing <- mas ] of _:_ -> select [ a | Just a <- mas ] _ -> do handle <- using (writeonly file) let justs = do a <- s liftIO (Text.hPutStrLn handle (Text.pack (show (Just a)))) return a let nothing = do let n = Nothing :: Maybe () liftIO (Text.hPutStrLn handle (Text.pack (show n))) empty justs <|> nothing -- | Get the current time date :: MonadIO io => io UTCTime date = liftIO getCurrentTime -- | Get the time a file was last modified datefile :: MonadIO io => FilePath -> io UTCTime datefile path = liftIO (Filesystem.getModified path) -- | Get the size of a file or a directory du :: MonadIO io => FilePath -> io Size du path = liftIO (fmap Size (Filesystem.getSize path)) {-| An abstract file size Specify the units you want by using an accessor like `kilobytes` The `Num` instance for `Size` interprets numeric literals as bytes -} newtype Size = Size { _bytes :: Integer } deriving (Num) instance Show Size where show = show . _bytes -- | Extract a size in bytes bytes :: Integral n => Size -> n bytes = fromInteger . _bytes -- | @1 kilobyte = 1000 bytes@ kilobytes :: Integral n => Size -> n kilobytes = (`div` 1000) . bytes -- | @1 megabyte = 1000 kilobytes@ megabytes :: Integral n => Size -> n megabytes = (`div` 1000) . kilobytes -- | @1 gigabyte = 1000 megabytes@ gigabytes :: Integral n => Size -> n gigabytes = (`div` 1000) . megabytes -- | @1 terabyte = 1000 gigabytes@ terabytes :: Integral n => Size -> n terabytes = (`div` 1000) . gigabytes -- | @1 kibibyte = 1024 bytes@ kibibytes :: Integral n => Size -> n kibibytes = (`div` 1024) . bytes -- | @1 mebibyte = 1024 kibibytes@ mebibytes :: Integral n => Size -> n mebibytes = (`div` 1024) . kibibytes -- | @1 gibibyte = 1024 mebibytes@ gibibytes :: Integral n => Size -> n gibibytes = (`div` 1024) . mebibytes -- | @1 tebibyte = 1024 gibibytes@ tebibytes :: Integral n => Size -> n tebibytes = (`div` 1024) . gibibytes {-| Count the number of characters in the stream (like @wc -c@) This uses the convention that the elements of the stream are implicitly ended by newlines that are one character wide -} countChars :: Integral n => Fold Text n countChars = Control.Foldl.Text.length + charsPerNewline * countLines charsPerNewline :: Num a => a #ifdef mingw32_HOST_OS charsPerNewline = 2 #else charsPerNewline = 1 #endif -- | Count the number of words in the stream (like @wc -w@) countWords :: Integral n => Fold Text n countWords = premap Text.words (handles traverse genericLength) {-| Count the number of lines in the stream (like @wc -l@) This uses the convention that each element of the stream represents one line -} countLines :: Integral n => Fold Text n countLines = genericLength
bitemyapp/Haskell-Turtle-Library
src/Turtle/Prelude.hs
bsd-3-clause
32,133
0
26
8,415
7,609
3,980
3,629
578
4
{-# LANGUAGE TemplateHaskell, GeneralizedNewtypeDeriving, DeriveDataTypeable, TypeFamilies, MultiParamTypeClasses #-} module Happstack.Auth.Internal.Data.User where import Data.Data import Data.SafeCopy import Data.IxSet import Happstack.Auth.Internal.Data.SaltedHash import Happstack.Auth.Internal.Data.UserId import Happstack.Auth.Internal.Data.Username data User = User { userid :: UserId , username :: Username , userpass :: SaltedHash } deriving (Read,Show,Ord,Eq,Typeable,Data) deriveSafeCopy 1 'base ''User inferIxSet "UserDB" ''User 'noCalcs [''UserId, ''Username]
mcmaniac/happstack-auth
src/Happstack/Auth/Internal/Data/User.hs
bsd-3-clause
641
0
8
120
141
85
56
16
0
-------------------------------------------------------------------------------- -- | -- Module : Graphics.Rendering.OpenGL.Raw.EXT.TextureCompressionRGTC -- Copyright : (c) Sven Panne 2015 -- License : BSD3 -- -- Maintainer : Sven Panne <[email protected]> -- Stability : stable -- Portability : portable -- -- The <https://www.opengl.org/registry/specs/EXT/texture_compression_rgtc.txt EXT_texture_compression_rgtc> extension. -- -------------------------------------------------------------------------------- module Graphics.Rendering.OpenGL.Raw.EXT.TextureCompressionRGTC ( -- * Enums gl_COMPRESSED_RED_GREEN_RGTC2_EXT, gl_COMPRESSED_RED_RGTC1_EXT, gl_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT, gl_COMPRESSED_SIGNED_RED_RGTC1_EXT ) where import Graphics.Rendering.OpenGL.Raw.Tokens
phaazon/OpenGLRaw
src/Graphics/Rendering/OpenGL/Raw/EXT/TextureCompressionRGTC.hs
bsd-3-clause
817
0
4
87
46
37
9
6
0
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE TupleSections #-} module Stack.Setup ( setupEnv , ensureCompiler , SetupOpts (..) , defaultStackSetupYaml ) where import Control.Applicative import Control.Exception.Enclosed (catchIO, tryAny) import Control.Monad (liftM, when, join, void, unless) import Control.Monad.Catch import Control.Monad.IO.Class (MonadIO, liftIO) import Control.Monad.Logger import Control.Monad.Reader (MonadReader, ReaderT (..), asks) import Control.Monad.State (get, put, modify) import Control.Monad.Trans.Control import Crypto.Hash (SHA1(SHA1)) import Data.Aeson.Extended import qualified Data.ByteString as S import qualified Data.ByteString.Char8 as S8 import qualified Data.ByteString.Lazy as LBS import Data.Char (isSpace) import Data.Conduit (Conduit, ($$), (=$), await, yield, awaitForever) import qualified Data.Conduit.Binary as CB import Data.Conduit.Lift (evalStateC) import qualified Data.Conduit.List as CL import Data.Either import Data.Foldable hiding (concatMap, or, maximum) import Data.IORef import Data.IORef.RunOnce (runOnce) import Data.List hiding (concat, elem, maximumBy) import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe import Data.Monoid import Data.Ord (comparing) import Data.Set (Set) import qualified Data.Set as Set import Data.Text (Text) import qualified Data.Text as T import qualified Data.Text.Encoding as T import qualified Data.Text.Encoding.Error as T import Data.Time.Clock (NominalDiffTime, diffUTCTime, getCurrentTime) import Data.Typeable (Typeable) import qualified Data.Yaml as Yaml import Distribution.System (OS, Arch (..), Platform (..)) import qualified Distribution.System as Cabal import Distribution.Text (simpleParse) import Language.Haskell.TH as TH (location) import Network.HTTP.Client.Conduit import Network.HTTP.Download.Verified import Path import Path.IO import Prelude hiding (concat, elem) -- Fix AMP warning import Safe (readMay) import Stack.Config (resolvePackageEntry) import Stack.Constants (distRelativeDir) import Stack.Fetch import Stack.GhcPkg (createDatabase, getCabalPkgVer, getGlobalDB, mkGhcPackagePath) import Stack.Setup.Installed import Stack.Types import Stack.Types.StackT import qualified System.Directory as D import System.Environment (getExecutablePath) import System.Exit (ExitCode (ExitSuccess)) import System.FilePath (searchPathSeparator) import qualified System.FilePath as FP import System.Process (rawSystem) import System.Process.Read import System.Process.Run (runIn) import Text.Printf (printf) -- | Default location of the stack-setup.yaml file defaultStackSetupYaml :: String defaultStackSetupYaml = "https://raw.githubusercontent.com/fpco/stackage-content/master/stack/stack-setup-2.yaml" data SetupOpts = SetupOpts { soptsInstallIfMissing :: !Bool , soptsUseSystem :: !Bool , soptsWantedCompiler :: !CompilerVersion , soptsCompilerCheck :: !VersionCheck , soptsStackYaml :: !(Maybe (Path Abs File)) -- ^ If we got the desired GHC version from that file , soptsForceReinstall :: !Bool , soptsSanityCheck :: !Bool -- ^ Run a sanity check on the selected GHC , soptsSkipGhcCheck :: !Bool -- ^ Don't check for a compatible GHC version/architecture , soptsSkipMsys :: !Bool -- ^ Do not use a custom msys installation on Windows , soptsUpgradeCabal :: !Bool -- ^ Upgrade the global Cabal library in the database to the newest -- version. Only works reliably with a stack-managed installation. , soptsResolveMissingGHC :: !(Maybe Text) -- ^ Message shown to user for how to resolve the missing GHC , soptsStackSetupYaml :: !String -- ^ Location of the main stack-setup.yaml file , soptsGHCBindistURL :: !(Maybe String) -- ^ Alternate GHC binary distribution (requires custom GHCVariant) } deriving Show data SetupException = UnsupportedSetupCombo OS Arch | MissingDependencies [String] | UnknownCompilerVersion Text CompilerVersion [CompilerVersion] | UnknownOSKey Text | GHCSanityCheckCompileFailed ReadProcessException (Path Abs File) | WantedMustBeGHC | RequireCustomGHCVariant | ProblemWhileDecompressing (Path Abs File) | SetupInfoMissingSevenz | GHCJSRequiresStandardVariant | GHCJSNotBooted deriving Typeable instance Exception SetupException instance Show SetupException where show (UnsupportedSetupCombo os arch) = concat [ "I don't know how to install GHC for " , show (os, arch) , ", please install manually" ] show (MissingDependencies tools) = "The following executables are missing and must be installed: " ++ intercalate ", " tools show (UnknownCompilerVersion oskey wanted known) = concat [ "No information found for " , compilerVersionString wanted , ".\nSupported versions for OS key '" ++ T.unpack oskey ++ "': " , intercalate ", " (map show known) ] show (UnknownOSKey oskey) = "Unable to find installation URLs for OS key: " ++ T.unpack oskey show (GHCSanityCheckCompileFailed e ghc) = concat [ "The GHC located at " , toFilePath ghc , " failed to compile a sanity check. Please see:\n\n" , " https://github.com/commercialhaskell/stack/blob/release/doc/install_and_upgrade.md\n\n" , "for more information. Exception was:\n" , show e ] show WantedMustBeGHC = "The wanted compiler must be GHC" show RequireCustomGHCVariant = "A custom --ghc-variant must be specified to use --ghc-bindist" show (ProblemWhileDecompressing archive) = "Problem while decompressing " ++ toFilePath archive show SetupInfoMissingSevenz = "SetupInfo missing Sevenz EXE/DLL" show GHCJSRequiresStandardVariant = "stack does not yet support using --ghc-variant with GHCJS" show GHCJSNotBooted = "GHCJS does not yet have its boot packages installed. Use \"stack setup\" to attempt to run ghcjs-boot." -- | Modify the environment variables (like PATH) appropriately, possibly doing installation too setupEnv :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasBuildConfig env, HasHttpManager env, HasGHCVariant env, MonadBaseControl IO m) => Maybe Text -- ^ Message to give user when necessary GHC is not available -> m EnvConfig setupEnv mResolveMissingGHC = do bconfig <- asks getBuildConfig let platform = getPlatform bconfig wc = whichCompiler (bcWantedCompiler bconfig) sopts = SetupOpts { soptsInstallIfMissing = configInstallGHC $ bcConfig bconfig , soptsUseSystem = configSystemGHC $ bcConfig bconfig , soptsWantedCompiler = bcWantedCompiler bconfig , soptsCompilerCheck = configCompilerCheck $ bcConfig bconfig , soptsStackYaml = Just $ bcStackYaml bconfig , soptsForceReinstall = False , soptsSanityCheck = False , soptsSkipGhcCheck = configSkipGHCCheck $ bcConfig bconfig , soptsSkipMsys = configSkipMsys $ bcConfig bconfig , soptsUpgradeCabal = False , soptsResolveMissingGHC = mResolveMissingGHC , soptsStackSetupYaml = defaultStackSetupYaml , soptsGHCBindistURL = Nothing } mghcBin <- ensureCompiler sopts -- Modify the initial environment to include the GHC path, if a local GHC -- is being used menv0 <- getMinimalEnvOverride let env = removeHaskellEnvVars $ augmentPathMap (maybe [] edBins mghcBin) $ unEnvOverride menv0 menv <- mkEnvOverride platform env compilerVer <- getCompilerVersion menv wc cabalVer <- getCabalPkgVer menv wc packages <- mapM (resolvePackageEntry menv (bcRoot bconfig)) (bcPackageEntries bconfig) let envConfig0 = EnvConfig { envConfigBuildConfig = bconfig , envConfigCabalVersion = cabalVer , envConfigCompilerVersion = compilerVer , envConfigPackages = Map.fromList $ concat packages } -- extra installation bin directories mkDirs <- runReaderT extraBinDirs envConfig0 let mpath = Map.lookup "PATH" env mkDirs' = map toFilePath . mkDirs depsPath = augmentPath (mkDirs' False) mpath localsPath = augmentPath (mkDirs' True) mpath deps <- runReaderT packageDatabaseDeps envConfig0 createDatabase menv wc deps localdb <- runReaderT packageDatabaseLocal envConfig0 createDatabase menv wc localdb globaldb <- getGlobalDB menv wc let mkGPP locals = mkGhcPackagePath locals localdb deps globaldb distDir <- runReaderT distRelativeDir envConfig0 executablePath <- liftIO getExecutablePath utf8EnvVars <- getUtf8LocaleVars menv envRef <- liftIO $ newIORef Map.empty let getEnvOverride' es = do m <- readIORef envRef case Map.lookup es m of Just eo -> return eo Nothing -> do eo <- mkEnvOverride platform $ Map.insert "PATH" (if esIncludeLocals es then localsPath else depsPath) $ (if esIncludeGhcPackagePath es then Map.insert (case wc of { Ghc -> "GHC_PACKAGE_PATH"; Ghcjs -> "GHCJS_PACKAGE_PATH" }) (mkGPP (esIncludeLocals es)) else id) $ (if esStackExe es then Map.insert "STACK_EXE" (T.pack executablePath) else id) $ (if esLocaleUtf8 es then Map.union utf8EnvVars else id) -- For reasoning and duplication, see: https://github.com/fpco/stack/issues/70 $ Map.insert "HASKELL_PACKAGE_SANDBOX" (T.pack $ toFilePathNoTrailingSlash deps) $ Map.insert "HASKELL_PACKAGE_SANDBOXES" (T.pack $ if esIncludeLocals es then intercalate [searchPathSeparator] [ toFilePathNoTrailingSlash localdb , toFilePathNoTrailingSlash deps , "" ] else intercalate [searchPathSeparator] [ toFilePathNoTrailingSlash deps , "" ]) $ Map.insert "HASKELL_DIST_DIR" (T.pack $ toFilePathNoTrailingSlash distDir) $ env !() <- atomicModifyIORef envRef $ \m' -> (Map.insert es eo m', ()) return eo return EnvConfig { envConfigBuildConfig = bconfig { bcConfig = maybe id addIncludeLib mghcBin (bcConfig bconfig) { configEnvOverride = getEnvOverride' } } , envConfigCabalVersion = cabalVer , envConfigCompilerVersion = compilerVer , envConfigPackages = envConfigPackages envConfig0 } -- | Add the include and lib paths to the given Config addIncludeLib :: ExtraDirs -> Config -> Config addIncludeLib (ExtraDirs _bins includes libs) config = config { configExtraIncludeDirs = Set.union (configExtraIncludeDirs config) (Set.fromList $ map T.pack includes) , configExtraLibDirs = Set.union (configExtraLibDirs config) (Set.fromList $ map T.pack libs) } -- | Ensure compiler (ghc or ghcjs) is installed and provide the PATHs to add if necessary ensureCompiler :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, HasGHCVariant env, MonadBaseControl IO m) => SetupOpts -> m (Maybe ExtraDirs) ensureCompiler sopts = do let wc = whichCompiler (soptsWantedCompiler sopts) when (getGhcVersion (soptsWantedCompiler sopts) < $(mkVersion "7.8")) $ do $logWarn "stack will almost certainly fail with GHC below version 7.8" $logWarn "Valiantly attempting to run anyway, but I know this is doomed" $logWarn "For more information, see: https://github.com/commercialhaskell/stack/issues/648" $logWarn "" -- Check the available GHCs menv0 <- getMinimalEnvOverride msystem <- if soptsUseSystem sopts then getSystemCompiler menv0 wc else return Nothing Platform expectedArch _ <- asks getPlatform let needLocal = case msystem of Nothing -> True Just _ | soptsSkipGhcCheck sopts -> False Just (system, arch) -> not (isWanted system) || arch /= expectedArch isWanted = isWantedCompiler (soptsCompilerCheck sopts) (soptsWantedCompiler sopts) -- If we need to install a GHC, try to do so mtools <- if needLocal then do getSetupInfo' <- runOnce (getSetupInfo sopts =<< asks getHttpManager) installed <- listInstalled -- Install GHC ghcVariant <- asks getGHCVariant config <- asks getConfig ghcPkgName <- parsePackageNameFromString ("ghc" ++ ghcVariantSuffix ghcVariant) let installedCompiler = case wc of Ghc -> getInstalledTool installed ghcPkgName (isWanted . GhcVersion) Ghcjs -> getInstalledGhcjs installed isWanted compilerTool <- case installedCompiler of Just tool -> return tool Nothing | soptsInstallIfMissing sopts -> do si <- getSetupInfo' downloadAndInstallCompiler si (soptsWantedCompiler sopts) (soptsCompilerCheck sopts) (soptsGHCBindistURL sopts) | otherwise -> do throwM $ CompilerVersionMismatch msystem (soptsWantedCompiler sopts, expectedArch) ghcVariant (soptsCompilerCheck sopts) (soptsStackYaml sopts) (fromMaybe ("Try running \"stack setup\" to install the correct GHC into " <> T.pack (toFilePath (configLocalPrograms config))) $ soptsResolveMissingGHC sopts) -- Install msys2 on windows, if necessary platform <- asks getPlatform mmsys2Tool <- case platform of Platform _ Cabal.Windows | not (soptsSkipMsys sopts) -> case getInstalledTool installed $(mkPackageName "msys2") (const True) of Just tool -> return (Just tool) Nothing | soptsInstallIfMissing sopts -> do si <- getSetupInfo' osKey <- getOSKey VersionedDownloadInfo version info <- case Map.lookup osKey $ siMsys2 si of Just x -> return x Nothing -> error $ "MSYS2 not found for " ++ T.unpack osKey let tool = Tool (PackageIdentifier $(mkPackageName "msys2") version) Just <$> downloadAndInstallTool si info tool (installMsys2Windows osKey) | otherwise -> do $logWarn "Continuing despite missing tool: msys2" return Nothing _ -> return Nothing return $ Just (compilerTool, mmsys2Tool) else return Nothing mpaths <- case mtools of Nothing -> return Nothing Just (compilerTool, mmsys2Tool) -> do let idents = catMaybes [Just compilerTool, mmsys2Tool] paths <- mapM extraDirs idents return $ Just $ mconcat paths menv <- case mpaths of Nothing -> return menv0 Just ed -> do config <- asks getConfig let m = augmentPathMap (edBins ed) (unEnvOverride menv0) mkEnvOverride (configPlatform config) (removeHaskellEnvVars m) when (soptsUpgradeCabal sopts) $ do unless needLocal $ do $logWarn "Trying to upgrade Cabal library on a GHC not installed by stack." $logWarn "This may fail, caveat emptor!" upgradeCabal menv wc case mtools of Just (ToolGhcjs cv, _) -> ensureGhcjsBooted menv cv (soptsInstallIfMissing sopts) _ -> return () when (soptsSanityCheck sopts) $ sanityCheck menv wc return mpaths -- | Install the newest version of Cabal globally upgradeCabal :: (MonadIO m, MonadLogger m, MonadReader env m, HasHttpManager env, HasConfig env, MonadBaseControl IO m, MonadMask m) => EnvOverride -> WhichCompiler -> m () upgradeCabal menv wc = do let name = $(mkPackageName "Cabal") rmap <- resolvePackages menv Set.empty (Set.singleton name) newest <- case Map.keys rmap of [] -> error "No Cabal library found in index, cannot upgrade" [PackageIdentifier name' version] | name == name' -> return version x -> error $ "Unexpected results for resolvePackages: " ++ show x installed <- getCabalPkgVer menv wc if installed >= newest then $logInfo $ T.concat [ "Currently installed Cabal is " , T.pack $ versionString installed , ", newest is " , T.pack $ versionString newest , ". I'm not upgrading Cabal." ] else withCanonicalizedSystemTempDirectory "stack-cabal-upgrade" $ \tmpdir -> do $logInfo $ T.concat [ "Installing Cabal-" , T.pack $ versionString newest , " to replace " , T.pack $ versionString installed ] let ident = PackageIdentifier name newest m <- unpackPackageIdents menv tmpdir Nothing (Set.singleton ident) compilerPath <- join $ findExecutable menv (compilerExeName wc) newestDir <- parseRelDir $ versionString newest let installRoot = toFilePath $ parent (parent compilerPath) </> $(mkRelDir "new-cabal") </> newestDir dir <- case Map.lookup ident m of Nothing -> error $ "upgradeCabal: Invariant violated, dir missing" Just dir -> return dir runIn dir (compilerExeName wc) menv ["Setup.hs"] Nothing platform <- asks getPlatform let setupExe = toFilePath $ dir </> (case platform of Platform _ Cabal.Windows -> $(mkRelFile "Setup.exe") _ -> $(mkRelFile "Setup")) dirArgument name' = concat [ "--" , name' , "dir=" , installRoot FP.</> name' ] runIn dir setupExe menv ( "configure" : map dirArgument (words "lib bin data doc") ) Nothing runIn dir setupExe menv ["build"] Nothing runIn dir setupExe menv ["install"] Nothing $logInfo "New Cabal library installed" -- | Get the version of the system compiler, if available getSystemCompiler :: (MonadIO m, MonadLogger m, MonadBaseControl IO m, MonadCatch m) => EnvOverride -> WhichCompiler -> m (Maybe (CompilerVersion, Arch)) getSystemCompiler menv wc = do let exeName = case wc of Ghc -> "ghc" Ghcjs -> "ghcjs" exists <- doesExecutableExist menv exeName if exists then do eres <- tryProcessStdout Nothing menv exeName ["--info"] let minfo = do Right bs <- Just eres pairs <- readMay $ S8.unpack bs :: Maybe [(String, String)] version <- lookup "Project version" pairs >>= parseVersionFromString arch <- lookup "Target platform" pairs >>= simpleParse . takeWhile (/= '-') return (version, arch) case (wc, minfo) of (Ghc, Just (version, arch)) -> return (Just (GhcVersion version, arch)) (Ghcjs, Just (_, arch)) -> do eversion <- tryAny $ getCompilerVersion menv Ghcjs case eversion of Left _ -> return Nothing Right version -> return (Just (version, arch)) (_, Nothing) -> return Nothing else return Nothing -- | Download the most recent SetupInfo getSetupInfo :: (MonadIO m, MonadThrow m, MonadLogger m, MonadReader env m, HasConfig env) => SetupOpts -> Manager -> m SetupInfo getSetupInfo sopts manager = do config <- asks getConfig setupInfos <- mapM loadSetupInfo (SetupInfoFileOrURL (soptsStackSetupYaml sopts) : configSetupInfoLocations config) return (mconcat setupInfos) where loadSetupInfo (SetupInfoInline si) = return si loadSetupInfo (SetupInfoFileOrURL urlOrFile) = do bs <- case parseUrl urlOrFile of Just req -> do bss <- liftIO $ flip runReaderT manager $ withResponse req $ \res -> responseBody res $$ CL.consume return $ S8.concat bss Nothing -> liftIO $ S.readFile urlOrFile (si,warnings) <- either throwM return (Yaml.decodeEither' bs) when (urlOrFile /= defaultStackSetupYaml) $ logJSONWarnings urlOrFile warnings return si getInstalledTool :: [Tool] -- ^ already installed -> PackageName -- ^ package to find -> (Version -> Bool) -- ^ which versions are acceptable -> Maybe Tool getInstalledTool installed name goodVersion = if null available then Nothing else Just $ Tool $ maximumBy (comparing packageIdentifierVersion) available where available = mapMaybe goodPackage installed goodPackage (Tool pi') = if packageIdentifierName pi' == name && goodVersion (packageIdentifierVersion pi') then Just pi' else Nothing goodPackage _ = Nothing getInstalledGhcjs :: [Tool] -> (CompilerVersion -> Bool) -> Maybe Tool getInstalledGhcjs installed goodVersion = if null available then Nothing else Just $ ToolGhcjs $ maximum available where available = mapMaybe goodPackage installed goodPackage (ToolGhcjs cv) = if goodVersion cv then Just cv else Nothing goodPackage _ = Nothing downloadAndInstallTool :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> DownloadInfo -> Tool -> (SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> m ()) -> m Tool downloadAndInstallTool si downloadInfo tool installer = do (file, at) <- downloadFromInfo downloadInfo tool dir <- installDir tool unmarkInstalled tool installer si file at dir markInstalled tool return tool downloadAndInstallCompiler :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasGHCVariant env, HasHttpManager env, MonadBaseControl IO m) => SetupInfo -> CompilerVersion -> VersionCheck -> (Maybe String) -> m Tool downloadAndInstallCompiler si wanted@(GhcVersion{}) versionCheck mbindistURL = do ghcVariant <- asks getGHCVariant (selectedVersion, downloadInfo) <- case mbindistURL of Just bindistURL -> do case ghcVariant of GHCCustom _ -> return () _ -> throwM RequireCustomGHCVariant case wanted of GhcVersion version -> return (version, DownloadInfo (T.pack bindistURL) Nothing Nothing) _ -> throwM WantedMustBeGHC _ -> do ghcKey <- getGhcKey case Map.lookup ghcKey $ siGHCs si of Nothing -> throwM $ UnknownOSKey ghcKey Just pairs -> getWantedCompilerInfo ghcKey versionCheck wanted GhcVersion pairs platform <- asks getPlatform let installer = case platform of Platform _ Cabal.Windows -> installGHCWindows selectedVersion _ -> installGHCPosix selectedVersion $logInfo $ "Preparing to install GHC" <> (case ghcVariant of GHCStandard -> "" v -> " (" <> T.pack (ghcVariantName v) <> ")") <> " to an isolated location." $logInfo "This will not interfere with any system-level installation." ghcPkgName <- parsePackageNameFromString ("ghc" ++ ghcVariantSuffix ghcVariant) let tool = Tool $ PackageIdentifier ghcPkgName selectedVersion downloadAndInstallTool si downloadInfo tool installer downloadAndInstallCompiler si wanted@(GhcjsVersion version _) versionCheck _mbindistUrl = do ghcVariant <- asks getGHCVariant case ghcVariant of GHCStandard -> return () _ -> throwM GHCJSRequiresStandardVariant (selectedVersion, downloadInfo) <- case Map.lookup "source" $ siGHCJSs si of Nothing -> throwM $ UnknownOSKey "source" Just pairs -> getWantedCompilerInfo "source" versionCheck wanted id pairs $logInfo "Preparing to install GHCJS to an isolated location." $logInfo "This will not interfere with any system-level installation." downloadAndInstallTool si downloadInfo (ToolGhcjs selectedVersion) (installGHCJSPosix version) getWantedCompilerInfo :: (Ord k, MonadThrow m) => Text -> VersionCheck -> CompilerVersion -> (k -> CompilerVersion) -> Map k a -> m (k, a) getWantedCompilerInfo key versionCheck wanted toCV pairs = do case mpair of Just pair -> return pair Nothing -> throwM $ UnknownCompilerVersion key wanted (map toCV (Map.keys pairs)) where mpair = listToMaybe $ sortBy (flip (comparing fst)) $ filter (isWantedCompiler versionCheck wanted . toCV . fst) (Map.toList pairs) getGhcKey :: (MonadReader env m, MonadThrow m, HasPlatform env, HasGHCVariant env, MonadLogger m, MonadIO m, MonadCatch m, MonadBaseControl IO m) => m Text getGhcKey = do ghcVariant <- asks getGHCVariant osKey <- getOSKey return $ osKey <> T.pack (ghcVariantSuffix ghcVariant) getOSKey :: (MonadReader env m, MonadThrow m, HasPlatform env, MonadLogger m, MonadIO m, MonadCatch m, MonadBaseControl IO m) => m Text getOSKey = do platform <- asks getPlatform case platform of Platform I386 Cabal.Linux -> return "linux32" Platform X86_64 Cabal.Linux -> return "linux64" Platform I386 Cabal.OSX -> return "macosx" Platform X86_64 Cabal.OSX -> return "macosx" Platform I386 Cabal.FreeBSD -> return "freebsd32" Platform X86_64 Cabal.FreeBSD -> return "freebsd64" Platform I386 Cabal.OpenBSD -> return "openbsd32" Platform X86_64 Cabal.OpenBSD -> return "openbsd64" Platform I386 Cabal.Windows -> return "windows32" Platform X86_64 Cabal.Windows -> return "windows64" Platform arch os -> throwM $ UnsupportedSetupCombo os arch downloadFromInfo :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => DownloadInfo -> Tool -> m (Path Abs File, ArchiveType) downloadFromInfo downloadInfo tool = do config <- asks getConfig at <- case extension of ".tar.xz" -> return TarXz ".tar.bz2" -> return TarBz2 ".tar.gz" -> return TarGz ".7z.exe" -> return SevenZ _ -> error $ "Unknown extension for url: " ++ T.unpack url relfile <- parseRelFile $ toolString tool ++ extension let path = configLocalPrograms config </> relfile chattyDownload (T.pack (toolString tool)) downloadInfo path return (path, at) where url = downloadInfoUrl downloadInfo extension = loop $ T.unpack url where loop fp | ext `elem` [".tar", ".bz2", ".xz", ".exe", ".7z", ".gz"] = loop fp' ++ ext | otherwise = "" where (fp', ext) = FP.splitExtension fp data ArchiveType = TarBz2 | TarXz | TarGz | SevenZ installGHCPosix :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => Version -> SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> m () installGHCPosix version _ archiveFile archiveType destDir = do platform <- asks getPlatform menv0 <- getMinimalEnvOverride menv <- mkEnvOverride platform (removeHaskellEnvVars (unEnvOverride menv0)) $logDebug $ "menv = " <> T.pack (show (unEnvOverride menv)) zipTool' <- case archiveType of TarXz -> return "xz" TarBz2 -> return "bzip2" TarGz -> return "gzip" SevenZ -> error "Don't know how to deal with .7z files on non-Windows" (zipTool, makeTool, tarTool) <- checkDependencies $ (,,) <$> checkDependency zipTool' <*> (checkDependency "gmake" <|> checkDependency "make") <*> checkDependency "tar" $logDebug $ "ziptool: " <> T.pack zipTool $logDebug $ "make: " <> T.pack makeTool $logDebug $ "tar: " <> T.pack tarTool withCanonicalizedSystemTempDirectory "stack-setup" $ \root -> do dir <- liftM (root Path.</>) $ parseRelDir $ "ghc-" ++ versionString version $logSticky $ T.concat ["Unpacking GHC into ", (T.pack . toFilePath $ root), " ..."] $logDebug $ "Unpacking " <> T.pack (toFilePath archiveFile) readInNull root tarTool menv ["xf", toFilePath archiveFile] Nothing $logSticky "Configuring GHC ..." readInNull dir (toFilePath $ dir Path.</> $(mkRelFile "configure")) menv ["--prefix=" ++ toFilePath destDir] Nothing $logSticky "Installing GHC ..." readInNull dir makeTool menv ["install"] Nothing $logStickyDone $ "Installed GHC." $logDebug $ "GHC installed to " <> T.pack (toFilePath destDir) installGHCJSPosix :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => Version -> SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> m () installGHCJSPosix version _ archiveFile archiveType destDir = do platform <- asks getPlatform menv0 <- getMinimalEnvOverride -- This ensures that locking is disabled for the invocations of stack below. let removeLockVar = Map.delete "STACK_LOCK" menv <- mkEnvOverride platform (removeLockVar (removeHaskellEnvVars (unEnvOverride menv0))) $logDebug $ "menv = " <> T.pack (show (unEnvOverride menv)) zipTool' <- case archiveType of TarXz -> return "xz" TarBz2 -> return "bzip2" TarGz -> return "gzip" SevenZ -> error "Don't know how to deal with .7z files on non-Windows" (zipTool, tarTool) <- checkDependencies $ (,) <$> checkDependency zipTool' <*> checkDependency "tar" $logDebug $ "ziptool: " <> T.pack zipTool $logDebug $ "tar: " <> T.pack tarTool -- NOTE: this is a bit of a hack - instead of using a temp directory, put -- the source tarball in the destination directory. This way, the absolute -- paths in the wrapper scripts will point to executables that exist in -- src/.stack-work/install/... - see -- https://github.com/commercialhaskell/stack/issues/1016 -- -- This is also used by 'ensureGhcjsBooted', because it can use the -- environment of the stack.yaml which came with ghcjs, in order to install -- cabal-install. This lets us also fix the version of cabal-install used. let srcDir = destDir Path.</> $(mkRelDir "src") createTree srcDir stackYaml <- ghcjsStackYaml version destDir $logSticky $ T.concat ["Unpacking GHCJS into ", (T.pack . toFilePath $ srcDir), " ..."] $logDebug $ "Unpacking " <> T.pack (toFilePath archiveFile) readInNull srcDir tarTool menv ["xf", toFilePath archiveFile] Nothing $logSticky "Installing GHCJS (this will take a long time) ..." let destBinDir = destDir Path.</> $(mkRelDir "bin") stackPath <- liftIO getExecutablePath createTree destBinDir runAndLog Nothing stackPath menv [ "--install-ghc" , "--stack-yaml" , toFilePath stackYaml , "--local-bin-path" , toFilePath destBinDir , "install" ] $logStickyDone "Installed GHCJS." ghcjsStackYaml :: MonadThrow m => Version -> Path Abs Dir -> m (Path Abs File) ghcjsStackYaml version destDir = liftM ((destDir Path.</> $(mkRelDir "src")) Path.</>) $ parseRelFile $ "ghcjs-" ++ versionString version ++ "/stack.yaml" ensureGhcjsBooted :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => EnvOverride -> CompilerVersion -> Bool -> m () ensureGhcjsBooted menv cv shouldBoot = do eres <- try $ sinkProcessStdout Nothing menv "ghcjs" [] (return ()) case eres of Right () -> return () Left (ReadProcessException _ _ _ err) | "no input files" `S.isInfixOf` LBS.toStrict err -> return () Left (ReadProcessException _ _ _ err) | "ghcjs_boot.completed" `S.isInfixOf` LBS.toStrict err -> if not shouldBoot then throwM GHCJSNotBooted else do stackYaml <- case cv of GhcjsVersion version _ -> ghcjsStackYaml version =<< installDir (ToolGhcjs cv) _ -> fail "ensureGhcjsBooted invoked on non GhcjsVersion" bootGhcjs menv stackYaml Left err -> throwM err bootGhcjs :: (MonadIO m, MonadBaseControl IO m, MonadLogger m, MonadCatch m) => EnvOverride -> Path Abs File -> m () bootGhcjs menv stackYaml = do stackPath <- liftIO getExecutablePath -- Install cabal-install if missing, or if the installed one is old. mcabal <- getCabalInstallVersion menv stackYaml shouldInstallCabal <- case mcabal of Nothing -> do $logInfo "No 'cabal' binary found for use with GHCJS. Installing a local copy of 'cabal' from source." return True Just v | v < $(mkVersion "1.22.4") -> do $logInfo $ "'cabal' binary found on PATH is too old to be used for booting GHCJS (version " <> versionText v <> "). Installing a local copy of 'cabal' from source." return True | otherwise -> return False when shouldInstallCabal $ do $logSticky "Building cabal-install for use by ghcjs-boot ... " runAndLog Nothing stackPath menv [ "--stack-yaml" , toFilePath stackYaml , "build" , "cabal-install" ] $logSticky "Booting GHCJS (this will take a long time) ..." runAndLog Nothing stackPath menv [ "--stack-yaml" , toFilePath stackYaml , "exec" , "--no-ghc-package-path" , "--" , "ghcjs-boot" , "--clean" ] $logStickyDone "GHCJS booted." -- TODO: something similar is done in Stack.Build.Execute. Create some utilities -- for this? runAndLog :: (MonadIO m, MonadBaseControl IO m, MonadLogger m) => Maybe (Path Abs Dir) -> String -> EnvOverride -> [String] -> m () runAndLog mdir name menv args = liftBaseWith $ \restore -> do let logLines = CB.lines =$ CL.mapM_ (void . restore . monadLoggerLog $(TH.location >>= liftLoc) "" LevelInfo . toLogStr) void $ restore $ sinkProcessStderrStdout mdir menv name args logLines logLines getCabalInstallVersion :: (MonadIO m, MonadBaseControl IO m, MonadLogger m, MonadCatch m) => EnvOverride -> Path Abs File -> m (Maybe Version) getCabalInstallVersion menv stackYaml = do ebs <- tryProcessStdout Nothing menv "stack" [ "--stack-yaml" , toFilePath stackYaml , "exec" , "--" , "cabal" , "--numeric-version"] case ebs of Left _ -> return Nothing Right bs -> Just <$> parseVersion (T.encodeUtf8 (T.dropWhileEnd isSpace (T.decodeUtf8 bs))) -- | Check if given processes appear to be present, throwing an exception if -- missing. checkDependencies :: (MonadIO m, MonadThrow m, MonadReader env m, HasConfig env) => CheckDependency a -> m a checkDependencies (CheckDependency f) = do menv <- getMinimalEnvOverride liftIO (f menv) >>= either (throwM . MissingDependencies) return checkDependency :: String -> CheckDependency String checkDependency tool = CheckDependency $ \menv -> do exists <- doesExecutableExist menv tool return $ if exists then Right tool else Left [tool] newtype CheckDependency a = CheckDependency (EnvOverride -> IO (Either [String] a)) deriving Functor instance Applicative CheckDependency where pure x = CheckDependency $ \_ -> return (Right x) CheckDependency f <*> CheckDependency x = CheckDependency $ \menv -> do f' <- f menv x' <- x menv return $ case (f', x') of (Left e1, Left e2) -> Left $ e1 ++ e2 (Left e, Right _) -> Left e (Right _, Left e) -> Left e (Right f'', Right x'') -> Right $ f'' x'' instance Alternative CheckDependency where empty = CheckDependency $ \_ -> return $ Left [] CheckDependency x <|> CheckDependency y = CheckDependency $ \menv -> do res1 <- x menv case res1 of Left _ -> y menv Right x' -> return $ Right x' installGHCWindows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => Version -> SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> m () installGHCWindows version si archiveFile archiveType destDir = do suffix <- case archiveType of TarXz -> return ".xz" TarBz2 -> return ".bz2" TarGz -> return ".gz" _ -> error $ "GHC on Windows must be a tarball file" tarFile <- case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of Nothing -> error $ "Invalid GHC filename: " ++ show archiveFile Just x -> parseAbsFile $ T.unpack x run7z <- setup7z si withCanonicalizedTempDirectory (toFilePath $ parent destDir) ((FP.dropTrailingPathSeparator $ toFilePath $ dirname destDir) ++ "-tmp") $ \tmpDir -> do run7z (parent archiveFile) archiveFile run7z tmpDir tarFile removeFile tarFile `catchIO` \e -> $logWarn (T.concat [ "Exception when removing " , T.pack $ toFilePath tarFile , ": " , T.pack $ show e ]) tarComponent <- parseRelDir $ "ghc-" ++ versionString version renameDir (tmpDir </> tarComponent) destDir $logInfo $ "GHC installed to " <> T.pack (toFilePath destDir) installMsys2Windows :: (MonadIO m, MonadMask m, MonadLogger m, MonadReader env m, HasConfig env, HasHttpManager env, MonadBaseControl IO m) => Text -- ^ OS Key -> SetupInfo -> Path Abs File -> ArchiveType -> Path Abs Dir -> m () installMsys2Windows osKey si archiveFile archiveType destDir = do suffix <- case archiveType of TarXz -> return ".xz" TarBz2 -> return ".bz2" _ -> error $ "MSYS2 must be a .tar.xz archive" tarFile <- case T.stripSuffix suffix $ T.pack $ toFilePath archiveFile of Nothing -> error $ "Invalid MSYS2 filename: " ++ show archiveFile Just x -> parseAbsFile $ T.unpack x run7z <- setup7z si exists <- liftIO $ D.doesDirectoryExist $ toFilePath destDir when exists $ liftIO (D.removeDirectoryRecursive $ toFilePath destDir) `catchIO` \e -> do $logError $ T.pack $ "Could not delete existing msys directory: " ++ toFilePath destDir throwM e run7z (parent archiveFile) archiveFile run7z (parent archiveFile) tarFile removeFile tarFile `catchIO` \e -> $logWarn (T.concat [ "Exception when removing " , T.pack $ toFilePath tarFile , ": " , T.pack $ show e ]) msys <- parseRelDir $ "msys" ++ T.unpack (fromMaybe "32" $ T.stripPrefix "windows" osKey) liftIO $ D.renameDirectory (toFilePath $ parent archiveFile </> msys) (toFilePath destDir) platform <- asks getPlatform menv0 <- getMinimalEnvOverride let oldEnv = unEnvOverride menv0 newEnv = augmentPathMap [toFilePath $ destDir </> $(mkRelDir "usr") </> $(mkRelDir "bin")] oldEnv menv <- mkEnvOverride platform newEnv -- I couldn't find this officially documented anywhere, but you need to run -- the shell once in order to initialize some pacman stuff. Once that run -- happens, you can just run commands as usual. runIn destDir "sh" menv ["--login", "-c", "true"] Nothing -- No longer installing git, it's unreliable -- (https://github.com/commercialhaskell/stack/issues/1046) and the -- MSYS2-installed version has bad CRLF defaults. -- -- Install git. We could install other useful things in the future too. -- runIn destDir "pacman" menv ["-Sy", "--noconfirm", "git"] Nothing -- | Download 7z as necessary, and get a function for unpacking things. -- -- Returned function takes an unpack directory and archive. setup7z :: (MonadReader env m, HasHttpManager env, HasConfig env, MonadThrow m, MonadIO m, MonadIO n, MonadLogger m, MonadBaseControl IO m) => SetupInfo -> m (Path Abs Dir -> Path Abs File -> n ()) setup7z si = do dir <- asks $ configLocalPrograms . getConfig let exe = dir </> $(mkRelFile "7z.exe") dll = dir </> $(mkRelFile "7z.dll") case (siSevenzDll si, siSevenzExe si) of (Just sevenzDll, Just sevenzExe) -> do chattyDownload "7z.dll" sevenzDll dll chattyDownload "7z.exe" sevenzExe exe return $ \outdir archive -> liftIO $ do ec <- rawSystem (toFilePath exe) [ "x" , "-o" ++ toFilePath outdir , "-y" , toFilePath archive ] when (ec /= ExitSuccess) $ throwM (ProblemWhileDecompressing archive) _ -> throwM SetupInfoMissingSevenz chattyDownload :: (MonadReader env m, HasHttpManager env, MonadIO m, MonadLogger m, MonadThrow m, MonadBaseControl IO m) => Text -- ^ label -> DownloadInfo -- ^ URL, content-length, and sha1 -> Path Abs File -- ^ destination -> m () chattyDownload label downloadInfo path = do let url = downloadInfoUrl downloadInfo req <- parseUrl $ T.unpack url $logSticky $ T.concat [ "Preparing to download " , label , " ..." ] $logDebug $ T.concat [ "Downloading from " , url , " to " , T.pack $ toFilePath path , " ..." ] hashChecks <- case downloadInfoSha1 downloadInfo of Just sha1ByteString -> do let sha1 = CheckHexDigestByteString sha1ByteString $logDebug $ T.concat [ "Will check against sha1 hash: " , T.decodeUtf8With T.lenientDecode sha1ByteString ] return [HashCheck SHA1 sha1] Nothing -> do $logWarn $ T.concat [ "No sha1 found in metadata," , " download hash won't be checked." ] return [] let dReq = DownloadRequest { drRequest = req , drHashChecks = hashChecks , drLengthCheck = mtotalSize , drRetryPolicy = drRetryPolicyDefault } runInBase <- liftBaseWith $ \run -> return (void . run) x <- verifiedDownload dReq path (chattyDownloadProgress runInBase) if x then $logStickyDone ("Downloaded " <> label <> ".") else $logStickyDone "Already downloaded." where mtotalSize = downloadInfoContentLength downloadInfo chattyDownloadProgress runInBase _ = do _ <- liftIO $ runInBase $ $logSticky $ label <> ": download has begun" CL.map (Sum . S.length) =$ chunksOverTime 1 =$ go where go = evalStateC 0 $ awaitForever $ \(Sum size) -> do modify (+ size) totalSoFar <- get liftIO $ runInBase $ $logSticky $ T.pack $ case mtotalSize of Nothing -> chattyProgressNoTotal totalSoFar Just 0 -> chattyProgressNoTotal totalSoFar Just totalSize -> chattyProgressWithTotal totalSoFar totalSize -- Example: ghc: 42.13 KiB downloaded... chattyProgressNoTotal totalSoFar = printf ("%s: " <> bytesfmt "%7.2f" totalSoFar <> " downloaded...") (T.unpack label) -- Example: ghc: 50.00 MiB / 100.00 MiB (50.00%) downloaded... chattyProgressWithTotal totalSoFar total = printf ("%s: " <> bytesfmt "%7.2f" totalSoFar <> " / " <> bytesfmt "%.2f" total <> " (%6.2f%%) downloaded...") (T.unpack label) percentage where percentage :: Double percentage = (fromIntegral totalSoFar / fromIntegral total * 100) -- | Given a printf format string for the decimal part and a number of -- bytes, formats the bytes using an appropiate unit and returns the -- formatted string. -- -- >>> bytesfmt "%.2" 512368 -- "500.359375 KiB" bytesfmt :: Integral a => String -> a -> String bytesfmt formatter bs = printf (formatter <> " %s") (fromIntegral (signum bs) * dec :: Double) (bytesSuffixes !! i) where (dec,i) = getSuffix (abs bs) getSuffix n = until p (\(x,y) -> (x / 1024, y+1)) (fromIntegral n,0) where p (n',numDivs) = n' < 1024 || numDivs == (length bytesSuffixes - 1) bytesSuffixes :: [String] bytesSuffixes = ["B","KiB","MiB","GiB","TiB","PiB","EiB","ZiB","YiB"] -- Await eagerly (collect with monoidal append), -- but space out yields by at least the given amount of time. -- The final yield may come sooner, and may be a superfluous mempty. -- Note that Integer and Float literals can be turned into NominalDiffTime -- (these literals are interpreted as "seconds") chunksOverTime :: (Monoid a, MonadIO m) => NominalDiffTime -> Conduit a m a chunksOverTime diff = do currentTime <- liftIO getCurrentTime evalStateC (currentTime, mempty) go where -- State is a tuple of: -- * the last time a yield happened (or the beginning of the sink) -- * the accumulated awaits since the last yield go = await >>= \case Nothing -> do (_, acc) <- get yield acc Just a -> do (lastTime, acc) <- get let acc' = acc <> a currentTime <- liftIO getCurrentTime if diff < diffUTCTime currentTime lastTime then put (currentTime, mempty) >> yield acc' else put (lastTime, acc') go -- | Perform a basic sanity check of GHC sanityCheck :: (MonadIO m, MonadMask m, MonadLogger m, MonadBaseControl IO m) => EnvOverride -> WhichCompiler -> m () sanityCheck menv wc = withCanonicalizedSystemTempDirectory "stack-sanity-check" $ \dir -> do let fp = toFilePath $ dir </> $(mkRelFile "Main.hs") liftIO $ writeFile fp $ unlines [ "import Distribution.Simple" -- ensure Cabal library is present , "main = putStrLn \"Hello World\"" ] let exeName = compilerExeName wc ghc <- join $ findExecutable menv exeName $logDebug $ "Performing a sanity check on: " <> T.pack (toFilePath ghc) eres <- tryProcessStdout (Just dir) menv exeName [ fp , "-no-user-package-db" ] case eres of Left e -> throwM $ GHCSanityCheckCompileFailed e ghc Right _ -> return () -- TODO check that the output of running the command is correct toFilePathNoTrailingSlash :: Path loc Dir -> FilePath toFilePathNoTrailingSlash = FP.dropTrailingPathSeparator . toFilePath -- Remove potentially confusing environment variables removeHaskellEnvVars :: Map Text Text -> Map Text Text removeHaskellEnvVars = Map.delete "GHCJS_PACKAGE_PATH" . Map.delete "GHC_PACKAGE_PATH" . Map.delete "HASKELL_PACKAGE_SANDBOX" . Map.delete "HASKELL_PACKAGE_SANDBOXES" . Map.delete "HASKELL_DIST_DIR" -- | Get map of environment variables to set to change the locale's encoding to UTF-8 getUtf8LocaleVars :: forall m env. (MonadReader env m, HasPlatform env, MonadLogger m, MonadCatch m, MonadBaseControl IO m, MonadIO m) => EnvOverride -> m (Map Text Text) getUtf8LocaleVars menv = do Platform _ os <- asks getPlatform if os == Cabal.Windows then -- On Windows, locale is controlled by the code page, so we don't set any environment -- variables. return Map.empty else do let checkedVars = map checkVar (Map.toList $ eoTextMap menv) -- List of environment variables that will need to be updated to set UTF-8 (because -- they currently do not specify UTF-8). needChangeVars = concatMap fst checkedVars -- Set of locale-related environment variables that have already have a value. existingVarNames = Set.unions (map snd checkedVars) -- True if a locale is already specified by one of the "global" locale variables. hasAnyExisting = or $ map (`Set.member` existingVarNames) ["LANG", "LANGUAGE", "LC_ALL"] if null needChangeVars && hasAnyExisting then -- If no variables need changes and at least one "global" variable is set, no -- changes to environment need to be made. return Map.empty else do -- Get a list of known locales by running @locale -a@. elocales <- tryProcessStdout Nothing menv "locale" ["-a"] let -- Filter the list to only include locales with UTF-8 encoding. utf8Locales = case elocales of Left _ -> [] Right locales -> filter isUtf8Locale (T.lines $ T.decodeUtf8With T.lenientDecode locales) mfallback = getFallbackLocale utf8Locales when (isNothing mfallback) ($logWarn "Warning: unable to set locale to UTF-8 encoding; GHC may fail with 'invalid character'") let -- Get the new values of variables to adjust. changes = Map.unions $ map (adjustedVarValue utf8Locales mfallback) needChangeVars -- Get the values of variables to add. adds | hasAnyExisting = -- If we already have a "global" variable, then nothing needs -- to be added. Map.empty | otherwise = -- If we don't already have a "global" variable, then set LANG to the -- fallback. case mfallback of Nothing -> Map.empty Just fallback -> Map.singleton "LANG" fallback return (Map.union changes adds) where -- Determines whether an environment variable is locale-related and, if so, whether it needs to -- be adjusted. checkVar :: (Text, Text) -> ([Text], Set Text) checkVar (k,v) = if k `elem` ["LANG", "LANGUAGE"] || "LC_" `T.isPrefixOf` k then if isUtf8Locale v then ([], Set.singleton k) else ([k], Set.singleton k) else ([], Set.empty) -- Adjusted value of an existing locale variable. Looks for valid UTF-8 encodings with -- same language /and/ territory, then with same language, and finally the first UTF-8 locale -- returned by @locale -a@. adjustedVarValue :: [Text] -> Maybe Text -> Text -> Map Text Text adjustedVarValue utf8Locales mfallback k = case Map.lookup k (eoTextMap menv) of Nothing -> Map.empty Just v -> case concatMap (matchingLocales utf8Locales) [ T.takeWhile (/= '.') v <> "." , T.takeWhile (/= '_') v <> "_"] of (v':_) -> Map.singleton k v' [] -> case mfallback of Just fallback -> Map.singleton k fallback Nothing -> Map.empty -- Determine the fallback locale, by looking for any UTF-8 locale prefixed with the list in -- @fallbackPrefixes@, and if not found, picking the first UTF-8 encoding returned by @locale -- -a@. getFallbackLocale :: [Text] -> Maybe Text getFallbackLocale utf8Locales = do case concatMap (matchingLocales utf8Locales) fallbackPrefixes of (v:_) -> Just v [] -> case utf8Locales of [] -> Nothing (v:_) -> Just v -- Filter the list of locales for any with the given prefixes (case-insitive). matchingLocales :: [Text] -> Text -> [Text] matchingLocales utf8Locales prefix = filter (\v -> (T.toLower prefix) `T.isPrefixOf` T.toLower v) utf8Locales -- Does the locale have one of the encodings in @utf8Suffixes@ (case-insensitive)? isUtf8Locale locale = or $ map (\v -> T.toLower v `T.isSuffixOf` T.toLower locale) utf8Suffixes -- Prefixes of fallback locales (case-insensitive) fallbackPrefixes = ["C.", "en_US.", "en_"] -- Suffixes of UTF-8 locales (case-insensitive) utf8Suffixes = [".UTF-8", ".utf8"]
rrnewton/stack
src/Stack/Setup.hs
bsd-3-clause
58,093
0
31
19,695
13,075
6,477
6,598
1,133
13
{-# LANGUAGE CPP #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Client.Install -- Copyright : (c) 2005 David Himmelstrup -- 2007 Bjorn Bringert -- 2007-2010 Duncan Coutts -- License : BSD-like -- -- Maintainer : [email protected] -- Stability : provisional -- Portability : portable -- -- High level interface to package installation. ----------------------------------------------------------------------------- module Distribution.Client.Install ( -- * High-level interface install, -- * Lower-level interface that allows to manipulate the install plan makeInstallContext, makeInstallPlan, processInstallPlan, InstallArgs, InstallContext, -- * Prune certain packages from the install plan pruneInstallPlan ) where import Data.List ( isPrefixOf, unfoldr, nub, sort, (\\) ) import qualified Data.Set as S import Data.Maybe ( isJust, fromMaybe, mapMaybe, maybeToList ) import Control.Exception as Exception ( Exception(toException), bracket, catches , Handler(Handler), handleJust, IOException, SomeException ) #ifndef mingw32_HOST_OS import Control.Exception as Exception ( Exception(fromException) ) #endif import System.Exit ( ExitCode(..) ) import Distribution.Compat.Exception ( catchIO, catchExit ) import Control.Applicative ( (<$>) ) import Control.Monad ( forM_, when, unless ) import System.Directory ( getTemporaryDirectory, doesDirectoryExist, doesFileExist, createDirectoryIfMissing, removeFile, renameDirectory ) import System.FilePath ( (</>), (<.>), equalFilePath, takeDirectory ) import System.IO ( openFile, IOMode(AppendMode), hClose ) import System.IO.Error ( isDoesNotExistError, ioeGetFileName ) import Distribution.Client.Targets import Distribution.Client.Configure ( chooseCabalVersion ) import Distribution.Client.Dependency import Distribution.Client.Dependency.Types ( Solver(..) ) import Distribution.Client.FetchUtils import qualified Distribution.Client.Haddock as Haddock (regenerateHaddockIndex) import Distribution.Client.IndexUtils as IndexUtils ( getSourcePackages, getInstalledPackages ) import qualified Distribution.Client.InstallPlan as InstallPlan import Distribution.Client.InstallPlan (InstallPlan) import Distribution.Client.Setup ( GlobalFlags(..) , ConfigFlags(..), configureCommand, filterConfigureFlags , ConfigExFlags(..), InstallFlags(..) ) import Distribution.Client.Config ( defaultCabalDir, defaultUserInstall ) import Distribution.Client.Sandbox.Timestamp ( withUpdateTimestamps ) import Distribution.Client.Sandbox.Types ( SandboxPackageInfo(..), UseSandbox(..), isUseSandbox , whenUsingSandbox ) import Distribution.Client.Tar (extractTarGzFile) import Distribution.Client.Types as Source import Distribution.Client.BuildReports.Types ( ReportLevel(..) ) import Distribution.Client.SetupWrapper ( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions, fromConfigFlags ) import qualified Distribution.Client.BuildReports.Anonymous as BuildReports import qualified Distribution.Client.BuildReports.Storage as BuildReports ( storeAnonymous, storeLocal, fromInstallPlan, fromPlanningFailure ) import qualified Distribution.Client.InstallSymlink as InstallSymlink ( symlinkBinaries ) import qualified Distribution.Client.PackageIndex as SourcePackageIndex import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade import qualified Distribution.Client.World as World import qualified Distribution.InstalledPackageInfo as Installed import Distribution.Client.Compat.ExecutablePath import Distribution.Client.JobControl import Distribution.Utils.NubList import Distribution.Simple.Compiler ( CompilerId(..), Compiler(compilerId), compilerFlavor , CompilerInfo(..), compilerInfo, PackageDB(..), PackageDBStack ) import Distribution.Simple.Program (ProgramConfiguration, defaultProgramConfiguration) import qualified Distribution.Simple.InstallDirs as InstallDirs import qualified Distribution.Simple.PackageIndex as PackageIndex import Distribution.Simple.PackageIndex (InstalledPackageIndex) import Distribution.Simple.Setup ( haddockCommand, HaddockFlags(..) , buildCommand, BuildFlags(..), emptyBuildFlags , toFlag, fromFlag, fromFlagOrDefault, flagToMaybe, defaultDistPref ) import qualified Distribution.Simple.Setup as Cabal ( Flag(..) , copyCommand, CopyFlags(..), emptyCopyFlags , registerCommand, RegisterFlags(..), emptyRegisterFlags , testCommand, TestFlags(..), emptyTestFlags ) import Distribution.Simple.Utils ( createDirectoryIfMissingVerbose, rawSystemExit, comparing , writeFileAtomic, withTempFile , withUTF8FileContents ) import Distribution.Simple.InstallDirs as InstallDirs ( PathTemplate, fromPathTemplate, toPathTemplate, substPathTemplate , initialPathTemplateEnv, installDirsTemplateEnv ) import Distribution.Package ( PackageIdentifier(..), PackageId, packageName, packageVersion , Package(..), PackageFixedDeps(..), PackageKey , Dependency(..), thisPackageVersion, InstalledPackageId, installedPackageId ) import qualified Distribution.PackageDescription as PackageDescription import Distribution.PackageDescription ( PackageDescription, GenericPackageDescription(..), Flag(..) , FlagName(..), FlagAssignment ) import Distribution.PackageDescription.Configuration ( finalizePackageDescription ) import Distribution.ParseUtils ( showPWarning ) import Distribution.Version ( Version, VersionRange, foldVersionRange ) import Distribution.Simple.Utils as Utils ( notice, info, warn, debug, debugNoWrap, die , intercalate, withTempDirectory ) import Distribution.Client.Utils ( determineNumJobs, inDir, mergeBy, MergeResult(..) , tryCanonicalizePath ) import Distribution.System ( Platform, OS(Windows), buildOS ) import Distribution.Text ( display ) import Distribution.Verbosity as Verbosity ( Verbosity, showForCabal, normal, verbose ) import Distribution.Simple.BuildPaths ( exeExtension ) --TODO: -- * assign flags to packages individually -- * complain about flags that do not apply to any package given as target -- so flags do not apply to dependencies, only listed, can use flag -- constraints for dependencies -- * only record applicable flags in world file -- * allow flag constraints -- * allow installed constraints -- * allow flag and installed preferences -- * change world file to use cabal section syntax -- * allow persistent configure flags for each package individually -- ------------------------------------------------------------ -- * Top level user actions -- ------------------------------------------------------------ -- | Installs the packages needed to satisfy a list of dependencies. -- install :: Verbosity -> PackageDBStack -> [Repo] -> Compiler -> Platform -> ProgramConfiguration -> UseSandbox -> Maybe SandboxPackageInfo -> GlobalFlags -> ConfigFlags -> ConfigExFlags -> InstallFlags -> HaddockFlags -> [UserTarget] -> IO () install verbosity packageDBs repos comp platform conf useSandbox mSandboxPkgInfo globalFlags configFlags configExFlags installFlags haddockFlags userTargets0 = do installContext <- makeInstallContext verbosity args (Just userTargets0) planResult <- foldProgress logMsg (return . Left) (return . Right) =<< makeInstallPlan verbosity args installContext case planResult of Left message -> do reportPlanningFailure verbosity args installContext message die' message Right installPlan -> processInstallPlan verbosity args installContext installPlan where args :: InstallArgs args = (packageDBs, repos, comp, platform, conf, useSandbox, mSandboxPkgInfo, globalFlags, configFlags, configExFlags, installFlags, haddockFlags) die' message = die (message ++ if isUseSandbox useSandbox then installFailedInSandbox else []) -- TODO: use a better error message, remove duplication. installFailedInSandbox = "\nNote: when using a sandbox, all packages are required to have " ++ "consistent dependencies. " ++ "Try reinstalling/unregistering the offending packages or " ++ "recreating the sandbox." logMsg message rest = debugNoWrap verbosity message >> rest -- TODO: Make InstallContext a proper data type with documented fields. -- | Common context for makeInstallPlan and processInstallPlan. type InstallContext = ( InstalledPackageIndex, SourcePackageDb , [UserTarget], [PackageSpecifier SourcePackage] ) -- TODO: Make InstallArgs a proper data type with documented fields or just get -- rid of it completely. -- | Initial arguments given to 'install' or 'makeInstallContext'. type InstallArgs = ( PackageDBStack , [Repo] , Compiler , Platform , ProgramConfiguration , UseSandbox , Maybe SandboxPackageInfo , GlobalFlags , ConfigFlags , ConfigExFlags , InstallFlags , HaddockFlags ) -- | Make an install context given install arguments. makeInstallContext :: Verbosity -> InstallArgs -> Maybe [UserTarget] -> IO InstallContext makeInstallContext verbosity (packageDBs, repos, comp, _, conf,_,_, globalFlags, _, _, _, _) mUserTargets = do installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf sourcePkgDb <- getSourcePackages verbosity repos (userTargets, pkgSpecifiers) <- case mUserTargets of Nothing -> -- We want to distinguish between the case where the user has given an -- empty list of targets on the command-line and the case where we -- specifically want to have an empty list of targets. return ([], []) Just userTargets0 -> do -- For install, if no target is given it means we use the current -- directory as the single target. let userTargets | null userTargets0 = [UserTargetLocalDir "."] | otherwise = userTargets0 pkgSpecifiers <- resolveUserTargets verbosity (fromFlag $ globalWorldFile globalFlags) (packageIndex sourcePkgDb) userTargets return (userTargets, pkgSpecifiers) return (installedPkgIndex, sourcePkgDb, userTargets, pkgSpecifiers) -- | Make an install plan given install context and install arguments. makeInstallPlan :: Verbosity -> InstallArgs -> InstallContext -> IO (Progress String String InstallPlan) makeInstallPlan verbosity (_, _, comp, platform, _, _, mSandboxPkgInfo, _, configFlags, configExFlags, installFlags, _) (installedPkgIndex, sourcePkgDb, _, pkgSpecifiers) = do solver <- chooseSolver verbosity (fromFlag (configSolver configExFlags)) (compilerInfo comp) notice verbosity "Resolving dependencies..." return $ planPackages comp platform mSandboxPkgInfo solver configFlags configExFlags installFlags installedPkgIndex sourcePkgDb pkgSpecifiers -- | Given an install plan, perform the actual installations. processInstallPlan :: Verbosity -> InstallArgs -> InstallContext -> InstallPlan -> IO () processInstallPlan verbosity args@(_,_, comp, _, _, _, _, _, _, _, installFlags, _) (installedPkgIndex, sourcePkgDb, userTargets, pkgSpecifiers) installPlan = do checkPrintPlan verbosity comp installedPkgIndex installPlan sourcePkgDb installFlags pkgSpecifiers unless (dryRun || nothingToInstall) $ do installPlan' <- performInstallations verbosity args installedPkgIndex installPlan postInstallActions verbosity args userTargets installPlan' where dryRun = fromFlag (installDryRun installFlags) nothingToInstall = null (InstallPlan.ready installPlan) -- ------------------------------------------------------------ -- * Installation planning -- ------------------------------------------------------------ planPackages :: Compiler -> Platform -> Maybe SandboxPackageInfo -> Solver -> ConfigFlags -> ConfigExFlags -> InstallFlags -> InstalledPackageIndex -> SourcePackageDb -> [PackageSpecifier SourcePackage] -> Progress String String InstallPlan planPackages comp platform mSandboxPkgInfo solver configFlags configExFlags installFlags installedPkgIndex sourcePkgDb pkgSpecifiers = resolveDependencies platform (compilerInfo comp) solver resolverParams >>= if onlyDeps then pruneInstallPlan pkgSpecifiers else return where resolverParams = setMaxBackjumps (if maxBackjumps < 0 then Nothing else Just maxBackjumps) . setIndependentGoals independentGoals . setReorderGoals reorderGoals . setAvoidReinstalls avoidReinstalls . setShadowPkgs shadowPkgs . setStrongFlags strongFlags . setPreferenceDefault (if upgradeDeps then PreferAllLatest else PreferLatestForSelected) . removeUpperBounds allowNewer . addPreferences -- preferences from the config file or command line [ PackageVersionPreference name ver | Dependency name ver <- configPreferences configExFlags ] . addConstraints -- version constraints from the config file or command line (map userToPackageConstraint (configExConstraints configExFlags)) . addConstraints --FIXME: this just applies all flags to all targets which -- is silly. We should check if the flags are appropriate [ PackageConstraintFlags (pkgSpecifierTarget pkgSpecifier) flags | let flags = configConfigurationsFlags configFlags , not (null flags) , pkgSpecifier <- pkgSpecifiers ] . addConstraints [ PackageConstraintStanzas (pkgSpecifierTarget pkgSpecifier) stanzas | pkgSpecifier <- pkgSpecifiers ] . maybe id applySandboxInstallPolicy mSandboxPkgInfo . (if reinstall then reinstallTargets else id) $ standardInstallPolicy installedPkgIndex sourcePkgDb pkgSpecifiers stanzas = concat [ if testsEnabled then [TestStanzas] else [] , if benchmarksEnabled then [BenchStanzas] else [] ] testsEnabled = fromFlagOrDefault False $ configTests configFlags benchmarksEnabled = fromFlagOrDefault False $ configBenchmarks configFlags reinstall = fromFlag (installReinstall installFlags) reorderGoals = fromFlag (installReorderGoals installFlags) independentGoals = fromFlag (installIndependentGoals installFlags) avoidReinstalls = fromFlag (installAvoidReinstalls installFlags) shadowPkgs = fromFlag (installShadowPkgs installFlags) strongFlags = fromFlag (installStrongFlags installFlags) maxBackjumps = fromFlag (installMaxBackjumps installFlags) upgradeDeps = fromFlag (installUpgradeDeps installFlags) onlyDeps = fromFlag (installOnlyDeps installFlags) allowNewer = fromFlag (configAllowNewer configExFlags) -- | Remove the provided targets from the install plan. pruneInstallPlan :: Package pkg => [PackageSpecifier pkg] -> InstallPlan -> Progress String String InstallPlan pruneInstallPlan pkgSpecifiers = -- TODO: this is a general feature and should be moved to D.C.Dependency -- Also, the InstallPlan.remove should return info more precise to the -- problem, rather than the very general PlanProblem type. either (Fail . explain) Done . InstallPlan.remove (\pkg -> packageName pkg `elem` targetnames) where explain :: [InstallPlan.PlanProblem] -> String explain problems = "Cannot select only the dependencies (as requested by the " ++ "'--only-dependencies' flag), " ++ (case pkgids of [pkgid] -> "the package " ++ display pkgid ++ " is " _ -> "the packages " ++ intercalate ", " (map display pkgids) ++ " are ") ++ "required by a dependency of one of the other targets." where pkgids = nub [ depid | InstallPlan.PackageMissingDeps _ depids <- problems , depid <- depids , packageName depid `elem` targetnames ] targetnames = map pkgSpecifierTarget pkgSpecifiers -- ------------------------------------------------------------ -- * Informational messages -- ------------------------------------------------------------ -- | Perform post-solver checks of the install plan and print it if -- either requested or needed. checkPrintPlan :: Verbosity -> Compiler -> InstalledPackageIndex -> InstallPlan -> SourcePackageDb -> InstallFlags -> [PackageSpecifier SourcePackage] -> IO () checkPrintPlan verbosity comp installed installPlan sourcePkgDb installFlags pkgSpecifiers = do -- User targets that are already installed. let preExistingTargets = [ p | let tgts = map pkgSpecifierTarget pkgSpecifiers, InstallPlan.PreExisting p <- InstallPlan.toList installPlan, packageName p `elem` tgts ] -- If there's nothing to install, we print the already existing -- target packages as an explanation. when nothingToInstall $ notice verbosity $ unlines $ "All the requested packages are already installed:" : map (display . packageId) preExistingTargets ++ ["Use --reinstall if you want to reinstall anyway."] let lPlan = linearizeInstallPlan comp installed installPlan -- Are any packages classified as reinstalls? let reinstalledPkgs = concatMap (extractReinstalls . snd) lPlan -- Packages that are already broken. let oldBrokenPkgs = map Installed.installedPackageId . PackageIndex.reverseDependencyClosure installed . map (Installed.installedPackageId . fst) . PackageIndex.brokenPackages $ installed let excluded = reinstalledPkgs ++ oldBrokenPkgs -- Packages that are reverse dependencies of replaced packages are very -- likely to be broken. We exclude packages that are already broken. let newBrokenPkgs = filter (\ p -> not (Installed.installedPackageId p `elem` excluded)) (PackageIndex.reverseDependencyClosure installed reinstalledPkgs) let containsReinstalls = not (null reinstalledPkgs) let breaksPkgs = not (null newBrokenPkgs) let adaptedVerbosity | containsReinstalls && not overrideReinstall = verbosity `max` verbose | otherwise = verbosity -- We print the install plan if we are in a dry-run or if we are confronted -- with a dangerous install plan. when (dryRun || containsReinstalls && not overrideReinstall) $ printPlan (dryRun || breaksPkgs && not overrideReinstall) adaptedVerbosity lPlan sourcePkgDb -- If the install plan is dangerous, we print various warning messages. In -- particular, if we can see that packages are likely to be broken, we even -- bail out (unless installation has been forced with --force-reinstalls). when containsReinstalls $ do if breaksPkgs then do (if dryRun || overrideReinstall then warn verbosity else die) $ unlines $ "The following packages are likely to be broken by the reinstalls:" : map (display . Installed.sourcePackageId) newBrokenPkgs ++ if overrideReinstall then if dryRun then [] else ["Continuing even though the plan contains dangerous reinstalls."] else ["Use --force-reinstalls if you want to install anyway."] else unless dryRun $ warn verbosity "Note that reinstalls are always dangerous. Continuing anyway..." where nothingToInstall = null (InstallPlan.ready installPlan) dryRun = fromFlag (installDryRun installFlags) overrideReinstall = fromFlag (installOverrideReinstall installFlags) linearizeInstallPlan :: Compiler -> InstalledPackageIndex -> InstallPlan -> [(ReadyPackage, PackageStatus)] linearizeInstallPlan comp installedPkgIndex plan = unfoldr next plan where next plan' = case InstallPlan.ready plan' of [] -> Nothing (pkg:_) -> Just ((pkg, status), plan'') where pkgid = installedPackageId pkg status = packageStatus comp installedPkgIndex pkg plan'' = InstallPlan.completed pkgid (BuildOk DocsNotTried TestsNotTried (Just $ Installed.emptyInstalledPackageInfo { Installed.sourcePackageId = packageId pkg , Installed.installedPackageId = pkgid })) (InstallPlan.processing [pkg] plan') --FIXME: This is a bit of a hack, -- pretending that each package is installed -- It's doubly a hack because the installed package ID -- didn't get updated... data PackageStatus = NewPackage | NewVersion [Version] | Reinstall [InstalledPackageId] [PackageChange] type PackageChange = MergeResult PackageIdentifier PackageIdentifier extractReinstalls :: PackageStatus -> [InstalledPackageId] extractReinstalls (Reinstall ipids _) = ipids extractReinstalls _ = [] packageStatus :: Compiler -> InstalledPackageIndex -> ReadyPackage -> PackageStatus packageStatus _comp installedPkgIndex cpkg = case PackageIndex.lookupPackageName installedPkgIndex (packageName cpkg) of [] -> NewPackage ps -> case filter ((== packageId cpkg) . Installed.sourcePackageId) (concatMap snd ps) of [] -> NewVersion (map fst ps) pkgs@(pkg:_) -> Reinstall (map Installed.installedPackageId pkgs) (changes pkg cpkg) where changes :: Installed.InstalledPackageInfo -> ReadyPackage -> [MergeResult PackageIdentifier PackageIdentifier] changes pkg pkg' = filter changed $ mergeBy (comparing packageName) -- get dependencies of installed package (convert to source pkg ids via -- index) (nub . sort . concatMap (maybeToList . fmap Installed.sourcePackageId . PackageIndex.lookupInstalledPackageId installedPkgIndex) . Installed.depends $ pkg) -- get dependencies of configured package (nub . sort . depends $ pkg') changed (InBoth pkgid pkgid') = pkgid /= pkgid' changed _ = True printPlan :: Bool -- is dry run -> Verbosity -> [(ReadyPackage, PackageStatus)] -> SourcePackageDb -> IO () printPlan dryRun verbosity plan sourcePkgDb = case plan of [] -> return () pkgs | verbosity >= Verbosity.verbose -> notice verbosity $ unlines $ ("In order, the following " ++ wouldWill ++ " be installed:") : map showPkgAndReason pkgs | otherwise -> notice verbosity $ unlines $ ("In order, the following " ++ wouldWill ++ " be installed (use -v for more details):") : map showPkg pkgs where wouldWill | dryRun = "would" | otherwise = "will" showPkg (pkg, _) = display (packageId pkg) ++ showLatest (pkg) showPkgAndReason (pkg', pr) = display (packageId pkg') ++ showLatest pkg' ++ showFlagAssignment (nonDefaultFlags pkg') ++ showStanzas (stanzas pkg') ++ " " ++ case pr of NewPackage -> "(new package)" NewVersion _ -> "(new version)" Reinstall _ cs -> "(reinstall)" ++ case cs of [] -> "" diff -> " changes: " ++ intercalate ", " (map change diff) showLatest :: ReadyPackage -> String showLatest pkg = case mLatestVersion of Just latestVersion -> if packageVersion pkg < latestVersion then (" (latest: " ++ display latestVersion ++ ")") else "" Nothing -> "" where mLatestVersion :: Maybe Version mLatestVersion = case SourcePackageIndex.lookupPackageName (packageIndex sourcePkgDb) (packageName pkg) of [] -> Nothing x -> Just $ packageVersion $ last x toFlagAssignment :: [Flag] -> FlagAssignment toFlagAssignment = map (\ f -> (flagName f, flagDefault f)) nonDefaultFlags :: ReadyPackage -> FlagAssignment nonDefaultFlags (ReadyPackage spkg fa _ _) = let defaultAssignment = toFlagAssignment (genPackageFlags (Source.packageDescription spkg)) in fa \\ defaultAssignment stanzas :: ReadyPackage -> [OptionalStanza] stanzas (ReadyPackage _ _ sts _) = sts showStanzas :: [OptionalStanza] -> String showStanzas = concatMap ((' ' :) . showStanza) showStanza TestStanzas = "*test" showStanza BenchStanzas = "*bench" -- FIXME: this should be a proper function in a proper place showFlagAssignment :: FlagAssignment -> String showFlagAssignment = concatMap ((' ' :) . showFlagValue) showFlagValue (f, True) = '+' : showFlagName f showFlagValue (f, False) = '-' : showFlagName f showFlagName (FlagName f) = f change (OnlyInLeft pkgid) = display pkgid ++ " removed" change (InBoth pkgid pkgid') = display pkgid ++ " -> " ++ display (packageVersion pkgid') change (OnlyInRight pkgid') = display pkgid' ++ " added" -- ------------------------------------------------------------ -- * Post installation stuff -- ------------------------------------------------------------ -- | Report a solver failure. This works slightly differently to -- 'postInstallActions', as (by definition) we don't have an install plan. reportPlanningFailure :: Verbosity -> InstallArgs -> InstallContext -> String -> IO () reportPlanningFailure verbosity (_, _, comp, platform, _, _, _ ,_, configFlags, _, installFlags, _) (_, sourcePkgDb, _, pkgSpecifiers) message = do when reportFailure $ do -- Only create reports for explicitly named packages let pkgids = filter (SourcePackageIndex.elemByPackageId (packageIndex sourcePkgDb)) $ mapMaybe theSpecifiedPackage pkgSpecifiers buildReports = BuildReports.fromPlanningFailure platform (compilerId comp) pkgids (configConfigurationsFlags configFlags) when (not (null buildReports)) $ info verbosity $ "Solver failure will be reported for " ++ intercalate "," (map display pkgids) -- Save reports BuildReports.storeLocal (compilerInfo comp) (fromNubList $ installSummaryFile installFlags) buildReports platform -- Save solver log case logFile of Nothing -> return () Just template -> forM_ pkgids $ \pkgid -> let env = initialPathTemplateEnv pkgid dummyPackageKey (compilerInfo comp) platform path = fromPathTemplate $ substPathTemplate env template in writeFile path message where reportFailure = fromFlag (installReportPlanningFailure installFlags) logFile = flagToMaybe (installLogFile installFlags) -- A PackageKey is calculated from the transitive closure of -- dependencies, but when the solver fails we don't have that. -- So we fail. dummyPackageKey = error "reportPlanningFailure: package key not available" -- | If a 'PackageSpecifier' refers to a single package, return Just that package. theSpecifiedPackage :: Package pkg => PackageSpecifier pkg -> Maybe PackageId theSpecifiedPackage pkgSpec = case pkgSpec of NamedPackage name [PackageConstraintVersion name' version] | name == name' -> PackageIdentifier name <$> trivialRange version NamedPackage _ _ -> Nothing SpecificSourcePackage pkg -> Just $ packageId pkg where -- | If a range includes only a single version, return Just that version. trivialRange :: VersionRange -> Maybe Version trivialRange = foldVersionRange Nothing Just -- "== v" (\_ -> Nothing) (\_ -> Nothing) (\_ _ -> Nothing) (\_ _ -> Nothing) -- | Various stuff we do after successful or unsuccessfully installing a bunch -- of packages. This includes: -- -- * build reporting, local and remote -- * symlinking binaries -- * updating indexes -- * updating world file -- * error reporting -- postInstallActions :: Verbosity -> InstallArgs -> [UserTarget] -> InstallPlan -> IO () postInstallActions verbosity (packageDBs, _, comp, platform, conf, useSandbox, mSandboxPkgInfo ,globalFlags, configFlags, _, installFlags, _) targets installPlan = do unless oneShot $ World.insert verbosity worldFile --FIXME: does not handle flags [ World.WorldPkgInfo dep [] | UserTargetNamed dep <- targets ] let buildReports = BuildReports.fromInstallPlan installPlan BuildReports.storeLocal (compilerInfo comp) (fromNubList $ installSummaryFile installFlags) buildReports (InstallPlan.planPlatform installPlan) when (reportingLevel >= AnonymousReports) $ BuildReports.storeAnonymous buildReports when (reportingLevel == DetailedReports) $ storeDetailedBuildReports verbosity logsDir buildReports regenerateHaddockIndex verbosity packageDBs comp platform conf useSandbox configFlags installFlags installPlan symlinkBinaries verbosity comp configFlags installFlags installPlan printBuildFailures installPlan updateSandboxTimestampsFile useSandbox mSandboxPkgInfo comp platform installPlan where reportingLevel = fromFlag (installBuildReports installFlags) logsDir = fromFlag (globalLogsDir globalFlags) oneShot = fromFlag (installOneShot installFlags) worldFile = fromFlag $ globalWorldFile globalFlags storeDetailedBuildReports :: Verbosity -> FilePath -> [(BuildReports.BuildReport, Maybe Repo)] -> IO () storeDetailedBuildReports verbosity logsDir reports = sequence_ [ do dotCabal <- defaultCabalDir let logFileName = display (BuildReports.package report) <.> "log" logFile = logsDir </> logFileName reportsDir = dotCabal </> "reports" </> remoteRepoName remoteRepo reportFile = reportsDir </> logFileName handleMissingLogFile $ do buildLog <- readFile logFile createDirectoryIfMissing True reportsDir -- FIXME writeFile reportFile (show (BuildReports.show report, buildLog)) | (report, Just Repo { repoKind = Left remoteRepo }) <- reports , isLikelyToHaveLogFile (BuildReports.installOutcome report) ] where isLikelyToHaveLogFile BuildReports.ConfigureFailed {} = True isLikelyToHaveLogFile BuildReports.BuildFailed {} = True isLikelyToHaveLogFile BuildReports.InstallFailed {} = True isLikelyToHaveLogFile BuildReports.InstallOk {} = True isLikelyToHaveLogFile _ = False handleMissingLogFile = Exception.handleJust missingFile $ \ioe -> warn verbosity $ "Missing log file for build report: " ++ fromMaybe "" (ioeGetFileName ioe) missingFile ioe | isDoesNotExistError ioe = Just ioe missingFile _ = Nothing regenerateHaddockIndex :: Verbosity -> [PackageDB] -> Compiler -> Platform -> ProgramConfiguration -> UseSandbox -> ConfigFlags -> InstallFlags -> InstallPlan -> IO () regenerateHaddockIndex verbosity packageDBs comp platform conf useSandbox configFlags installFlags installPlan | haddockIndexFileIsRequested && shouldRegenerateHaddockIndex = do defaultDirs <- InstallDirs.defaultInstallDirs (compilerFlavor comp) (fromFlag (configUserInstall configFlags)) True let indexFileTemplate = fromFlag (installHaddockIndex installFlags) indexFile = substHaddockIndexFileName defaultDirs indexFileTemplate notice verbosity $ "Updating documentation index " ++ indexFile --TODO: might be nice if the install plan gave us the new InstalledPackageInfo installedPkgIndex <- getInstalledPackages verbosity comp packageDBs conf Haddock.regenerateHaddockIndex verbosity installedPkgIndex conf indexFile | otherwise = return () where haddockIndexFileIsRequested = fromFlag (installDocumentation installFlags) && isJust (flagToMaybe (installHaddockIndex installFlags)) -- We want to regenerate the index if some new documentation was actually -- installed. Since the index can be only per-user or per-sandbox (see -- #1337), we don't do it for global installs or special cases where we're -- installing into a specific db. shouldRegenerateHaddockIndex = (isUseSandbox useSandbox || normalUserInstall) && someDocsWereInstalled installPlan where someDocsWereInstalled = any installedDocs . InstallPlan.toList normalUserInstall = (UserPackageDB `elem` packageDBs) && all (not . isSpecificPackageDB) packageDBs installedDocs (InstallPlan.Installed _ (BuildOk DocsOk _ _)) = True installedDocs _ = False isSpecificPackageDB (SpecificPackageDB _) = True isSpecificPackageDB _ = False substHaddockIndexFileName defaultDirs = fromPathTemplate . substPathTemplate env where env = env0 ++ installDirsTemplateEnv absoluteDirs env0 = InstallDirs.compilerTemplateEnv (compilerInfo comp) ++ InstallDirs.platformTemplateEnv platform ++ InstallDirs.abiTemplateEnv (compilerInfo comp) platform absoluteDirs = InstallDirs.substituteInstallDirTemplates env0 templateDirs templateDirs = InstallDirs.combineInstallDirs fromFlagOrDefault defaultDirs (configInstallDirs configFlags) symlinkBinaries :: Verbosity -> Compiler -> ConfigFlags -> InstallFlags -> InstallPlan -> IO () symlinkBinaries verbosity comp configFlags installFlags plan = do failed <- InstallSymlink.symlinkBinaries comp configFlags installFlags plan case failed of [] -> return () [(_, exe, path)] -> warn verbosity $ "could not create a symlink in " ++ bindir ++ " for " ++ exe ++ " because the file exists there already but is not " ++ "managed by cabal. You can create a symlink for this executable " ++ "manually if you wish. The executable file has been installed at " ++ path exes -> warn verbosity $ "could not create symlinks in " ++ bindir ++ " for " ++ intercalate ", " [ exe | (_, exe, _) <- exes ] ++ " because the files exist there already and are not " ++ "managed by cabal. You can create symlinks for these executables " ++ "manually if you wish. The executable files have been installed at " ++ intercalate ", " [ path | (_, _, path) <- exes ] where bindir = fromFlag (installSymlinkBinDir installFlags) printBuildFailures :: InstallPlan -> IO () printBuildFailures plan = case [ (pkg, reason) | InstallPlan.Failed pkg reason <- InstallPlan.toList plan ] of [] -> return () failed -> die . unlines $ "Error: some packages failed to install:" : [ display (packageId pkg) ++ printFailureReason reason | (pkg, reason) <- failed ] where printFailureReason reason = case reason of DependentFailed pkgid -> " depends on " ++ display pkgid ++ " which failed to install." DownloadFailed e -> " failed while downloading the package." ++ showException e UnpackFailed e -> " failed while unpacking the package." ++ showException e ConfigureFailed e -> " failed during the configure step." ++ showException e BuildFailed e -> " failed during the building phase." ++ showException e TestsFailed e -> " failed during the tests phase." ++ showException e InstallFailed e -> " failed during the final install step." ++ showException e -- This will never happen, but we include it for completeness PlanningFailed -> " failed during the planning phase." showException e = " The exception was:\n " ++ show e ++ maybeOOM e #ifdef mingw32_HOST_OS maybeOOM _ = "" #else maybeOOM e = maybe "" onExitFailure (fromException e) onExitFailure (ExitFailure n) | n == 9 || n == -9 = "\nThis may be due to an out-of-memory condition." onExitFailure _ = "" #endif -- | If we're working inside a sandbox and some add-source deps were installed, -- update the timestamps of those deps. updateSandboxTimestampsFile :: UseSandbox -> Maybe SandboxPackageInfo -> Compiler -> Platform -> InstallPlan -> IO () updateSandboxTimestampsFile (UseSandbox sandboxDir) (Just (SandboxPackageInfo _ _ _ allAddSourceDeps)) comp platform installPlan = withUpdateTimestamps sandboxDir (compilerId comp) platform $ \_ -> do let allInstalled = [ pkg | InstallPlan.Installed pkg _ <- InstallPlan.toList installPlan ] allSrcPkgs = [ pkg | ReadyPackage pkg _ _ _ <- allInstalled ] allPaths = [ pth | LocalUnpackedPackage pth <- map packageSource allSrcPkgs] allPathsCanonical <- mapM tryCanonicalizePath allPaths return $! filter (`S.member` allAddSourceDeps) allPathsCanonical updateSandboxTimestampsFile _ _ _ _ _ = return () -- ------------------------------------------------------------ -- * Actually do the installations -- ------------------------------------------------------------ data InstallMisc = InstallMisc { rootCmd :: Maybe FilePath, libVersion :: Maybe Version } -- | If logging is enabled, contains location of the log file and the verbosity -- level for logging. type UseLogFile = Maybe (PackageIdentifier -> PackageKey -> FilePath, Verbosity) performInstallations :: Verbosity -> InstallArgs -> InstalledPackageIndex -> InstallPlan -> IO InstallPlan performInstallations verbosity (packageDBs, _, comp, _, _conf, useSandbox, _, globalFlags, configFlags, configExFlags, installFlags, haddockFlags) installedPkgIndex installPlan = do -- With 'install -j' it can be a bit hard to tell whether a sandbox is used. whenUsingSandbox useSandbox $ \sandboxDir -> when parallelInstall $ notice verbosity $ "Notice: installing into a sandbox located at " ++ sandboxDir jobControl <- if parallelInstall then newParallelJobControl else newSerialJobControl buildLimit <- newJobLimit numJobs fetchLimit <- newJobLimit (min numJobs numFetchJobs) installLock <- newLock -- serialise installation cacheLock <- newLock -- serialise access to setup exe cache executeInstallPlan verbosity comp jobControl useLogFile installPlan $ \rpkg -> -- Calculate the package key (ToDo: Is this right for source install) let pkg_key = readyPackageKey comp rpkg in installReadyPackage platform cinfo configFlags rpkg $ \configFlags' src pkg pkgoverride -> fetchSourcePackage verbosity fetchLimit src $ \src' -> installLocalPackage verbosity buildLimit (packageId pkg) src' distPref $ \mpath -> do setupOpts <- setupScriptOptions installedPkgIndex cacheLock installUnpackedPackage verbosity buildLimit installLock numJobs pkg_key setupOpts miscOptions configFlags' installFlags haddockFlags cinfo platform pkg pkgoverride mpath useLogFile where platform = InstallPlan.planPlatform installPlan cinfo = InstallPlan.planCompiler installPlan numJobs = determineNumJobs (installNumJobs installFlags) numFetchJobs = 2 parallelInstall = numJobs >= 2 -- TODO sh provide a useDistPref default -- TODO sh remove undefined distPref = fromFlagOrDefault (useDistPref $ defaultSetupScriptOptions undefined undefined undefined) (configDistPref configFlags) setupScriptOptions index lock = do defaultOptions <- fromConfigFlags verbosity configFlags let opts = defaultOptions { useCabalVersion = chooseCabalVersion configExFlags (libVersion miscOptions), -- Hack: we typically want to allow the UserPackageDB for finding the -- Cabal lib when compiling any Setup.hs even if we're doing a global -- install. However we also allow looking in a specific package db. usePackageDB = if UserPackageDB `elem` packageDBs then packageDBs else let (db@GlobalPackageDB:dbs) = packageDBs in db : UserPackageDB : dbs, --TODO: use Ord instance: -- insert UserPackageDB packageDBs usePackageIndex = if UserPackageDB `elem` packageDBs then Just index else Nothing, -- TODO sh analyze that 'conf' value and find out if it contains valueable information, that is required here -- useProgramConfig = conf, useDistPref = distPref, useLoggingHandle = Nothing, useWorkingDir = Nothing, forceExternalSetupMethod = parallelInstall, useWin32CleanHack = False, setupCacheLock = Just lock } return opts reportingLevel = fromFlag (installBuildReports installFlags) logsDir = fromFlag (globalLogsDir globalFlags) -- Should the build output be written to a log file instead of stdout? useLogFile :: UseLogFile useLogFile = fmap ((\f -> (f, loggingVerbosity)) . substLogFileName) logFileTemplate where installLogFile' = flagToMaybe $ installLogFile installFlags defaultTemplate = toPathTemplate $ logsDir </> "$pkgid" <.> "log" -- If the user has specified --remote-build-reporting=detailed, use the -- default log file location. If the --build-log option is set, use the -- provided location. Otherwise don't use logging, unless building in -- parallel (in which case the default location is used). logFileTemplate :: Maybe PathTemplate logFileTemplate | useDefaultTemplate = Just defaultTemplate | otherwise = installLogFile' -- If the user has specified --remote-build-reporting=detailed or -- --build-log, use more verbose logging. loggingVerbosity :: Verbosity loggingVerbosity | overrideVerbosity = max Verbosity.verbose verbosity | otherwise = verbosity useDefaultTemplate :: Bool useDefaultTemplate | reportingLevel == DetailedReports = True | isJust installLogFile' = False | parallelInstall = True | otherwise = False overrideVerbosity :: Bool overrideVerbosity | reportingLevel == DetailedReports = True | isJust installLogFile' = True | parallelInstall = False | otherwise = False substLogFileName :: PathTemplate -> PackageIdentifier -> PackageKey -> FilePath substLogFileName template pkg pkg_key = fromPathTemplate . substPathTemplate env $ template where env = initialPathTemplateEnv (packageId pkg) pkg_key (compilerInfo comp) platform miscOptions = InstallMisc { rootCmd = if fromFlag (configUserInstall configFlags) || (isUseSandbox useSandbox) then Nothing -- ignore --root-cmd if --user -- or working inside a sandbox. else flagToMaybe (installRootCmd installFlags), libVersion = flagToMaybe (configCabalVersion configExFlags) } executeInstallPlan :: Verbosity -> Compiler -> JobControl IO (PackageId, PackageKey, BuildResult) -> UseLogFile -> InstallPlan -> (ReadyPackage -> IO BuildResult) -> IO InstallPlan executeInstallPlan verbosity comp jobCtl useLogFile plan0 installPkg = tryNewTasks 0 plan0 where tryNewTasks taskCount plan = do case InstallPlan.ready plan of [] | taskCount == 0 -> return plan | otherwise -> waitForTasks taskCount plan pkgs -> do sequence_ [ do info verbosity $ "Ready to install " ++ display pkgid spawnJob jobCtl $ do buildResult <- installPkg pkg return (packageId pkg, pkg_key, buildResult) | pkg <- pkgs , let pkgid = packageId pkg pkg_key = readyPackageKey comp pkg ] let taskCount' = taskCount + length pkgs plan' = InstallPlan.processing pkgs plan waitForTasks taskCount' plan' waitForTasks taskCount plan = do info verbosity $ "Waiting for install task to finish..." (pkgid, pkg_key, buildResult) <- collectJob jobCtl printBuildResult pkgid pkg_key buildResult let taskCount' = taskCount-1 plan' = updatePlan pkgid buildResult plan tryNewTasks taskCount' plan' updatePlan :: PackageIdentifier -> BuildResult -> InstallPlan -> InstallPlan updatePlan pkgid (Right buildSuccess) = InstallPlan.completed (Source.fakeInstalledPackageId pkgid) buildSuccess updatePlan pkgid (Left buildFailure) = InstallPlan.failed (Source.fakeInstalledPackageId pkgid) buildFailure depsFailure where depsFailure = DependentFailed pkgid -- So this first pkgid failed for whatever reason (buildFailure). -- All the other packages that depended on this pkgid, which we -- now cannot build, we mark as failing due to 'DependentFailed' -- which kind of means it was not their fault. -- Print build log if something went wrong, and 'Installed $PKGID' -- otherwise. printBuildResult :: PackageId -> PackageKey -> BuildResult -> IO () printBuildResult pkgid pkg_key buildResult = case buildResult of (Right _) -> notice verbosity $ "Installed " ++ display pkgid (Left _) -> do notice verbosity $ "Failed to install " ++ display pkgid when (verbosity >= normal) $ case useLogFile of Nothing -> return () Just (mkLogFileName, _) -> do let logName = mkLogFileName pkgid pkg_key putStr $ "Build log ( " ++ logName ++ " ):\n" printFile logName printFile :: FilePath -> IO () printFile path = readFile path >>= putStr -- | Call an installer for an 'SourcePackage' but override the configure -- flags with the ones given by the 'ReadyPackage'. In particular the -- 'ReadyPackage' specifies an exact 'FlagAssignment' and exactly -- versioned package dependencies. So we ignore any previous partial flag -- assignment or dependency constraints and use the new ones. -- -- NB: when updating this function, don't forget to also update -- 'configurePackage' in D.C.Configure. installReadyPackage :: Platform -> CompilerInfo -> ConfigFlags -> ReadyPackage -> (ConfigFlags -> PackageLocation (Maybe FilePath) -> PackageDescription -> PackageDescriptionOverride -> a) -> a installReadyPackage platform cinfo configFlags (ReadyPackage (SourcePackage _ gpkg source pkgoverride) flags stanzas deps) installPkg = installPkg configFlags { configConfigurationsFlags = flags, -- We generate the legacy constraints as well as the new style precise deps. -- In the end only one set gets passed to Setup.hs configure, depending on -- the Cabal version we are talking to. configConstraints = [ thisPackageVersion (packageId deppkg) | deppkg <- deps ], configDependencies = [ (packageName (Installed.sourcePackageId deppkg), Installed.installedPackageId deppkg) | deppkg <- deps ], -- Use '--exact-configuration' if supported. configExactConfiguration = toFlag True, configBenchmarks = toFlag False, configTests = toFlag (TestStanzas `elem` stanzas) } source pkg pkgoverride where pkg = case finalizePackageDescription flags (const True) platform cinfo [] (enableStanzas stanzas gpkg) of Left _ -> error "finalizePackageDescription ReadyPackage failed" Right (desc, _) -> desc fetchSourcePackage :: Verbosity -> JobLimit -> PackageLocation (Maybe FilePath) -> (PackageLocation FilePath -> IO BuildResult) -> IO BuildResult fetchSourcePackage verbosity fetchLimit src installPkg = do fetched <- checkFetched src case fetched of Just src' -> installPkg src' Nothing -> onFailure DownloadFailed $ do loc <- withJobLimit fetchLimit $ fetchPackage verbosity src installPkg loc installLocalPackage :: Verbosity -> JobLimit -> PackageIdentifier -> PackageLocation FilePath -> FilePath -> (Maybe FilePath -> IO BuildResult) -> IO BuildResult installLocalPackage verbosity jobLimit pkgid location distPref installPkg = case location of LocalUnpackedPackage dir -> installPkg (Just dir) LocalTarballPackage tarballPath -> installLocalTarballPackage verbosity jobLimit pkgid tarballPath distPref installPkg RemoteTarballPackage _ tarballPath -> installLocalTarballPackage verbosity jobLimit pkgid tarballPath distPref installPkg RepoTarballPackage _ _ tarballPath -> installLocalTarballPackage verbosity jobLimit pkgid tarballPath distPref installPkg installLocalTarballPackage :: Verbosity -> JobLimit -> PackageIdentifier -> FilePath -> FilePath -> (Maybe FilePath -> IO BuildResult) -> IO BuildResult installLocalTarballPackage verbosity jobLimit pkgid tarballPath distPref installPkg = do tmp <- getTemporaryDirectory withTempDirectory verbosity tmp (display pkgid) $ \tmpDirPath -> onFailure UnpackFailed $ do let relUnpackedPath = display pkgid absUnpackedPath = tmpDirPath </> relUnpackedPath descFilePath = absUnpackedPath </> display (packageName pkgid) <.> "cabal" withJobLimit jobLimit $ do info verbosity $ "Extracting " ++ tarballPath ++ " to " ++ tmpDirPath ++ "..." extractTarGzFile tmpDirPath relUnpackedPath tarballPath exists <- doesFileExist descFilePath when (not exists) $ die $ "Package .cabal file not found: " ++ show descFilePath maybeRenameDistDir absUnpackedPath installPkg (Just absUnpackedPath) where -- 'cabal sdist' puts pre-generated files in the 'dist' -- directory. This fails when a nonstandard build directory name -- is used (as is the case with sandboxes), so we need to rename -- the 'dist' dir here. -- -- TODO: 'cabal get happy && cd sandbox && cabal install ../happy' still -- fails even with this workaround. We probably can live with that. maybeRenameDistDir :: FilePath -> IO () maybeRenameDistDir absUnpackedPath = do let distDirPath = absUnpackedPath </> defaultDistPref distDirPathTmp = absUnpackedPath </> (defaultDistPref ++ "-tmp") distDirPathNew = absUnpackedPath </> distPref distDirExists <- doesDirectoryExist distDirPath when (distDirExists && (not $ distDirPath `equalFilePath` distDirPathNew)) $ do -- NB: we need to handle the case when 'distDirPathNew' is a -- subdirectory of 'distDirPath' (e.g. the former is -- 'dist/dist-sandbox-3688fbc2' and the latter is 'dist'). debug verbosity $ "Renaming '" ++ distDirPath ++ "' to '" ++ distDirPathTmp ++ "'." renameDirectory distDirPath distDirPathTmp when (distDirPath `isPrefixOf` distDirPathNew) $ createDirectoryIfMissingVerbose verbosity False distDirPath debug verbosity $ "Renaming '" ++ distDirPathTmp ++ "' to '" ++ distDirPathNew ++ "'." renameDirectory distDirPathTmp distDirPathNew installUnpackedPackage :: Verbosity -> JobLimit -> Lock -> Int -> PackageKey -> SetupScriptOptions -> InstallMisc -> ConfigFlags -> InstallFlags -> HaddockFlags -> CompilerInfo -> Platform -> PackageDescription -> PackageDescriptionOverride -> Maybe FilePath -- ^ Directory to change to before starting the installation. -> UseLogFile -- ^ File to log output to (if any) -> IO BuildResult installUnpackedPackage verbosity buildLimit installLock numJobs pkg_key scriptOptions miscOptions configFlags installFlags haddockFlags cinfo platform pkg pkgoverride workingDir useLogFile = do -- Override the .cabal file if necessary case pkgoverride of Nothing -> return () Just pkgtxt -> do let descFilePath = fromMaybe "." workingDir </> display (packageName pkgid) <.> "cabal" info verbosity $ "Updating " ++ display (packageName pkgid) <.> "cabal" ++ " with the latest revision from the index." writeFileAtomic descFilePath pkgtxt -- Make sure that we pass --libsubdir etc to 'setup configure' (necessary if -- the setup script was compiled against an old version of the Cabal lib). configFlags' <- addDefaultInstallDirs configFlags -- Filter out flags not supported by the old versions of the Cabal lib. let configureFlags :: Version -> ConfigFlags configureFlags = filterConfigureFlags configFlags' { configVerbosity = toFlag verbosity' } -- Path to the optional log file. mLogPath <- maybeLogPath -- Configure phase onFailure ConfigureFailed $ withJobLimit buildLimit $ do when (numJobs > 1) $ notice verbosity $ "Configuring " ++ display pkgid ++ "..." setup configureCommand configureFlags mLogPath -- Build phase onFailure BuildFailed $ do when (numJobs > 1) $ notice verbosity $ "Building " ++ display pkgid ++ "..." setup buildCommand' buildFlags mLogPath -- Doc generation phase docsResult <- if shouldHaddock then (do setup haddockCommand haddockFlags' mLogPath return DocsOk) `catchIO` (\_ -> return DocsFailed) `catchExit` (\_ -> return DocsFailed) else return DocsNotTried -- Tests phase onFailure TestsFailed $ do when (testsEnabled && PackageDescription.hasTests pkg) $ setup Cabal.testCommand testFlags mLogPath let testsResult | testsEnabled = TestsOk | otherwise = TestsNotTried -- Install phase onFailure InstallFailed $ criticalSection installLock $ do -- Capture installed package configuration file maybePkgConf <- maybeGenPkgConf mLogPath -- Actual installation withWin32SelfUpgrade verbosity pkg_key configFlags cinfo platform pkg $ do case rootCmd miscOptions of (Just cmd) -> reexec cmd Nothing -> do setup Cabal.copyCommand copyFlags mLogPath when shouldRegister $ do setup Cabal.registerCommand registerFlags mLogPath return (Right (BuildOk docsResult testsResult maybePkgConf)) where pkgid = packageId pkg buildCommand' = buildCommand defaultProgramConfiguration buildFlags _ = emptyBuildFlags { buildDistPref = configDistPref configFlags, buildVerbosity = toFlag verbosity' } shouldHaddock = fromFlag (installDocumentation installFlags) haddockFlags' _ = haddockFlags { haddockVerbosity = toFlag verbosity', haddockDistPref = configDistPref configFlags } testsEnabled = fromFlag (configTests configFlags) && fromFlagOrDefault False (installRunTests installFlags) testFlags _ = Cabal.emptyTestFlags { Cabal.testDistPref = configDistPref configFlags } copyFlags _ = Cabal.emptyCopyFlags { Cabal.copyDistPref = configDistPref configFlags, Cabal.copyDest = toFlag InstallDirs.NoCopyDest, Cabal.copyVerbosity = toFlag verbosity' } shouldRegister = PackageDescription.hasLibs pkg registerFlags _ = Cabal.emptyRegisterFlags { Cabal.regDistPref = configDistPref configFlags, Cabal.regVerbosity = toFlag verbosity' } verbosity' = maybe verbosity snd useLogFile tempTemplate name = name ++ "-" ++ display pkgid addDefaultInstallDirs :: ConfigFlags -> IO ConfigFlags addDefaultInstallDirs configFlags' = do defInstallDirs <- InstallDirs.defaultInstallDirs flavor userInstall False return $ configFlags' { configInstallDirs = fmap Cabal.Flag . InstallDirs.substituteInstallDirTemplates env $ InstallDirs.combineInstallDirs fromFlagOrDefault defInstallDirs (configInstallDirs configFlags) } where CompilerId flavor _ = compilerInfoId cinfo env = initialPathTemplateEnv pkgid pkg_key cinfo platform userInstall = fromFlagOrDefault defaultUserInstall (configUserInstall configFlags') maybeGenPkgConf :: Maybe FilePath -> IO (Maybe Installed.InstalledPackageInfo) maybeGenPkgConf mLogPath = if shouldRegister then do tmp <- getTemporaryDirectory withTempFile tmp (tempTemplate "pkgConf") $ \pkgConfFile handle -> do hClose handle let registerFlags' version = (registerFlags version) { Cabal.regGenPkgConf = toFlag (Just pkgConfFile) } setup Cabal.registerCommand registerFlags' mLogPath withUTF8FileContents pkgConfFile $ \pkgConfText -> case Installed.parseInstalledPackageInfo pkgConfText of Installed.ParseFailed perror -> pkgConfParseFailed perror Installed.ParseOk warns pkgConf -> do unless (null warns) $ warn verbosity $ unlines (map (showPWarning pkgConfFile) warns) return (Just pkgConf) else return Nothing pkgConfParseFailed :: Installed.PError -> IO a pkgConfParseFailed perror = die $ "Couldn't parse the output of 'setup register --gen-pkg-config':" ++ show perror maybeLogPath :: IO (Maybe FilePath) maybeLogPath = case useLogFile of Nothing -> return Nothing Just (mkLogFileName, _) -> do let logFileName = mkLogFileName (packageId pkg) pkg_key logDir = takeDirectory logFileName unless (null logDir) $ createDirectoryIfMissing True logDir logFileExists <- doesFileExist logFileName when logFileExists $ removeFile logFileName return (Just logFileName) setup cmd flags mLogPath = Exception.bracket (maybe (return Nothing) (\path -> Just `fmap` openFile path AppendMode) mLogPath) (maybe (return ()) hClose) (\logFileHandle -> -- TODO setupWrapper verbosity scriptOptions { useLoggingHandle = logFileHandle , useWorkingDir = workingDir } (Just pkg) cmd flags []) reexec cmd = do -- look for our own executable file and re-exec ourselves using a helper -- program like sudo to elevate privileges: self <- getExecutablePath weExist <- doesFileExist self if weExist then inDir workingDir $ rawSystemExit verbosity cmd [self, "install", "--only" ,"--verbose=" ++ showForCabal verbosity] else die $ "Unable to find cabal executable at: " ++ self -- helper onFailure :: (SomeException -> BuildFailure) -> IO BuildResult -> IO BuildResult onFailure result action = action `catches` [ Handler $ \ioe -> handler (ioe :: IOException) , Handler $ \exit -> handler (exit :: ExitCode) ] where handler :: Exception e => e -> IO BuildResult handler = return . Left . result . toException -- ------------------------------------------------------------ -- * Weird windows hacks -- ------------------------------------------------------------ withWin32SelfUpgrade :: Verbosity -> PackageKey -> ConfigFlags -> CompilerInfo -> Platform -> PackageDescription -> IO a -> IO a withWin32SelfUpgrade _ _ _ _ _ _ action | buildOS /= Windows = action withWin32SelfUpgrade verbosity pkg_key configFlags cinfo platform pkg action = do defaultDirs <- InstallDirs.defaultInstallDirs compFlavor (fromFlag (configUserInstall configFlags)) (PackageDescription.hasLibs pkg) Win32SelfUpgrade.possibleSelfUpgrade verbosity (exeInstallPaths defaultDirs) action where pkgid = packageId pkg (CompilerId compFlavor _) = compilerInfoId cinfo exeInstallPaths defaultDirs = [ InstallDirs.bindir absoluteDirs </> exeName <.> exeExtension | exe <- PackageDescription.executables pkg , PackageDescription.buildable (PackageDescription.buildInfo exe) , let exeName = prefix ++ PackageDescription.exeName exe ++ suffix prefix = substTemplate prefixTemplate suffix = substTemplate suffixTemplate ] where fromFlagTemplate = fromFlagOrDefault (InstallDirs.toPathTemplate "") prefixTemplate = fromFlagTemplate (configProgPrefix configFlags) suffixTemplate = fromFlagTemplate (configProgSuffix configFlags) templateDirs = InstallDirs.combineInstallDirs fromFlagOrDefault defaultDirs (configInstallDirs configFlags) absoluteDirs = InstallDirs.absoluteInstallDirs pkgid pkg_key cinfo InstallDirs.NoCopyDest platform templateDirs substTemplate = InstallDirs.fromPathTemplate . InstallDirs.substPathTemplate env where env = InstallDirs.initialPathTemplateEnv pkgid pkg_key cinfo platform
plumlife/cabal
cabal-install/Distribution/Client/Install.hs
bsd-3-clause
65,435
0
31
18,427
12,327
6,403
5,924
1,139
12
------------------------------------------------------------------------------- -- | This module lets you get API docs for free. It lets you generate -- an 'API' from the type that represents your API using 'docs': -- -- @docs :: 'HasDocs' api => 'Proxy' api -> 'API'@ -- -- Alternatively, if you wish to add one or more introductions to your -- documentation, use 'docsWithIntros': -- -- @'docsWithIntros' :: 'HasDocs' api => [DocIntro] -> 'Proxy' api -> 'API'@ -- -- You can then call 'markdown' on the 'API' value: -- -- @'markdown' :: 'API' -> String@ -- -- or define a custom pretty printer: -- -- @yourPrettyDocs :: 'API' -> String -- or blaze-html's HTML, or ...@ -- -- The only thing you'll need to do will be to implement some classes -- for your captures, get parameters and request or response bodies. -- -- See example/greet.hs for an example. module Servant.Docs ( -- * 'HasDocs' class and key functions HasDocs(..), docs, pretty, markdown -- * Generating docs with extra information , docsWith, docsWithIntros, docsWithOptions , ExtraInfo(..), extraInfo , DocOptions(..) , defaultDocOptions, maxSamples , -- * Classes you need to implement for your types ToSample(..) , toSample , noSamples , singleSample , samples , sampleByteString , sampleByteStrings , ToParam(..) , ToCapture(..) , -- * ADTs to represent an 'API' Endpoint, path, method, defEndpoint , API, apiIntros, apiEndpoints, emptyAPI , DocCapture(..), capSymbol, capDesc , DocQueryParam(..), ParamKind(..), paramName, paramValues, paramDesc, paramKind , DocNote(..), noteTitle, noteBody , DocIntro(..), introTitle, introBody , Response(..), respStatus, respTypes, respBody, defResponse , Action, captures, headers, notes, params, rqtypes, rqbody, response, defAction , single ) where import Servant.Docs.Internal import Servant.Docs.Internal.Pretty
zerobuzz/servant
servant-docs/src/Servant/Docs.hs
bsd-3-clause
1,890
0
5
328
273
195
78
26
0
-- C->Haskell Compiler: Marshalling library -- -- Copyright (c) [1999...2005] Manuel M T Chakravarty -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- 1. Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- 2. Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- 3. The name of the author may not be used to endorse or promote products -- derived from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES -- OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN -- NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -- PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -- LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- --- Description --------------------------------------------------------------- -- -- Language: Haskell 98 -- -- This module provides the marshaling routines for Haskell files produced by -- C->Haskell for binding to C library interfaces. It exports all of the -- low-level FFI (language-independent plus the C-specific parts) together -- with the C->HS-specific higher-level marshalling routines. -- module C2HS ( -- * Re-export the language-independent component of the FFI module Foreign, -- * Re-export the C language component of the FFI module Foreign.C, -- * Composite marshalling functions withCStringLenIntConv, peekCStringLenIntConv, withIntConv, withFloatConv, peekIntConv, peekFloatConv, withBool, peekBool, withEnum, peekEnum, -- * Conditional results using 'Maybe' nothingIf, nothingIfNull, -- * Bit masks combineBitMasks, containsBitMask, extractBitMasks, -- * Conversion between C and Haskell types cIntConv, cFloatConv, cToBool, cFromBool, cToEnum, cFromEnum ) where import Foreign import Foreign.C import Control.Monad (liftM) -- Composite marshalling functions -- ------------------------------- -- Strings with explicit length -- withCStringLenIntConv :: Num n => String -> ((CString, n) -> IO a) -> IO a withCStringLenIntConv s f = withCStringLen s $ \(p, n) -> f (p, fromIntegral n) peekCStringLenIntConv :: Integral n => (CString, n) -> IO String peekCStringLenIntConv (s, n) = peekCStringLen (s, fromIntegral n) -- Marshalling of numerals -- withIntConv :: (Storable b, Integral a, Integral b) => a -> (Ptr b -> IO c) -> IO c withIntConv = with . fromIntegral withFloatConv :: (Storable b, RealFloat a, RealFloat b) => a -> (Ptr b -> IO c) -> IO c withFloatConv = with . realToFrac peekIntConv :: (Storable a, Integral a, Integral b) => Ptr a -> IO b peekIntConv = liftM fromIntegral . peek peekFloatConv :: (Storable a, RealFloat a, RealFloat b) => Ptr a -> IO b peekFloatConv = liftM realToFrac . peek -- Everything else below is deprecated. -- These functions are not used by code generated by c2hs. {-# DEPRECATED withBool "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED peekBool "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED withEnum "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED peekEnum "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED nothingIf "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED nothingIfNull "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED combineBitMasks "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED containsBitMask "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED extractBitMasks "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED cIntConv "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED cFloatConv "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED cFromBool "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED cToBool "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED cToEnum "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} {-# DEPRECATED cFromEnum "The C2HS module will soon stop providing unnecessary\nutility functions. Please use standard FFI library functions instead." #-} -- Passing Booleans by reference -- withBool :: (Integral a, Storable a) => Bool -> (Ptr a -> IO b) -> IO b withBool = with . fromBool peekBool :: (Integral a, Storable a) => Ptr a -> IO Bool peekBool = liftM toBool . peek -- Passing enums by reference -- withEnum :: (Enum a, Integral b, Storable b) => a -> (Ptr b -> IO c) -> IO c withEnum = with . cFromEnum peekEnum :: (Enum a, Integral b, Storable b) => Ptr b -> IO a peekEnum = liftM cToEnum . peek -- Conditional results using 'Maybe' -- --------------------------------- -- Wrap the result into a 'Maybe' type. -- -- * the predicate determines when the result is considered to be non-existing, -- ie, it is represented by `Nothing' -- -- * the second argument allows to map a result wrapped into `Just' to some -- other domain -- nothingIf :: (a -> Bool) -> (a -> b) -> a -> Maybe b nothingIf p f x = if p x then Nothing else Just $ f x -- |Instance for special casing null pointers. -- nothingIfNull :: (Ptr a -> b) -> Ptr a -> Maybe b nothingIfNull = nothingIf (== nullPtr) -- Support for bit masks -- --------------------- -- Given a list of enumeration values that represent bit masks, combine these -- masks using bitwise disjunction. -- combineBitMasks :: (Enum a, Bits b) => [a] -> b combineBitMasks = foldl (.|.) 0 . map (fromIntegral . fromEnum) -- Tests whether the given bit mask is contained in the given bit pattern -- (i.e., all bits set in the mask are also set in the pattern). -- containsBitMask :: (Bits a, Enum b) => a -> b -> Bool bits `containsBitMask` bm = let bm' = fromIntegral . fromEnum $ bm in bm' .&. bits == bm' -- |Given a bit pattern, yield all bit masks that it contains. -- -- * This does *not* attempt to compute a minimal set of bit masks that when -- combined yield the bit pattern, instead all contained bit masks are -- produced. -- extractBitMasks :: (Bits a, Enum b, Bounded b) => a -> [b] extractBitMasks bits = [bm | bm <- [minBound..maxBound], bits `containsBitMask` bm] -- Conversion routines -- ------------------- -- |Integral conversion -- cIntConv :: (Integral a, Integral b) => a -> b cIntConv = fromIntegral -- |Floating conversion -- cFloatConv :: (RealFloat a, RealFloat b) => a -> b cFloatConv = realToFrac -- |Obtain C value from Haskell 'Bool'. -- cFromBool :: Num a => Bool -> a cFromBool = fromBool -- |Obtain Haskell 'Bool' from C value. -- cToBool :: (Eq a, Num a) => a -> Bool cToBool = toBool -- |Convert a C enumeration to Haskell. -- cToEnum :: (Integral i, Enum e) => i -> e cToEnum = toEnum . fromIntegral -- |Convert a Haskell enumeration to C. -- cFromEnum :: (Enum e, Integral i) => e -> i cFromEnum = fromIntegral . fromEnum
reinerp/CoreFoundation
C2HS.hs
bsd-3-clause
8,868
0
10
1,698
1,218
700
518
74
2
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RecordWildCards #-} module Trombone.Pipeline ( module Pipe , Connection(..) , Filter(..) , Message(..) , Pipeline(..) , Predicate(..) , Processor(..) , ProcessorId(..) , TransType(..) , Transformer(..) , broadcast , buildJsonRequest , connections , expand , outgoingConns , processorMsgs ) where import Control.Applicative import Data.Aeson as Pipe import Data.Maybe ( fromMaybe, mapMaybe ) import Data.Text as Pipe ( Text, cons ) import Network.HTTP.Types import Trombone.Db.Template as Pipe import Trombone.RoutePattern import qualified Data.HashMap.Strict as HMS import qualified Data.Vector as Vect data TransType = TransExclude | TransInclude | TransBind | TransRename | TransCopy | TransAggregate deriving (Eq, Ord, Show) data Transformer = Transformer TransType [Value] deriving (Eq, Show) data Predicate = PredEqualTo | PredNotEqualTo | PredGreaterThan | PredGreaterThanOrEqual | PredLessThan | PredLessThanOrEqual deriving (Show) data Filter = Filter { property :: Text , predicate :: Predicate , value :: Value } deriving (Show) data Processor = Processor { processorId :: Int -- ^ A unique identifier , processorFields :: [Text] -- ^ List of input fields , processorMethod :: Method -- ^ Any valid HTTP method , processorUri :: RoutePattern -- ^ A route pattern , processorExpand :: Maybe Text -- ^ An optional "expansion" property } deriving (Show) data Connection = Connection { source :: ProcessorId , destination :: ProcessorId , transformers :: [Transformer] , filters :: [Filter] } deriving (Show) data ProcessorId = Id Int | In | Out deriving (Eq, Show) data Message = Message ProcessorId Object deriving (Eq, Show) type MessageQueue = [Message] data Pipeline = Pipeline [Processor] [Connection] MessageQueue deriving (Show) broadcast :: [Connection] -> Value -> [Message] broadcast conns (Object o) = mapMaybe f conns where f :: Connection -> Maybe Message f (Connection _ dest funs filters) = Message <$> Just dest <*> (foldr runTransformer <$> applyFilters o filters <*> Just funs) broadcast conns (Array a) = concatMap (broadcast conns) (Vect.toList a) broadcast conns Null = broadcast conns (Object HMS.empty) broadcast _ _ = [] applyFilters :: Object -> [Filter] -> Maybe Object applyFilters = foldr runFilter . Just runFilter :: Filter -> Maybe Object -> Maybe Object runFilter Filter{..} (Just o) = case HMS.lookup property o of Nothing -> Nothing Just v -> if compare v value then Just o else Nothing where compare :: Value -> Value -> Bool compare (Number v1) (Number v2) = case predicate of PredEqualTo -> v1 == v2 PredNotEqualTo -> v1 /= v2 PredGreaterThan -> v1 > v2 PredGreaterThanOrEqual -> v1 >= v2 PredLessThan -> v1 < v2 PredLessThanOrEqual -> v1 <= v2 compare v1 v2 = case predicate of PredEqualTo -> v1 == v2 PredNotEqualTo -> v1 /= v2 _ -> False runFilter _ _ = Nothing runTransformer :: Transformer -> Object -> Object runTransformer (Transformer TransExclude args) o = HMS.filterWithKey pred o where pred k _ = String k `notElem` args runTransformer (Transformer TransInclude args) o = HMS.filterWithKey pred o where pred k _ = String k `elem` args runTransformer (Transformer TransRename (String from:String to:_)) o = case HMS.lookup from o of Nothing -> o Just v -> HMS.insert to v $ HMS.delete from o runTransformer (Transformer TransCopy (String from:String to:_)) o = case HMS.lookup from o of Nothing -> o Just v -> HMS.insert to v o runTransformer (Transformer TransBind (String key:val:_)) o = HMS.insert key val o runTransformer (Transformer TransAggregate (String key:_)) o = HMS.fromList [(cons '*' key, Object o)] runTransformer _ o = o expand :: Maybe Text -> Object -> Value expand Nothing obj = Object obj expand (Just v) obj = case HMS.lookup v obj of Just x -> f x Nothing -> Object obj where f (Object o) = Object $ HMS.union o obj f (Array a) = Array $ Vect.map f a f x = x buildJsonRequest :: [Message] -> Object buildJsonRequest = foldr f HMS.empty where f (Message _ o1) = HMS.union o1 -- | Return the subset of the message queue relevant to a specific processor. processorMsgs :: ProcessorId -> MessageQueue -> MessageQueue processorMsgs p = filter $ \(Message pid _) -> pid == p -- | Count the number of source or destination endpoints connected to a specific -- processor in the given list of connections. connections :: ProcessorId -> [Connection] -> (Connection -> ProcessorId) -> Int connections _ [] _ = 0 connections p (x:xs) f | p == f x = 1 + connections p xs f | otherwise = connections p xs f -- | Return all connections for which the source is the specified processor. outgoingConns :: ProcessorId -> [Connection] -> [Connection] outgoingConns p = filter $ (==) p . source
johanneshilden/trombone
Trombone/Pipeline.hs
bsd-3-clause
5,820
0
11
1,885
1,649
886
763
139
11
module Database.PostgreSQL.PQTypes.ToSQL ( ParamAllocator(..) , ToSQL(..) , putAsPtr ) where import Data.ByteString.Unsafe import Data.Int import Data.Kind (Type) import Data.Text.Encoding import Data.Time import Data.Word import Foreign.C import Foreign.Marshal.Alloc import Foreign.Ptr import Foreign.Storable import qualified Data.ByteString.Char8 as BS import qualified Data.ByteString.Lazy.Char8 as BSL import qualified Data.Text as T import qualified Data.Text.Lazy as TL import qualified Data.UUID.Types as U import Database.PostgreSQL.PQTypes.Format import Database.PostgreSQL.PQTypes.Internal.C.Interface import Database.PostgreSQL.PQTypes.Internal.C.Types import Database.PostgreSQL.PQTypes.Internal.Utils -- | 'alloca'-like producer of 'PGparam' objects. newtype ParamAllocator = ParamAllocator (forall r. (Ptr PGparam -> IO r) -> IO r) -- | Class which represents \"from Haskell type -- to SQL (libpqtypes) type\" transformation. class PQFormat t => ToSQL t where -- | Destination type (used by libpqtypes). type PQDest t :: Type -- | Put supplied value into inner 'PGparam'. toSQL :: t -- ^ Value to be put. -> ParamAllocator -- ^ 'PGparam' allocator. -> (Ptr (PQDest t) -> IO r) -- ^ Continuation that puts -- converted value into inner 'PGparam'. -> IO r -- | Function that abstracts away common elements of most 'ToSQL' -- instance definitions to make them easier to write and less verbose. putAsPtr :: Storable t => t -> (Ptr t -> IO r) -> IO r putAsPtr x conv = alloca $ \ptr -> poke ptr x >> conv ptr -- NULLables instance ToSQL t => ToSQL (Maybe t) where type PQDest (Maybe t) = PQDest t toSQL mt allocParam conv = case mt of Nothing -> conv nullPtr Just t -> toSQL t allocParam conv -- NUMERICS instance ToSQL Int16 where type PQDest Int16 = CShort toSQL n _ = putAsPtr (fromIntegral n) instance ToSQL Int32 where type PQDest Int32 = CInt toSQL n _ = putAsPtr (fromIntegral n) instance ToSQL Int64 where type PQDest Int64 = CLLong toSQL n _ = putAsPtr (fromIntegral n) instance ToSQL Int where type PQDest Int = CLLong toSQL n _ = putAsPtr (fromIntegral n) instance ToSQL Float where type PQDest Float = CFloat toSQL n _ = putAsPtr (realToFrac n) instance ToSQL Double where type PQDest Double = CDouble toSQL n _ = putAsPtr (realToFrac n) -- CHAR instance ToSQL Char where type PQDest Char = CChar toSQL c _ conv | c > '\255' = hpqTypesError $ "toSQL (Char): character " ++ show c ++ " cannot be losslessly converted to CChar" | otherwise = putAsPtr (castCharToCChar c) conv instance ToSQL Word8 where type PQDest Word8 = CChar toSQL c _ = putAsPtr (fromIntegral c) -- VARIABLE-LENGTH CHARACTER TYPES -- | Encodes underlying C string as UTF-8, so if you are working -- with a different encoding, you should not rely on this instance. instance ToSQL T.Text where type PQDest T.Text = PGbytea toSQL = toSQL . encodeUtf8 -- | Encodes underlying C string as UTF-8, so if you are working -- with a different encoding, you should not rely on this instance. instance ToSQL TL.Text where type PQDest TL.Text = PGbytea toSQL = toSQL . TL.toStrict -- | Encodes underlying C string as UTF-8, so if you are working -- with a different encoding, you should not rely on this instance. instance ToSQL String where type PQDest String = PGbytea toSQL = toSQL . T.pack instance ToSQL U.UUID where type PQDest U.UUID = PGuuid toSQL uuid _ = putAsPtr $ PGuuid w1 w2 w3 w4 where (w1, w2, w3, w4) = U.toWords uuid -- BYTEA instance ToSQL BS.ByteString where type PQDest BS.ByteString = PGbytea toSQL bs _ conv = unsafeUseAsCStringLen bs $ \cslen -> -- Note: it seems that ByteString can actually store NULL pointer -- inside. This is bad, since NULL pointers are treated by libpqtypes -- as NULL values. To get around that, nullStringCStringLen is used -- (a static pointer to empty string defined on C level). Actually, -- it would be sufficient to pass any non-NULL pointer there, but -- this is much uglier and dangerous. flip putAsPtr conv . cStringLenToBytea $ if fst cslen == nullPtr then nullStringCStringLen else cslen instance ToSQL BSL.ByteString where type PQDest BSL.ByteString = PGbytea toSQL = toSQL . BSL.toStrict -- DATE instance ToSQL Day where type PQDest Day = PGdate toSQL day _ = putAsPtr (dayToPGdate day) -- TIME instance ToSQL TimeOfDay where type PQDest TimeOfDay = PGtime toSQL tod _ = putAsPtr (timeOfDayToPGtime tod) -- TIMESTAMP instance ToSQL LocalTime where type PQDest LocalTime = PGtimestamp toSQL LocalTime{..} _ = putAsPtr PGtimestamp { pgTimestampEpoch = 0 , pgTimestampDate = dayToPGdate localDay , pgTimestampTime = timeOfDayToPGtime localTimeOfDay } -- TIMESTAMPTZ instance ToSQL UTCTime where type PQDest UTCTime = PGtimestamp toSQL UTCTime{..} _ = putAsPtr PGtimestamp { pgTimestampEpoch = 0 , pgTimestampDate = dayToPGdate utctDay , pgTimestampTime = timeOfDayToPGtime $ timeToTimeOfDay utctDayTime } instance ToSQL ZonedTime where type PQDest ZonedTime = PGtimestamp toSQL ZonedTime{..} _ = putAsPtr PGtimestamp { pgTimestampEpoch = 0 , pgTimestampDate = dayToPGdate $ localDay zonedTimeToLocalTime , pgTimestampTime = (timeOfDayToPGtime $ localTimeOfDay zonedTimeToLocalTime) { pgTimeGMTOff = fromIntegral (timeZoneMinutes zonedTimeZone) * 60 } } -- BOOL instance ToSQL Bool where type PQDest Bool = CInt toSQL True _ = putAsPtr 1 toSQL False _ = putAsPtr 0 ---------------------------------------- timeOfDayToPGtime :: TimeOfDay -> PGtime timeOfDayToPGtime TimeOfDay{..} = PGtime { pgTimeHour = fromIntegral todHour , pgTimeMin = fromIntegral todMin , pgTimeSec = sec , pgTimeUSec = usec , pgTimeWithTZ = 0 , pgTimeIsDST = 0 , pgTimeGMTOff = 0 , pgTimeTZAbbr = BS.empty } where (sec, usec) = floor ((toRational todSec) * 1000000) `divMod` 1000000 dayToPGdate :: Day -> PGdate dayToPGdate day = PGdate { pgDateIsBC = isBC , pgDateYear = fromIntegral $ adjustBC year , pgDateMon = fromIntegral $ mon - 1 , pgDateMDay = fromIntegral mday , pgDateJDay = 0 , pgDateYDay = 0 , pgDateWDay = 0 } where (year, mon, mday) = toGregorian day -- Note: inverses of appropriate functions -- in pgDateToDay defined in FromSQL module isBC = if year <= 0 then 1 else 0 adjustBC = if isBC == 1 then succ . negate else id
scrive/hpqtypes
src/Database/PostgreSQL/PQTypes/ToSQL.hs
bsd-3-clause
6,526
0
14
1,363
1,625
892
733
-1
-1
{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE TemplateHaskell #-} module Test.Delorean.Duration where import Delorean.Duration import P import System.IO import Test.Delorean.Arbitrary () import Test.Delorean.ParserCheck import Test.QuickCheck prop_consistency :: Int -> Property prop_consistency n = (n >= 0 && n < 100) ==> let h = Hours $ n m = Minutes . (*60) $ n s = Seconds . (*60) . (*60) $ n in h == m && h == s prop_ord :: Duration -> Duration -> Property prop_ord a b = compare a b === on compare durationToSeconds a b prop_symmetricDuration :: Duration -> Property prop_symmetricDuration = symmetric durationParser renderDuration return [] tests :: IO Bool tests = $quickCheckAll
ambiata/delorean
test/Test/Delorean/Duration.hs
bsd-3-clause
780
0
13
198
229
125
104
24
1
import Data.Monoid import Control.Monad import HVG import HVG.Type import HVG.Context2D import HVG.ContextState main = drawCanvas "canvas" (Size 1000 800) $ do box 450 10 100 590 1 $ pure $ do textTop "world" text "aaa" name "a" ellipse 10 50 80 40 $ do text "---" link "a" "b" "red" g 150 50 $ do name "b" box 10 100 180 80 1 $ pure $ do text "Hi" name "c" box 120 240 160 80 1 $ pure $ do text "yes" name "d" box (-70) 290 160 80 1 $ pure $ do text "no" curveLink "b" "c" curveLink "b" "d" forM_ (zip [1..] (take 10 sepSeries)) $ \(i, d) -> do ellipse (d * 800 + 10) 700 30 30 $ do text (show i) {- textWithBorder :: String -> Builder () textWithBorder str = local $ do addEntity $ do width <- measureText str "width" width = 30 strokeRect (Point 0 0) (Size (width + 10) 20) putStrLn "ctx.strokeRect(0, 0, 40, 20);" putStrLn "ctx.strokeRect(0, 0, width+40, 20);" -} {- sepSeries 0 1/2 1/4 3/4 1/8 3/8 5/8 7/8 1/16 3/16 5/16 7/16 9/16 11/16 13/16 15/16 ... -} sepSeries :: [Double] sepSeries = 0 : inners where inners = 0.5 : mix halfs (map (+ 0.5) halfs) halfs = map (/ 2) inners mix (a:as) (b:bs) = a : b : mix as bs g :: Double -> Double -> Builder Link () -> Builder Link () g x y body = local $ do applyTransform (translateMatrix x y) body box :: Double -> Double -> Double -> Double -> Int -> [Builder Link ()] -> Builder Link () box x y w h level bodies = local $ do applyTransform (translateMatrix x y) setSize (Size w h) tran <- getTransform let center = Point (w / 2) (h / 2) link = map pt2link $ join $ flip map sepSeries $ \d -> [ Point (w * d) 0 , Point w (h * d) , Point (w * (1 - d)) h , Point 0 (h * (1 - d)) ] pt2link p = LinkPoint (movePoint tran p) (pointDistance center p) addEntity link $ do strokeStyle "#000" transform tran lineWidth 2 forM_ [1 .. level - 1] $ \i -> do beginPath moveTo (Point 0 (h / fromIntegral level * fromIntegral i)) lineTo (Point w (h / fromIntegral level * fromIntegral i)) stroke lineWidth 3 strokeRect (Point 0 0) (Size w h) forM_ (zip [1..] bodies) $ \(i, body) -> do setSize (Size w (h / fromIntegral level)) body applyTransform (translateMatrix 0 (h / fromIntegral level)) ellipse :: Double -> Double -> Double -> Double -> Builder Link () -> Builder Link () ellipse x y w h body = local $ do applyTransform (translateMatrix x y) tran <- getTransform let centerTran = tran <> translateMatrix (w/2) (h/2) setSize (Size w h) let sepToPoint ratio = let arg = ratio * 2 * 3.14159265358979323846 in movePoint centerTran ( Point (w/2 * cos arg) (h/2 * sin arg) ) link = map (\p -> LinkPoint p 0) $ map sepToPoint sepSeries addEntity link $ do strokeStyle "#000" transform centerTran lineWidth 3 beginPath moveTo (Point 0 (h/2)) bezierCurveTo (Point (0.552284749*w/2) (h/2)) (Point (w/2) (0.552284749*h/2)) (Point (w/2) 0) bezierCurveTo (Point (w/2) (-0.552284749*h/2)) (Point (0.552284749*w/2) (-h/2)) (Point 0 (-h/2)) bezierCurveTo (Point (-0.552284749*w/2) (-h/2)) (Point (-w/2) (-0.552284749*h/2)) (Point (-w/2) 0) bezierCurveTo (Point (-w/2) (0.552284749*h/2)) (Point (-0.552284749*w/2) (h/2)) (Point 0 (h/2)) stroke body textTop :: String -> Builder Link () textTop str = local $ do tran <- getTransform Size w h <- getSize addEntity [] $ do transform tran textBaseline TextMiddle textAlign TextCenter font "15px sans-serif" fillStyle "#000" fillText str (Point (w / 2) 15) Nothing text :: String -> Builder Link () text str = local $ do tran <- getTransform Size w h <- getSize addEntity [] $ do transform tran textBaseline TextMiddle textAlign TextCenter font "15px sans-serif" fillStyle "#000" fillText str (Point (w / 2) (h / 2)) Nothing link :: String -> String -> String -> Builder Link () link aName bName color = fork $ do aLink <- queryInfo aName bLink <- queryInfo bName let bestLinkPair n aLink bLink = fst $ foldl (\(best, bestDis) (cha, chaDis) -> if bestDis <= chaDis then (best, bestDis) else (cha, chaDis)) ((Point 0 0, Point 0 0), 1/0) [((a, b), aCost + pointDistance a b + bCost) | LinkPoint a aCost <- take n aLink, LinkPoint b bCost <- take n bLink] (aEnd, bEnd) = bestLinkPair 64 aLink bLink addEntity [LinkPoint (interpolatePoint aEnd bEnd 0.5) 0] $ do transform identityMatrix strokeStyle color -- "#000" lineWidth 1 beginPath moveTo aEnd lineTo bEnd stroke curveLink :: String -> String -> Builder Link () curveLink aName bName = fork $ do aLink <- queryInfo aName bLink <- queryInfo bName let bestLinkPair n aLink bLink = fst $ foldl (\(best, bestDis) (cha, chaDis) -> if bestDis <= chaDis then (best, bestDis) else (cha, chaDis)) ((Point 0 0, Point 0 0), 1/0) [ ((a, b), aCost + pointDistance a b + bCost) | LinkPoint a aCost <- take n aLink , LinkPoint b bCost <- take n bLink] (aEnd, bEnd) = bestLinkPair 64 aLink bLink Point x1 y1 = aEnd Point x2 y2 = bEnd addEntity [LinkPoint (interpolatePoint aEnd bEnd 0.5) 0] $ do transform identityMatrix strokeStyle "#000" lineWidth 1 beginPath moveTo aEnd if abs (x1 - x2) < 10 || abs (y1 - y2) < 10 then lineTo bEnd else if abs (x1 - x2) < abs (y1 - y2) then bezierCurveTo (Point x1 (y1 + 40 * (y2 - y1) / abs (y2 - y1))) (Point x2 (y2 - 40 * (y2 - y1) / abs (y2 - y1))) bEnd else bezierCurveTo (Point (x1 + 40 * (x2 - x1) / abs (x2 - x1)) y1) (Point (x2 - 40 * (x2 - x1) / abs (x2 - x1)) y2) bEnd stroke
CindyLinz/Haskell-HVG
demo.hs
bsd-3-clause
6,116
1
21
1,870
2,741
1,318
1,423
186
4
module Main ( main -- :: IO () ) where import Prelude hiding (words) import qualified Data.ByteString as S import qualified Codec.Compression.Snappy as Snappy import qualified Codec.Compression.QuickLZ as QuickLZ import qualified Codec.Compression.LZ4 as LZ4 import Criterion.Main import Criterion.Config import Control.DeepSeq (NFData) instance NFData S.ByteString main :: IO () main = do words <- S.readFile "/usr/share/dict/words" let cfg = defaultConfig { cfgPerformGC = ljust True } defaultMainWith cfg (return ()) [ bgroup "/usr/share/dict/words" [ bench "snappy" $ nf Snappy.compress words , bench "quicklz" $ nf QuickLZ.compress words , bench "lz4" $ nf LZ4.compress words , bench "lz4 HC" $ nf LZ4.compressHC words , bench "lz4 ultra" $ nf LZ4.compressPlusHC words ] ]
mwotton/lz4hs
bench/Bench1.hs
bsd-3-clause
878
0
13
211
241
131
110
22
1
{-# LANGUAGE CPP #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE KindSignatures #-} #if __GLASGOW_HASKELL__ >= 706 {-# LANGUAGE PolyKinds #-} #endif #if __GLASGOW_HASKELL__ >= 800 {-# LANGUAGE TypeInType #-} #endif {-# LANGUAGE Trustworthy #-} ------------------------------------------------------------------------------- -- | -- Module : Control.Lens.Type -- Copyright : (C) 2012-16 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <[email protected]> -- Stability : provisional -- Portability : Rank2Types -- -- This module exports the majority of the types that need to appear in user -- signatures or in documentation when talking about lenses. The remaining types -- for consuming lenses are distributed across various modules in the hierarchy. ------------------------------------------------------------------------------- module Control.Lens.Type ( -- * Other Equality, Equality', As , Iso, Iso' , Prism , Prism' , Review , AReview -- * Lenses, Folds and Traversals , Lens, Lens' , Traversal, Traversal' , Traversal1, Traversal1' , Setter, Setter' , Getter, Fold , Fold1 -- * Indexed , IndexedLens, IndexedLens' , IndexedTraversal, IndexedTraversal' , IndexedTraversal1, IndexedTraversal1' , IndexedSetter, IndexedSetter' , IndexedGetter, IndexedFold , IndexedFold1 -- * Index-Preserving , IndexPreservingLens, IndexPreservingLens' , IndexPreservingTraversal, IndexPreservingTraversal' , IndexPreservingTraversal1, IndexPreservingTraversal1' , IndexPreservingSetter, IndexPreservingSetter' , IndexPreservingGetter, IndexPreservingFold , IndexPreservingFold1 -- * Common , Simple , LensLike, LensLike' , Over, Over' , IndexedLensLike, IndexedLensLike' , Optical, Optical' , Optic, Optic' ) where import Prelude () import Control.Lens.Internal.Prelude import Control.Lens.Internal.Setter import Control.Lens.Internal.Indexed import Data.Bifunctor import Data.Functor.Apply #if __GLASGOW_HASKELL__ >= 800 import Data.Kind #endif -- $setup -- >>> :set -XNoOverloadedStrings -- >>> import Control.Lens -- >>> import Debug.SimpleReflect.Expr -- >>> import Debug.SimpleReflect.Vars as Vars hiding (f,g,h) -- >>> let f :: Expr -> Expr; f = Debug.SimpleReflect.Vars.f -- >>> let g :: Expr -> Expr; g = Debug.SimpleReflect.Vars.g -- >>> let h :: Expr -> Expr -> Expr; h = Debug.SimpleReflect.Vars.h -- >>> let getter :: Expr -> Expr; getter = fun "getter" -- >>> let setter :: Expr -> Expr -> Expr; setter = fun "setter" -- >>> import Numeric.Natural -- >>> let nat :: Prism' Integer Natural; nat = prism toInteger $ \i -> if i < 0 then Left i else Right (fromInteger i) ------------------------------------------------------------------------------- -- Lenses ------------------------------------------------------------------------------- -- | A 'Lens' is actually a lens family as described in -- <http://comonad.com/reader/2012/mirrored-lenses/>. -- -- With great power comes great responsibility and a 'Lens' is subject to the -- three common sense 'Lens' laws: -- -- 1) You get back what you put in: -- -- @ -- 'Control.Lens.Getter.view' l ('Control.Lens.Setter.set' l v s) ≡ v -- @ -- -- 2) Putting back what you got doesn't change anything: -- -- @ -- 'Control.Lens.Setter.set' l ('Control.Lens.Getter.view' l s) s ≡ s -- @ -- -- 3) Setting twice is the same as setting once: -- -- @ -- 'Control.Lens.Setter.set' l v' ('Control.Lens.Setter.set' l v s) ≡ 'Control.Lens.Setter.set' l v' s -- @ -- -- These laws are strong enough that the 4 type parameters of a 'Lens' cannot -- vary fully independently. For more on how they interact, read the \"Why is -- it a Lens Family?\" section of -- <http://comonad.com/reader/2012/mirrored-lenses/>. -- -- There are some emergent properties of these laws: -- -- 1) @'Control.Lens.Setter.set' l s@ must be injective for every @s@ This is a consequence of law #1 -- -- 2) @'Control.Lens.Setter.set' l@ must be surjective, because of law #2, which indicates that it is possible to obtain any 'v' from some 's' such that @'Control.Lens.Setter.set' s v = s@ -- -- 3) Given just the first two laws you can prove a weaker form of law #3 where the values @v@ that you are setting match: -- -- @ -- 'Control.Lens.Setter.set' l v ('Control.Lens.Setter.set' l v s) ≡ 'Control.Lens.Setter.set' l v s -- @ -- -- Every 'Lens' can be used directly as a 'Control.Lens.Setter.Setter' or 'Traversal'. -- -- You can also use a 'Lens' for 'Control.Lens.Getter.Getting' as if it were a -- 'Fold' or 'Getter'. -- -- Since every 'Lens' is a valid 'Traversal', the -- 'Traversal' laws are required of any 'Lens' you create: -- -- @ -- l 'pure' ≡ 'pure' -- 'fmap' (l f) '.' l g ≡ 'Data.Functor.Compose.getCompose' '.' l ('Data.Functor.Compose.Compose' '.' 'fmap' f '.' g) -- @ -- -- @ -- type 'Lens' s t a b = forall f. 'Functor' f => 'LensLike' f s t a b -- @ type Lens s t a b = forall f. Functor f => (a -> f b) -> s -> f t -- | @ -- type 'Lens'' = 'Simple' 'Lens' -- @ type Lens' s a = Lens s s a a -- | Every 'IndexedLens' is a valid 'Lens' and a valid 'Control.Lens.Traversal.IndexedTraversal'. type IndexedLens i s t a b = forall f p. (Indexable i p, Functor f) => p a (f b) -> s -> f t -- | @ -- type 'IndexedLens'' i = 'Simple' ('IndexedLens' i) -- @ type IndexedLens' i s a = IndexedLens i s s a a -- | An 'IndexPreservingLens' leaves any index it is composed with alone. type IndexPreservingLens s t a b = forall p f. (Conjoined p, Functor f) => p a (f b) -> p s (f t) -- | @ -- type 'IndexPreservingLens'' = 'Simple' 'IndexPreservingLens' -- @ type IndexPreservingLens' s a = IndexPreservingLens s s a a ------------------------------------------------------------------------------ -- Traversals ------------------------------------------------------------------------------ -- | A 'Traversal' can be used directly as a 'Control.Lens.Setter.Setter' or a 'Fold' (but not as a 'Lens') and provides -- the ability to both read and update multiple fields, subject to some relatively weak 'Traversal' laws. -- -- These have also been known as multilenses, but they have the signature and spirit of -- -- @ -- 'Data.Traversable.traverse' :: 'Data.Traversable.Traversable' f => 'Traversal' (f a) (f b) a b -- @ -- -- and the more evocative name suggests their application. -- -- Most of the time the 'Traversal' you will want to use is just 'Data.Traversable.traverse', but you can also pass any -- 'Lens' or 'Iso' as a 'Traversal', and composition of a 'Traversal' (or 'Lens' or 'Iso') with a 'Traversal' (or 'Lens' or 'Iso') -- using ('.') forms a valid 'Traversal'. -- -- The laws for a 'Traversal' @t@ follow from the laws for 'Data.Traversable.Traversable' as stated in \"The Essence of the Iterator Pattern\". -- -- @ -- t 'pure' ≡ 'pure' -- 'fmap' (t f) '.' t g ≡ 'Data.Functor.Compose.getCompose' '.' t ('Data.Functor.Compose.Compose' '.' 'fmap' f '.' g) -- @ -- -- One consequence of this requirement is that a 'Traversal' needs to leave the same number of elements as a -- candidate for subsequent 'Traversal' that it started with. Another testament to the strength of these laws -- is that the caveat expressed in section 5.5 of the \"Essence of the Iterator Pattern\" about exotic -- 'Data.Traversable.Traversable' instances that 'Data.Traversable.traverse' the same entry multiple times was actually already ruled out by the -- second law in that same paper! type Traversal s t a b = forall f. Applicative f => (a -> f b) -> s -> f t -- | @ -- type 'Traversal'' = 'Simple' 'Traversal' -- @ type Traversal' s a = Traversal s s a a type Traversal1 s t a b = forall f. Apply f => (a -> f b) -> s -> f t type Traversal1' s a = Traversal1 s s a a -- | Every 'IndexedTraversal' is a valid 'Control.Lens.Traversal.Traversal' or -- 'Control.Lens.Fold.IndexedFold'. -- -- The 'Indexed' constraint is used to allow an 'IndexedTraversal' to be used -- directly as a 'Control.Lens.Traversal.Traversal'. -- -- The 'Control.Lens.Traversal.Traversal' laws are still required to hold. -- -- In addition, the index @i@ should satisfy the requirement that it stays -- unchanged even when modifying the value @a@, otherwise traversals like -- 'indices' break the 'Traversal' laws. type IndexedTraversal i s t a b = forall p f. (Indexable i p, Applicative f) => p a (f b) -> s -> f t -- | @ -- type 'IndexedTraversal'' i = 'Simple' ('IndexedTraversal' i) -- @ type IndexedTraversal' i s a = IndexedTraversal i s s a a type IndexedTraversal1 i s t a b = forall p f. (Indexable i p, Apply f) => p a (f b) -> s -> f t type IndexedTraversal1' i s a = IndexedTraversal1 i s s a a -- | An 'IndexPreservingLens' leaves any index it is composed with alone. type IndexPreservingTraversal s t a b = forall p f. (Conjoined p, Applicative f) => p a (f b) -> p s (f t) -- | @ -- type 'IndexPreservingTraversal'' = 'Simple' 'IndexPreservingTraversal' -- @ type IndexPreservingTraversal' s a = IndexPreservingTraversal s s a a type IndexPreservingTraversal1 s t a b = forall p f. (Conjoined p, Apply f) => p a (f b) -> p s (f t) type IndexPreservingTraversal1' s a = IndexPreservingTraversal1 s s a a ------------------------------------------------------------------------------ -- Setters ------------------------------------------------------------------------------ -- | The only 'LensLike' law that can apply to a 'Setter' @l@ is that -- -- @ -- 'Control.Lens.Setter.set' l y ('Control.Lens.Setter.set' l x a) ≡ 'Control.Lens.Setter.set' l y a -- @ -- -- You can't 'Control.Lens.Getter.view' a 'Setter' in general, so the other two laws are irrelevant. -- -- However, two 'Functor' laws apply to a 'Setter': -- -- @ -- 'Control.Lens.Setter.over' l 'id' ≡ 'id' -- 'Control.Lens.Setter.over' l f '.' 'Control.Lens.Setter.over' l g ≡ 'Control.Lens.Setter.over' l (f '.' g) -- @ -- -- These can be stated more directly: -- -- @ -- l 'pure' ≡ 'pure' -- l f '.' 'untainted' '.' l g ≡ l (f '.' 'untainted' '.' g) -- @ -- -- You can compose a 'Setter' with a 'Lens' or a 'Traversal' using ('.') from the @Prelude@ -- and the result is always only a 'Setter' and nothing more. -- -- >>> over traverse f [a,b,c,d] -- [f a,f b,f c,f d] -- -- >>> over _1 f (a,b) -- (f a,b) -- -- >>> over (traverse._1) f [(a,b),(c,d)] -- [(f a,b),(f c,d)] -- -- >>> over both f (a,b) -- (f a,f b) -- -- >>> over (traverse.both) f [(a,b),(c,d)] -- [(f a,f b),(f c,f d)] type Setter s t a b = forall f. Settable f => (a -> f b) -> s -> f t -- | A 'Setter'' is just a 'Setter' that doesn't change the types. -- -- These are particularly common when talking about monomorphic containers. /e.g./ -- -- @ -- 'sets' Data.Text.map :: 'Setter'' 'Data.Text.Internal.Text' 'Char' -- @ -- -- @ -- type 'Setter'' = 'Simple' 'Setter' -- @ type Setter' s a = Setter s s a a -- | Every 'IndexedSetter' is a valid 'Setter'. -- -- The 'Setter' laws are still required to hold. type IndexedSetter i s t a b = forall f p. (Indexable i p, Settable f) => p a (f b) -> s -> f t -- | @ -- type 'IndexedSetter'' i = 'Simple' ('IndexedSetter' i) -- @ type IndexedSetter' i s a = IndexedSetter i s s a a -- | An 'IndexPreservingSetter' can be composed with a 'IndexedSetter', 'IndexedTraversal' or 'IndexedLens' -- and leaves the index intact, yielding an 'IndexedSetter'. type IndexPreservingSetter s t a b = forall p f. (Conjoined p, Settable f) => p a (f b) -> p s (f t) -- | @ -- type 'IndexedPreservingSetter'' i = 'Simple' 'IndexedPreservingSetter' -- @ type IndexPreservingSetter' s a = IndexPreservingSetter s s a a ----------------------------------------------------------------------------- -- Isomorphisms ----------------------------------------------------------------------------- -- | Isomorphism families can be composed with another 'Lens' using ('.') and 'id'. -- -- Since every 'Iso' is both a valid 'Lens' and a valid 'Prism', the laws for those types -- imply the following laws for an 'Iso' 'f': -- -- @ -- f '.' 'Control.Lens.Iso.from' f ≡ 'id' -- 'Control.Lens.Iso.from' f '.' f ≡ 'id' -- @ -- -- Note: Composition with an 'Iso' is index- and measure- preserving. type Iso s t a b = forall p f. (Profunctor p, Functor f) => p a (f b) -> p s (f t) -- | @ -- type 'Iso'' = 'Control.Lens.Type.Simple' 'Iso' -- @ type Iso' s a = Iso s s a a ------------------------------------------------------------------------------ -- Review Internals ------------------------------------------------------------------------------ -- | This is a limited form of a 'Prism' that can only be used for 're' operations. -- -- Like with a 'Getter', there are no laws to state for a 'Review'. -- -- You can generate a 'Review' by using 'unto'. You can also use any 'Prism' or 'Iso' -- directly as a 'Review'. type Review t b = forall p f. (Choice p, Bifunctor p, Settable f) => Optic' p f t b -- | If you see this in a signature for a function, the function is expecting a 'Review' -- (in practice, this usually means a 'Prism'). type AReview t b = Optic' Tagged Identity t b ------------------------------------------------------------------------------ -- Prism Internals ------------------------------------------------------------------------------ -- | A 'Prism' @l@ is a 'Traversal' that can also be turned -- around with 'Control.Lens.Review.re' to obtain a 'Getter' in the -- opposite direction. -- -- There are three laws that a 'Prism' should satisfy: -- -- First, if I 'Control.Lens.Review.re' or 'Control.Lens.Review.review' a value with a 'Prism' and then 'Control.Lens.Fold.preview' or use ('Control.Lens.Fold.^?'), I will get it back: -- -- @ -- 'Control.Lens.Fold.preview' l ('Control.Lens.Review.review' l b) ≡ 'Just' b -- @ -- -- Second, if you can extract a value @a@ using a 'Prism' @l@ from a value @s@, then the value @s@ is completely described by @l@ and @a@: -- -- @ -- 'Control.Lens.Fold.preview' l s ≡ 'Just' a ⟹ 'Control.Lens.Review.review' l a ≡ s -- @ -- -- Third, if you get non-match @t@, you can convert it result back to @s@: -- -- @ -- 'Control.Lens.Combinators.matching' l s ≡ 'Left' t ⟹ 'Control.Lens.Combinators.matching' l t ≡ 'Left' s -- @ -- -- The first two laws imply that the 'Traversal' laws hold for every 'Prism' and that we 'Data.Traversable.traverse' at most 1 element: -- -- @ -- 'Control.Lens.Fold.lengthOf' l x '<=' 1 -- @ -- -- It may help to think of this as an 'Iso' that can be partial in one direction. -- -- Every 'Prism' is a valid 'Traversal'. -- -- Every 'Iso' is a valid 'Prism'. -- -- For example, you might have a @'Prism'' 'Integer' 'Numeric.Natural.Natural'@ allows you to always -- go from a 'Numeric.Natural.Natural' to an 'Integer', and provide you with tools to check if an 'Integer' is -- a 'Numeric.Natural.Natural' and/or to edit one if it is. -- -- -- @ -- 'nat' :: 'Prism'' 'Integer' 'Numeric.Natural.Natural' -- 'nat' = 'Control.Lens.Prism.prism' 'toInteger' '$' \\ i -> -- if i '<' 0 -- then 'Left' i -- else 'Right' ('fromInteger' i) -- @ -- -- Now we can ask if an 'Integer' is a 'Numeric.Natural.Natural'. -- -- >>> 5^?nat -- Just 5 -- -- >>> (-5)^?nat -- Nothing -- -- We can update the ones that are: -- -- >>> (-3,4) & both.nat *~ 2 -- (-3,8) -- -- And we can then convert from a 'Numeric.Natural.Natural' to an 'Integer'. -- -- >>> 5 ^. re nat -- :: Natural -- 5 -- -- Similarly we can use a 'Prism' to 'Data.Traversable.traverse' the 'Left' half of an 'Either': -- -- >>> Left "hello" & _Left %~ length -- Left 5 -- -- or to construct an 'Either': -- -- >>> 5^.re _Left -- Left 5 -- -- such that if you query it with the 'Prism', you will get your original input back. -- -- >>> 5^.re _Left ^? _Left -- Just 5 -- -- Another interesting way to think of a 'Prism' is as the categorical dual of a 'Lens' -- -- a co-'Lens', so to speak. This is what permits the construction of 'Control.Lens.Prism.outside'. -- -- Note: Composition with a 'Prism' is index-preserving. type Prism s t a b = forall p f. (Choice p, Applicative f) => p a (f b) -> p s (f t) -- | A 'Simple' 'Prism'. type Prism' s a = Prism s s a a ------------------------------------------------------------------------------- -- Equality ------------------------------------------------------------------------------- -- | A witness that @(a ~ s, b ~ t)@. -- -- Note: Composition with an 'Equality' is index-preserving. #if __GLASGOW_HASKELL__ >= 800 type Equality (s :: k1) (t :: k2) (a :: k1) (b :: k2) = forall k3 (p :: k1 -> k3 -> Type) (f :: k2 -> k3) . #elif __GLASGOW_HASKELL__ >= 706 type Equality (s :: k1) (t :: k2) (a :: k1) (b :: k2) = forall (p :: k1 -> * -> *) (f :: k2 -> *) . #else type Equality s t a b = forall p (f :: * -> *) . #endif p a (f b) -> p s (f t) -- | A 'Simple' 'Equality'. type Equality' s a = Equality s s a a -- | Composable `asTypeOf`. Useful for constraining excess -- polymorphism, @foo . (id :: As Int) . bar@. type As a = Equality' a a ------------------------------------------------------------------------------- -- Getters ------------------------------------------------------------------------------- -- | A 'Getter' describes how to retrieve a single value in a way that can be -- composed with other 'LensLike' constructions. -- -- Unlike a 'Lens' a 'Getter' is read-only. Since a 'Getter' -- cannot be used to write back there are no 'Lens' laws that can be applied to -- it. In fact, it is isomorphic to an arbitrary function from @(s -> a)@. -- -- Moreover, a 'Getter' can be used directly as a 'Control.Lens.Fold.Fold', -- since it just ignores the 'Applicative'. type Getter s a = forall f. (Contravariant f, Functor f) => (a -> f a) -> s -> f s -- | Every 'IndexedGetter' is a valid 'Control.Lens.Fold.IndexedFold' and can be used for 'Control.Lens.Getter.Getting' like a 'Getter'. type IndexedGetter i s a = forall p f. (Indexable i p, Contravariant f, Functor f) => p a (f a) -> s -> f s -- | An 'IndexPreservingGetter' can be used as a 'Getter', but when composed with an 'IndexedTraversal', -- 'IndexedFold', or 'IndexedLens' yields an 'IndexedFold', 'IndexedFold' or 'IndexedGetter' respectively. type IndexPreservingGetter s a = forall p f. (Conjoined p, Contravariant f, Functor f) => p a (f a) -> p s (f s) -------------------------- -- Folds -------------------------- -- | A 'Fold' describes how to retrieve multiple values in a way that can be composed -- with other 'LensLike' constructions. -- -- A @'Fold' s a@ provides a structure with operations very similar to those of the 'Data.Foldable.Foldable' -- typeclass, see 'Control.Lens.Fold.foldMapOf' and the other 'Fold' combinators. -- -- By convention, if there exists a 'foo' method that expects a @'Data.Foldable.Foldable' (f a)@, then there should be a -- @fooOf@ method that takes a @'Fold' s a@ and a value of type @s@. -- -- A 'Getter' is a legal 'Fold' that just ignores the supplied 'Data.Monoid.Monoid'. -- -- Unlike a 'Control.Lens.Traversal.Traversal' a 'Fold' is read-only. Since a 'Fold' cannot be used to write back -- there are no 'Lens' laws that apply. type Fold s a = forall f. (Contravariant f, Applicative f) => (a -> f a) -> s -> f s -- | Every 'IndexedFold' is a valid 'Control.Lens.Fold.Fold' and can be used for 'Control.Lens.Getter.Getting'. type IndexedFold i s a = forall p f. (Indexable i p, Contravariant f, Applicative f) => p a (f a) -> s -> f s -- | An 'IndexPreservingFold' can be used as a 'Fold', but when composed with an 'IndexedTraversal', -- 'IndexedFold', or 'IndexedLens' yields an 'IndexedFold' respectively. type IndexPreservingFold s a = forall p f. (Conjoined p, Contravariant f, Applicative f) => p a (f a) -> p s (f s) -- | A relevant Fold (aka 'Fold1') has one or more targets. type Fold1 s a = forall f. (Contravariant f, Apply f) => (a -> f a) -> s -> f s type IndexedFold1 i s a = forall p f. (Indexable i p, Contravariant f, Apply f) => p a (f a) -> s -> f s type IndexPreservingFold1 s a = forall p f. (Conjoined p, Contravariant f, Apply f) => p a (f a) -> p s (f s) ------------------------------------------------------------------------------- -- Simple Overloading ------------------------------------------------------------------------------- -- | A 'Simple' 'Lens', 'Simple' 'Traversal', ... can -- be used instead of a 'Lens','Traversal', ... -- whenever the type variables don't change upon setting a value. -- -- @ -- 'Data.Complex.Lens._imagPart' :: 'Simple' 'Lens' ('Data.Complex.Complex' a) a -- 'Control.Lens.Traversal.traversed' :: 'Simple' ('IndexedTraversal' 'Int') [a] a -- @ -- -- Note: To use this alias in your own code with @'LensLike' f@ or -- 'Setter', you may have to turn on @LiberalTypeSynonyms@. -- -- This is commonly abbreviated as a \"prime\" marker, /e.g./ 'Lens'' = 'Simple' 'Lens'. type Simple f s a = f s s a a ------------------------------------------------------------------------------- -- Optics ------------------------------------------------------------------------------- -- | A valid 'Optic' @l@ should satisfy the laws: -- -- @ -- l 'pure' ≡ 'pure' -- l ('Procompose' f g) = 'Procompose' (l f) (l g) -- @ -- -- This gives rise to the laws for 'Equality', 'Iso', 'Prism', 'Lens', -- 'Traversal', 'Traversal1', 'Setter', 'Fold', 'Fold1', and 'Getter' as well -- along with their index-preserving variants. -- -- @ -- type 'LensLike' f s t a b = 'Optic' (->) f s t a b -- @ type Optic p f s t a b = p a (f b) -> p s (f t) -- | @ -- type 'Optic'' p f s a = 'Simple' ('Optic' p f) s a -- @ type Optic' p f s a = Optic p f s s a a -- | @ -- type 'LensLike' f s t a b = 'Optical' (->) (->) f s t a b -- @ -- -- @ -- type 'Over' p f s t a b = 'Optical' p (->) f s t a b -- @ -- -- @ -- type 'Optic' p f s t a b = 'Optical' p p f s t a b -- @ type Optical p q f s t a b = p a (f b) -> q s (f t) -- | @ -- type 'Optical'' p q f s a = 'Simple' ('Optical' p q f) s a -- @ type Optical' p q f s a = Optical p q f s s a a -- | Many combinators that accept a 'Lens' can also accept a -- 'Traversal' in limited situations. -- -- They do so by specializing the type of 'Functor' that they require of the -- caller. -- -- If a function accepts a @'LensLike' f s t a b@ for some 'Functor' @f@, -- then they may be passed a 'Lens'. -- -- Further, if @f@ is an 'Applicative', they may also be passed a -- 'Traversal'. type LensLike f s t a b = (a -> f b) -> s -> f t -- | @ -- type 'LensLike'' f = 'Simple' ('LensLike' f) -- @ type LensLike' f s a = LensLike f s s a a -- | Convenient alias for constructing indexed lenses and their ilk. type IndexedLensLike i f s t a b = forall p. Indexable i p => p a (f b) -> s -> f t -- | Convenient alias for constructing simple indexed lenses and their ilk. type IndexedLensLike' i f s a = IndexedLensLike i f s s a a -- | This is a convenient alias for use when you need to consume either indexed or non-indexed lens-likes based on context. type Over p f s t a b = p a (f b) -> s -> f t -- | This is a convenient alias for use when you need to consume either indexed or non-indexed lens-likes based on context. -- -- @ -- type 'Over'' p f = 'Simple' ('Over' p f) -- @ type Over' p f s a = Over p f s s a a
ddssff/lens
src/Control/Lens/Type.hs
bsd-3-clause
23,271
0
10
4,175
2,684
1,753
931
100
0
main :: IO () main = interact $ const "Hello, world!\n"
YoshikuniJujo/funpaala
samples/25_nml/helloI.hs
bsd-3-clause
56
0
6
11
23
11
12
2
1
{-# LANGUAGE DuplicateRecordFields #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE TypeFamilies #-} module AST.V0_16 (module AST.V0_16, module ElmFormat.AST.Shared) where import Data.Bifunctor import Data.Coapplicative import Data.Foldable import Data.Functor.Const import Data.Functor.Compose import qualified Data.Indexed as I import Data.Kind import qualified Cheapskate.Types as Markdown import ElmFormat.AST.Shared import qualified Data.Maybe as Maybe import Data.Text (Text) newtype ForceMultiline = ForceMultiline Bool deriving (Eq, Show) instance Semigroup ForceMultiline where (ForceMultiline a) <> (ForceMultiline b) = ForceMultiline (a || b) data Comment = BlockComment (List String) | LineComment String | CommentTrickOpener | CommentTrickCloser | CommentTrickBlock String deriving (Eq, Ord, Show) type Comments = List Comment eolToComment :: Maybe String -> Comments eolToComment eol = Maybe.maybeToList (fmap LineComment eol) data CommentType = BeforeTerm | AfterTerm | Inside | BeforeSeparator | AfterSeparator type C1 (l1 :: CommentType) = Commented Comments type C2 (l1 :: CommentType) (l2 :: CommentType) = Commented (Comments, Comments) type C3 (l1 :: CommentType) (l2 :: CommentType) (l3 :: CommentType) = Commented (Comments, Comments, Comments) type C0Eol = Commented (Maybe String) type C1Eol (l1 :: CommentType) = Commented (Comments, Maybe String) type C2Eol (l1 :: CommentType) (l2 :: CommentType) = Commented (Comments, Comments, Maybe String) class AsCommentedList f where type CommentsFor f :: Type -> Type toCommentedList :: f a -> List (CommentsFor f a) fromCommentedList :: List (CommentsFor f a) -> Either Text (f a) {-| This represents a list of things separated by comments. Currently, the first item will never have leading comments. However, if Elm ever changes to allow optional leading delimiters, then comments before the first delimiter will go there. -} newtype Sequence a = Sequence (List (C2Eol 'BeforeSeparator 'AfterSeparator a)) deriving (Eq, Functor, Show) instance Foldable Sequence where foldMap f (Sequence items) = foldMap (f . extract) items instance Semigroup (Sequence a) where (Sequence left) <> (Sequence right) = Sequence (left <> right) instance Monoid (Sequence a) where mempty = Sequence [] instance AsCommentedList Sequence where type CommentsFor Sequence = C2Eol 'BeforeSeparator 'AfterSeparator toCommentedList (Sequence items) = items fromCommentedList = Right . Sequence {-| This represents a list of things between clear start and end delimiters. Comments can appear before and after any item, or alone if there are no items. For example: ( {- nothing -} ) ( a, b ) TODO: this should be replaced with (Sequence a, Comments) -} data ContainedCommentedList a = Empty (C1 'Inside ()) | Items [C2 'BeforeTerm 'AfterTerm a] {-| This represents a list of things that have no clear start and end delimiters. If there is more than one item in the list, then comments can appear. Comments can appear after the first item, before the last item, and around any other item. An end-of-line comment can appear after the last item. If there is only one item in the list, an end-of-line comment can appear after the item. TODO: this should be replaced with (Sequence a) -} data ExposedCommentedList a = Single (C0Eol a) | Multiple (C1Eol 'AfterTerm a) [C2Eol 'BeforeTerm 'AfterTerm a] (C1Eol 'BeforeTerm a) {-| This represents a list of things that have a clear start delimiter but no clear end delimiter. There must be at least one item. Comments can appear before the last item, or around any other item. An end-of-line comment can also appear after the last item. For example: = a = a, b, c TODO: this should be replaced with (Sequence a) -} data OpenCommentedList a = OpenCommentedList [C2Eol 'BeforeTerm 'AfterTerm a] (C1Eol 'BeforeTerm a) deriving (Eq, Show, Functor) instance Foldable OpenCommentedList where foldMap f (OpenCommentedList rest last) = foldMap (f . extract) rest <> (f . extract) last instance AsCommentedList OpenCommentedList where type CommentsFor OpenCommentedList = C2Eol 'BeforeTerm 'AfterTerm toCommentedList (OpenCommentedList rest (C (cLast, eolLast) last)) = rest ++ [ C (cLast, [], eolLast) last ] fromCommentedList list = case reverse list of C (cLast, cLastInvalid, eolLast) last : revRest -> Right $ OpenCommentedList (reverse revRest) (C (cLast ++ cLastInvalid, eolLast) last) [] -> Left "AsCommentedList may not be empty" exposedToOpen :: Comments -> ExposedCommentedList a -> OpenCommentedList a exposedToOpen pre exposed = case exposed of Single (C eol item) -> OpenCommentedList [] (C (pre, eol) item) Multiple (C (postFirst, eol) first') rest' lst -> OpenCommentedList (C (pre, postFirst, eol) first' : rest') lst {-| Represents a delimiter-separated pair. Comments can appear after the key or before the value. For example: key = value key : value -} data Pair key value = Pair { _key :: C1 'AfterTerm key , _value :: C1 'BeforeTerm value , forceMultiline :: ForceMultiline } deriving (Show, Eq, Functor) mapPair :: (a1 -> a2) -> (b1 -> b2) -> Pair a1 b1 -> Pair a2 b2 mapPair fa fb (Pair k v fm) = Pair (fa <$> k) (fb <$> v) fm data Multiline = JoinAll | SplitAll deriving (Eq, Show) isMultiline :: Multiline -> Bool isMultiline JoinAll = False isMultiline SplitAll = True data FunctionApplicationMultiline = FASplitFirst | FAJoinFirst Multiline deriving (Eq, Show) data Assoc = L | N | R deriving (Eq, Show) assocToString :: Assoc -> String assocToString assoc = case assoc of L -> "left" N -> "non" R -> "right" data NameWithArgs name arg = NameWithArgs name [C1 'BeforeTerm arg] deriving (Eq, Show, Functor) instance Foldable (NameWithArgs name) where foldMap f (NameWithArgs _ args) = foldMap (f . extract) args data TypeConstructor ctorRef = NamedConstructor ctorRef | TupleConstructor Int -- will be 2 or greater, indicating the number of elements in the tuple deriving (Eq, Show, Functor) data BinopsClause varRef expr = BinopsClause Comments varRef Comments expr deriving (Eq, Show, Functor) instance Bifunctor BinopsClause where bimap fvr fe = \case BinopsClause c1 vr c2 e -> BinopsClause c1 (fvr vr) c2 (fe e) data IfClause e = IfClause (C2 'BeforeTerm 'AfterTerm e) (C2 'BeforeTerm 'AfterTerm e) deriving (Eq, Show, Functor) data TopLevelStructure a = DocComment Markdown.Blocks | BodyComment Comment | Entry a deriving (Eq, Show, Functor) instance Foldable TopLevelStructure where foldMap _ (DocComment _) = mempty foldMap _ (BodyComment _) = mempty foldMap f (Entry a) = f a data LocalName = TypeName UppercaseIdentifier | CtorName UppercaseIdentifier | VarName LowercaseIdentifier deriving (Eq, Ord, Show) data NodeKind = TopLevelNK | CommonDeclarationNK | TopLevelDeclarationNK | ExpressionNK | LetDeclarationNK | CaseBranchNK | PatternNK | TypeNK data AST typeRef ctorRef varRef (getType :: NodeKind -> Type) (kind :: NodeKind) where TopLevel :: [TopLevelStructure (getType 'TopLevelDeclarationNK)] -> AST typeRef ctorRef varRef getType 'TopLevelNK -- -- Declarations -- Definition :: getType 'PatternNK -> [C1 'BeforeTerm (getType 'PatternNK)] -> Comments -> getType 'ExpressionNK -> AST typeRef ctorRef varRef getType 'CommonDeclarationNK TypeAnnotation :: C1 'AfterTerm (Ref ()) -> C1 'BeforeTerm (getType 'TypeNK) -> AST typeRef ctorRef varRef getType 'CommonDeclarationNK CommonDeclaration :: getType 'CommonDeclarationNK -> AST typeRef ctorRef varRef getType 'TopLevelDeclarationNK Datatype :: { nameWithArgs :: C2 'BeforeTerm 'AfterTerm (NameWithArgs UppercaseIdentifier LowercaseIdentifier) , tags :: OpenCommentedList (NameWithArgs UppercaseIdentifier (getType 'TypeNK)) } -> AST typeRef ctorRef varRef getType 'TopLevelDeclarationNK TypeAlias :: Comments -> C2 'BeforeTerm 'AfterTerm (NameWithArgs UppercaseIdentifier LowercaseIdentifier) -> C1 'BeforeTerm (getType 'TypeNK) -> AST typeRef ctorRef varRef getType 'TopLevelDeclarationNK PortAnnotation :: C2 'BeforeTerm 'AfterTerm LowercaseIdentifier -> Comments -> getType 'TypeNK -> AST typeRef ctorRef varRef getType 'TopLevelDeclarationNK PortDefinition_until_0_16 :: C2 'BeforeTerm 'AfterTerm LowercaseIdentifier -> Comments -> getType 'ExpressionNK -> AST typeRef ctorRef varRef getType 'TopLevelDeclarationNK Fixity_until_0_18 :: Assoc -> Comments -> Int -> Comments -> varRef -> AST typeRef ctorRef varRef getType 'TopLevelDeclarationNK Fixity :: C1 'BeforeTerm Assoc -> C1 'BeforeTerm Int -> C2 'BeforeTerm 'AfterTerm SymbolIdentifier -> C1 'BeforeTerm LowercaseIdentifier -> AST typeRef ctorRef varRef getType 'TopLevelDeclarationNK -- -- Expressions -- Unit :: Comments -> AST typeRef ctorRef varRef getType 'ExpressionNK Literal :: LiteralValue -> AST typeRef ctorRef varRef getType 'ExpressionNK VarExpr :: varRef -> AST typeRef ctorRef varRef getType 'ExpressionNK App :: getType 'ExpressionNK -> [C1 'BeforeTerm (getType 'ExpressionNK)] -> FunctionApplicationMultiline -> AST typeRef ctorRef varRef getType 'ExpressionNK Unary :: UnaryOperator -> getType 'ExpressionNK -> AST typeRef ctorRef varRef getType 'ExpressionNK Binops :: getType 'ExpressionNK -> List (BinopsClause varRef (getType 'ExpressionNK)) -- Non-empty -> Bool -> AST typeRef ctorRef varRef getType 'ExpressionNK Parens :: C2 'BeforeTerm 'AfterTerm (getType 'ExpressionNK) -> AST typeRef ctorRef varRef getType 'ExpressionNK ExplicitList :: { terms :: Sequence (getType 'ExpressionNK) , trailingComments_el :: Comments , forceMultiline_el :: ForceMultiline } -> AST typeRef ctorRef varRef getType 'ExpressionNK Range :: C2 'BeforeTerm 'AfterTerm (getType 'ExpressionNK) -> C2 'BeforeTerm 'AfterTerm (getType 'ExpressionNK) -> Bool -> AST typeRef ctorRef varRef getType 'ExpressionNK Tuple :: [C2 'BeforeTerm 'AfterTerm (getType 'ExpressionNK)] -> Bool -> AST typeRef ctorRef varRef getType 'ExpressionNK TupleFunction :: Int -- will be 2 or greater, indicating the number of elements in the tuple -> AST typeRef ctorRef varRef getType 'ExpressionNK Record :: { base_r :: Maybe (C2 'BeforeTerm 'AfterTerm LowercaseIdentifier) , fields_r :: Sequence (Pair LowercaseIdentifier (getType 'ExpressionNK)) , trailingComments_r :: Comments , forceMultiline_r :: ForceMultiline } -> AST typeRef ctorRef varRef getType 'ExpressionNK Access :: getType 'ExpressionNK -> LowercaseIdentifier -> AST typeRef ctorRef varRef getType 'ExpressionNK AccessFunction :: LowercaseIdentifier -> AST typeRef ctorRef varRef getType 'ExpressionNK Lambda :: [C1 'BeforeTerm (getType 'PatternNK)] -> Comments -> getType 'ExpressionNK -> Bool -> AST typeRef ctorRef varRef getType 'ExpressionNK If :: IfClause (getType 'ExpressionNK) -> [C1 'BeforeTerm (IfClause (getType 'ExpressionNK))] -> C1 'BeforeTerm (getType 'ExpressionNK) -> AST typeRef ctorRef varRef getType 'ExpressionNK Let :: [getType 'LetDeclarationNK] -> Comments -> getType 'ExpressionNK -> AST typeRef ctorRef varRef getType 'ExpressionNK LetCommonDeclaration :: getType 'CommonDeclarationNK -> AST typeRef ctorRef varRef getType 'LetDeclarationNK LetComment :: Comment -> AST typeRef ctorRef varRef getType 'LetDeclarationNK Case :: (C2 'BeforeTerm 'AfterTerm (getType 'ExpressionNK), Bool) -> [getType 'CaseBranchNK] -> AST typeRef ctorRef varRef getType 'ExpressionNK CaseBranch :: { beforePattern :: Comments , beforeArrow :: Comments , afterArrow :: Comments , pattern :: getType 'PatternNK , body :: getType 'ExpressionNK } -> AST typeRef ctorRef varRef getType 'CaseBranchNK -- for type checking and code gen only GLShader :: String -> AST typeRef ctorRef varRef getType 'ExpressionNK -- -- Patterns -- Anything :: AST typeRef ctorRef varRef getType 'PatternNK UnitPattern :: Comments -> AST typeRef ctorRef varRef getType 'PatternNK LiteralPattern :: LiteralValue -> AST typeRef ctorRef varRef getType 'PatternNK VarPattern :: LowercaseIdentifier -> AST typeRef ctorRef varRef getType 'PatternNK OpPattern :: SymbolIdentifier -> AST typeRef ctorRef varRef getType 'PatternNK DataPattern :: ctorRef -> [C1 'BeforeTerm (getType 'PatternNK)] -> AST typeRef ctorRef varRef getType 'PatternNK PatternParens :: C2 'BeforeTerm 'AfterTerm (getType 'PatternNK) -> AST typeRef ctorRef varRef getType 'PatternNK TuplePattern :: [C2 'BeforeTerm 'AfterTerm (getType 'PatternNK)] -> AST typeRef ctorRef varRef getType 'PatternNK EmptyListPattern :: Comments -> AST typeRef ctorRef varRef getType 'PatternNK ListPattern :: [C2 'BeforeTerm 'AfterTerm (getType 'PatternNK)] -> AST typeRef ctorRef varRef getType 'PatternNK ConsPattern :: { first_cp :: C0Eol (getType 'PatternNK) , rest_cp :: Sequence (getType 'PatternNK) } -> AST typeRef ctorRef varRef getType 'PatternNK EmptyRecordPattern :: Comments -> AST typeRef ctorRef varRef getType 'PatternNK RecordPattern :: [C2 'BeforeTerm 'AfterTerm LowercaseIdentifier] -> AST typeRef ctorRef varRef getType 'PatternNK Alias :: C1 'AfterTerm (getType 'PatternNK) -> C1 'BeforeTerm LowercaseIdentifier -> AST typeRef ctorRef varRef getType 'PatternNK -- -- Types -- UnitType :: Comments -> AST typeRef ctorRef varRef getType 'TypeNK TypeVariable :: LowercaseIdentifier -> AST typeRef ctorRef varRef getType 'TypeNK TypeConstruction :: TypeConstructor typeRef -> [C1 'BeforeTerm (getType 'TypeNK)] -> ForceMultiline -> AST typeRef ctorRef varRef getType 'TypeNK TypeParens :: C2 'BeforeTerm 'AfterTerm (getType 'TypeNK) -> AST typeRef ctorRef varRef getType 'TypeNK TupleType :: [C2Eol 'BeforeTerm 'AfterTerm (getType 'TypeNK)] -> ForceMultiline -> AST typeRef ctorRef varRef getType 'TypeNK RecordType :: { base_rt :: Maybe (C2 'BeforeTerm 'AfterTerm LowercaseIdentifier) , fields_rt :: Sequence (Pair LowercaseIdentifier (getType 'TypeNK)) , trailingComments_rt :: Comments , forceMultiline_rt :: ForceMultiline } -> AST typeRef ctorRef varRef getType 'TypeNK FunctionType :: { first_ft :: C0Eol (getType 'TypeNK) , rest_ft :: Sequence (getType 'TypeNK) , forceMultiline_ft :: ForceMultiline } -> AST typeRef ctorRef varRef getType 'TypeNK deriving instance ( Eq typeRef, Eq ctorRef, Eq varRef , Eq (getType 'CommonDeclarationNK) , Eq (getType 'TopLevelDeclarationNK) , Eq (getType 'ExpressionNK) , Eq (getType 'LetDeclarationNK) , Eq (getType 'CaseBranchNK) , Eq (getType 'PatternNK) , Eq (getType 'TypeNK) ) => Eq (AST typeRef ctorRef varRef getType kind) deriving instance ( Show typeRef, Show ctorRef, Show varRef , Show (getType 'CommonDeclarationNK) , Show (getType 'TopLevelDeclarationNK) , Show (getType 'ExpressionNK) , Show (getType 'LetDeclarationNK) , Show (getType 'CaseBranchNK) , Show (getType 'PatternNK) , Show (getType 'TypeNK) ) => Show (AST typeRef ctorRef varRef getType kind) mapAll :: (typeRef1 -> typeRef2) -> (ctorRef1 -> ctorRef2) -> (varRef1 -> varRef2) -> (forall kind. getType1 kind -> getType2 kind) -> (forall kind. AST typeRef1 ctorRef1 varRef1 getType1 kind -> AST typeRef2 ctorRef2 varRef2 getType2 kind ) mapAll ftyp fctor fvar fast = \case TopLevel tls -> TopLevel (fmap (fmap fast) tls) -- Declaration Definition name args c e -> Definition (fast name) (fmap (fmap fast) args) c (fast e) TypeAnnotation name t -> TypeAnnotation name (fmap fast t) CommonDeclaration d -> CommonDeclaration (fast d) Datatype nameWithArgs ctors -> Datatype nameWithArgs (fmap (fmap fast) ctors) TypeAlias c nameWithArgs t -> TypeAlias c nameWithArgs (fmap fast t) PortAnnotation name c t -> PortAnnotation name c (fast t) PortDefinition_until_0_16 name c e -> PortDefinition_until_0_16 name c (fast e) Fixity_until_0_18 a c n c' name -> Fixity_until_0_18 a c n c' (fvar name) Fixity a n op name -> Fixity a n op name -- Expressions Unit c -> Unit c Literal l -> Literal l VarExpr var -> VarExpr (fvar var) App first rest ml -> App (fast first) (fmap (fmap fast) rest) ml Unary op e -> Unary op (fast e) Binops first ops ml -> Binops (fast first) (fmap (bimap fvar fast) ops) ml Parens e -> Parens (fmap fast e) ExplicitList terms c ml -> ExplicitList (fmap fast terms) c ml Range left right ml -> Range (fmap fast left) (fmap fast right) ml Tuple terms ml -> Tuple (fmap (fmap fast) terms) ml TupleFunction n -> TupleFunction n Record base fields c ml -> Record base (fmap (fmap fast) fields) c ml Access e field -> Access (fast e) field AccessFunction field -> AccessFunction field Lambda args c e ml -> Lambda (fmap (fmap fast) args) c (fast e) ml If cond elsifs els -> If (fmap fast cond) (fmap (fmap $ fmap fast) elsifs) (fmap fast els) Let decls c e -> Let (fmap fast decls) c (fast e) LetCommonDeclaration d -> LetCommonDeclaration (fast d) LetComment c -> LetComment c Case (cond, ml) branches -> Case (fmap fast cond, ml) (fmap fast branches) CaseBranch c1 c2 c3 p e -> CaseBranch c1 c2 c3 (fast p) (fast e) GLShader s -> GLShader s -- Patterns Anything -> Anything UnitPattern c -> UnitPattern c LiteralPattern l -> LiteralPattern l VarPattern l -> VarPattern l OpPattern s -> OpPattern s DataPattern ctor pats -> DataPattern (fctor ctor) (fmap (fmap fast) pats) PatternParens pat -> PatternParens (fmap fast pat) TuplePattern pats -> TuplePattern (fmap (fmap fast) pats) EmptyListPattern c -> EmptyListPattern c ListPattern pats -> ListPattern (fmap (fmap fast) pats) ConsPattern first rest -> ConsPattern (fmap fast first) (fmap fast rest) EmptyRecordPattern c -> EmptyRecordPattern c RecordPattern fields -> RecordPattern fields Alias pat name -> Alias (fmap fast pat) name -- Types UnitType c -> UnitType c TypeVariable name -> TypeVariable name TypeConstruction name args forceMultiline -> TypeConstruction (fmap ftyp name) (fmap (fmap fast) args) forceMultiline TypeParens typ -> TypeParens (fmap fast typ) TupleType typs forceMultiline -> TupleType (fmap (fmap fast) typs) forceMultiline RecordType base fields c ml -> RecordType base (fmap (fmap fast) fields) c ml FunctionType first rest ml -> FunctionType (fmap fast first) (fmap fast rest) ml instance I.IFunctor (AST typeRef ctorRef varRef) where -- TODO: it's probably worth making an optimized version of this imap = mapAll id id id -- -- Recursion schemes -- topDownReferencesWithContext :: forall context ns typeRef2 ctorRef2 varRef2 ann kind. Functor ann => Coapplicative ann => (LocalName -> context -> context) -- TODO: since the caller typically passes a function that builds a Map or Set, this could be optimized by taking `List (LocalName)` instead of one at a time -> (context -> (ns, UppercaseIdentifier) -> typeRef2) -> (context -> (ns, UppercaseIdentifier) -> ctorRef2) -> (context -> Ref ns -> varRef2) -> context -> I.Fix ann (AST (ns, UppercaseIdentifier) (ns, UppercaseIdentifier) (Ref ns)) kind -> I.Fix ann (AST typeRef2 ctorRef2 varRef2) kind topDownReferencesWithContext defineLocal fType fCtor fVar initialContext initialAst = let namesFromPattern' :: forall a b c kind'. -- We actually only care about PatternNK' here AST a b c (Const [LocalName]) kind' -> Const [LocalName] kind' namesFromPattern' = \case Anything -> mempty UnitPattern _ -> mempty LiteralPattern _ -> mempty VarPattern l -> Const $ pure $ VarName l OpPattern _ -> mempty DataPattern _ args -> foldMap extract args PatternParens p -> extract p TuplePattern ps -> foldMap extract ps EmptyListPattern _ -> mempty ListPattern ps -> foldMap extract ps ConsPattern p ps -> extract p <> fold ps EmptyRecordPattern _ -> mempty RecordPattern ps -> Const $ fmap (VarName . extract) ps Alias p name -> extract p <> Const (pure $ VarName $ extract name) namesFromPattern :: Coapplicative ann' => I.Fix ann' (AST a b c) kind' -> [LocalName] namesFromPattern = getConst . I.cata (namesFromPattern' . extract) namesFrom :: Coapplicative ann' => I.Fix ann' (AST a b c) kind' -> [LocalName] namesFrom decl = case extract $ I.unFix decl of Definition p _ _ _ -> namesFromPattern p TypeAnnotation _ _ -> mempty CommonDeclaration d -> namesFrom d Datatype (C _ (NameWithArgs name _)) tags -> TypeName name : fmap (\(NameWithArgs name _) -> CtorName name) (toList tags) TypeAlias _ (C _ (NameWithArgs name _)) _ -> [TypeName name] PortAnnotation (C _ name) _ _ -> [VarName name] PortDefinition_until_0_16 (C _ name) _ _ -> [VarName name] Fixity_until_0_18 _ _ _ _ _ -> [] Fixity _ _ _ _ -> [] LetCommonDeclaration d -> namesFrom d LetComment _ -> mempty newDefinitionsAtNode :: forall kind'. AST (ns, UppercaseIdentifier) (ns, UppercaseIdentifier) (Ref ns) (I.Fix ann (AST (ns, UppercaseIdentifier) (ns, UppercaseIdentifier) (Ref ns))) kind' -> [LocalName] newDefinitionsAtNode node = case node of TopLevel decls -> foldMap (foldMap namesFrom) decls CommonDeclaration d -> newDefinitionsAtNode (extract $ I.unFix d) Definition first rest _ _ -> foldMap namesFromPattern (first : fmap extract rest) Lambda args _ _ _ -> foldMap (namesFromPattern . extract) args Let decls _ _ -> foldMap namesFrom decls LetCommonDeclaration d -> newDefinitionsAtNode (extract $ I.unFix d) CaseBranch _ _ _ p _ -> namesFromPattern p -- TODO: actually implement this for all node types _ -> [] step :: forall kind'. context -> AST (ns, UppercaseIdentifier) (ns, UppercaseIdentifier) (Ref ns) (I.Fix ann (AST (ns, UppercaseIdentifier) (ns, UppercaseIdentifier) (Ref ns))) kind' -> AST typeRef2 ctorRef2 varRef2 (Compose ((,) context) (I.Fix ann (AST (ns, UppercaseIdentifier) (ns, UppercaseIdentifier) (Ref ns))) ) kind' step context node = let context' = foldl (flip defineLocal) context (newDefinitionsAtNode node) in mapAll (fType context') (fCtor context') (fVar context') id $ I.imap (Compose . (,) context') node in I.ana (\(Compose (context, ast)) -> step context <$> I.unFix ast) (Compose (initialContext, initialAst))
avh4/elm-format
elm-format-lib/src/AST/V0_16.hs
bsd-3-clause
25,397
0
20
7,045
7,308
3,710
3,598
-1
-1
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE RecordWildCards #-} module Network.Sock.Handler ( sock , sockWS ) where ------------------------------------------------------------------------------ import System.Random (randomRIO) ------------------------------------------------------------------------------ import Control.Monad.Trans (liftIO) ------------------------------------------------------------------------------ import qualified Data.Aeson as AE (encode, object) import Data.Aeson ((.=)) import qualified Data.Binary as BI (encode) import Data.ByteString.Extra (convertBL2BS, convertTS2BL) import qualified Data.Conduit as C import qualified Data.Conduit.TMChan as C (sourceTMChan, sinkTMChan) import Data.Digest.Pure.MD5 (md5) import Data.Monoid import Data.Proxy import qualified Data.Text as TS (Text, isPrefixOf, isInfixOf, isSuffixOf) ------------------------------------------------------------------------------ import qualified Network.HTTP.Types as H import qualified Network.HTTP.Types.Extra as H import qualified Network.HTTP.Types.Request as H import qualified Network.HTTP.Types.Response as H import qualified Network.WebSockets as WS ------------------------------------------------------------------------------ import Network.Sock.Application import Network.Sock.Request import Network.Sock.Server import Network.Sock.Session import Network.Sock.Types.Handler import Network.Sock.Handler.Common (responseOptions) import Network.Sock.Handler.EventSource import Network.Sock.Handler.HTMLFile import Network.Sock.Handler.JSONP import Network.Sock.Handler.WebSocket import Network.Sock.Handler.XHR ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- | sock :: (H.IsRequest req, H.IsResponse res) => req -> Server res sock req = do router <- getServerApplicationRouter case router $ H.requestPath req of Just app -> handleSubroutes app req Nothing -> return H.response404 ------------------------------------------------------------------------------ -- | sockWS :: ServerState -> WS.Request -> WS.WebSockets WS.Hybi00 () sockWS state req = do let router = serverApplicationRouter state case router . H.decodePathSegments $ WS.requestPath req of Just app -> handleSubroutesWS app req Nothing -> WS.rejectRequest req "Invalid path." ------------------------------------------------------------------------------ -- | handleSubroutes :: (H.IsRequest req, H.IsResponse res) => Application (C.ResourceT IO) -> req -> Server res handleSubroutes app req = case (H.requestMethod req, suffix) of -- TODO: Add OPTIONS response. ("GET", []) -> return responseGreeting ("GET", [""]) -> return responseGreeting ("GET", ["info"]) -> responseInfo (applicationSettings app) req ("OPTIONS", ["info"]) -> return $ responseOptions ["OPTIONS", "GET"] req ("GET", [r]) | isIframe r -> return $ responseIframe (applicationSettings app) req (_, [srvrid, sid, trans]) | okID srvrid && okID sid -> responseTransport trans (Request req sid app) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-40 | otherwise -> return H.response404 _ -> return H.response404 where suffix = drop (length . settingsApplicationPrefix $ applicationSettings app) $ H.requestPath req isIframe p = TS.isPrefixOf "iframe" p && TS.isSuffixOf ".html" p okID sid = not (TS.isInfixOf "." sid || sid == "") ------------------------------------------------------------------------------ -- | Used as a response to http://example.com/<application_prefix>/<server_id>/<session_id>/<transport> -- -- Documentation: http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-36 and the following sections. responseTransport :: H.IsResponse res => TS.Text -> Request -> Server res responseTransport trans req = case trans of "websocket" -> return H.response404 -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-50 "xhr" -> handle (Proxy :: Proxy XHRPolling) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-74 "xhr_streaming" -> handle (Proxy :: Proxy XHRStreaming) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-83 "xhr_send" -> handle (Proxy :: Proxy XHRSend) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-74 "eventsource" -> handle (Proxy :: Proxy EventSource) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-91 "htmlfile" -> handle (Proxy :: Proxy HTMLFile) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-100 "jsonp" -> handle (Proxy :: Proxy JSONPPolling) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-108 "jsonp_send" -> handle (Proxy :: Proxy JSONPSend) -- http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-108 _ -> return H.response404 where handle tag = handleReuqest tag req ------------------------------------------------------------------------------ -- | Used as a response to: -- -- * http://example.com/<application_prefix>/ -- * http://example.com/<application_prefix> -- -- Documentation: http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-12 responseGreeting :: H.IsResponse res => res responseGreeting = H.response200 H.headerPlain "Welcome to SockJS!\n" ------------------------------------------------------------------------------ -- | Used as a response to http://example.com/<application_prefix>/iframe*.html -- -- Documentation: http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-15 responseIframe :: (H.IsRequest req, H.IsResponse res) => ApplicationSettings -> req -> res responseIframe appSet req = go . convertTS2BL $ settingsSockURL appSet where go url = case lookup "If-None-Match" (H.requestHeaders req) of (Just s) | s == hashed -> H.response304 _ -> H.response200 headers content where content = "<!DOCTYPE html>\n\ \<html>\n\ \<head>\n\ \ <meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\" />\n\ \ <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n\ \ <script>\n\ \ document.domain = document.domain;\n\ \ _sockjs_onload = function(){SockJS.bootstrap_iframe();};\n\ \ </script>\n\ \ <script src=\"" <> url <> "\"></script>\n\ \</head>\n\ \<body>\n\ \ <h2>Don't panic!</h2>\n\ \ <p>This is a SockJS hidden iframe. It's used for cross domain magic.</p>\n\ \</body>\n\ \</html>" hashed = convertBL2BS . BI.encode $ md5 content headers = H.headerHTML <> H.headerCached <> H.headerETag hashed ------------------------------------------------------------------------------ -- | Used as a response to http://example.com/info -- -- Documentation: http://sockjs.github.com/sockjs-protocol/sockjs-protocol-0.3.html#section-26 responseInfo :: (H.IsRequest req, H.IsResponse res) => ApplicationSettings -> req -> Server res responseInfo appSet req = do ent <- liftIO $ randomRIO ((0, 4294967295) :: (Int, Int)) return . H.response200 (H.headerJSON <> H.headerNotCached <> H.headerCORS "*" req) . AE.encode $ AE.object [ "websocket" .= settingsWebsocketsEnabled appSet , "cookie_needed" .= settingsCookiesNeeded appSet , "origins" .= settingsAllowedOrigins appSet , "entropy" .= ent ] ------------------------------------------------------------------------------ -- | handleSubroutesWS :: Application (C.ResourceT IO) -> WS.Request -> WS.WebSockets WS.Hybi00 () handleSubroutesWS app@Application{..} req = case suffix of [_, _, "websocket"] -> do s <- newSession "wssession" let action = C.runResourceT $ applicationDefinition (C.sourceTMChan $ sessionIncomingBuffer s) (C.sinkTMChan $ sessionOutgoingBuffer s) runApplicationWS app s req -- TODO: Handle raw WebSocket connection. _ -> WS.rejectRequest req "Invalid path." where suffix = drop (length $ settingsApplicationPrefix applicationSettings) . H.decodePathSegments $ WS.requestPath req
Palmik/wai-sockjs
src/Network/Sock/Handler.hs
bsd-3-clause
9,566
0
17
2,406
1,636
888
748
120
9
-- Copyright (c) 2014-present, Facebook, Inc. -- All rights reserved. -- -- This source code is distributed under the terms of a BSD license, -- found in the LICENSE file. {-# LANGUAGE CPP #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE RecordWildCards #-} -- | Psuedo-parallel operations. Most users should import "Haxl.Core" -- instead. -- module Haxl.Core.Parallel ( -- * Parallel operations pAnd , pOr ) where import Haxl.Core.Monad -- ----------------------------------------------------------------------------- -- Parallel operations -- Bind more tightly than .&&, .|| infixr 5 `pAnd` infixr 4 `pOr` -- | Parallel version of '(.||)'. Both arguments are evaluated in -- parallel, and if either returns 'True' then the other is -- not evaluated any further. -- -- WARNING: exceptions may be unpredictable when using 'pOr'. If one -- argument returns 'True' before the other completes, then 'pOr' -- returns 'True' immediately, ignoring a possible exception that -- the other argument may have produced if it had been allowed to -- complete. pOr :: GenHaxl u Bool -> GenHaxl u Bool -> GenHaxl u Bool GenHaxl a `pOr` GenHaxl b = GenHaxl $ \env@Env{..} -> do let !senv = speculate env ra <- a senv case ra of Done True -> return (Done True) Done False -> b env -- not speculative Throw _ -> return ra Blocked ia a' -> do rb <- b senv case rb of Done True -> return rb Done False -> return ra Throw _ -> return rb Blocked _ b' -> return (Blocked ia (Cont (toHaxl a' `pOr` toHaxl b'))) -- Note [pOr Blocked/Blocked] -- This will only wake up when ia is filled, which -- is whatever the left side was waiting for. This is -- suboptimal because the right side might wake up first, -- but handling this non-determinism would involve a much -- more complicated implementation here. -- | Parallel version of '(.&&)'. Both arguments are evaluated in -- parallel, and if either returns 'False' then the other is -- not evaluated any further. -- -- WARNING: exceptions may be unpredictable when using 'pAnd'. If one -- argument returns 'False' before the other completes, then 'pAnd' -- returns 'False' immediately, ignoring a possible exception that -- the other argument may have produced if it had been allowed to -- complete. pAnd :: GenHaxl u Bool -> GenHaxl u Bool -> GenHaxl u Bool GenHaxl a `pAnd` GenHaxl b = GenHaxl $ \env@Env{..} -> do let !senv = speculate env ra <- a senv case ra of Done False -> return (Done False) Done True -> b env Throw _ -> return ra Blocked ia a' -> do rb <- b senv case rb of Done False -> return rb Done True -> return ra Throw _ -> return rb Blocked _ b' -> return (Blocked ia (Cont (toHaxl a' `pAnd` toHaxl b'))) -- See Note [pOr Blocked/Blocked]
simonmar/Haxl
Haxl/Core/Parallel.hs
bsd-3-clause
2,905
0
24
699
566
285
281
40
7
{-# LANGUAGE ViewPatterns #-} module Transform.Extract.Glyph ( extractor ) where import Hoops.Match import Hoops.SyntaxToken import Transform.Extract.Common import Transform.Extract.Util extractor :: BlockKind -> ExtractFunc extractor kind = case kind of "HC_Define_Glyph" -> extract _ -> const $ return Nothing extract :: ExtractFunc extract = let definition = match "definition[$!int] = (char) $int;" glyph = match "HC_Define_Glyph($str, $!int, $!var);" -- go :: Entry -> ListsExtractFunc IntegersT go entry tokens = case tokens of (definition -> CapturesRest [Integer num] rest) -> do modifyIntegers $ (num :) go entry rest (glyph -> CapturesRest [String name] rest) -> do lift $ tellEntry entry $ "Glyph (" ++ show name ++ " (" go entry rest _ : rest -> go entry rest [] -> return $ Just $ cgsReadMetafile (entryPath entry) Nothing in \tokens -> scopedEntry "glyph" "hmf" $ \entry -> evalListsExtractor $ do res <- go entry tokens vals <- fmap reverse $ gets integers lift $ do tellEntry entry $ unwords $ map show vals tellEntry entry "))" return res
thomaseding/cgs
src/Transform/Extract/Glyph.hs
bsd-3-clause
1,240
0
18
351
368
180
188
32
4
module Data.Blockchain.Crypto.Hash ( Hash , ToHash(..) , hashToHex , fromByteString , unsafeFromByteString ) where import qualified Crypto.Hash as Crypto import qualified Data.Aeson as Aeson import qualified Data.ByteArray.Encoding as Byte import qualified Data.ByteString as BS import qualified Data.ByteString.Lazy as Lazy import qualified Data.Hashable as H import qualified Data.Maybe as Maybe import qualified Data.Text as Text import qualified Data.Text.Encoding as Text import qualified Data.Blockchain.Types.Hex as Hex -- Types ----------------------------------------------------------------------------------------------------- newtype Hash a = Hash { unHash :: Crypto.Digest Crypto.SHA256 } deriving (Eq, Ord) instance H.Hashable (Hash a) where hashWithSalt _ = H.hash . show instance Show (Hash a) where show = show . unHash instance Aeson.ToJSON (Hash a) where toJSON = Aeson.String . Text.pack . show . unHash instance Aeson.FromJSON (Hash a) where parseJSON = Aeson.withText "Hash" $ maybe (fail "Invalid bytestring hash") return . fromByteString . Text.encodeUtf8 instance Monoid (Hash a) where mempty = Hash $ Crypto.hash (mempty :: BS.ByteString) mappend (Hash h1) (Hash h2) = Hash $ Crypto.hashFinalize $ Crypto.hashUpdates Crypto.hashInit [h1, h2] class ToHash a where hash :: a -> Hash a default hash :: Aeson.ToJSON a => a -> Hash a hash = Hash . Crypto.hash . Lazy.toStrict . Aeson.encode instance ToHash BS.ByteString where hash = Hash . Crypto.hash -- Utils ----------------------------------------------------------------------------------------------------- -- Note: ignore all possible invariants that `Numeric.readHex` would normally need to check. -- We are only converting string-ified hashes, which should always be valid hex strings. hashToHex :: Hash a -> Hex.Hex256 hashToHex = Maybe.fromMaybe (error "Unexpected hex conversion failure") . Hex.hex256 . show . unHash fromByteString :: BS.ByteString -> Maybe (Hash a) fromByteString bs = case Byte.convertFromBase Byte.Base16 bs of Left _ -> Nothing Right bs' -> Hash <$> Crypto.digestFromByteString (bs' :: BS.ByteString) unsafeFromByteString :: BS.ByteString -> Hash a unsafeFromByteString = Maybe.fromMaybe (error "Invalid hash string") . fromByteString
TGOlson/blockchain
lib/Data/Blockchain/Crypto/Hash.hs
bsd-3-clause
2,438
0
11
491
616
342
274
-1
-1
{-# LANGUAGE RecordWildCards #-} {-# LANGUAGE UndecidableInstances #-} {-# OPTIONS_GHC -Wno-unused-top-binds #-} module GeneratedColumnTestSQL (specsWith) where import Database.Persist.TH import Init share [mkPersist sqlSettings, mkMigrate "migrate1"] [persistLowerCase| GenTest sql=gen_test fieldOne Text Maybe fieldTwo Text Maybe fieldThree Text Maybe generated=COALESCE(field_one,field_two) deriving Show Eq MigrateTestV1 sql=gen_migrate_test sickness Int cromulence Int generated=5 |] share [mkPersist sqlSettings, mkMigrate "migrate2"] [persistLowerCase| MigrateTestV2 sql=gen_migrate_test sickness Int generated=3 cromulence Int |] specsWith :: Runner SqlBackend m => RunDb SqlBackend m -> Spec specsWith runDB = describe "PersistLiteral field" $ do it "should read a generated column" $ runDB $ do rawExecute "DROP TABLE IF EXISTS gen_test;" [] rawExecute "DROP TABLE IF EXISTS gen_migrate_test;" [] runMigration migrate1 insert_ GenTest { genTestFieldOne = Just "like, literally this exact string" , genTestFieldTwo = Just "like, totally some other string" , genTestFieldThree = Nothing } Just (Entity _ GenTest{..}) <- selectFirst [] [] liftIO $ genTestFieldThree @?= Just "like, literally this exact string" k1 <- insert $ MigrateTestV1 0 0 Just (MigrateTestV1 sickness1 cromulence1) <- get k1 liftIO $ sickness1 @?= 0 liftIO $ cromulence1 @?= 5 it "should support adding or removing generation expressions from columns" $ runDB $ do runMigration migrate2 k2 <- insert $ MigrateTestV2 0 0 Just (MigrateTestV2 sickness2 cromulence2) <- get k2 liftIO $ sickness2 @?= 3 liftIO $ cromulence2 @?= 0
paul-rouse/persistent
persistent-test/src/GeneratedColumnTestSQL.hs
mit
1,806
0
16
417
364
173
191
-1
-1
-- -- -- ------------------ -- Exercise 11.22. ------------------ -- -- -- module E'11'22 where -- mapFuns :: [a -> b] -> a -> [b] -- mapFuns functions argument -- -- = map (\function -> function argument) functions -- My first step: mapFuns'1 :: [a -> b] -> a -> [b] mapFuns'1 functions = \argument -> ( ($ argument) `map` functions ) -- My second (final) step: mapFuns' :: [a -> b] -> a -> [b] mapFuns' = flip ( \argument -> ( ($ argument) `map` ) ) {- GHCi> mapFuns' [(+1)] 0 -} -- [1] -- Other solutions for "mapFuns": mapFuns'' :: [a -> b] -> a -> [b] mapFuns'' = \functions argument -> ($ argument) `map` functions mapFuns'3 :: [a -> b] -> a -> [b] mapFuns'3 functions = \argument -> ($ argument) `map` functions mapFuns'4 :: [a -> b] -> a -> [b] mapFuns'4 = \functions argument -> zipWith ($) functions $ repeat argument mapFuns'5 :: [a -> b] -> a -> [b] mapFuns'5 functions = \argument -> (flip map) functions ($ argument) mapFuns'6 :: [a -> b] -> a -> [b] mapFuns'6 = \functions argument -> (\function -> function argument) `map` functions -- mapFuns'7 :: a -> [a -> b] -> [b] -- mapFuns'7 argument -- -- = ( ($ argument) `map` )
pascal-knodel/haskell-craft
_/links/E'11'22.hs
mit
1,205
0
9
282
367
223
144
21
1
{-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} import Language.Haskell.TH (runIO) import Control.Monad (forM_) import Text.Printf (printf) import System.Environment (getArgs) import qualified Satchmo.Core.SAT.Minisat import qualified Satchmo.Core.Decode import CO4 import CO4.Prelude import CO4.Example.SudokuStandalone $( compileFile [Cache,ImportPrelude] "test/CO4/Example/SudokuStandalone.hs" ) uUnary 0 = knownZ uUnary i = union knownZ $ knownS $ uUnary $ i-1 matrixAllocator n a = kList n $ kList n a blockAllocator n = matrixAllocator n $ uUnary $ (n*n) - 1 boardAllocator n = matrixAllocator n $ blockAllocator n fromUnary :: Unary -> Int fromUnary u = case u of Z -> 0 S u' -> 1 + (fromUnary u') result :: Int -> IO () result n = do result <- solveAndTest (boardAllocator n) encConstraint constraint case result of Nothing -> putStrLn "none" Just b -> forM_ (rows b $ unaryLength b) $ putStrLn . concatMap (printf "%3i " . fromUnary) main :: IO () main = getArgs >>= result . read . head
apunktbau/co4
test/CO4/Example/Sudoku.hs
gpl-3.0
1,191
0
15
266
375
193
182
32
2
-------------------------------------------------------------------- -- | -- Module : Flickr.Groups.Pools -- Description : flickr.groups.pools - manage photo group pooling. -- Copyright : (c) Sigbjorn Finne, 2008 -- License : BSD3 -- -- Maintainer : Sigbjorn Finne <[email protected]> -- Stability : provisional -- Portability : portable -- -- flickr.groups.pools API, manage photo group pooling. -------------------------------------------------------------------- module Flickr.Groups.Pools where import Flickr.Monad import Flickr.Types import Flickr.Types.Import import Control.Monad ( liftM ) -- | Add a photo to a group's pool. add :: PhotoID -> GroupID -> FM () add pid gid = withWritePerm $ postMethod $ do flickCall_ "flickr.groups.pools.add" [ ("photo_id", pid) , ("group_id", gid) ] -- | Returns next and previous photos for a photo in a group pool. getContext :: PhotoID -> GroupID -> FM (Photo,Photo) getContext pid gid = flickTranslate toPhotoPair $ flickrCall "flickr.groups.pools.getContext" [ ("photo_id", pid) , ("group_id", gid) ] -- | Returns a list of groups to which you can add photos. getGroups :: FM [Group] getGroups = flickTranslate toGroupList $ flickrCall "flickr.groups.pools.getGroups" [] -- | Returns a list of pool photos for a given group, -- based on the permissions of the group and the user logged in (if any). getPhotos :: GroupID -> [Tag] -> Maybe UserID -> [PhotoInfo] -> FM [Photo] getPhotos gid ts uid ps = liftM snd $ flickTranslate toPhotoList $ flickrCall "flickr.groups.Pools.getPhotos" (lsArg "tags" ts $ mbArg "user_id" uid $ lsArg "extras" (map show ps) [ ("group_id", gid) ]) -- | Remove a photo from a group pool. remove :: PhotoID -> GroupID -> FM () remove pid gid = withWritePerm $ postMethod $ flickCall_ "flickr.groups.pools.remove" [ ("photo_id", pid) , ("group_id", gid) ]
BeautifulDestinations/hs-flickr
Flickr/Groups/Pools.hs
bsd-3-clause
2,023
12
11
464
391
217
174
34
1
-- | -- Module : Foundation.System.Entropy.Unix -- License : BSD-style -- Maintainer : Vincent Hanquez <[email protected]> -- Stability : experimental -- Portability : Good -- {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE ForeignFunctionInterface #-} module Foundation.System.Entropy.Unix ( EntropyCtx , entropyOpen , entropyGather , entropyClose , entropyMaximumSize ) where import Foreign.Ptr import Control.Exception as E import Control.Monad import System.IO import System.IO.Unsafe (unsafePerformIO) import Basement.Compat.Base import Basement.Compat.C.Types import Prelude (fromIntegral) import Foundation.System.Entropy.Common import Foundation.Numerical data EntropyCtx = EntropyCtx Handle | EntropySyscall entropyOpen :: IO EntropyCtx entropyOpen = do if supportSyscall then return EntropySyscall else do mh <- openDev "/dev/urandom" case mh of Nothing -> E.throwIO EntropySystemMissing Just h -> return $ EntropyCtx h -- | try to fill the ptr with the amount of data required. -- Return the number of bytes, or a negative number otherwise entropyGather :: EntropyCtx -> Ptr Word8 -> Int -> IO Bool entropyGather (EntropyCtx h) ptr n = gatherDevEntropy h ptr n entropyGather EntropySyscall ptr n = (==) 0 <$> c_sysrandom_linux ptr (fromIntegral n) entropyClose :: EntropyCtx -> IO () entropyClose (EntropyCtx h) = hClose h entropyClose EntropySyscall = return () entropyMaximumSize :: Int entropyMaximumSize = 4096 openDev :: [Char] -> IO (Maybe Handle) openDev filepath = (Just `fmap` openAndNoBuffering) `E.catch` \(_ :: IOException) -> return Nothing where openAndNoBuffering = do h <- openBinaryFile filepath ReadMode hSetBuffering h NoBuffering return h gatherDevEntropy :: Handle -> Ptr Word8 -> Int -> IO Bool gatherDevEntropy h ptr sz = loop ptr sz `E.catch` failOnException where loop _ 0 = return True loop p n = do r <- hGetBufSome h p n if r >= 0 then loop (p `plusPtr` r) (n - r) else return False failOnException :: E.IOException -> IO Bool failOnException _ = return False supportSyscall :: Bool supportSyscall = unsafePerformIO ((==) 0 <$> c_sysrandom_linux nullPtr 0) {-# NOINLINE supportSyscall #-} -- return 0 on success, !0 for failure foreign import ccall unsafe "foundation_sysrandom_linux" c_sysrandom_linux :: Ptr Word8 -> CSize -> IO Int
vincenthz/hs-foundation
foundation/Foundation/System/Entropy/Unix.hs
bsd-3-clause
2,510
0
14
561
624
332
292
59
3
{-# LANGUAGE TypeOperators #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleInstances #-} module Main where import Prelude hiding (lookup) import Char (ord) import qualified Data.Map as Map import Control.Monad ((>=>)) import Generics.Instant -- Generalized tries, as from http://www.haskell.org/haskellwiki/GHC/Type_families#An_associated_data_type_example class Representable k => GMapKey k where data GMap k :: * -> * empty :: GMap k v lookup :: k -> GMap k v -> Maybe v insert :: k -> v -> GMap k v -> GMap k v instance GMapKey Int where data GMap Int v = GMapInt (Map.Map Int v) empty = GMapInt Map.empty lookup k (GMapInt m) = Map.lookup k m insert k v (GMapInt m) = GMapInt (Map.insert k v m) instance GMapKey Char where data GMap Char v = GMapChar (GMap Int v) empty = GMapChar empty lookup k (GMapChar m) = lookup (ord k) m insert k v (GMapChar m) = GMapChar (insert (ord k) v m) instance GMapKey U where data GMap U v = GMapUnit (Maybe v) empty = GMapUnit Nothing lookup U (GMapUnit v) = v insert U v (GMapUnit _) = GMapUnit $ Just v instance (GMapKey a, GMapKey b) => GMapKey (a :*: b) where data GMap (a :*: b) v = GMapProd (GMap a (GMap b v)) empty = GMapProd empty lookup (a :*: b) (GMapProd gm) = lookup a gm >>= lookup b insert (a :*: b) v (GMapProd gm) = GMapProd $ case lookup a gm of Nothing -> insert a (insert b v empty) gm Just gm2 -> insert a (insert b v gm2 ) gm instance (GMapKey a, GMapKey b) => GMapKey (a :+: b) where data GMap (a :+: b) v = GMapSum (GMap a v) (GMap b v) empty = GMapSum empty empty lookup (L a) (GMapSum gm1 _gm2) = lookup a gm1 lookup (R b) (GMapSum _gm1 gm2 ) = lookup b gm2 insert (L a) v (GMapSum gm1 gm2) = GMapSum (insert a v gm1) gm2 insert (R a) v (GMapSum gm1 gm2) = GMapSum gm1 (insert a v gm2) -- Uninteresting cases, but necessary instance (GMapKey a) => GMapKey (CEq c p q a) where data GMap (CEq c p q a) v = GMapCon (GMap a v) empty = GMapCon empty lookup (C c) (GMapCon m) = lookup c m insert (C c) v (GMapCon m) = GMapCon (insert c v m) instance (GMapKey a) => GMapKey (Var a) where data GMap (Var a) v = GMapVar (GMap a v) empty = GMapVar empty lookup (Var x) (GMapVar m) = lookup x m insert (Var x) v (GMapVar m) = GMapVar (insert x v m) instance (GMapKey a) => GMapKey (Rec a) where data GMap (Rec a) v = GMapRec (GMap a v) empty = GMapRec empty lookup (Rec x) (GMapRec m) = lookup x m insert (Rec x) v (GMapRec m) = GMapRec (insert x v m) -- Boilerplate code, but unavoidable (for now) instance GMapKey k => GMapKey [k] where data GMap [k] v = GMapList (GMap (Rep [k]) v) empty = GMapList empty lookup k (GMapList m) = lookup (from k) m insert k v (GMapList m) = GMapList (insert (from k) v m) -- Example t1 :: Maybe String t1 = lookup [1,2,3] $ insert ([1..3] :: [Int]) "[1,2,3]" $ empty
dreixel/instant-generics
examples/GMapAssoc.hs
bsd-3-clause
3,277
0
12
1,012
1,399
705
694
68
1
-------------------------------------------------------------------- -- | -- Module : Flickr.People -- Description : flickr.people - access a user's attributes etc. -- Copyright : (c) Sigbjorn Finne, 2008 -- License : BSD3 -- -- Maintainer : Sigbjorn Finne <[email protected]> -- Stability : provisional -- Portability : portable -- -- flickr.people API, accessing a user's attributes etc. -- <http://www.flickr.com/services/api/> -------------------------------------------------------------------- module Flickr.People where import Flickr.Monad import Flickr.Types import Flickr.Types.Import import Flickr.Utils import Text.XML.Light.Proc ( findChild ) import Control.Monad -- | Return a user's NSID, given their email address findByEmail :: {-EMail-}String -> FM User findByEmail e = flickTranslate toUser $ flickrCall "flickr.people.findByEmail" [ ("find_email", e) ] -- | Return a user's NSID, given their username. findByUsername :: UserName -> FM User findByUsername u = flickTranslate toUser $ flickrCall "flickr.people.findByUsername" [ ("username", u) ] -- | Get information about a user. getInfo :: UserID -> Bool -> FM User getInfo uid authCall = (if authCall then withReadPerm else id) $ do flickTranslate toUser $ flickCall "flickr.people.getInfo" [ ("user_id", uid) ] -- | Returns the list of public groups a user is a member of. getPublicGroups :: UserID -> FM [Group] getPublicGroups uid = flickTranslate toGroupList $ flickrCall "flickr.people.getPublicGroups" [ ("user_id", uid) ] -- | Get a list of public photos for the given user. getPublicPhotos :: UserID -> Maybe Safety -> [PhotoInfo] -> FM [Photo] getPublicPhotos uid s ps = liftM snd $ flickTranslate toPhotoList $ flickrCall "flickr.people.getPublicPhotos" (mbArg "safe_search" (fmap (show.succ.fromEnum) s) $ lsArg "extras" (map show ps) [ ("user_id", uid) ]) -- | Returns information for the calling user related to photo uploads. getUploadStatus :: FM (User, Bandwidth, FileSize, PhotosetQuota) getUploadStatus = flickTranslate toRes $ flickrCall "flickr.people.getUploadStatus" [] where toRes s = parseDoc eltRes s eltRes e = do u <- eltUser e b <- findChild (nsName "bandwidth") e >>= eltBandwidth f <- findChild (nsName "filesize") e >>= eltFileSize s <- findChild (nsName "sets") e >>= eltPhotosetQuota return (u,b,f,s)
sof/flickr
Flickr/People.hs
bsd-3-clause
2,495
4
14
508
527
282
245
45
2
{-# LANGUAGE PartialTypeSignatures #-} module T10403 where data I a = I a instance Functor I where fmap f (I a) = I (f a) newtype B t a = B a instance Functor (B t) where fmap f (B a) = B (f a) newtype H f = H (f ()) app :: H (B t) app = h (H . I) (B ()) h :: _ => _ --h :: Functor m => (a -> b) -> m a -> H m h f b = (H . fmap (const ())) (fmap f b)
fmthoma/ghc
testsuite/tests/partial-sigs/should_compile/T10403.hs
bsd-3-clause
364
0
11
109
203
107
96
13
1
{- | Copyright : Copyright (C) 2006-2018 Bjorn Buckwalter License : BSD3 Maintainer : [email protected] Stability : Stable Defines convenience functions for inspecting and manipulating quantities with 'RealFloat' floating-point representations. The dimensionally-typed versions of functions from Patrick Perry's @ieee754@ package copy that package's API as closely as possible, by permission. In turn they are based on the @tango@ math library for the D language. -} {-# LANGUAGE ScopedTypeVariables #-} module Numeric.Units.Dimensional.Float ( -- * Lifted Predicates from 'RealFloat' isDenormalized, isInfinite, isNaN, isNegativeZero -- * Convenience Functions , isFiniteNumber, scaleFloat -- * Lifted Functions from "Numeric.IEEE" -- ** Values , infinity, minNormal, maxFinite, epsilon, nan -- ** Arithmetic , predIEEE, succIEEE, bisectIEEE, copySign -- ** NaN with Payload , nanWithPayload, nanPayload, F.maxNaNPayload -- ** Comparisons , identicalIEEE, minNum, maxNum, minNaN, maxNaN ) where import Control.Applicative import Data.Word (Word64) import Prelude (RealFloat) import qualified Prelude as P import Numeric.IEEE (IEEE) import qualified Numeric.IEEE as F import Numeric.Units.Dimensional.Internal (liftQ, liftQ2) import Numeric.Units.Dimensional.Prelude hiding (RealFloat(..)) import Numeric.Units.Dimensional.Coercion -- $setup -- >>> :set -XExtendedDefaultRules -- >>> :set -XNegativeLiterals -- | 'True' if the representation of the argument is too small to be represented in normalized format. isDenormalized :: RealFloat a => Quantity d a -> Bool isDenormalized = P.isDenormalized . unQuantity -- | 'True' if the representation of the argument is a number and is not infinite. -- -- >>> isFiniteNumber (_1 / _0) -- False -- -- >>> isFiniteNumber (_0 / _0) -- False -- -- >>> isFiniteNumber (_3 / _2) -- True isFiniteNumber :: RealFloat a => Quantity d a -> Bool isFiniteNumber = not . liftA2 (||) isNaN isInfinite -- | 'True' if the representation of the argument is an IEEE infinity or negative infinity. -- -- >>> isInfinite (_1 / _0) -- True -- -- >>> isInfinite (42 *~ micro farad) -- False isInfinite :: RealFloat a => Quantity d a -> Bool isInfinite = P.isInfinite . unQuantity -- | 'True' if the representation of the argument is an IEEE "not-a-number" (NaN) value. -- -- >>> isNaN _3 -- False -- -- >>> isNaN (_1 / _0) -- False -- -- >>> isNaN (asin _4) -- True isNaN :: RealFloat a => Quantity d a -> Bool isNaN = P.isNaN . unQuantity -- | 'True' if the representation of the argument is an IEEE negative zero. -- -- >>> isNegativeZero _0 -- False -- -- >>> isNegativeZero $ (-1e-200 *~ one) * (1e-200 *~ one) -- True isNegativeZero :: RealFloat a => Quantity d a -> Bool isNegativeZero = P.isNegativeZero . unQuantity -- | Multiplies a floating-point quantity by an integer power of the radix of the representation type. -- -- Use 'P.floatRadix' to determine the radix. -- -- >>> let x = 3 *~ meter -- >>> scaleFloat 3 x -- 24.0 m scaleFloat :: RealFloat a => Int -> Quantity d a -> Quantity d a scaleFloat x = Quantity . P.scaleFloat x . unQuantity -- | An infinite floating-point quantity. infinity :: IEEE a => Quantity d a infinity = Quantity F.infinity -- | The smallest representable positive quantity whose representation is normalized. minNormal :: IEEE a => Quantity d a minNormal = Quantity F.minNormal -- | The largest representable finite floating-point quantity. maxFinite :: IEEE a => Quantity d a maxFinite = Quantity F.maxFinite -- | The smallest positive value @x@ such that @_1 + x@ is representable. epsilon :: IEEE a => Dimensionless a epsilon = Quantity F.epsilon -- | @copySign x y@ returns the quantity @x@ with its sign changed to match that of @y@. copySign :: IEEE a => Quantity d a -> Quantity d a -> Quantity d a copySign = liftQ2 F.copySign -- | Return 'True' if two floating-point quantities are /exactly/ (bitwise) equal. identicalIEEE :: IEEE a => Quantity d a -> Quantity d a -> Bool identicalIEEE (Quantity x) (Quantity y) = F.identicalIEEE x y -- | Return the next largest representable floating-point quantity (@Infinity@ and @NaN@ are unchanged). succIEEE :: IEEE a => Quantity d a -> Quantity d a succIEEE = liftQ F.succIEEE -- | Return the next smallest representable floating-point quantity (@Infinity@ and @NaN@ are unchanged). predIEEE :: IEEE a => Quantity d a -> Quantity d a predIEEE = liftQ F.predIEEE -- | Given two floating-point quantities with the same sign, return the quantity whose representation is halfway -- between their representations on the IEEE number line. If the signs of the values differ or either is @NaN@, -- the value is undefined. bisectIEEE :: IEEE a => Quantity d a -> Quantity d a -> Quantity d a bisectIEEE (Quantity x) (Quantity y) = Quantity $ F.bisectIEEE x y -- | Default @NaN@ quantity. nan :: IEEE a => Quantity d a nan = Quantity F.nan -- | Quiet @NaN@ quantity with a positive integer payload. -- Payload must be less than 'maxNaNPayload' of the representation type. -- -- Beware that while some platforms allow using 0 as a payload, this behavior is not portable. nanWithPayload :: IEEE a => Word64 -> Quantity d a nanWithPayload = Quantity . F.nanWithPayload -- | The payload stored in a @NaN@ quantity. Undefined if the argument is not @NaN@. nanPayload :: IEEE a => Quantity d a -> Word64 nanPayload = F.nanPayload . unQuantity -- | Return the minimum of two quantities; if one value is @NaN@, return the other. Prefer the first if both values are @NaN@. minNum :: RealFloat a => Quantity d a -> Quantity d a -> Quantity d a minNum = liftQ2 F.minNum -- | Return the maximum of two quantities; if one value is @NaN@, return the other. Prefer the first if both values are @NaN@. maxNum :: RealFloat a => Quantity d a -> Quantity d a -> Quantity d a maxNum = liftQ2 F.maxNum -- | Return the minimum of two quantities; if one value is @NaN@, return it. Prefer the first if both values are @NaN@. minNaN :: RealFloat a => Quantity d a -> Quantity d a -> Quantity d a minNaN = liftQ2 F.minNaN -- | Return the maximum of two quantities; if one value is @NaN@, return it. Prefer the first if both values are @NaN@. maxNaN :: RealFloat a => Quantity d a -> Quantity d a -> Quantity d a maxNaN = liftQ2 F.maxNaN
bjornbm/dimensional-dk
src/Numeric/Units/Dimensional/Float.hs
bsd-3-clause
6,285
0
8
1,117
1,081
590
491
62
1
{-# LANGUAGE BangPatterns #-} module PermutationsCombinations where -- I was reading http://home.pipeline.com/~hbaker1/ThermoGC.html at the time I wrote this and trying to convince myself -- that negative temperature is a thing by demonstrating that (adiff 1e-4 (\x -> bCombineEnergies 4000 [x]) y) is -- negative for y > 2000. (Spoilers: it indeed is.) import Foreign.C.Types (CInt) import Foreign.Marshal.Alloc (alloca) import Foreign.Storable (peek) import Foreign.Ptr (Ptr) import System.IO.Unsafe (unsafeDupablePerformIO) foreign import ccall unsafe "lgamma_r" lgamma_r_ :: Double -> Ptr CInt -> IO Double foreign import ccall unsafe "lgammaf_r" lgammaf_r_ :: Float -> Ptr CInt -> IO Float lgamma :: Double -> (Double, Int) lgamma x = unsafeDupablePerformIO . alloca $ \signp -> do output <- lgamma_r_ x signp sign <- peek signp return (output, fromEnum sign) lgammaf :: Float -> (Float, Int) lgammaf x = unsafeDupablePerformIO . alloca $ \signp -> do output <- lgammaf_r_ x signp sign <- peek signp return (output, fromEnum sign) lgamp :: Double -> Double lgamp x | x < 0 = error "tried to ignore sign of lgamma on negative value" lgamp x | otherwise = fst (lgamma x) -- permutations n p = number of different sequences of length p that can be drawn from a set of n distinct elements permutations n p = exp (lpermutations n p) -- log(permutations n p) lpermutations n p = lgamp (1+n) - lgamp (1+n-p) -- log2(permutations n p) bpermutations n p = (lpermutations n p) / (log 2) -- combinations n p = number of different sets of size p that can be drawn from a set of n distinct elements combinations n p = exp (lcombinations n p) -- log(combinations n p) lcombinations n p = lgamp (1+n) - lgamp (1+p) - lgamp (1+n-p) -- log2(combinations n p) bcombinations n p = (lcombinations n p) / (log 2) -- binary logarithm of number of possible states that a system can be in (i.e. entropy of that system in bits): -- + when there are `n` particles, -- + and `n - sum eLevels` of them are in the ground state -- + and [eLevels !! 0] are in state 1, [eLevels !! 1] are in state 2, and so on. -- -- At least I am almost sure that's what this calculates, anyway. -- bCombineEnergies n eLevels = (lCombineEnergies n eLevels) / (log 2) -- same as bCombineEnergies but in units of e rather than bits lCombineEnergies n eLevels = go n 0 eLevels where go !n !ac eLevels | n < 0 = error "ran out of pigeonholes!" go !n !ac [] = ac go !n !ac (eLevel:eLevels) = go (n - eLevel) (ac + lcombinations n eLevel) eLevels -- (crappy) approximate differential of `f` at point `x`, using an interval of `h` to measure it adiff h f x = (f (x + h) - f x) / h
RichardBarrell/snippets
PermutationsCombinations.hs
isc
2,701
0
11
544
692
354
338
34
3
{- HAAP: Haskell Automated Assessment Platform This module provides the @Rank@ plugin to generate rankings as HTML webpages. -} {-# LANGUAGE FlexibleContexts, OverloadedStrings, GeneralizedNewtypeDeriving #-} module HAAP.Web.Test.Rank where import HAAP.Core import HAAP.Pretty import HAAP.Test.Spec import HAAP.Test.Rank import HAAP.Utils import HAAP.Web.Hakyll import HAAP.IO import HAAP.Plugin import Data.Traversable import Data.List import qualified Data.Text as T import qualified Control.Monad.Reader as Reader import Control.Monad.IO.Class renderHaapRank :: (HasPlugin Rank t m,HasPlugin Hakyll t m,Pretty a,Score score) => HaapRank t m a score -> Haap t m FilePath renderHaapRank rank = do scores <- runHaapRank rank renderHaapRankScores rank scores renderHaapSpecRank :: (HasPlugin Spec t m,MonadIO m,HasPlugin Rank t m,HasPlugin Hakyll t m,Pretty a,Score score) => HaapSpecRank t m a score -> Haap t m FilePath renderHaapSpecRank rank = do scores <- runHaapSpecRank rank renderHaapRankScores (haapSpecRank rank) scores renderHaapRankScores :: (HasPlugin Rank t m,HasPlugin Hakyll t m,Pretty a,Score score) => HaapRank t m a score -> HaapRankRes a score -> Haap t m FilePath renderHaapRankScores rank scores = do hp <- getHakyllP hakyllFocus ["templates"] $ hakyllRules $ create [fromFilePath $ rankPath rank] $ do route $ idRoute `composeRoutes` funRoute (hakyllRoute hp) compile $ do let headerCtx = field "header" (return . itemBody) let colCtx = field "col" (return . scoreShow . snd . itemBody) `mappend` field "header" (return . prettyString . fst . itemBody) `mappend` constField "ranktag" (T.unpack $ rankTag rank) `mappend` field "class" (return . scoreClass . snd . itemBody) let rowCtx = field "id" (return . prettyString . fst3 . itemBody) `mappend` listFieldWith "cols" colCtx (mapM makeItem . snd3 . itemBody) `mappend` constField "ranktag" (T.unpack $ rankTag rank) `mappend` field "score" (return . scoreShow . Just . thr3 . itemBody) `mappend` field "class" (return . scoreClass . Just . thr3 . itemBody) let pageCtx :: Context String pageCtx = constField "title" (T.unpack $ rankTitle rank) `mappend` constField "notes" (T.unpack $ rankNotes rank) `mappend` constField "projectpath" (fileToRoot $ hakyllRoute hp $ rankPath rank) `mappend` constField "idtag" (T.unpack $ rankIdTag rank) `mappend` constField "ranktag" (T.unpack $ rankTag rank) `mappend` listField "headers" headerCtx (mapM makeItem headers) `mappend` listField "rows" rowCtx (mapM makeItem scores') makeItem "" >>= loadAndApplyHTMLTemplate "templates/ranks.html" pageCtx >>= hakyllCompile hp return $ hakyllRoute hp $ rankPath rank where scores' = map (mapSnd3 (zipLeft headernums)) scores numscores [] = 0 numscores (x:xs) = max (length $ snd3 x) (numscores xs) headernums = if numscores scores == 0 then [] else [1..numscores scores] headers = case rankHeaders rank of Nothing -> map show headernums Just xs -> map T.unpack xs scoreClass Nothing = "hspec-failure" scoreClass (Just x) = if okScore x then "hspec-success" else "hspec-failure" scoreShow Nothing = "-" scoreShow (Just x) = prettyString x
hpacheco/HAAP
src/HAAP/Web/Test/Rank.hs
mit
3,587
0
25
928
1,103
562
541
60
7
------------------------------------------------------------ ---- | ---- Module: School ---- Description: School records accounting ---- Copyright: (c) 2015 Alex Dzyoba <[email protected]> ---- License: MIT ------------------------------------------------------------ module School (School, empty, add, grade, sorted) where import Data.List (sort, nub) type Grade = Int type Name = String data School = Empty | School [(Grade, Name)] deriving Show -- | School type access. -- -- Get the list of school records. -- This is used instead of record syntax, -- because we must return [] for Empty -- list :: School -> [(Grade, Name)] list Empty = [] list (School x) = x -- | Return empty School. So sad... empty :: School empty = Empty -- | Add a new student to a school grade add :: Grade -> Name -> School -> School add grade name Empty = School [(grade, name)] add grade name school = School $ list school ++ [(grade, name)] -- | List students in grade in alphabetical order grade :: Grade -> School -> [Name] grade inGrade school = sort [ n | (g, n) <- list school, g == inGrade ] -- | List of school grades (sorted) grades :: School -> [Grade] grades s = nub . sort $ [ g | (g, n) <- list s ] -- | Glue students list to the grade studentsOfGrade :: School -> Grade -> (Grade, [Name]) studentsOfGrade school inGrade = (inGrade, grade inGrade school) -- | Sort school records by grades AND names sorted :: School -> [(Grade, [Name])] sorted school = map (studentsOfGrade school) (grades school)
dzeban/haskell-exercism
grade-school/School.hs
mit
1,524
0
9
284
407
236
171
22
1
lend amount balance = let reserve = 100 newBalance = balance - amount in if balance < reserve then Nothing else Just newBalance lend2 amount balance if amount < reserve then Just newbalance else Nothing where reserve = 100 newbalance = balance - amount
akampjes/learning-realworldhaskell
ch03/Lending.hs
mit
414
1
9
205
90
44
46
-1
-1
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} ------------------------------------------- -- | -- Module : Web.Stripe.Recipient -- Copyright : (c) David Johnson, 2014 -- Maintainer : [email protected] -- Stability : experimental -- Portability : POSIX -- -- < https:/\/\stripe.com/docs/api#recipients > -- -- @ -- {-\# LANGUAGE OverloadedStrings \#-} -- import Web.Stripe -- import Web.Stripe.Recipient -- -- main :: IO () -- main = do -- let config = StripeConfig (StripeKey "secret_key") -- result <- stripe config $ -- createRecipient (Name "simon marlow") -- Individual -- case result of -- Right recipient -> print recipient -- Left stripeError -> print stripeError -- @ module Web.Stripe.Recipient ( -- * API CreateRecipient , createRecipient , GetRecipient , getRecipient , UpdateRecipient , updateRecipient , DeleteRecipient , deleteRecipient , GetRecipients , getRecipients -- * Types , AccountNumber (..) , AddressCity (..) , AddressCountry (..) , AddressLine1 (..) , AddressLine2 (..) , AddressState (..) , AddressZip (..) , BankAccount (..) , BankAccountId (..) , BankAccountStatus (..) , CardNumber (..) , Country (..) , CVC (..) , DefaultCard (..) , Description (..) , ExpandParams (..) , ExpMonth (..) , ExpYear (..) , Email (..) , IsVerified (..) , Limit (..) , MetaData (..) , Name (..) , NewBankAccount (..) , NewCard (..) , Recipient (..) , RecipientId (..) , RecipientType (..) , RoutingNumber (..) , StripeDeleteResult (..) , TaxID (..) , TokenId (..) ) where import Web.Stripe.StripeRequest (Method (GET, POST, DELETE), StripeHasParam, StripeRequest (..), ToStripeParam(..), StripeReturn, mkStripeRequest) import Web.Stripe.Util ((</>)) import Web.Stripe.Types (AccountNumber (..), BankAccount (..), CVC (..), CardId (..), CardNumber, BankAccountId (..), BankAccountStatus(..), CardNumber (..), Country (..), DefaultCard(..), Description(..), Email(..), ExpMonth (..), ExpYear(..), IsVerified(..), RoutingNumber (..), AccountNumber (..), Country (..), AddressCity (..), AddressCountry (..), AddressLine1 (..), AddressLine2 (..), AddressState (..), AddressZip (..), Country(..), ExpYear (..), Limit(..), Name(..), NewBankAccount(..), NewCard(..), Recipient (..), RecipientId (..), ExpandParams(..), RecipientType (..), StripeDeleteResult(..), RoutingNumber (..), EndingBefore(..), StartingAfter(..), StripeList (..), TaxID(..), TokenId(..), TokenId (..), MetaData(..)) import Web.Stripe.Types.Util (getRecipientId) ------------------------------------------------------------------------------ -- | Base Request for issues create `Recipient` requests createRecipient :: Name -- ^ `Recipient` `Name` -> RecipientType -- ^ `Individual` or `Corporation` -> StripeRequest CreateRecipient createRecipient name recipienttype = request where request = mkStripeRequest POST url params url = "recipients" params = toStripeParam name $ toStripeParam recipienttype $ [] data CreateRecipient type instance StripeReturn CreateRecipient = Recipient instance StripeHasParam CreateRecipient TaxID instance StripeHasParam CreateRecipient NewBankAccount instance StripeHasParam CreateRecipient TokenId instance StripeHasParam CreateRecipient NewCard instance StripeHasParam CreateRecipient CardId instance StripeHasParam CreateRecipient Email instance StripeHasParam CreateRecipient Description instance StripeHasParam CreateRecipient MetaData ------------------------------------------------------------------------------ -- | Retrieve a 'Recipient' getRecipient :: RecipientId -- ^ The `RecipientId` of the `Recipient` to be retrieved -> StripeRequest GetRecipient getRecipient recipientid = request where request = mkStripeRequest GET url params url = "recipients" </> getRecipientId recipientid params = [] data GetRecipient type instance StripeReturn GetRecipient = Recipient instance StripeHasParam GetRecipient ExpandParams ------------------------------------------------------------------------------ -- | Update `Recipient` updateRecipient :: RecipientId -- ^ `RecipientId` of `Recipient` to update -> StripeRequest UpdateRecipient updateRecipient recipientid = request where request = mkStripeRequest POST url params url = "recipients" </> getRecipientId recipientid params = [] data UpdateRecipient type instance StripeReturn UpdateRecipient = Recipient instance StripeHasParam UpdateRecipient Name instance StripeHasParam UpdateRecipient TaxID instance StripeHasParam UpdateRecipient NewBankAccount instance StripeHasParam UpdateRecipient TokenId instance StripeHasParam UpdateRecipient NewCard instance StripeHasParam UpdateRecipient DefaultCard instance StripeHasParam UpdateRecipient CardId instance StripeHasParam UpdateRecipient Email instance StripeHasParam UpdateRecipient Description instance StripeHasParam UpdateRecipient MetaData ------------------------------------------------------------------------------ -- | Delete a `Recipient` deleteRecipient :: RecipientId -- ^ `RecipiendId` of `Recipient` to delete -> StripeRequest DeleteRecipient deleteRecipient recipientid = request where request = mkStripeRequest DELETE url params url = "recipients" </> getRecipientId recipientid params = [] data DeleteRecipient type instance StripeReturn DeleteRecipient = StripeDeleteResult ------------------------------------------------------------------------------ -- | Retrieve multiple 'Recipient's getRecipients :: StripeRequest GetRecipients getRecipients = request where request = mkStripeRequest GET url params url = "recipients" params = [] data GetRecipients type instance StripeReturn GetRecipients = StripeList Recipient instance StripeHasParam GetRecipients ExpandParams instance StripeHasParam GetRecipients (EndingBefore RecipientId) instance StripeHasParam GetRecipients Limit instance StripeHasParam GetRecipients (StartingAfter RecipientId) instance StripeHasParam GetRecipients IsVerified
dmjio/stripe
stripe-core/src/Web/Stripe/Recipient.hs
mit
7,542
0
9
2,278
1,241
774
467
-1
-1
{-# htermination delFromFM :: FiniteMap Int b -> Int -> FiniteMap Int b #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_delFromFM_5.hs
mit
95
0
3
18
5
3
2
1
0
cuenta_signo:: [Int] -> (Int, Int) cuenta_signo l | l == [] = (0,0) | otherwise = (length [x | x<-l, x>0], length [x | x<-l, x<0] )
betoesquivel/haskell
act16.hs
mit
136
0
10
31
104
54
50
4
1
{-# LANGUAGE OverloadedStrings #-} module Metawave.Parsers.FLAC where import Data.Bits import qualified Data.Map.Strict as M import qualified Data.ByteString.Char8 as C import qualified Data.ByteString.Lazy.Char8 as CL import Data.Attoparsec.Bytestring.Char8 import Metawave.Parsers.Bitwise data MetadataBlock = StreamInfo { minBlockSamples :: Int ,maxBlockSamples :: Int ,minFrameBytes :: Int ,maxFrameBytes :: Int ,sampleRate :: Int ,channels :: Int ,bitsPerSample :: Int ,totalSamples :: Int ,md5signature :: C.ByteString } | Padding { padBytes :: Int } | Application { appID :: Int ,appData :: C.ByteString } | SeekTable { seekpoints :: [Seekpoint] } | VorbisComments { comments :: M.Map C.ByteString C.ByteString } | Cuesheet { catalogNumber :: C.ByteString ,leadInSamples :: Int ,compactDisc :: Bool ,numTracks :: Int ,tracks :: [CuesheetTrack] } | Picture { apicType :: APIC ,mimeLength :: Int ,mimeString :: C.ByteString ,descLength :: Int ,descString :: C.ByteString ,width :: Int ,height :: Int ,colorDepth :: Int ,colorIndex :: Int ,picLength :: Int ,picture :: C.ByteString } data Seekpoint = Seekpoint { firstSample :: Int ,byteOffset :: Int ,sampleSize :: Int } data CuesheetTrack = CuesheetTrack { offsetSamples :: Int ,trackNumber :: Int ,isrc :: C.ByteString ,audio :: Bool ,preEmphasis :: Bool ,indices :: [CuesheetIndex] } data CuesheetIndex = CuesheetIndex { indexOffset :: Int ,indexNumber :: Int } data APIC = Other | Icon32 | IconOther | FrontCover | BackCover | Leaflet | CDLabel | Lead | Artist | Conductor | Band | Composer | Lyricist | RecordingLoc | Recording | Performance | Movie | Fish | Illustration | BandLogo | StudioLogo deriving (Eq, Show) parseFLAC :: Parser [MetadataBlock] parseFLAC = string "fLaC" >> many1 parseMetadataBlock parseMetadataBlock :: Parser MetadataBlock parseMetadataBlock = do finalBlockType <- anyWord8 length2 <- anyWord8 length1 <- anyWord8 length0 <- anyWord8 let final = testBit finalBlockType 7 blockTYpe = clearBit finalBlockType 7 blocklen =
TravisWhitaker/Metawave
src/Metawave/Parsers/FLAC.hs
mit
2,711
1
10
996
568
355
213
-1
-1
import Data.List solve = foldl1' lcm [1..20]
jwtouron/haskell-play
ProjectEuler/Problem5.hs
mit
46
1
6
8
24
11
13
2
1
module Hsbin.Routine ( align , cleanBin , cleanHash , cleanTmp , doesBinExist , compile , execute , msg , msgLn ) where import Control.Applicative ((<$>)) import Control.Exception (finally) import Control.Monad (filterM, unless) import System.Directory (copyFile, createDirectoryIfMissing, doesDirectoryExist, doesFileExist, getDirectoryContents, removeDirectoryRecursive, removeFile) import System.Exit (ExitCode(..)) import System.FilePath ((</>), takeFileName) import System.IO (hPutStr, hPutStrLn, stderr) import System.Process import Hsbin.Types compile :: HsbinEnv -> HsbinConfig -> HsbinScript -> IO () compile henv hcfg hscr = do createDirectoryIfMissing True tmpDir go `finally` removeDirectoryRecursive tmpDir where tmpDir = hsTmpDir henv hscr go = do let args = hsOpts hscr ++ [ "-outputdir", tmpDir , "-o", hsTmpBinPath henv hscr , hsPath hscr] ph <- run (hcBuildType hcfg) args ec <- waitForProcess ph case ec of ExitSuccess -> copyFile (hsTmpBinPath henv hscr) (hsBinPath henv hscr) _ -> error $ hsName hscr ++ " compilation failed" run GHC args = runProcess "ghc" args Nothing Nothing Nothing Nothing Nothing run Stack args = runProcess "stack" (["ghc", "--"] ++ args) Nothing Nothing Nothing Nothing Nothing execute :: HsbinEnv -> HsbinScript -> [String] -> IO () execute henv hscr args = do ph <- runProcess (hsBinPath henv hscr) args Nothing Nothing Nothing Nothing Nothing ec <- waitForProcess ph unless (ec == ExitSuccess) $ error $ hsName hscr ++ " execution failed" doesBinExist :: HsbinEnv -> HsbinScript -> IO Bool doesBinExist henv hscr = doesFileExist $ hsBinPath henv hscr cleanBin :: HsbinEnv -> HsbinConfig -> IO [FilePath] cleanBin henv hcfg = do fs <- filterFile (map (exe . hsName) $ hcScripts hcfg) (heBinDir henv) mapM_ removeFile fs return $ map takeFileName fs cleanHash :: HsbinEnv -> HsbinConfig -> IO [FilePath] cleanHash henv hcfg = do fs <- filterFile (map hsName $ hcScripts hcfg) (heHashDir henv) mapM_ removeFile fs return $ map takeFileName fs cleanTmp :: HsbinEnv -> HsbinConfig -> IO [FilePath] cleanTmp henv hcfg = do let tmpDir = heTmpDir henv b <- doesDirectoryExist tmpDir if b then do fs <- filterDir (map hsName $ hcScripts hcfg) tmpDir mapM_ removeDirectoryRecursive fs return $ map takeFileName fs else return [] filterFile :: [String] -> FilePath -> IO [FilePath] filterFile names dir = filterM doesFileExist =<< filterContents names dir filterDir :: [String] -> FilePath -> IO [FilePath] filterDir names dir = filterM doesDirectoryExist =<< filterContents names dir filterContents :: [String] -> FilePath -> IO [FilePath] filterContents names dir = map (dir </>) <$> filter (`notElem` ([".", ".."] ++ names)) <$> getDirectoryContents dir msg :: String -> IO () msg = hPutStr stderr msgLn :: String -> IO () msgLn = hPutStrLn stderr align :: Int -> String -> String align n = take n . (++ replicate n ' ')
iquiw/hsbin
src/Hsbin/Routine.hs
mit
3,411
0
14
985
1,065
542
523
84
3
module FizzBuzz2 where import Control.Monad import Control.Monad.Trans.State import qualified Data.DList as DL fizzBuzz :: Integer -> String fizzBuzz n | n `mod` 15 == 0 = "FizzBuzz" | n `mod` 5 == 0 = "Fizz" | n `mod` 3 == 0 = "Buzz" | otherwise = show n fizzbuzzList :: [Integer] -> [String] fizzbuzzList list = let dlist = execState (mapM_ addResult list) DL.empty in DL.apply dlist [] -- convert back to normal list addResult :: Integer -> State (DL.DList String) () addResult n = do xs <- get let result = fizzBuzz n -- snoc appends to the end, unlike -- cons which adds to the front put (DL.snoc xs result) main :: IO () main = mapM_ putStrLn $ fizzbuzzList [1..100]
NickAger/LearningHaskell
HaskellProgrammingFromFirstPrinciples/Chapter23.hsproj/FizzBuzz2.hs
mit
766
0
11
216
265
137
128
22
1
module NgLint.Output.Pretty where import Data.List import NgLint.Messages import NgLint.Output.Common import System.Console.ANSI import Text.Parsec.Pos printMessage :: LintMessage -> IO () printMessage (LintMessage pos code) = do setSGR [SetColor Foreground Vivid Yellow] putStr $ replicate (sourceColumn pos - 1) ' ' putStrLn ("^-- " ++ show code) setSGR [Reset] printMessageGroup :: [String] -> [LintMessage] -> IO () printMessageGroup lns messages = do let (LintMessage pos _) = head messages setSGR [SetConsoleIntensity BoldIntensity] putStrLn $ "In " ++ sourceName pos ++ ", line " ++ show (sourceLine pos) ++ ":" setSGR [Reset] putStrLn (lns !! (sourceLine pos - 1)) mapM_ printMessage messages putChar '\n' printMessages :: Formatter printMessages contents messages = do let lns = lines contents messageGroups = groupBy eq messages eq (LintMessage p1 _) (LintMessage p2 _) = p1 == p2 mapM_ (printMessageGroup lns) messageGroups
federicobond/nglint
src/NgLint/Output/Pretty.hs
mit
1,010
0
12
209
357
173
184
27
1