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 RecordWildCards #-} {-# LANGUAGE ScopedTypeVariables #-} module Passman.Engine.Conversions where import Control.Error.Safe (assertErr) import Data.Bits (shift) import Data.Foldable (all) import Data.Semigroup ((<>)) import Data.Vector.Unboxed (Vector, (!)) import qualified Data.Vector.Unboxed as V import qualified Passman.Engine.ByteString as B import Passman.Engine.Errors import Passman.Engine.Strength (Strength(..)) data CharSpace = CharSpace { charSpaceName :: String , charSpaceSymbols :: Vector Char } charSpaceSize :: CharSpace -> Int charSpaceSize CharSpace{..} = V.length charSpaceSymbols makeCharSpace :: String -> String -> CharSpace makeCharSpace name symbols = CharSpace name $ V.fromList symbols type Converter = B.ByteString -> String data ConverterSpec = ConverterSpec CharSpace Strength makeConverter :: Maybe Int -> ConverterSpec -> Either EngineError Converter makeConverter inLength spec = do validateBase spec validateInputRequirements inLength spec return $ convert spec validateBase :: ConverterSpec -> Either EngineError () validateBase (ConverterSpec charSpace _) = assertErr invalidBase checkBase where checkBase = 2 <= base && base <= 256 invalidBase = InvalidOutputBase base base = charSpaceSize charSpace validateInputRequirements :: Maybe Int -> ConverterSpec -> Either EngineError () validateInputRequirements provided spec = assertErr insufficientInput checkInputLength where checkInputLength = all (inLength <=) provided insufficientInput = ExcessiveDerivedBits outLength inLength (inLength, outLength) = inputOutputLength spec inputOutputLength :: ConverterSpec -> (Int, Int) inputOutputLength (ConverterSpec CharSpace{..} Strength{..}) = (inLength, outLength) where base = V.length charSpaceSymbols rawOutputLength = ceiling $ fromIntegral strengthBits / logBase (2 :: Double) (fromIntegral base) outLength = rawOutputLength + (rawOutputLength `mod` 2) inLength = ceiling $ fromIntegral outLength * logBase (256 :: Double) (fromIntegral base) inputLength :: ConverterSpec -> Int inputLength = fst . inputOutputLength integerOfBytes :: Int -> B.ByteString -> Integer integerOfBytes inLength bytes = B.foldr (\a b -> fromIntegral a + shift b 8) 0 $ B.take inLength (bytes <> zeroes) where zeroes = B.replicate inLength 0 materialize :: Int -> Vector Char -> Integer -> String materialize outputLength chars src = take outputLength $ materialize' src where base = V.length chars materialize' n = let (q, r) = n `quotRem` fromIntegral base in chars ! fromIntegral r : materialize' q convert :: ConverterSpec -> B.ByteString -> String convert spec@(ConverterSpec charSpace _) bytes = materialize outLength (charSpaceSymbols charSpace) $ integerOfBytes inLength bytes where (inLength, outLength) = inputOutputLength spec
chwthewke/passman-hs
src/Passman/Engine/Conversions.hs
bsd-3-clause
3,136
0
12
721
848
449
399
64
1
{-# LANGUAGE Rank2Types, TemplateHaskell, BangPatterns, MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, UndecidableInstances, ScopedTypeVariables #-} ----------------------------------------------------------------------------- -- | -- Module : Numeric.AD.Mode.Reverse -- Copyright : (c) Edward Kmett 2010 -- License : BSD3 -- Maintainer : ekmett@gmail.com -- Stability : experimental -- Portability : GHC only -- -- Mixed-Mode Automatic Differentiation. -- -- For reverse mode AD we use 'System.Mem.StableName.StableName' to recover sharing information from -- the tape to avoid combinatorial explosion, and thus run asymptotically faster -- than it could without such sharing information, but the use of side-effects -- contained herein is benign. -- ----------------------------------------------------------------------------- module Numeric.AD.Mode.Reverse ( -- * Gradient grad , grad' , gradWith , gradWith' -- * Jacobian , jacobian , jacobian' , jacobianWith , jacobianWith' -- * Hessian , hessian , hessianF -- * Derivatives , diff , diff' , diffF , diffF' -- * Unsafe Variadic Gradient , vgrad, vgrad' , Grad ) where import Control.Applicative ((<$>)) import Data.Traversable (Traversable) import Numeric.AD.Types import Numeric.AD.Internal.Classes import Numeric.AD.Internal.Composition import Numeric.AD.Internal.Reverse import Numeric.AD.Internal.Var -- | The 'grad' function calculates the gradient of a non-scalar-to-scalar function with 'Reverse' AD in a single pass. -- -- >>> grad (\[x,y,z] -> x*y+z) [1,2,3] -- [2,1,1] grad :: (Traversable f, Num a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> f a grad f as = unbind vs (partialArray bds $ f vs) where (vs,bds) = bind as {-# INLINE grad #-} -- | The 'grad'' function calculates the result and gradient of a non-scalar-to-scalar function with 'Reverse' AD in a single pass. -- -- >>> grad' (\[x,y,z] -> 4*x*exp y+cos z) [1,2,3] -- (28.566231899122155,[29.5562243957226,29.5562243957226,-0.1411200080598672]) grad' :: (Traversable f, Num a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> (a, f a) grad' f as = (primal r, unbind vs $ partialArray bds r) where (vs, bds) = bind as r = f vs {-# INLINE grad' #-} -- | @'grad' g f@ function calculates the gradient of a non-scalar-to-scalar function @f@ with reverse-mode AD in a single pass. -- The gradient is combined element-wise with the argument using the function @g@. -- -- @ -- 'grad' = 'gradWith' (\_ dx -> dx) -- 'id' = 'gradWith' const -- @ -- -- gradWith :: (Traversable f, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> f b gradWith g f as = unbindWith g vs (partialArray bds $ f vs) where (vs,bds) = bind as {-# INLINE gradWith #-} -- | @'grad'' g f@ calculates the result and gradient of a non-scalar-to-scalar function @f@ with 'Reverse' AD in a single pass -- the gradient is combined element-wise with the argument using the function @g@. -- -- @'grad'' == 'gradWith'' (\_ dx -> dx)@ gradWith' :: (Traversable f, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> (a, f b) gradWith' g f as = (primal r, unbindWith g vs $ partialArray bds r) where (vs, bds) = bind as r = f vs {-# INLINE gradWith' #-} -- | The 'jacobian' function calculates the jacobian of a non-scalar-to-non-scalar function with reverse AD lazily in @m@ passes for @m@ outputs. -- -- >>> jacobian (\[x,y] -> [y,x,x*y]) [2,1] -- [[0,1],[1,0],[1,2]] -- -- >>> jacobian (\[x,y] -> [exp y,cos x,x+y]) [1,2] -- [[0.0,7.38905609893065],[-0.8414709848078965,0.0],[1.0,1.0]] jacobian :: (Traversable f, Functor g, Num a) => (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (f a) jacobian f as = unbind vs . partialArray bds <$> f vs where (vs, bds) = bind as {-# INLINE jacobian #-} -- | The 'jacobian'' function calculates both the result and the Jacobian of a nonscalar-to-nonscalar function, using @m@ invocations of reverse AD, -- where @m@ is the output dimensionality. Applying @fmap snd@ to the result will recover the result of 'jacobian' -- | An alias for 'gradF'' -- -- ghci> jacobian' (\[x,y] -> [y,x,x*y]) [2,1] -- [(1,[0,1]),(2,[1,0]),(2,[1,2])] jacobian' :: (Traversable f, Functor g, Num a) => (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (a, f a) jacobian' f as = row <$> f vs where (vs, bds) = bind as row a = (primal a, unbind vs (partialArray bds a)) {-# INLINE jacobian' #-} -- | 'jacobianWith g f' calculates the Jacobian of a non-scalar-to-non-scalar function @f@ with reverse AD lazily in @m@ passes for @m@ outputs. -- -- Instead of returning the Jacobian matrix, the elements of the matrix are combined with the input using the @g@. -- -- @ -- 'jacobian' = 'jacobianWith' (\_ dx -> dx) -- 'jacobianWith' 'const' = (\f x -> 'const' x '<$>' f x) -- @ jacobianWith :: (Traversable f, Functor g, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (f b) jacobianWith g f as = unbindWith g vs . partialArray bds <$> f vs where (vs, bds) = bind as {-# INLINE jacobianWith #-} -- | 'jacobianWith' g f' calculates both the result and the Jacobian of a nonscalar-to-nonscalar function @f@, using @m@ invocations of reverse AD, -- where @m@ is the output dimensionality. Applying @fmap snd@ to the result will recover the result of 'jacobianWith' -- -- Instead of returning the Jacobian matrix, the elements of the matrix are combined with the input using the @g@. -- -- @'jacobian'' == 'jacobianWith'' (\_ dx -> dx)@ jacobianWith' :: (Traversable f, Functor g, Num a) => (a -> a -> b) -> (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (a, f b) jacobianWith' g f as = row <$> f vs where (vs, bds) = bind as row a = (primal a, unbindWith g vs (partialArray bds a)) {-# INLINE jacobianWith' #-} -- | Compute the derivative of a function. -- -- >>> diff sin 0 -- 1.0 -- -- >>> cos 0 -- 1.0 diff :: Num a => (forall s. Mode s => AD s a -> AD s a) -> a -> a diff f a = derivative $ f (var a 0) {-# INLINE diff #-} -- | The 'diff'' function calculates the value and derivative, as a -- pair, of a scalar-to-scalar function. -- -- -- >>> diff' sin 0 -- (0.0,1.0) diff' :: Num a => (forall s. Mode s => AD s a -> AD s a) -> a -> (a, a) diff' f a = derivative' $ f (var a 0) {-# INLINE diff' #-} -- | Compute the derivatives of a function that returns a vector with regards to its single input. -- -- >>> diffF (\a -> [sin a, cos a]) 0 -- [1.0,0.0] diffF :: (Functor f, Num a) => (forall s. Mode s => AD s a -> f (AD s a)) -> a -> f a diffF f a = derivative <$> f (var a 0) {-# INLINE diffF #-} -- | Compute the derivatives of a function that returns a vector with regards to its single input -- as well as the primal answer. -- -- >>> diffF' (\a -> [sin a, cos a]) 0 -- [(0.0,1.0),(1.0,0.0)] diffF' :: (Functor f, Num a) => (forall s. Mode s => AD s a -> f (AD s a)) -> a -> f (a, a) diffF' f a = derivative' <$> f (var a 0) {-# INLINE diffF' #-} -- | Compute the 'hessian' via the 'jacobian' of the gradient. gradient is computed in reverse mode and then the 'jacobian' is computed in reverse mode. -- -- However, since the @'grad' f :: f a -> f a@ is square this is not as fast as using the forward-mode 'jacobian' of a reverse mode gradient provided by 'Numeric.AD.hessian'. -- -- >>> hessian (\[x,y] -> x*y) [1,2] -- [[0,1],[1,0]] hessian :: (Traversable f, Num a) => (forall s. Mode s => f (AD s a) -> AD s a) -> f a -> f (f a) hessian f = jacobian (grad (decomposeMode . f . fmap composeMode)) -- | Compute the order 3 Hessian tensor on a non-scalar-to-non-scalar function via the reverse-mode Jacobian of the reverse-mode Jacobian of the function. -- -- Less efficient than 'Numeric.AD.Mode.Mixed.hessianF'. -- -- >>> hessianF (\[x,y] -> [x*y,x+y,exp x*cos y]) [1,2] -- [[[0.0,1.0],[1.0,0.0]],[[0.0,0.0],[0.0,0.0]],[[-1.1312043837568135,-2.4717266720048188],[-2.4717266720048188,1.1312043837568135]]] hessianF :: (Traversable f, Functor g, Num a) => (forall s. Mode s => f (AD s a) -> g (AD s a)) -> f a -> g (f (f a)) hessianF f = decomposeFunctor . jacobian (ComposeFunctor . jacobian (fmap decomposeMode . f . fmap composeMode))
yairchu/ad
src/Numeric/AD/Mode/Reverse.hs
bsd-3-clause
8,302
0
14
1,675
1,953
1,050
903
78
1
{- (c) The University of Glasgow 2006 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998 -} {-# LANGUAGE CPP, DeriveDataTypeable, ScopedTypeVariables #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types] -- in module PlaceHolder {-# LANGUAGE ConstraintKinds #-} -- | Abstract Haskell syntax for expressions. module HsExpr where #include "HsVersions.h" -- friends: import HsDecls import HsPat import HsLit import PlaceHolder ( PostTc,PostRn,DataId ) import HsTypes import HsBinds -- others: import TcEvidence import CoreSyn import Var import Name import BasicTypes import ConLike import SrcLoc import Util import StaticFlags( opt_PprStyle_Debug ) import Outputable import FastString import Type -- libraries: import Data.Data hiding (Fixity) import Data.Maybe (isNothing) {- ************************************************************************ * * \subsection{Expressions proper} * * ************************************************************************ -} -- * Expressions proper type LHsExpr id = Located (HsExpr id) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when -- in a list -- For details on above see note [Api annotations] in ApiAnnotation ------------------------- -- | PostTcExpr is an evidence expression attached to the syntax tree by the -- type checker (c.f. postTcType). type PostTcExpr = HsExpr Id -- | We use a PostTcTable where there are a bunch of pieces of evidence, more -- than is convenient to keep individually. type PostTcTable = [(Name, PostTcExpr)] noPostTcExpr :: PostTcExpr noPostTcExpr = HsLit (HsString "" (fsLit "noPostTcExpr")) noPostTcTable :: PostTcTable noPostTcTable = [] ------------------------- -- | SyntaxExpr is like 'PostTcExpr', but it's filled in a little earlier, -- by the renamer. It's used for rebindable syntax. -- -- E.g. @(>>=)@ is filled in before the renamer by the appropriate 'Name' for -- @(>>=)@, and then instantiated by the type checker with its type args -- etc type SyntaxExpr id = HsExpr id noSyntaxExpr :: SyntaxExpr id -- Before renaming, and sometimes after, -- (if the syntax slot makes no sense) noSyntaxExpr = HsLit (HsString "" (fsLit "noSyntaxExpr")) type CmdSyntaxTable id = [(Name, SyntaxExpr id)] -- See Note [CmdSyntaxTable] {- Note [CmdSyntaxtable] ~~~~~~~~~~~~~~~~~~~~~ Used only for arrow-syntax stuff (HsCmdTop), the CmdSyntaxTable keeps track of the methods needed for a Cmd. * Before the renamer, this list is an empty list * After the renamer, it takes the form @[(std_name, HsVar actual_name)]@ For example, for the 'arr' method * normal case: (GHC.Control.Arrow.arr, HsVar GHC.Control.Arrow.arr) * with rebindable syntax: (GHC.Control.Arrow.arr, arr_22) where @arr_22@ is whatever 'arr' is in scope * After the type checker, it takes the form [(std_name, <expression>)] where <expression> is the evidence for the method. This evidence is instantiated with the class, but is still polymorphic in everything else. For example, in the case of 'arr', the evidence has type forall b c. (b->c) -> a b c where 'a' is the ambient type of the arrow. This polymorphism is important because the desugarer uses the same evidence at multiple different types. This is Less Cool than what we normally do for rebindable syntax, which is to make fully-instantiated piece of evidence at every use site. The Cmd way is Less Cool because * The renamer has to predict which methods are needed. See the tedious RnExpr.methodNamesCmd. * The desugarer has to know the polymorphic type of the instantiated method. This is checked by Inst.tcSyntaxName, but is less flexible than the rest of rebindable syntax, where the type is less pre-ordained. (And this flexibility is useful; for example we can typecheck do-notation with (>>=) :: m1 a -> (a -> m2 b) -> m2 b.) -} -- | A Haskell expression. data HsExpr id = HsVar (Located id) -- ^ Variable -- See Note [Located RdrNames] | HsUnboundVar OccName -- ^ Unbound variable; also used for "holes" _, or _x. -- Turned from HsVar to HsUnboundVar by the renamer, when -- it finds an out-of-scope variable -- Turned into HsVar by type checker, to support deferred -- type errors. (The HsUnboundVar only has an OccName.) | HsRecFld (AmbiguousFieldOcc id) -- ^ Variable pointing to record selector | HsOverLabel FastString -- ^ Overloaded label (See Note [Overloaded labels] -- in GHC.OverloadedLabels) | HsIPVar HsIPName -- ^ Implicit parameter | HsOverLit (HsOverLit id) -- ^ Overloaded literals | HsLit HsLit -- ^ Simple (non-overloaded) literals | HsLam (MatchGroup id (LHsExpr id)) -- ^ Lambda abstraction. Currently always a single match -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsLamCase (PostTc id Type) (MatchGroup id (LHsExpr id)) -- ^ Lambda-case -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnCase','ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsApp (LHsExpr id) (LHsExpr id) -- ^ Application -- | Operator applications: -- NB Bracketed ops such as (+) come out as Vars. -- NB We need an expr for the operator in an OpApp/Section since -- the typechecker may need to apply the operator to a few types. | OpApp (LHsExpr id) -- left operand (LHsExpr id) -- operator (PostRn id Fixity) -- Renamer adds fixity; bottom until then (LHsExpr id) -- right operand -- | Negation operator. Contains the negated expression and the name -- of 'negate' -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnMinus' -- For details on above see note [Api annotations] in ApiAnnotation | NegApp (LHsExpr id) (SyntaxExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsPar (LHsExpr id) -- ^ Parenthesised expr; see Note [Parens in HsSyn] | SectionL (LHsExpr id) -- operand; see Note [Sections in HsSyn] (LHsExpr id) -- operator | SectionR (LHsExpr id) -- operator; see Note [Sections in HsSyn] (LHsExpr id) -- operand -- | Used for explicit tuples and sections thereof -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitTuple [LHsTupArg id] Boxity -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCase (LHsExpr id) (MatchGroup id (LHsExpr id)) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsIf (Maybe (SyntaxExpr id)) -- cond function -- Nothing => use the built-in 'if' -- See Note [Rebindable if] (LHsExpr id) -- predicate (LHsExpr id) -- then part (LHsExpr id) -- else part -- | Multi-way if -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf' -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- For details on above see note [Api annotations] in ApiAnnotation | HsMultiIf (PostTc id Type) [LGRHS id (LHsExpr id)] -- | let(rec) -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsLet (Located (HsLocalBinds id)) (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsDo (HsStmtContext Name) -- The parameterisation is unimportant -- because in this context we never use -- the PatGuard or ParStmt variant (Located [ExprLStmt id]) -- "do":one or more stmts (PostTc id Type) -- Type of the whole expression -- | Syntactic list: [a,b,c,...] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitList (PostTc id Type) -- Gives type of components of list (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromListN witness [LHsExpr id] -- | Syntactic parallel array: [:e1, ..., en:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnComma', -- 'ApiAnnotation.AnnVbar' -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | ExplicitPArr (PostTc id Type) -- type of elements of the parallel array [LHsExpr id] -- | Record construction -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordCon { rcon_con_name :: Located id -- The constructor name; -- not used after type checking , rcon_con_like :: PostTc id ConLike -- The data constructor or pattern synonym , rcon_con_expr :: PostTcExpr -- Instantiated constructor function , rcon_flds :: HsRecordBinds id } -- The fields -- | Record update -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnDotdot','ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | RecordUpd { rupd_expr :: LHsExpr id , rupd_flds :: [LHsRecUpdField id] , rupd_cons :: PostTc id [ConLike] -- Filled in by the type checker to the -- _non-empty_ list of DataCons that have -- all the upd'd fields , rupd_in_tys :: PostTc id [Type] -- Argument types of *input* record type , rupd_out_tys :: PostTc id [Type] -- and *output* record type -- The original type can be reconstructed -- with conLikeResTy , rupd_wrap :: PostTc id HsWrapper -- See note [Record Update HsWrapper] } -- For a type family, the arg types are of the *instance* tycon, -- not the family tycon -- | Expression with an explicit type signature. @e :: type@ -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon' -- For details on above see note [Api annotations] in ApiAnnotation | ExprWithTySig (LHsExpr id) (LHsSigWcType id) | ExprWithTySigOut -- Post typechecking (LHsExpr id) (LHsSigWcType Name) -- Retain the signature, -- as HsSigType Name, for -- round-tripping purposes -- | Arithmetic sequence -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnClose' @']'@ -- For details on above see note [Api annotations] in ApiAnnotation | ArithSeq PostTcExpr (Maybe (SyntaxExpr id)) -- For OverloadedLists, the fromList witness (ArithSeqInfo id) -- | Arithmetic sequence for parallel array -- -- > [:e1..e2:] or [:e1, e2..e3:] -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@, -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnDotdot', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' @':]'@ -- For details on above see note [Api annotations] in ApiAnnotation | PArrSeq PostTcExpr (ArithSeqInfo id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# SCC'@, -- 'ApiAnnotation.AnnVal' or 'ApiAnnotation.AnnValStr', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsSCC SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- "set cost centre" SCC pragma (LHsExpr id) -- expr whose cost is to be measured -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{-\# CORE'@, -- 'ApiAnnotation.AnnVal', 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCoreAnn SourceText -- Note [Pragma source text] in BasicTypes StringLiteral -- hdaume: core annotation (LHsExpr id) ----------------------------------------------------------- -- MetaHaskell Extensions -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsBracket (HsBracket id) -- See Note [Pending Splices] | HsRnBracketOut (HsBracket Name) -- Output of the renamer is the *original* renamed -- expression, plus [PendingRnSplice] -- _renamed_ splices to be type checked | HsTcBracketOut (HsBracket Name) -- Output of the type checker is the *original* -- renamed expression, plus [PendingTcSplice] -- _typechecked_ splices to be -- pasted back in by the desugarer -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsSpliceE (HsSplice id) ----------------------------------------------------------- -- Arrow notation extension -- | @proc@ notation for Arrows -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnProc', -- 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | HsProc (LPat id) -- arrow abstraction, proc (LHsCmdTop id) -- body of the abstraction -- always has an empty stack --------------------------------------- -- static pointers extension -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnStatic', -- For details on above see note [Api annotations] in ApiAnnotation | HsStatic (LHsExpr id) --------------------------------------- -- The following are commands, not expressions proper -- They are only used in the parsing stage and are removed -- immediately in parser.RdrHsSyn.checkCommand -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation | HsArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg (PostTc id Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands --------------------------------------- -- Haskell program coverage (Hpc) Support | HsTick (Tickish id) (LHsExpr id) -- sub-expression | HsBinTick Int -- module-local tick number for True Int -- module-local tick number for False (LHsExpr id) -- sub-expression -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen', -- 'ApiAnnotation.AnnOpen' @'{-\# GENERATED'@, -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnColon','ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnMinus', -- 'ApiAnnotation.AnnVal','ApiAnnotation.AnnColon', -- 'ApiAnnotation.AnnVal', -- 'ApiAnnotation.AnnClose' @'\#-}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsTickPragma -- A pragma introduced tick SourceText -- Note [Pragma source text] in BasicTypes (StringLiteral,(Int,Int),(Int,Int)) -- external span for this tick ((SourceText,SourceText),(SourceText,SourceText)) -- Source text for the four integers used in the span. -- See note [Pragma source text] in BasicTypes (LHsExpr id) --------------------------------------- -- These constructors only appear temporarily in the parser. -- The renamer translates them into the Right Thing. | EWildPat -- wildcard -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | EAsPat (Located id) -- as pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow' -- For details on above see note [Api annotations] in ApiAnnotation | EViewPat (LHsExpr id) -- view pattern (LHsExpr id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde' -- For details on above see note [Api annotations] in ApiAnnotation | ELazyPat (LHsExpr id) -- ~ pattern -- | Use for type application in expressions. -- 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnAt' -- For details on above see note [Api annotations] in ApiAnnotation | HsType (LHsWcType id) -- Explicit type argument; e.g f @Int x y -- NB: Has wildcards, but no implicit quant. | HsTypeOut (LHsWcType Name) -- just for pretty-printing --------------------------------------- -- Finally, HsWrap appears only in typechecker output | HsWrap HsWrapper -- TRANSLATION (HsExpr id) deriving (Typeable) deriving instance (DataId id) => Data (HsExpr id) -- | HsTupArg is used for tuple sections -- (,a,) is represented by ExplicitTuple [Missing ty1, Present a, Missing ty3] -- Which in turn stands for (\x:ty1 \y:ty2. (x,a,y)) type LHsTupArg id = Located (HsTupArg id) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' -- For details on above see note [Api annotations] in ApiAnnotation data HsTupArg id = Present (LHsExpr id) -- ^ The argument | Missing (PostTc id Type) -- ^ The argument is missing, but this is its type deriving (Typeable) deriving instance (DataId id) => Data (HsTupArg id) tupArgPresent :: LHsTupArg id -> Bool tupArgPresent (L _ (Present {})) = True tupArgPresent (L _ (Missing {})) = False {- Note [Parens in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~ HsPar (and ParPat in patterns, HsParTy in types) is used as follows * Generally HsPar is optional; the pretty printer adds parens where necessary. Eg (HsApp f (HsApp g x)) is fine, and prints 'f (g x)' * HsPars are pretty printed as '( .. )' regardless of whether or not they are strictly necssary * HsPars are respected when rearranging operator fixities. So a * (b + c) means what it says (where the parens are an HsPar) Note [Sections in HsSyn] ~~~~~~~~~~~~~~~~~~~~~~~~ Sections should always appear wrapped in an HsPar, thus HsPar (SectionR ...) The parser parses sections in a wider variety of situations (See Note [Parsing sections]), but the renamer checks for those parens. This invariant makes pretty-printing easier; we don't need a special case for adding the parens round sections. Note [Rebindable if] ~~~~~~~~~~~~~~~~~~~~ The rebindable syntax for 'if' is a bit special, because when rebindable syntax is *off* we do not want to treat (if c then t else e) as if it was an application (ifThenElse c t e). Why not? Because we allow an 'if' to return *unboxed* results, thus if blah then 3# else 4# whereas that would not be possible using a all to a polymorphic function (because you can't call a polymorphic function at an unboxed type). So we use Nothing to mean "use the old built-in typing rule". Note [Record Update HsWrapper] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ There is a wrapper in RecordUpd which is used for the *required* constraints for pattern synonyms. This wrapper is created in the typechecking and is then directly used in the desugaring without modification. For example, if we have the record pattern synonym P, pattern P :: (Show a) => a -> Maybe a pattern P{x} = Just x foo = (Just True) { x = False } then `foo` desugars to something like foo = case Just True of P x -> P False hence we need to provide the correct dictionaries to P's matcher on the RHS so that we can build the expression. Note [Located RdrNames] ~~~~~~~~~~~~~~~~~~~~~~~ A number of syntax elements have seemingly redundant locations attached to them. This is deliberate, to allow transformations making use of the API Annotations to easily correlate a Located Name in the RenamedSource with a Located RdrName in the ParsedSource. There are unfortunately enough differences between the ParsedSource and the RenamedSource that the API Annotations cannot be used directly with RenamedSource, so this allows a simple mapping to be used based on the location. -} instance OutputableBndr id => Outputable (HsExpr id) where ppr expr = pprExpr expr ----------------------- -- pprExpr, pprLExpr, pprBinds call pprDeeper; -- the underscore versions do not pprLExpr :: OutputableBndr id => LHsExpr id -> SDoc pprLExpr (L _ e) = pprExpr e pprExpr :: OutputableBndr id => HsExpr id -> SDoc pprExpr e | isAtomicHsExpr e || isQuietHsExpr e = ppr_expr e | otherwise = pprDeeper (ppr_expr e) isQuietHsExpr :: HsExpr id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsExpr (HsPar _) = True -- applications don't display anything themselves isQuietHsExpr (HsApp _ _) = True isQuietHsExpr (OpApp _ _ _ _) = True isQuietHsExpr _ = False pprBinds :: (OutputableBndr idL, OutputableBndr idR) => HsLocalBindsLR idL idR -> SDoc pprBinds b = pprDeeper (ppr b) ----------------------- ppr_lexpr :: OutputableBndr id => LHsExpr id -> SDoc ppr_lexpr e = ppr_expr (unLoc e) ppr_expr :: forall id. OutputableBndr id => HsExpr id -> SDoc ppr_expr (HsVar (L _ v)) = pprPrefixOcc v ppr_expr (HsUnboundVar v) = pprPrefixOcc v ppr_expr (HsIPVar v) = ppr v ppr_expr (HsOverLabel l) = char '#' <> ppr l ppr_expr (HsLit lit) = ppr lit ppr_expr (HsOverLit lit) = ppr lit ppr_expr (HsPar e) = parens (ppr_lexpr e) ppr_expr (HsCoreAnn _ (StringLiteral _ s) e) = vcat [text "HsCoreAnn" <+> ftext s, ppr_lexpr e] ppr_expr (HsApp e1 e2) = let (fun, args) = collect_args e1 [e2] in hang (ppr_lexpr fun) 2 (sep (map pprParendExpr args)) where collect_args (L _ (HsApp fun arg)) args = collect_args fun (arg:args) collect_args fun args = (fun, args) ppr_expr (OpApp e1 op _ e2) = case unLoc op of HsVar (L _ v) -> pp_infixly v HsRecFld f -> pp_infixly f _ -> pp_prefixly where pp_e1 = pprDebugParendExpr e1 -- In debug mode, add parens pp_e2 = pprDebugParendExpr e2 -- to make precedence clear pp_prefixly = hang (ppr op) 2 (sep [pp_e1, pp_e2]) pp_infixly v = sep [pp_e1, sep [pprInfixOcc v, nest 2 pp_e2]] ppr_expr (NegApp e _) = char '-' <+> pprDebugParendExpr e ppr_expr (SectionL expr op) = case unLoc op of HsVar (L _ v) -> pp_infixly v _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text " \\ x_ ->", ppr op]) 4 (hsep [pp_expr, text "x_ )"]) pp_infixly v = (sep [pp_expr, pprInfixOcc v]) ppr_expr (SectionR op expr) = case unLoc op of HsVar (L _ v) -> pp_infixly v _ -> pp_prefixly where pp_expr = pprDebugParendExpr expr pp_prefixly = hang (hsep [text "( \\ x_ ->", ppr op, text "x_"]) 4 (pp_expr <> rparen) pp_infixly v = sep [pprInfixOcc v, pp_expr] ppr_expr (ExplicitTuple exprs boxity) = tupleParens (boxityTupleSort boxity) (fcat (ppr_tup_args $ map unLoc exprs)) where ppr_tup_args [] = [] ppr_tup_args (Present e : es) = (ppr_lexpr e <> punc es) : ppr_tup_args es ppr_tup_args (Missing _ : es) = punc es : ppr_tup_args es punc (Present {} : _) = comma <> space punc (Missing {} : _) = comma punc [] = empty ppr_expr (HsLam matches) = pprMatches (LambdaExpr :: HsMatchContext id) matches ppr_expr (HsLamCase _ matches) = sep [ sep [text "\\case {"], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_expr (HsCase expr matches) = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_expr (HsIf _ e1 e2 e3) = sep [hsep [text "if", nest 2 (ppr e1), ptext (sLit "then")], nest 4 (ppr e2), text "else", nest 4 (ppr e3)] ppr_expr (HsMultiIf _ alts) = sep $ text "if" : map ppr_alt alts where ppr_alt (L _ (GRHS guards expr)) = sep [ vbar <+> interpp'SP guards , text "->" <+> pprDeeper (ppr expr) ] -- special case: let ... in let ... ppr_expr (HsLet (L _ binds) expr@(L _ (HsLet _ _))) = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lexpr expr] ppr_expr (HsLet (L _ binds) expr) = sep [hang (text "let") 2 (pprBinds binds), hang (text "in") 2 (ppr expr)] ppr_expr (HsDo do_or_list_comp (L _ stmts) _) = pprDo do_or_list_comp stmts ppr_expr (ExplicitList _ _ exprs) = brackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (ExplicitPArr _ exprs) = paBrackets (pprDeeperList fsep (punctuate comma (map ppr_lexpr exprs))) ppr_expr (RecordCon { rcon_con_name = con_id, rcon_flds = rbinds }) = hang (ppr con_id) 2 (ppr rbinds) ppr_expr (RecordUpd { rupd_expr = aexp, rupd_flds = rbinds }) = hang (pprLExpr aexp) 2 (braces (fsep (punctuate comma (map ppr rbinds)))) ppr_expr (ExprWithTySig expr sig) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ExprWithTySigOut expr sig) = hang (nest 2 (ppr_lexpr expr) <+> dcolon) 4 (ppr sig) ppr_expr (ArithSeq _ _ info) = brackets (ppr info) ppr_expr (PArrSeq _ info) = paBrackets (ppr info) ppr_expr EWildPat = char '_' ppr_expr (ELazyPat e) = char '~' <> pprParendExpr e ppr_expr (EAsPat v e) = ppr v <> char '@' <> pprParendExpr e ppr_expr (EViewPat p e) = ppr p <+> text "->" <+> ppr e ppr_expr (HsSCC _ (StringLiteral _ lbl) expr) = sep [ text "{-# SCC" <+> doubleQuotes (ftext lbl) <+> ptext (sLit "#-}"), pprParendExpr expr ] ppr_expr (HsWrap co_fn e) = pprHsWrapper (pprExpr e) co_fn ppr_expr (HsType (HsWC { hswc_body = ty })) = char '@' <> pprParendHsType (unLoc ty) ppr_expr (HsTypeOut (HsWC { hswc_body = ty })) = char '@' <> pprParendHsType (unLoc ty) ppr_expr (HsSpliceE s) = pprSplice s ppr_expr (HsBracket b) = pprHsBracket b ppr_expr (HsRnBracketOut e []) = ppr e ppr_expr (HsRnBracketOut e ps) = ppr e $$ text "pending(rn)" <+> ppr ps ppr_expr (HsTcBracketOut e []) = ppr e ppr_expr (HsTcBracketOut e ps) = ppr e $$ text "pending(tc)" <+> ppr ps ppr_expr (HsProc pat (L _ (HsCmdTop cmd _ _ _))) = hsep [text "proc", ppr pat, ptext (sLit "->"), ppr cmd] ppr_expr (HsStatic e) = hsep [text "static", pprParendExpr e] ppr_expr (HsTick tickish exp) = pprTicks (ppr exp) $ ppr tickish <+> ppr_lexpr exp ppr_expr (HsBinTick tickIdTrue tickIdFalse exp) = pprTicks (ppr exp) $ hcat [text "bintick<", ppr tickIdTrue, text ",", ppr tickIdFalse, text ">(", ppr exp, text ")"] ppr_expr (HsTickPragma _ externalSrcLoc _ exp) = pprTicks (ppr exp) $ hcat [text "tickpragma<", pprExternalSrcLoc externalSrcLoc, text ">(", ppr exp, text ")"] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_expr (HsArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_expr (HsArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]] ppr_expr (HsArrForm op _ args) = hang (text "(|" <+> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <+> text "|)") ppr_expr (HsRecFld f) = ppr f pprExternalSrcLoc :: (StringLiteral,(Int,Int),(Int,Int)) -> SDoc pprExternalSrcLoc (StringLiteral _ src,(n1,n2),(n3,n4)) = ppr (src,(n1,n2),(n3,n4)) {- HsSyn records exactly where the user put parens, with HsPar. So generally speaking we print without adding any parens. However, some code is internally generated, and in some places parens are absolutely required; so for these places we use pprParendExpr (but don't print double parens of course). For operator applications we don't add parens, because the operator fixities should do the job, except in debug mode (-dppr-debug) so we can see the structure of the parse tree. -} pprDebugParendExpr :: OutputableBndr id => LHsExpr id -> SDoc pprDebugParendExpr expr = getPprStyle (\sty -> if debugStyle sty then pprParendExpr expr else pprLExpr expr) pprParendExpr :: OutputableBndr id => LHsExpr id -> SDoc pprParendExpr expr | hsExprNeedsParens (unLoc expr) = parens (pprLExpr expr) | otherwise = pprLExpr expr -- Using pprLExpr makes sure that we go 'deeper' -- I think that is usually (always?) right hsExprNeedsParens :: HsExpr id -> Bool -- True of expressions for which '(e)' and 'e' -- mean the same thing hsExprNeedsParens (ArithSeq {}) = False hsExprNeedsParens (PArrSeq {}) = False hsExprNeedsParens (HsLit {}) = False hsExprNeedsParens (HsOverLit {}) = False hsExprNeedsParens (HsVar {}) = False hsExprNeedsParens (HsUnboundVar {}) = False hsExprNeedsParens (HsIPVar {}) = False hsExprNeedsParens (HsOverLabel {}) = False hsExprNeedsParens (ExplicitTuple {}) = False hsExprNeedsParens (ExplicitList {}) = False hsExprNeedsParens (ExplicitPArr {}) = False hsExprNeedsParens (RecordCon {}) = False hsExprNeedsParens (RecordUpd {}) = False hsExprNeedsParens (HsPar {}) = False hsExprNeedsParens (HsBracket {}) = False hsExprNeedsParens (HsRnBracketOut {}) = False hsExprNeedsParens (HsTcBracketOut {}) = False hsExprNeedsParens (HsDo sc _ _) | isListCompExpr sc = False hsExprNeedsParens (HsRecFld{}) = False hsExprNeedsParens (HsType {}) = False hsExprNeedsParens (HsTypeOut {}) = False hsExprNeedsParens _ = True isAtomicHsExpr :: HsExpr id -> Bool -- True of a single token isAtomicHsExpr (HsVar {}) = True isAtomicHsExpr (HsLit {}) = True isAtomicHsExpr (HsOverLit {}) = True isAtomicHsExpr (HsIPVar {}) = True isAtomicHsExpr (HsOverLabel {}) = True isAtomicHsExpr (HsUnboundVar {}) = True isAtomicHsExpr (HsWrap _ e) = isAtomicHsExpr e isAtomicHsExpr (HsPar e) = isAtomicHsExpr (unLoc e) isAtomicHsExpr (HsRecFld{}) = True isAtomicHsExpr _ = False {- ************************************************************************ * * \subsection{Commands (in arrow abstractions)} * * ************************************************************************ We re-use HsExpr to represent these. -} type LHsCmd id = Located (HsCmd id) data HsCmd id -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.Annlarrowtail', -- 'ApiAnnotation.Annrarrowtail','ApiAnnotation.AnnLarrowtail', -- 'ApiAnnotation.AnnRarrowtail' -- For details on above see note [Api annotations] in ApiAnnotation = HsCmdArrApp -- Arrow tail, or arrow application (f -< arg) (LHsExpr id) -- arrow expression, f (LHsExpr id) -- input expression, arg (PostTc id Type) -- type of the arrow expressions f, -- of the form a t t', where arg :: t HsArrAppType -- higher-order (-<<) or first-order (-<) Bool -- True => right-to-left (f -< arg) -- False => left-to-right (arg >- f) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(|'@, -- 'ApiAnnotation.AnnClose' @'|)'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdArrForm -- Command formation, (| e cmd1 .. cmdn |) (LHsExpr id) -- the operator -- after type-checking, a type abstraction to be -- applied to the type of the local environment tuple (Maybe Fixity) -- fixity (filled in by the renamer), for forms that -- were converted from OpApp's by the renamer [LHsCmdTop id] -- argument commands | HsCmdApp (LHsCmd id) (LHsExpr id) | HsCmdLam (MatchGroup id (LHsCmd id)) -- kappa -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLam', -- 'ApiAnnotation.AnnRarrow', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdPar (LHsCmd id) -- parenthesised command -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@, -- 'ApiAnnotation.AnnClose' @')'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdCase (LHsExpr id) (MatchGroup id (LHsCmd id)) -- bodies are HsCmd's -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnCase', -- 'ApiAnnotation.AnnOf','ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@ -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdIf (Maybe (SyntaxExpr id)) -- cond function (LHsExpr id) -- predicate (LHsCmd id) -- then part (LHsCmd id) -- else part -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnIf', -- 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnThen','ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnElse', -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdLet (Located (HsLocalBinds id)) -- let(rec) (LHsCmd id) -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet', -- 'ApiAnnotation.AnnOpen' @'{'@, -- 'ApiAnnotation.AnnClose' @'}'@,'ApiAnnotation.AnnIn' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdDo (Located [CmdLStmt id]) (PostTc id Type) -- Type of the whole expression -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDo', -- 'ApiAnnotation.AnnOpen', 'ApiAnnotation.AnnSemi', -- 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnClose' -- For details on above see note [Api annotations] in ApiAnnotation | HsCmdWrap HsWrapper (HsCmd id) -- If cmd :: arg1 --> res -- wrap :: arg1 "->" arg2 -- Then (HsCmdWrap wrap cmd) :: arg2 --> res deriving (Typeable) deriving instance (DataId id) => Data (HsCmd id) data HsArrAppType = HsHigherOrderApp | HsFirstOrderApp deriving (Data, Typeable) {- | Top-level command, introducing a new arrow. This may occur inside a proc (where the stack is empty) or as an argument of a command-forming operator. -} type LHsCmdTop id = Located (HsCmdTop id) data HsCmdTop id = HsCmdTop (LHsCmd id) (PostTc id Type) -- Nested tuple of inputs on the command's stack (PostTc id Type) -- return type of the command (CmdSyntaxTable id) -- See Note [CmdSyntaxTable] deriving (Typeable) deriving instance (DataId id) => Data (HsCmdTop id) instance OutputableBndr id => Outputable (HsCmd id) where ppr cmd = pprCmd cmd ----------------------- -- pprCmd and pprLCmd call pprDeeper; -- the underscore versions do not pprLCmd :: OutputableBndr id => LHsCmd id -> SDoc pprLCmd (L _ c) = pprCmd c pprCmd :: OutputableBndr id => HsCmd id -> SDoc pprCmd c | isQuietHsCmd c = ppr_cmd c | otherwise = pprDeeper (ppr_cmd c) isQuietHsCmd :: HsCmd id -> Bool -- Parentheses do display something, but it gives little info and -- if we go deeper when we go inside them then we get ugly things -- like (...) isQuietHsCmd (HsCmdPar _) = True -- applications don't display anything themselves isQuietHsCmd (HsCmdApp _ _) = True isQuietHsCmd _ = False ----------------------- ppr_lcmd :: OutputableBndr id => LHsCmd id -> SDoc ppr_lcmd c = ppr_cmd (unLoc c) ppr_cmd :: forall id. OutputableBndr id => HsCmd id -> SDoc ppr_cmd (HsCmdPar c) = parens (ppr_lcmd c) ppr_cmd (HsCmdApp c e) = let (fun, args) = collect_args c [e] in hang (ppr_lcmd fun) 2 (sep (map pprParendExpr args)) where collect_args (L _ (HsCmdApp fun arg)) args = collect_args fun (arg:args) collect_args fun args = (fun, args) ppr_cmd (HsCmdLam matches) = pprMatches (LambdaExpr :: HsMatchContext id) matches ppr_cmd (HsCmdCase expr matches) = sep [ sep [text "case", nest 4 (ppr expr), ptext (sLit "of {")], nest 2 (pprMatches (CaseAlt :: HsMatchContext id) matches <+> char '}') ] ppr_cmd (HsCmdIf _ e ct ce) = sep [hsep [text "if", nest 2 (ppr e), ptext (sLit "then")], nest 4 (ppr ct), text "else", nest 4 (ppr ce)] -- special case: let ... in let ... ppr_cmd (HsCmdLet (L _ binds) cmd@(L _ (HsCmdLet _ _))) = sep [hang (text "let") 2 (hsep [pprBinds binds, ptext (sLit "in")]), ppr_lcmd cmd] ppr_cmd (HsCmdLet (L _ binds) cmd) = sep [hang (text "let") 2 (pprBinds binds), hang (text "in") 2 (ppr cmd)] ppr_cmd (HsCmdDo (L _ stmts) _) = pprDo ArrowExpr stmts ppr_cmd (HsCmdWrap w cmd) = pprHsWrapper (ppr_cmd cmd) w ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp True) = hsep [ppr_lexpr arrow, larrowt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsFirstOrderApp False) = hsep [ppr_lexpr arg, arrowt, ppr_lexpr arrow] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp True) = hsep [ppr_lexpr arrow, larrowtt, ppr_lexpr arg] ppr_cmd (HsCmdArrApp arrow arg _ HsHigherOrderApp False) = hsep [ppr_lexpr arg, arrowtt, ppr_lexpr arrow] ppr_cmd (HsCmdArrForm (L _ (HsVar (L _ v))) (Just _) [arg1, arg2]) = sep [pprCmdArg (unLoc arg1), hsep [pprInfixOcc v, pprCmdArg (unLoc arg2)]] ppr_cmd (HsCmdArrForm op _ args) = hang (text "(|" <> ppr_lexpr op) 4 (sep (map (pprCmdArg.unLoc) args) <> text "|)") pprCmdArg :: OutputableBndr id => HsCmdTop id -> SDoc pprCmdArg (HsCmdTop cmd@(L _ (HsCmdArrForm _ Nothing [])) _ _ _) = ppr_lcmd cmd pprCmdArg (HsCmdTop cmd _ _ _) = parens (ppr_lcmd cmd) instance OutputableBndr id => Outputable (HsCmdTop id) where ppr = pprCmdArg {- ************************************************************************ * * \subsection{Record binds} * * ************************************************************************ -} type HsRecordBinds id = HsRecFields id (LHsExpr id) {- ************************************************************************ * * \subsection{@Match@, @GRHSs@, and @GRHS@ datatypes} * * ************************************************************************ @Match@es are sets of pattern bindings and right hand sides for functions, patterns or case branches. For example, if a function @g@ is defined as: \begin{verbatim} g (x,y) = y g ((x:ys),y) = y+1, \end{verbatim} then \tr{g} has two @Match@es: @(x,y) = y@ and @((x:ys),y) = y+1@. It is always the case that each element of an @[Match]@ list has the same number of @pats@s inside it. This corresponds to saying that a function defined by pattern matching must have the same number of patterns in each equation. -} data MatchGroup id body = MG { mg_alts :: Located [LMatch id body] -- The alternatives , mg_arg_tys :: [PostTc id Type] -- Types of the arguments, t1..tn , mg_res_ty :: PostTc id Type -- Type of the result, tr , mg_origin :: Origin } -- The type is the type of the entire group -- t1 -> ... -> tn -> tr -- where there are n patterns deriving (Typeable) deriving instance (Data body,DataId id) => Data (MatchGroup id body) type LMatch id body = Located (Match id body) -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnSemi' when in a -- list -- For details on above see note [Api annotations] in ApiAnnotation data Match id body = Match { m_fixity :: MatchFixity id, -- See note [m_fixity in Match] m_pats :: [LPat id], -- The patterns m_type :: (Maybe (LHsType id)), -- A type signature for the result of the match -- Nothing after typechecking -- NB: No longer supported m_grhss :: (GRHSs id body) } deriving (Typeable) deriving instance (Data body,DataId id) => Data (Match id body) {- Note [m_fixity in Match] ~~~~~~~~~~~~~~~~~~~~~~ The parser initially creates a FunBind with a single Match in it for every function definition it sees. These are then grouped together by getMonoBind into a single FunBind, where all the Matches are combined. In the process, all the original FunBind fun_id's bar one are discarded, including the locations. This causes a problem for source to source conversions via API Annotations, so the original fun_ids and infix flags are preserved in the Match, when it originates from a FunBind. Example infix function definition requiring individual API Annotations (&&& ) [] [] = [] xs &&& [] = xs ( &&& ) [] ys = ys -} -- |When a Match is part of a FunBind, it captures one complete equation for the -- function. As such it has the function name, and its fixity. data MatchFixity id = NonFunBindMatch | FunBindMatch (Located id) -- of the Id Bool -- is infix deriving (Typeable) deriving instance (DataId id) => Data (MatchFixity id) isInfixMatch :: Match id body -> Bool isInfixMatch match = case m_fixity match of FunBindMatch _ True -> True _ -> False isEmptyMatchGroup :: MatchGroup id body -> Bool isEmptyMatchGroup (MG { mg_alts = ms }) = null $ unLoc ms -- | Is there only one RHS in this group? isSingletonMatchGroup :: MatchGroup id body -> Bool isSingletonMatchGroup (MG { mg_alts = L _ [match] }) | L _ (Match { m_grhss = GRHSs { grhssGRHSs = [_] } }) <- match = True isSingletonMatchGroup _ = False matchGroupArity :: MatchGroup id body -> Arity -- Precondition: MatchGroup is non-empty -- This is called before type checking, when mg_arg_tys is not set matchGroupArity (MG { mg_alts = alts }) | L _ (alt1:_) <- alts = length (hsLMatchPats alt1) | otherwise = panic "matchGroupArity" hsLMatchPats :: LMatch id body -> [LPat id] hsLMatchPats (L _ (Match _ pats _ _)) = pats -- | GRHSs are used both for pattern bindings and for Matches -- -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnEqual','ApiAnnotation.AnnWhere', -- 'ApiAnnotation.AnnOpen','ApiAnnotation.AnnClose' -- 'ApiAnnotation.AnnRarrow','ApiAnnotation.AnnSemi' -- For details on above see note [Api annotations] in ApiAnnotation data GRHSs id body = GRHSs { grhssGRHSs :: [LGRHS id body], -- ^ Guarded RHSs grhssLocalBinds :: Located (HsLocalBinds id) -- ^ The where clause } deriving (Typeable) deriving instance (Data body,DataId id) => Data (GRHSs id body) type LGRHS id body = Located (GRHS id body) -- | Guarded Right Hand Side. data GRHS id body = GRHS [GuardLStmt id] -- Guards body -- Right hand side deriving (Typeable) deriving instance (Data body,DataId id) => Data (GRHS id body) -- We know the list must have at least one @Match@ in it. pprMatches :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> MatchGroup idR body -> SDoc pprMatches ctxt (MG { mg_alts = matches }) = vcat (map (pprMatch ctxt) (map unLoc (unLoc matches))) -- Don't print the type; it's only a place-holder before typechecking -- Exported to HsBinds, which can't see the defn of HsMatchContext pprFunBind :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => idL -> MatchGroup idR body -> SDoc pprFunBind fun matches = pprMatches (FunRhs fun) matches -- Exported to HsBinds, which can't see the defn of HsMatchContext pprPatBind :: forall bndr id body. (OutputableBndr bndr, OutputableBndr id, Outputable body) => LPat bndr -> GRHSs id body -> SDoc pprPatBind pat (grhss) = sep [ppr pat, nest 2 (pprGRHSs (PatBindRhs :: HsMatchContext id) grhss)] pprMatch :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> Match idR body -> SDoc pprMatch ctxt match = sep [ sep (herald : map (nest 2 . pprParendLPat) other_pats) , nest 2 ppr_maybe_ty , nest 2 (pprGRHSs ctxt (m_grhss match)) ] where is_infix = isInfixMatch match (herald, other_pats) = case ctxt of FunRhs fun | not is_infix -> (pprPrefixOcc fun, m_pats match) -- f x y z = e -- Not pprBndr; the AbsBinds will -- have printed the signature | null pats2 -> (pp_infix, []) -- x &&& y = e | otherwise -> (parens pp_infix, pats2) -- (x &&& y) z = e where pp_infix = pprParendLPat pat1 <+> pprInfixOcc fun <+> pprParendLPat pat2 LambdaExpr -> (char '\\', m_pats match) _ -> ASSERT( null pats1 ) (ppr pat1, []) -- No parens around the single pat (pat1:pats1) = m_pats match (pat2:pats2) = pats1 ppr_maybe_ty = case m_type match of Just ty -> dcolon <+> ppr ty Nothing -> empty pprGRHSs :: (OutputableBndr idR, Outputable body) => HsMatchContext idL -> GRHSs idR body -> SDoc pprGRHSs ctxt (GRHSs grhss (L _ binds)) = vcat (map (pprGRHS ctxt . unLoc) grhss) $$ ppUnless (isEmptyLocalBinds binds) (text "where" $$ nest 4 (pprBinds binds)) pprGRHS :: (OutputableBndr idR, Outputable body) => HsMatchContext idL -> GRHS idR body -> SDoc pprGRHS ctxt (GRHS [] body) = pp_rhs ctxt body pprGRHS ctxt (GRHS guards body) = sep [vbar <+> interpp'SP guards, pp_rhs ctxt body] pp_rhs :: Outputable body => HsMatchContext idL -> body -> SDoc pp_rhs ctxt rhs = matchSeparator ctxt <+> pprDeeper (ppr rhs) {- ************************************************************************ * * \subsection{Do stmts and list comprehensions} * * ************************************************************************ -} type LStmt id body = Located (StmtLR id id body) type LStmtLR idL idR body = Located (StmtLR idL idR body) type Stmt id body = StmtLR id id body type CmdLStmt id = LStmt id (LHsCmd id) type CmdStmt id = Stmt id (LHsCmd id) type ExprLStmt id = LStmt id (LHsExpr id) type ExprStmt id = Stmt id (LHsExpr id) type GuardLStmt id = LStmt id (LHsExpr id) type GuardStmt id = Stmt id (LHsExpr id) type GhciLStmt id = LStmt id (LHsExpr id) type GhciStmt id = Stmt id (LHsExpr id) -- The SyntaxExprs in here are used *only* for do-notation and monad -- comprehensions, which have rebindable syntax. Otherwise they are unused. -- | API Annotations when in qualifier lists or guards -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnVbar', -- 'ApiAnnotation.AnnComma','ApiAnnotation.AnnThen', -- 'ApiAnnotation.AnnBy','ApiAnnotation.AnnBy', -- 'ApiAnnotation.AnnGroup','ApiAnnotation.AnnUsing' -- For details on above see note [Api annotations] in ApiAnnotation data StmtLR idL idR body -- body should always be (LHs**** idR) = LastStmt -- Always the last Stmt in ListComp, MonadComp, PArrComp, -- and (after the renamer) DoExpr, MDoExpr -- Not used for GhciStmtCtxt, PatGuard, which scope over other stuff body Bool -- True <=> return was stripped by ApplicativeDo (SyntaxExpr idR) -- The return operator, used only for -- MonadComp For ListComp, PArrComp, we -- use the baked-in 'return' For DoExpr, -- MDoExpr, we don't apply a 'return' at -- all See Note [Monad Comprehensions] | -- - 'ApiAnnotation.AnnKeywordId' : -- 'ApiAnnotation.AnnLarrow' -- For details on above see note [Api annotations] in ApiAnnotation | BindStmt (LPat idL) body (SyntaxExpr idR) -- The (>>=) operator; see Note [The type of bind in Stmts] (SyntaxExpr idR) -- The fail operator -- The fail operator is noSyntaxExpr -- if the pattern match can't fail -- | 'ApplicativeStmt' represents an applicative expression built with -- <$> and <*>. It is generated by the renamer, and is desugared into the -- appropriate applicative expression by the desugarer, but it is intended -- to be invisible in error messages. -- -- For full details, see Note [ApplicativeDo] in RnExpr -- | ApplicativeStmt [ ( SyntaxExpr idR , ApplicativeArg idL idR) ] -- [(<$>, e1), (<*>, e2), ..., (<*>, en)] (Maybe (SyntaxExpr idR)) -- 'join', if necessary (PostTc idR Type) -- Type of the body | BodyStmt body -- See Note [BodyStmt] (SyntaxExpr idR) -- The (>>) operator (SyntaxExpr idR) -- The `guard` operator; used only in MonadComp -- See notes [Monad Comprehensions] (PostTc idR Type) -- Element type of the RHS (used for arrows) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnLet' -- 'ApiAnnotation.AnnOpen' @'{'@,'ApiAnnotation.AnnClose' @'}'@, -- For details on above see note [Api annotations] in ApiAnnotation | LetStmt (Located (HsLocalBindsLR idL idR)) -- ParStmts only occur in a list/monad comprehension | ParStmt [ParStmtBlock idL idR] (SyntaxExpr idR) -- Polymorphic `mzip` for monad comprehensions (SyntaxExpr idR) -- The `>>=` operator -- See notes [Monad Comprehensions] -- After renaming, the ids are the binders -- bound by the stmts and used after themp | TransStmt { trS_form :: TransForm, trS_stmts :: [ExprLStmt idL], -- Stmts to the *left* of the 'group' -- which generates the tuples to be grouped trS_bndrs :: [(idR, idR)], -- See Note [TransStmt binder map] trS_using :: LHsExpr idR, trS_by :: Maybe (LHsExpr idR), -- "by e" (optional) -- Invariant: if trS_form = GroupBy, then grp_by = Just e trS_ret :: SyntaxExpr idR, -- The monomorphic 'return' function for -- the inner monad comprehensions trS_bind :: SyntaxExpr idR, -- The '(>>=)' operator trS_fmap :: SyntaxExpr idR -- The polymorphic 'fmap' function for desugaring -- Only for 'group' forms } -- See Note [Monad Comprehensions] -- Recursive statement (see Note [How RecStmt works] below) -- | - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRec' -- For details on above see note [Api annotations] in ApiAnnotation | RecStmt { recS_stmts :: [LStmtLR idL idR body] -- The next two fields are only valid after renaming , recS_later_ids :: [idR] -- The ids are a subset of the variables bound by the -- stmts that are used in stmts that follow the RecStmt , recS_rec_ids :: [idR] -- Ditto, but these variables are the "recursive" ones, -- that are used before they are bound in the stmts of -- the RecStmt. -- An Id can be in both groups -- Both sets of Ids are (now) treated monomorphically -- See Note [How RecStmt works] for why they are separate -- Rebindable syntax , recS_bind_fn :: SyntaxExpr idR -- The bind function , recS_ret_fn :: SyntaxExpr idR -- The return function , recS_mfix_fn :: SyntaxExpr idR -- The mfix function -- These fields are only valid after typechecking , recS_later_rets :: [PostTcExpr] -- (only used in the arrow version) , recS_rec_rets :: [PostTcExpr] -- These expressions correspond 1-to-1 -- with recS_later_ids and recS_rec_ids, -- and are the expressions that should be -- returned by the recursion. -- They may not quite be the Ids themselves, -- because the Id may be *polymorphic*, but -- the returned thing has to be *monomorphic*, -- so they may be type applications , recS_ret_ty :: PostTc idR Type -- The type of -- do { stmts; return (a,b,c) } -- With rebindable syntax the type might not -- be quite as simple as (m (tya, tyb, tyc)). } deriving (Typeable) deriving instance (Data body, DataId idL, DataId idR) => Data (StmtLR idL idR body) data TransForm -- The 'f' below is the 'using' function, 'e' is the by function = ThenForm -- then f or then f by e (depending on trS_by) | GroupForm -- then group using f or then group by e using f (depending on trS_by) deriving (Data, Typeable) data ParStmtBlock idL idR = ParStmtBlock [ExprLStmt idL] [idR] -- The variables to be returned (SyntaxExpr idR) -- The return operator deriving( Typeable ) deriving instance (DataId idL, DataId idR) => Data (ParStmtBlock idL idR) data ApplicativeArg idL idR = ApplicativeArgOne -- pat <- expr (pat must be irrefutable) (LPat idL) (LHsExpr idL) | ApplicativeArgMany -- do { stmts; return vars } [ExprLStmt idL] -- stmts (SyntaxExpr idL) -- return (v1,..,vn), or just (v1,..,vn) (LPat idL) -- (v1,...,vn) deriving( Typeable ) deriving instance (DataId idL, DataId idR) => Data (ApplicativeArg idL idR) {- Note [The type of bind in Stmts] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Some Stmts, notably BindStmt, keep the (>>=) bind operator. We do NOT assume that it has type (>>=) :: m a -> (a -> m b) -> m b In some cases (see Trac #303, #1537) it might have a more exotic type, such as (>>=) :: m i j a -> (a -> m j k b) -> m i k b So we must be careful not to make assumptions about the type. In particular, the monad may not be uniform throughout. Note [TransStmt binder map] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ The [(idR,idR)] in a TransStmt behaves as follows: * Before renaming: [] * After renaming: [ (x27,x27), ..., (z35,z35) ] These are the variables bound by the stmts to the left of the 'group' and used either in the 'by' clause, or in the stmts following the 'group' Each item is a pair of identical variables. * After typechecking: [ (x27:Int, x27:[Int]), ..., (z35:Bool, z35:[Bool]) ] Each pair has the same unique, but different *types*. Note [BodyStmt] ~~~~~~~~~~~~~~~ BodyStmts are a bit tricky, because what they mean depends on the context. Consider the following contexts: A do expression of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E any_ty: do { ....; E; ... } E :: m any_ty Translation: E >> ... A list comprehensions of type [elt_ty] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] [ .. | ..., E, ... ] [ .. | .... | ..., E | ... ] E :: Bool Translation: if E then fail else ... A guard list, guarding a RHS of type rhs_ty ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E BooParStmtBlockl: f x | ..., E, ... = ...rhs... E :: Bool Translation: if E then fail else ... A monad comprehension of type (m res_ty) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * BodyStmt E Bool: [ .. | .... E ] E :: Bool Translation: guard E >> ... Array comprehensions are handled like list comprehensions. Note [How RecStmt works] ~~~~~~~~~~~~~~~~~~~~~~~~ Example: HsDo [ BindStmt x ex , RecStmt { recS_rec_ids = [a, c] , recS_stmts = [ BindStmt b (return (a,c)) , LetStmt a = ...b... , BindStmt c ec ] , recS_later_ids = [a, b] , return (a b) ] Here, the RecStmt binds a,b,c; but - Only a,b are used in the stmts *following* the RecStmt, - Only a,c are used in the stmts *inside* the RecStmt *before* their bindings Why do we need *both* rec_ids and later_ids? For monads they could be combined into a single set of variables, but not for arrows. That follows from the types of the respective feedback operators: mfix :: MonadFix m => (a -> m a) -> m a loop :: ArrowLoop a => a (b,d) (c,d) -> a b c * For mfix, the 'a' covers the union of the later_ids and the rec_ids * For 'loop', 'c' is the later_ids and 'd' is the rec_ids Note [Typing a RecStmt] ~~~~~~~~~~~~~~~~~~~~~~~ A (RecStmt stmts) types as if you had written (v1,..,vn, _, ..., _) <- mfix (\~(_, ..., _, r1, ..., rm) -> do { stmts ; return (v1,..vn, r1, ..., rm) }) where v1..vn are the later_ids r1..rm are the rec_ids Note [Monad Comprehensions] ~~~~~~~~~~~~~~~~~~~~~~~~~~~ Monad comprehensions require separate functions like 'return' and '>>=' for desugaring. These functions are stored in the statements used in monad comprehensions. For example, the 'return' of the 'LastStmt' expression is used to lift the body of the monad comprehension: [ body | stmts ] => stmts >>= \bndrs -> return body In transform and grouping statements ('then ..' and 'then group ..') the 'return' function is required for nested monad comprehensions, for example: [ body | stmts, then f, rest ] => f [ env | stmts ] >>= \bndrs -> [ body | rest ] BodyStmts require the 'Control.Monad.guard' function for boolean expressions: [ body | exp, stmts ] => guard exp >> [ body | stmts ] Parallel statements require the 'Control.Monad.Zip.mzip' function: [ body | stmts1 | stmts2 | .. ] => mzip stmts1 (mzip stmts2 (..)) >>= \(bndrs1, (bndrs2, ..)) -> return body In any other context than 'MonadComp', the fields for most of these 'SyntaxExpr's stay bottom. -} instance (OutputableBndr idL) => Outputable (ParStmtBlock idL idR) where ppr (ParStmtBlock stmts _ _) = interpp'SP stmts instance (OutputableBndr idL, OutputableBndr idR, Outputable body) => Outputable (StmtLR idL idR body) where ppr stmt = pprStmt stmt pprStmt :: forall idL idR body . (OutputableBndr idL, OutputableBndr idR, Outputable body) => (StmtLR idL idR body) -> SDoc pprStmt (LastStmt expr ret_stripped _) = ifPprDebug (text "[last]") <+> (if ret_stripped then text "return" else empty) <+> ppr expr pprStmt (BindStmt pat expr _ _) = hsep [ppr pat, larrow, ppr expr] pprStmt (LetStmt (L _ binds)) = hsep [text "let", pprBinds binds] pprStmt (BodyStmt expr _ _ _) = ppr expr pprStmt (ParStmt stmtss _ _) = sep (punctuate (text " | ") (map ppr stmtss)) pprStmt (TransStmt { trS_stmts = stmts, trS_by = by, trS_using = using, trS_form = form }) = sep $ punctuate comma (map ppr stmts ++ [pprTransStmt by using form]) pprStmt (RecStmt { recS_stmts = segment, recS_rec_ids = rec_ids , recS_later_ids = later_ids }) = text "rec" <+> vcat [ ppr_do_stmts segment , ifPprDebug (vcat [ text "rec_ids=" <> ppr rec_ids , text "later_ids=" <> ppr later_ids])] pprStmt (ApplicativeStmt args mb_join _) = getPprStyle $ \style -> if userStyle style then pp_for_user else pp_debug where -- make all the Applicative stuff invisible in error messages by -- flattening the whole ApplicativeStmt nest back to a sequence -- of statements. pp_for_user = vcat $ punctuate semi $ concatMap flattenArg args -- ppr directly rather than transforming here, because we need to -- inject a "return" which is hard when we're polymorphic in the id -- type. flattenStmt :: ExprLStmt idL -> [SDoc] flattenStmt (L _ (ApplicativeStmt args _ _)) = concatMap flattenArg args flattenStmt stmt = [ppr stmt] flattenArg (_, ApplicativeArgOne pat expr) = [ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr :: ExprStmt idL)] flattenArg (_, ApplicativeArgMany stmts _ _) = concatMap flattenStmt stmts pp_debug = let ap_expr = sep (punctuate (text " |") (map pp_arg args)) in if isNothing mb_join then ap_expr else text "join" <+> parens ap_expr pp_arg (_, ApplicativeArgOne pat expr) = ppr (BindStmt pat expr noSyntaxExpr noSyntaxExpr :: ExprStmt idL) pp_arg (_, ApplicativeArgMany stmts return pat) = ppr pat <+> text "<-" <+> ppr (HsDo DoExpr (noLoc (stmts ++ [noLoc (LastStmt (noLoc return) False noSyntaxExpr)])) (error "pprStmt")) pprTransformStmt :: OutputableBndr id => [id] -> LHsExpr id -> Maybe (LHsExpr id) -> SDoc pprTransformStmt bndrs using by = sep [ text "then" <+> ifPprDebug (braces (ppr bndrs)) , nest 2 (ppr using) , nest 2 (pprBy by)] pprTransStmt :: Outputable body => Maybe body -> body -> TransForm -> SDoc pprTransStmt by using ThenForm = sep [ text "then", nest 2 (ppr using), nest 2 (pprBy by)] pprTransStmt by using GroupForm = sep [ text "then group", nest 2 (pprBy by), nest 2 (ptext (sLit "using") <+> ppr using)] pprBy :: Outputable body => Maybe body -> SDoc pprBy Nothing = empty pprBy (Just e) = text "by" <+> ppr e pprDo :: (OutputableBndr id, Outputable body) => HsStmtContext any -> [LStmt id body] -> SDoc pprDo DoExpr stmts = text "do" <+> ppr_do_stmts stmts pprDo GhciStmtCtxt stmts = text "do" <+> ppr_do_stmts stmts pprDo ArrowExpr stmts = text "do" <+> ppr_do_stmts stmts pprDo MDoExpr stmts = text "mdo" <+> ppr_do_stmts stmts pprDo ListComp stmts = brackets $ pprComp stmts pprDo PArrComp stmts = paBrackets $ pprComp stmts pprDo MonadComp stmts = brackets $ pprComp stmts pprDo _ _ = panic "pprDo" -- PatGuard, ParStmtCxt ppr_do_stmts :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => [LStmtLR idL idR body] -> SDoc -- Print a bunch of do stmts, with explicit braces and semicolons, -- so that we are not vulnerable to layout bugs ppr_do_stmts stmts = lbrace <+> pprDeeperList vcat (punctuate semi (map ppr stmts)) <+> rbrace pprComp :: (OutputableBndr id, Outputable body) => [LStmt id body] -> SDoc pprComp quals -- Prints: body | qual1, ..., qualn | not (null quals) , L _ (LastStmt body _ _) <- last quals = hang (ppr body <+> vbar) 2 (pprQuals (dropTail 1 quals)) | otherwise = pprPanic "pprComp" (pprQuals quals) pprQuals :: (OutputableBndr id, Outputable body) => [LStmt id body] -> SDoc -- Show list comprehension qualifiers separated by commas pprQuals quals = interpp'SP quals {- ************************************************************************ * * Template Haskell quotation brackets * * ************************************************************************ -} data HsSplice id = HsTypedSplice -- $$z or $$(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsUntypedSplice -- $z or $(f 4) id -- A unique name to identify this splice point (LHsExpr id) -- See Note [Pending Splices] | HsQuasiQuote -- See Note [Quasi-quote overview] in TcSplice id -- Splice point id -- Quoter SrcSpan -- The span of the enclosed string FastString -- The enclosed string deriving (Typeable ) deriving instance (DataId id) => Data (HsSplice id) isTypedSplice :: HsSplice id -> Bool isTypedSplice (HsTypedSplice {}) = True isTypedSplice _ = False -- Quasi-quotes are untyped splices -- See Note [Pending Splices] type SplicePointName = Name data PendingRnSplice = PendingRnSplice UntypedSpliceFlavour SplicePointName (LHsExpr Name) deriving (Data, Typeable) data UntypedSpliceFlavour = UntypedExpSplice | UntypedPatSplice | UntypedTypeSplice | UntypedDeclSplice deriving( Data, Typeable ) data PendingTcSplice = PendingTcSplice SplicePointName (LHsExpr Id) deriving( Data, Typeable ) {- Note [Pending Splices] ~~~~~~~~~~~~~~~~~~~~~~ When we rename an untyped bracket, we name and lift out all the nested splices, so that when the typechecker hits the bracket, it can typecheck those nested splices without having to walk over the untyped bracket code. So for example [| f $(g x) |] looks like HsBracket (HsApp (HsVar "f") (HsSpliceE _ (g x))) which the renamer rewrites to HsRnBracketOut (HsApp (HsVar f) (HsSpliceE sn (g x))) [PendingRnSplice UntypedExpSplice sn (g x)] * The 'sn' is the Name of the splice point, the SplicePointName * The PendingRnExpSplice gives the splice that splice-point name maps to; and the typechecker can now conveniently find these sub-expressions * The other copy of the splice, in the second argument of HsSpliceE in the renamed first arg of HsRnBracketOut is used only for pretty printing There are four varieties of pending splices generated by the renamer, distinguished by their UntypedSpliceFlavour * Pending expression splices (UntypedExpSplice), e.g., [|$(f x) + 2|] UntypedExpSplice is also used for * quasi-quotes, where the pending expression expands to $(quoter "...blah...") (see RnSplice.makePending, HsQuasiQuote case) * cross-stage lifting, where the pending expression expands to $(lift x) (see RnSplice.checkCrossStageLifting) * Pending pattern splices (UntypedPatSplice), e.g., [| \$(f x) -> x |] * Pending type splices (UntypedTypeSplice), e.g., [| f :: $(g x) |] * Pending declaration (UntypedDeclSplice), e.g., [| let $(f x) in ... |] There is a fifth variety of pending splice, which is generated by the type checker: * Pending *typed* expression splices, (PendingTcSplice), e.g., [||1 + $$(f 2)||] It would be possible to eliminate HsRnBracketOut and use HsBracketOut for the output of the renamer. However, when pretty printing the output of the renamer, e.g., in a type error message, we *do not* want to print out the pending splices. In contrast, when pretty printing the output of the type checker, we *do* want to print the pending splices. So splitting them up seems to make sense, although I hate to add another constructor to HsExpr. -} instance OutputableBndr id => Outputable (HsSplice id) where ppr s = pprSplice s pprPendingSplice :: OutputableBndr id => SplicePointName -> LHsExpr id -> SDoc pprPendingSplice n e = angleBrackets (ppr n <> comma <+> ppr e) pprSplice :: OutputableBndr id => HsSplice id -> SDoc pprSplice (HsTypedSplice n e) = ppr_splice (text "$$") n e pprSplice (HsUntypedSplice n e) = ppr_splice (text "$") n e pprSplice (HsQuasiQuote n q _ s) = ppr_quasi n q s ppr_quasi :: OutputableBndr id => id -> id -> FastString -> SDoc ppr_quasi n quoter quote = ifPprDebug (brackets (ppr n)) <> char '[' <> ppr quoter <> vbar <> ppr quote <> text "|]" ppr_splice :: OutputableBndr id => SDoc -> id -> LHsExpr id -> SDoc ppr_splice herald n e = herald <> ifPprDebug (brackets (ppr n)) <> eDoc where -- We use pprLExpr to match pprParendExpr: -- Using pprLExpr makes sure that we go 'deeper' -- I think that is usually (always?) right pp_as_was = pprLExpr e eDoc = case unLoc e of HsPar _ -> pp_as_was HsVar _ -> pp_as_was _ -> parens pp_as_was data HsBracket id = ExpBr (LHsExpr id) -- [| expr |] | PatBr (LPat id) -- [p| pat |] | DecBrL [LHsDecl id] -- [d| decls |]; result of parser | DecBrG (HsGroup id) -- [d| decls |]; result of renamer | TypBr (LHsType id) -- [t| type |] | VarBr Bool id -- True: 'x, False: ''T -- (The Bool flag is used only in pprHsBracket) | TExpBr (LHsExpr id) -- [|| expr ||] deriving (Typeable) deriving instance (DataId id) => Data (HsBracket id) isTypedBracket :: HsBracket id -> Bool isTypedBracket (TExpBr {}) = True isTypedBracket _ = False instance OutputableBndr id => Outputable (HsBracket id) where ppr = pprHsBracket pprHsBracket :: OutputableBndr id => HsBracket id -> SDoc pprHsBracket (ExpBr e) = thBrackets empty (ppr e) pprHsBracket (PatBr p) = thBrackets (char 'p') (ppr p) pprHsBracket (DecBrG gp) = thBrackets (char 'd') (ppr gp) pprHsBracket (DecBrL ds) = thBrackets (char 'd') (vcat (map ppr ds)) pprHsBracket (TypBr t) = thBrackets (char 't') (ppr t) pprHsBracket (VarBr True n) = char '\'' <> ppr n pprHsBracket (VarBr False n) = text "''" <> ppr n pprHsBracket (TExpBr e) = thTyBrackets (ppr e) thBrackets :: SDoc -> SDoc -> SDoc thBrackets pp_kind pp_body = char '[' <> pp_kind <> vbar <+> pp_body <+> text "|]" thTyBrackets :: SDoc -> SDoc thTyBrackets pp_body = text "[||" <+> pp_body <+> ptext (sLit "||]") instance Outputable PendingRnSplice where ppr (PendingRnSplice _ n e) = pprPendingSplice n e instance Outputable PendingTcSplice where ppr (PendingTcSplice n e) = pprPendingSplice n e {- ************************************************************************ * * \subsection{Enumerations and list comprehensions} * * ************************************************************************ -} data ArithSeqInfo id = From (LHsExpr id) | FromThen (LHsExpr id) (LHsExpr id) | FromTo (LHsExpr id) (LHsExpr id) | FromThenTo (LHsExpr id) (LHsExpr id) (LHsExpr id) deriving (Typeable) deriving instance (DataId id) => Data (ArithSeqInfo id) instance OutputableBndr id => Outputable (ArithSeqInfo id) where ppr (From e1) = hcat [ppr e1, pp_dotdot] ppr (FromThen e1 e2) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot] ppr (FromTo e1 e3) = hcat [ppr e1, pp_dotdot, ppr e3] ppr (FromThenTo e1 e2 e3) = hcat [ppr e1, comma, space, ppr e2, pp_dotdot, ppr e3] pp_dotdot :: SDoc pp_dotdot = text " .. " {- ************************************************************************ * * \subsection{HsMatchCtxt} * * ************************************************************************ -} data HsMatchContext id -- Context of a Match = FunRhs id -- Function binding for f | LambdaExpr -- Patterns of a lambda | CaseAlt -- Patterns and guards on a case alternative | IfAlt -- Guards of a multi-way if alternative | ProcExpr -- Patterns of a proc | PatBindRhs -- A pattern binding eg [y] <- e = e | RecUpd -- Record update [used only in DsExpr to -- tell matchWrapper what sort of -- runtime error message to generate] | StmtCtxt (HsStmtContext id) -- Pattern of a do-stmt, list comprehension, -- pattern guard, etc | ThPatSplice -- A Template Haskell pattern splice | ThPatQuote -- A Template Haskell pattern quotation [p| (a,b) |] | PatSyn -- A pattern synonym declaration deriving (Data, Typeable) data HsStmtContext id = ListComp | MonadComp | PArrComp -- Parallel array comprehension | DoExpr -- do { ... } | MDoExpr -- mdo { ... } ie recursive do-expression | ArrowExpr -- do-notation in an arrow-command context | GhciStmtCtxt -- A command-line Stmt in GHCi pat <- rhs | PatGuard (HsMatchContext id) -- Pattern guard for specified thing | ParStmtCtxt (HsStmtContext id) -- A branch of a parallel stmt | TransStmtCtxt (HsStmtContext id) -- A branch of a transform stmt deriving (Data, Typeable) isListCompExpr :: HsStmtContext id -> Bool -- Uses syntax [ e | quals ] isListCompExpr ListComp = True isListCompExpr PArrComp = True isListCompExpr MonadComp = True isListCompExpr (ParStmtCtxt c) = isListCompExpr c isListCompExpr (TransStmtCtxt c) = isListCompExpr c isListCompExpr _ = False isMonadCompExpr :: HsStmtContext id -> Bool isMonadCompExpr MonadComp = True isMonadCompExpr (ParStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr (TransStmtCtxt ctxt) = isMonadCompExpr ctxt isMonadCompExpr _ = False matchSeparator :: HsMatchContext id -> SDoc matchSeparator (FunRhs {}) = text "=" matchSeparator CaseAlt = text "->" matchSeparator IfAlt = text "->" matchSeparator LambdaExpr = text "->" matchSeparator ProcExpr = text "->" matchSeparator PatBindRhs = text "=" matchSeparator (StmtCtxt _) = text "<-" matchSeparator RecUpd = panic "unused" matchSeparator ThPatSplice = panic "unused" matchSeparator ThPatQuote = panic "unused" matchSeparator PatSyn = panic "unused" pprMatchContext :: Outputable id => HsMatchContext id -> SDoc pprMatchContext ctxt | want_an ctxt = text "an" <+> pprMatchContextNoun ctxt | otherwise = text "a" <+> pprMatchContextNoun ctxt where want_an (FunRhs {}) = True -- Use "an" in front want_an ProcExpr = True want_an _ = False pprMatchContextNoun :: Outputable id => HsMatchContext id -> SDoc pprMatchContextNoun (FunRhs fun) = text "equation for" <+> quotes (ppr fun) pprMatchContextNoun CaseAlt = text "case alternative" pprMatchContextNoun IfAlt = text "multi-way if alternative" pprMatchContextNoun RecUpd = text "record-update construct" pprMatchContextNoun ThPatSplice = text "Template Haskell pattern splice" pprMatchContextNoun ThPatQuote = text "Template Haskell pattern quotation" pprMatchContextNoun PatBindRhs = text "pattern binding" pprMatchContextNoun LambdaExpr = text "lambda abstraction" pprMatchContextNoun ProcExpr = text "arrow abstraction" pprMatchContextNoun (StmtCtxt ctxt) = text "pattern binding in" $$ pprStmtContext ctxt pprMatchContextNoun PatSyn = text "pattern synonym declaration" ----------------- pprAStmtContext, pprStmtContext :: Outputable id => HsStmtContext id -> SDoc pprAStmtContext ctxt = article <+> pprStmtContext ctxt where pp_an = text "an" pp_a = text "a" article = case ctxt of MDoExpr -> pp_an PArrComp -> pp_an GhciStmtCtxt -> pp_an _ -> pp_a ----------------- pprStmtContext GhciStmtCtxt = text "interactive GHCi command" pprStmtContext DoExpr = text "'do' block" pprStmtContext MDoExpr = text "'mdo' block" pprStmtContext ArrowExpr = text "'do' block in an arrow command" pprStmtContext ListComp = text "list comprehension" pprStmtContext MonadComp = text "monad comprehension" pprStmtContext PArrComp = text "array comprehension" pprStmtContext (PatGuard ctxt) = text "pattern guard for" $$ pprMatchContext ctxt -- Drop the inner contexts when reporting errors, else we get -- Unexpected transform statement -- in a transformed branch of -- transformed branch of -- transformed branch of monad comprehension pprStmtContext (ParStmtCtxt c) | opt_PprStyle_Debug = sep [text "parallel branch of", pprAStmtContext c] | otherwise = pprStmtContext c pprStmtContext (TransStmtCtxt c) | opt_PprStyle_Debug = sep [text "transformed branch of", pprAStmtContext c] | otherwise = pprStmtContext c -- Used to generate the string for a *runtime* error message matchContextErrString :: Outputable id => HsMatchContext id -> SDoc matchContextErrString (FunRhs fun) = text "function" <+> ppr fun matchContextErrString CaseAlt = text "case" matchContextErrString IfAlt = text "multi-way if" matchContextErrString PatBindRhs = text "pattern binding" matchContextErrString RecUpd = text "record update" matchContextErrString LambdaExpr = text "lambda" matchContextErrString ProcExpr = text "proc" matchContextErrString ThPatSplice = panic "matchContextErrString" -- Not used at runtime matchContextErrString ThPatQuote = panic "matchContextErrString" -- Not used at runtime matchContextErrString PatSyn = panic "matchContextErrString" -- Not used at runtime matchContextErrString (StmtCtxt (ParStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (TransStmtCtxt c)) = matchContextErrString (StmtCtxt c) matchContextErrString (StmtCtxt (PatGuard _)) = text "pattern guard" matchContextErrString (StmtCtxt GhciStmtCtxt) = text "interactive GHCi command" matchContextErrString (StmtCtxt DoExpr) = text "'do' block" matchContextErrString (StmtCtxt ArrowExpr) = text "'do' block" matchContextErrString (StmtCtxt MDoExpr) = text "'mdo' block" matchContextErrString (StmtCtxt ListComp) = text "list comprehension" matchContextErrString (StmtCtxt MonadComp) = text "monad comprehension" matchContextErrString (StmtCtxt PArrComp) = text "array comprehension" pprMatchInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsMatchContext idL -> Match idR body -> SDoc pprMatchInCtxt ctxt match = hang (text "In" <+> pprMatchContext ctxt <> colon) 4 (pprMatch ctxt match) pprStmtInCtxt :: (OutputableBndr idL, OutputableBndr idR, Outputable body) => HsStmtContext idL -> StmtLR idL idR body -> SDoc pprStmtInCtxt ctxt (LastStmt e _ _) | isListCompExpr ctxt -- For [ e | .. ], do not mutter about "stmts" = hang (text "In the expression:") 2 (ppr e) pprStmtInCtxt ctxt stmt = hang (text "In a stmt of" <+> pprAStmtContext ctxt <> colon) 2 (ppr_stmt stmt) where -- For Group and Transform Stmts, don't print the nested stmts! ppr_stmt (TransStmt { trS_by = by, trS_using = using , trS_form = form }) = pprTransStmt by using form ppr_stmt stmt = pprStmt stmt
gridaphobe/ghc
compiler/hsSyn/HsExpr.hs
bsd-3-clause
84,578
0
20
23,689
14,557
7,668
6,889
968
10
{-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} module Data.Default.Aux (Default(..)) where import Data.Default import Foreign.Ptr (Ptr, FunPtr, IntPtr, WordPtr, nullPtr, nullFunPtr, ptrToIntPtr, ptrToWordPtr) import Data.Bits (Bits, zeroBits) instance Default (Ptr a) where def = nullPtr instance Default (FunPtr a) where def = nullFunPtr instance Default IntPtr where def = ptrToIntPtr nullPtr instance Default WordPtr where def = ptrToWordPtr nullPtr instance {-# OVERLAPPABLE #-} Bits a => Default a where def = zeroBits
michaeljklein/CPlug
src/Data/Default/Aux.hs
bsd-3-clause
588
0
7
111
158
91
67
17
0
module ParserTest where import Test.Hspec import qualified Parser as Parser testParser = hspec $ do describe "Parser" $ do it "1. consumes head of lexemes when head of lexemes is identical to lookahead" $ do Parser.match "sTag" ["sTag", "eTag"] `shouldBe` ["eTag"] it "2. consumes head of lexemes when head of lexemes is identical to lookahead" $ do Parser.match "sTag" ["sTag", "the", "red", "dog", "eTag"] `shouldBe` ["the", "red", "dog", "eTag"]
chris-bacon/HTML-LaTeX-Compiler
tests/ParserTest.hs
bsd-3-clause
496
0
16
116
122
68
54
9
1
{- Copyright (c) 2014-2015, Johan Nordlander, Jonas Duregรฅrd, Michaล‚ Paล‚ka, Patrik Jansson and Josef Svenningsson All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Chalmers University of Technology nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -} {-# LANGUAGE FlexibleInstances #-} module AR where import qualified Data.Map as Map import Data.Map (Map, keys, elems) import Data.List import Data.Maybe dom :: Map a b -> [a] rng :: Map a b -> [b] dom = keys rng = elems a `subsetof` b = all (`elem` b) a a `equal` b = a `subsetof` b && b `subsetof` a unique xs = xs == nub xs data Component = Atomic (Map PortName Port) (Map VarName Type) [Runnable] | Composition (Map PortName Port) (Map CompName Component) [Connector] ports (Atomic iface _ _) = iface ports (Composition iface _ _) = iface data PortKind = SenderReceiver (Map VarName Type) | ClientServer (Map OpName Operation) -- a sum (choice) of operations instance Eq PortKind where SenderReceiver ts == SenderReceiver ts' = ts == ts' ClientServer ops == ClientServer ops' = ops == ops' _ == _ = False data Port = Provided PortKind | Required PortKind deriving Eq inverse (Provided p) = Required p inverse (Required p) = Provided p data Operation = Op (Map VarName ArgType) [Int] -- ^ a product (tuple) of arguments, set of error codes instance Eq Operation where Op args errs == Op args' errs' = args == args' && errs == errs' data ArgType = In Type | InOut Type | Out Type deriving Eq type Connector = (PortRef, PortRef) data PortRef = Qual CompName PortName | Ext PortName deriving Eq type PortName = String type CompName = String type FieldName = String type TagName = String type OpName = String type VarName = String type Statevars = Map VarName Value type Arguments = Map VarName Value type Response = Either Int (Map VarName Value) -- | Four different kinds of |Runnable|s data Runnable = Init Behavior -- ^ should set up initial state etc. | DataReceived PortName (Statevars -> Arguments -> Behavior) -- ^ async. method | OperationInvoked PortName OpName (Statevars -> Arguments -> Behavior) -- ^ sync. operation | Timing Double (Statevars -> Behavior) -- ^ repeated execution {- There are different classes of runnables. This type is not covering all of them. For example, in the full AUTOSAR standard, a runnable could have a set of waitPoints, but this simplified description assumes this set is empty. -} -- | Observable effect of a |Runnable| data Behavior = Sending PortName Arguments Behavior -- ^ | Invoking PortName OpName Arguments (Response -> Behavior) -- ^ Invoke operation (must check "port matching") | Responding Response Behavior -- ^ Act. on a call (might be better to merge with Idling) | Idling Statevars | Crashed | Comp (Map CompName Behavior) data Observation = Send PortRef Arguments | Invoke PortRef OpName Arguments | Respond Response | Tau update :: k -> v -> Map k v -> Map k v update = undefined connections :: env -> CompName -> PortName -> [PortRef] connections = undefined runnables :: env -> CompName -> [Runnable] runnables = undefined data Msg = Msg CompName PortName Arguments deriving Eq type ComponentLinks = [(CompName, CompName)] -- | perhaps a queue or at least timestamped messages type MsgPool = [Msg] type State = (Map CompName Behavior, MsgPool, ComponentLinks) reduce :: env -> State -> [(State, Observation)] reduce env (bhvs, msgs, links) = [ ((update c next bhvs, Msg c' p' args : msgs, links), Tau) | (c,Sending p args next) <- Map.assocs bhvs , Qual c' p' <- connections env c p ] ++ [ ((update c (run svars args) bhvs, delete (Msg c p args) msgs, links), Tau) | (c,Idling svars) <- Map.assocs bhvs , DataReceived p run <- runnables env c , Msg c1 p1 args <- msgs , c == c1, p == p1 ] ++ [ ((update c' (run svars args) bhvs, msgs, (c,c'):links), Tau) | (c,Invoking p op args cont) <- Map.assocs bhvs , (c',Idling svars) <- Map.assocs bhvs , OperationInvoked p' op' run <- runnables env c' , Qual c' p' `elem` connections env c p ] ++ [ ((update c (cont resp) (update c' next bhvs), msgs, delete (c,c') links), Tau) | (c,Invoking p op args cont) <- Map.assocs bhvs , (c',Responding resp next) <- Map.assocs bhvs , (c,c') `elem` links ] ++ [ ((update c next bhvs, msgs, links), Send (Ext p') args) | (c,Sending p args next) <- Map.assocs bhvs , Ext p' <- connections env c p ] ++ [ ((update c (Invoking p op args cont) bhvs, msgs, links), Invoke (Ext p') op args) | (c,Invoking p op args cont) <- Map.assocs bhvs , Ext p' <- connections env c p ] ++ [ ] -------------------------------------------------------------- validComp partial (Atomic iface sig runns) = unique (dom iface) && unique int_rcvs && unique int_ops && int_rcvs `subsetof` ext_rcvs && int_ops `subsetof` ext_ops && (partial || total) where ext_rcvs = [ p | (p, Provided (SenderReceiver _)) <- Map.assocs iface ] ext_ops = [ (p,o) | (p, Provided (ClientServer ops)) <- Map.assocs iface, o <- dom ops ] int_rcvs = [ p | DataReceived p _ <- runns ] int_ops = [ (p,o) | OperationInvoked p o _ <- runns ] total = ext_rcvs `subsetof` int_rcvs && ext_ops `subsetof` int_ops validComp partial (Composition iface comps conns) = unique (dom iface) && unique (dom comps) && all (validComp partial) (rng comps) && all (validConn all_ports) conns && all (== 1) (map fan_out req_clisrv) && all (>= 1) (map fan_out req_sndrcv) where all_ports = [ (Qual c p, port) | (c,comp) <- Map.assocs comps, (p,port) <- Map.assocs $ ports comp ] ++ [ (Ext p, inverse port) | (p,port) <- Map.assocs iface ] req_sndrcv = [ r | (r,Required (SenderReceiver _)) <- all_ports ] req_clisrv = [ r | (r,Required (ClientServer _)) <- all_ports ] fan_out r = length [ q | (p,q) <- conns, p == r ] validConn ports (r,r') = case (lookup r ports, lookup r' ports) of (Just (Required p), Just (Provided p')) -> p == p' _ -> False ------------------------------------------------------------------ data Type = TInt | TBool | TChar | TArray Type | TStruct (Map FieldName Type) | TUnion (Map TagName Type) instance Eq Type where TInt == TInt = True TBool == TBool = True TChar == TChar = True TArray t == TArray t' = t == t' TStruct ts == TStruct ts' = ts == ts' TUnion ts == TUnion ts' = ts == ts' _ == _ = False data Value = VInt Int | VBool Bool | VChar Char | VArray [Value] | VStruct (Map FieldName Value) | VUnion TagName Value deriving Eq hasType TInt (VInt _) = True hasType TBool (VBool _) = True hasType TChar (VChar _) = True hasType (TArray t) (VArray vs) = all (hasType t) vs hasType (TStruct ts) (VStruct fs) = unique (dom fs) && dom ts `equal` dom fs && and [ hasTypeIn ts f v | (f,v) <- Map.assocs fs ] hasType (TUnion ts) (VUnion tag v) = hasTypeIn ts tag v hasTypeIn ts k v = case Map.lookup k ts of Just t -> hasType t v; _ -> False
josefs/autosar
oldARSim/AR.hs
bsd-3-clause
10,018
0
16
3,405
2,662
1,411
1,251
173
2
module Signal.Wavelet.List2Test where import Test.HUnit (Assertion) import Signal.Wavelet.List2 import Signal.Wavelet.List.Common (inv) import Test.ArbitraryInstances (DwtInputList(..)) import Test.Data.Wavelet as DW import Test.Utils ((=~), (@=~?)) testDwt :: ([Double], [Double], [Double]) -> Assertion testDwt (ls, sig, expected) = expected @=~? dwt ls sig dataDwt :: [([Double], [Double], [Double])] dataDwt = DW.dataDwt testIdwt :: ([Double], [Double], [Double]) -> Assertion testIdwt (ls, sig, expected) = expected @=~? idwt ls sig dataIdwt :: [([Double], [Double], [Double])] dataIdwt = DW.dataIdwt propDWTInvertible :: DwtInputList -> Bool propDWTInvertible (DwtInputList (ls, sig)) = idwt (inv ls) (dwt ls sig) =~ sig
jstolarek/lattice-structure-hs
tests/Signal/Wavelet/List2Test.hs
bsd-3-clause
779
0
8
142
298
181
117
20
1
-- | NLP.WordNet.Prims provides primitive operations over the word net database. -- The general scheme of things is to call 'initializeWordNet' to get a 'WordNetEnv'. -- Once you have this, you can start querying. A query usually looks like (suppose -- we want "Dog" as a Noun: -- -- 'getIndexString' on "Dog". This will give us back a cannonicalized string, in this -- case, still "dog". We then use 'indexLookup' to get back an index for this string. -- Then, we call 'indexToSenseKey' to with the index and the sense number (the Index -- contains the number of senses) to get back a SenseKey. We finally call -- 'getSynsetForSense' on the sense key to get back a Synset. -- -- We can continue to query like this or we can use the offsets provided in the -- various fields of the Synset to query directly on an offset. Given an offset -- and a part of speech, we can use 'readSynset' directly to get a synset (instead -- of going through all this business with indices and sensekeys. module NLP.WordNet.Prims ( initializeWordNet, initializeWordNetWithOptions, closeWordNet, getIndexString, getSynsetForSense, readSynset, indexToSenseKey, indexLookup ) where import System.IO -- hiding (try, catch) import System.Environment import Numeric (readHex, readDec) import Data.Char (toLower, isSpace) import Data.Array import Data.Foldable (forM_) import Control.Exception import Control.Monad (when, liftM, mplus, unless) import Data.List (findIndex, find, elemIndex) import Data.Maybe (isNothing, fromJust, isJust, fromMaybe) import NLP.WordNet.PrimTypes import NLP.WordNet.Util import NLP.WordNet.Consts -- | initializeWordNet looks for the word net data files in the -- default directories, starting with environment variables WNSEARCHDIR -- and WNHOME, and then falling back to 'defaultPath' as defined in -- NLP.WordNet.Consts. initializeWordNet :: IO WordNetEnv initializeWordNet = initializeWordNetWithOptions Nothing Nothing -- | initializeWordNetWithOptions looks for the word net data files in the -- specified directory. Use this if wordnet is installed in a non-standard -- place on your machine and you don't have the appropriate env vars set up. initializeWordNetWithOptions :: Maybe FilePath -> -- word net data directory Maybe (String -> SomeException -> IO ()) -> -- "warning" function (by default, warnings go to stderr) IO WordNetEnv initializeWordNetWithOptions mSearchdir mWarn = do searchdir <- case mSearchdir of { Nothing -> getDefaultSearchDir ; Just d -> return d } let warn = fromMaybe (\s e -> hPutStrLn stderr (s ++ "\n" ++ show e)) mWarn version <- tryMaybe $ getEnv "WNDBVERSION" dHands <- mapM (\pos' -> do idxH <- openFileEx (makePath [searchdir, "index." ++ partName pos']) (BinaryMode ReadMode) dataH <- openFileEx (makePath [searchdir, "data." ++ partName pos']) (BinaryMode ReadMode) return (idxH, dataH) ) allPOS -- the following are unnecessary sense <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file index.sense") $ openFileEx (makePath [searchdir, "index.sense"]) (BinaryMode ReadMode) cntlst <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file cntlist.rev") $ openFileEx (makePath [searchdir, "cntlist.rev"]) (BinaryMode ReadMode) keyidx <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file index.key") $ openFileEx (makePath [searchdir, "index.key" ]) (BinaryMode ReadMode) rkeyidx <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open file index.key.rev") $ openFileEx (makePath [searchdir, "index.key.rev"]) (BinaryMode ReadMode) vsent <- tryMaybeWarn (warn "Warning: initializeWordNet: cannot open sentence files (sentidx.vrb and sents.vrb)") $ do idx <- openFileEx (makePath [searchdir, "sentidx.vrb"]) (BinaryMode ReadMode) snt <- openFileEx (makePath [searchdir, "sents.vrb" ]) (BinaryMode ReadMode) return (idx, snt) mHands <- mapM (\pos' -> openFileEx (makePath [searchdir, partName pos' ++ ".exc"]) (BinaryMode ReadMode)) allPOS return WordNetEnv { dataHandles = listArray (Noun, Adv) dHands, excHandles = listArray (Noun, Adv) mHands, senseHandle = sense, countListHandle = cntlst, keyIndexHandle = keyidx, revKeyIndexHandle = rkeyidx, vSentHandle = vsent, wnReleaseVersion = version, dataDirectory = searchdir, warnAbout = warn } where getDefaultSearchDir = do Just searchdir <- tryMaybe (getEnv "WNSEARCHDIR") >>= \m1 -> tryMaybe (getEnv "WNHOME") >>= \m2 -> return (m1 `mplus` liftM (++dictDir) m2 `mplus` Just defaultPath) return searchdir -- | closeWordNet is not strictly necessary. However, a 'WordNetEnv' tends to -- hog a few Handles, so if you run out of Handles and won't be using -- your WordNetEnv for a while, you can close it and always create a new -- one later. closeWordNet :: WordNetEnv -> IO () closeWordNet wne = do mapM_ (\ (h1,h2) -> hClose h1 >> hClose h2) (elems (dataHandles wne)) mapM_ hClose (elems (excHandles wne)) mapM_ (`forM_` hClose) [senseHandle wne, countListHandle wne, keyIndexHandle wne, revKeyIndexHandle wne, liftM fst (vSentHandle wne), liftM snd (vSentHandle wne)] -- | getIndexString takes a string and a part of speech and tries to find -- that string (or something like it) in the database. It is essentially -- a cannonicalization routine and should be used before querying the -- database, to ensure that your string is in the right form. getIndexString :: WordNetEnv -> String -> POS -> IO (Maybe String) getIndexString wne str partOfSpeech = getIndexString' . cannonWNString $ str where getIndexString' [] = return Nothing getIndexString' (s:ss) = do i <- binarySearch (fst (dataHandles wne ! partOfSpeech)) s if isJust i then return (Just s) else getIndexString' ss -- | getSynsetForSense takes a sensekey and finds the appropriate Synset. SenseKeys can -- be built using indexToSenseKey. getSynsetForSense :: WordNetEnv -> SenseKey -> IO (Maybe Synset) getSynsetForSense wne _ | isNothing (senseHandle wne) = ioError $ userError "no sense dictionary" getSynsetForSense wne key' = do l <- binarySearch (fromJust $ senseHandle wne) (senseKeyString key') -- ++ " " ++ charForPOS (senseKeyPOS key)) case l of Nothing -> return Nothing Just l' -> do offset <- maybeRead $ takeWhile (not . isSpace) $ drop 1 $ dropWhile (not . isSpace) l' ss <- readSynset wne (senseKeyPOS key') offset (senseKeyWord key') return (Just ss) -- | readSynset takes a part of speech, and an offset (the offset can be found -- in another Synset) and (perhaps) a word we're looking for (this is optional) -- and will return its Synset. readSynset :: WordNetEnv -> POS -> Offset -> String -> IO Synset readSynset wne searchPos offset w = do let h = snd (dataHandles wne ! searchPos) hSeek h AbsoluteSeek offset toks <- liftM words $ hGetLine h --print toks (ptrTokS:fnumS:posS:numWordsS:rest1) <- matchN 4 toks hiam <- maybeRead ptrTokS fn <- maybeRead fnumS let ss1 = synset0 { hereIAm = hiam, pos = readEPOS posS, fnum = fn, ssType = if readEPOS posS == Satellite then IndirectAnt else UnknownEPos } let numWords = case readHex numWordsS of (n,_):_ -> n _ -> 0 --read numWordsS let (wrds,ptrCountS:rest2) = splitAt (numWords*2) rest1 -- words and lexids let ptrCount = case readDec ptrCountS of (n,_):_ -> n _ -> 0 -- print (toks, ptrCountS, ptrCount) wrds' <- readWords ss1 wrds let ss2 = ss1 { ssWords = wrds', whichWord = elemIndex w wrds } let (ptrs,rest3) = splitAt (ptrCount*4) rest2 let (fp,ss3) = readPtrs (False,ss2) ptrs let ss4 = if fp && searchPos == Adj && ssType ss3 == UnknownEPos then ss3 { ssType = Pertainym } else ss3 let (ss5,rest4) = if searchPos /= Verb then (ss4, rest3) else let (fcountS:_) = rest3 (_ , rest5) = splitAt (read fcountS * 3) rest4 in (ss4, rest5) let ss6 = ss5 { defn = unwords $ drop 1 rest4 } return ss6 where readWords ss (w':lid:xs) = do let s = map toLower $ replaceChar ' ' '_' w' idx <- indexLookup wne s (fromEPOS $ pos ss) -- print (w,st,idx) let posn = case idx of Nothing -> Nothing Just ix -> elemIndex (hereIAm ss) (indexOffsets ix) rest <- readWords ss xs return ((w', fst $ head $ readHex lid, maybe AllSenses SenseNumber posn) : rest) readWords _ _ = return [] readPtrs (fp,ss) (typ:off:ppos:lexp:xs) = let (fp',ss') = readPtrs (fp,ss) xs this = (getPointerType typ, read off, readEPOS ppos, fst $ head $ readHex (take 2 lexp), fst $ head $ readHex (drop 2 lexp)) in if searchPos == Adj && ssType ss' == UnknownEPos then if getPointerType typ == Antonym then (fp' , ss' { forms = this : forms ss', ssType = DirectAnt }) else (True, ss' { forms = this : forms ss' }) else (fp', ss' { forms = this : forms ss' }) readPtrs (fp,ss) _ = (fp,ss) -- | indexToSenseKey takes an Index (as returned by, ex., indexLookup) and a sense -- number and returns a SenseKey for that sense. indexToSenseKey :: WordNetEnv -> Index -> Int -> IO (Maybe SenseKey) indexToSenseKey wne idx sense = do let cpos = fromEPOS $ indexPOS idx ss1 <- readSynset wne cpos (indexOffsets idx !! (sense-1)) "" ss2 <- followSatellites ss1 --print ss2 case findIndex ((==indexWord idx) . map toLower) (map (\ (w,_,_) -> w) $ ssWords ss2) of Nothing -> return Nothing Just j -> do let skey = ((indexWord idx ++ "%") ++) (if ssType ss2 == Satellite then show (fromEnum Satellite) ++ ":" ++ padTo 2 (show $ fnum ss2) ++ ":" ++ headWord ss2 ++ ":" ++ padTo 2 (show $ headSense ss2) else show (fromEnum $ pos ss2) ++ ":" ++ padTo 2 (show $ fnum ss2) ++ ":" ++ padTo 2 (show $ lexId ss2 j) ++ "::") return (Just $ SenseKey cpos skey (indexWord idx)) where followSatellites ss | ssType ss == Satellite = case find (\ (f,_,_,_,_) -> f == Similar) (forms ss) of Nothing -> return ss Just (_,offset,p,_,_) -> do adjss <- readSynset wne (fromEPOS p) offset "" case ssWords adjss of (hw,_,hs):_ -> return (ss { headWord = map toLower hw, headSense = hs }) _ -> return ss | otherwise = return ss -- indexLookup takes a word and part of speech and gives back its index. indexLookup :: WordNetEnv -> String -> POS -> IO (Maybe Index) indexLookup wne w pos' = do ml <- binarySearch (fst (dataHandles wne ! pos')) w case ml of Nothing -> return Nothing Just l -> do (wdS:posS:ccntS:pcntS:rest1) <- matchN 4 (words l) isc <- maybeRead ccntS pc <- maybeRead pcntS let idx1 = index0 { indexWord = wdS, indexPOS = readEPOS posS, indexSenseCount = isc } let (ptrs,rest2) = splitAt pc rest1 let idx2 = idx1 { indexForms = map getPointerType ptrs } (ocntS:tcntS:rest3) <- matchN 2 rest2 itc <- maybeRead tcntS otc <- maybeRead ocntS let idx3 = idx2 { indexTaggedCount = itc } let (offsets,_) = splitAt otc rest3 io <- mapM maybeRead offsets return (Just $ idx3 { indexOffsets = io }) -- do binary search on an index file binarySearch :: Handle -> String -> IO (Maybe String) binarySearch h s = do hSeek h SeekFromEnd 0 bot <- hTell h binarySearch' 0 bot (bot `div` 2) where binarySearch' :: Integer -> Integer -> Integer -> IO (Maybe String) binarySearch' top bot mid = do hSeek h AbsoluteSeek (mid-1) when (mid /= 1) readUntilNL eof <- hIsEOF h if eof then if top >= bot-1 then return Nothing else binarySearch' top (bot-1) ((top+bot-1) `div` 2) else do l <- hGetLine h let key' = takeWhile (/=' ') l if key' == s then return (Just l) else case (bot - top) `div` 2 of 0 -> return Nothing d -> case key' `compare` s of LT -> binarySearch' mid bot (mid + d) GT -> binarySearch' top mid (top + d) EQ -> undefined readUntilNL = do eof <- hIsEOF h unless eof $ do hGetLine h return ()
pikajude/WordNet-ghc74
NLP/WordNet/Prims.hs
bsd-3-clause
13,742
0
26
4,294
3,747
1,909
1,838
241
11
module Main where import SDL hiding (Event) import SDL.Video.Renderer (Rectangle(..), drawRect, fillRect) import SDL.Vect (Point(..)) import qualified SDL.Event as SDLEvent import Linear (V4(..), V2(..)) import qualified Data.Set as Set import qualified Data.Map.Strict as Map import Data.Maybe (mapMaybe, fromMaybe) import Control.Lens import Control.Monad (unless) import qualified Control.Wire as Wire $(makeLensesFor [ ("keyboardEventKeysym", "keysym"), ("keyboardEventKeyMotion", "keyMotion") ] ''KeyboardEventData) $(makeLensesFor [ ("keysymKeycode", "keycode") ] ''Keysym) data Direction = MoveLeft | MoveRight | MoveUp | MoveDown deriving (Eq, Ord) data SceneEvent = Move Direction deriving (Eq, Ord) data Event = SceneEvent SceneEvent | Quit deriving (Eq, Ord) $(makePrisms ''Event) type Events = Set.Set Event data Scene = Scene { _position :: (Int, Int) } $(makeLenses ''Scene) type Draw = Renderer -> IO () height = 100 width = 100 main :: IO () main = do initializeAll window <- createWindow "Lonely Rectangle" defaultWindow renderer <- createRenderer window (-1) defaultRenderer appLoop renderer $ appWire $ Scene (50, 50) createRect :: (Integral i, Num r) => (i, i) -> (i, i) -> Rectangle r createRect (x, y) (w, h) = let leftCorner = P (V2 (fromIntegral x) (fromIntegral y)) in let dimensions = V2 (fromIntegral w) (fromIntegral h) in Rectangle leftCorner dimensions renderScene :: Scene -> Renderer -> IO () renderScene (Scene position) renderer = do rendererDrawColor renderer $= V4 0 255 0 255 fillRect renderer $ Just $ createRect position (height, width) parseEvents :: [SDLEvent.Event] -> Events parseEvents = foldl parseEvent Set.empty where parseEvent s (SDLEvent.Event _ (KeyboardEvent keyboardEvent)) = parseKeyboardEvent keyboardEvent s parseEvent s (SDLEvent.Event _ (WindowClosedEvent _)) = Set.insert Quit s parseEvent s _ = s eventsMap = Map.fromList [ (KeycodeQ, Quit), (KeycodeLeft, SceneEvent $ Move MoveLeft), (KeycodeRight, SceneEvent $ Move MoveRight), (KeycodeUp, SceneEvent $ Move MoveUp), (KeycodeDown, SceneEvent $ Move MoveDown), (KeycodeA, SceneEvent $ Move MoveLeft), (KeycodeD, SceneEvent $ Move MoveRight), (KeycodeW, SceneEvent $ Move MoveUp), (KeycodeS, SceneEvent $ Move MoveDown) ] parseKeyboardEvent :: KeyboardEventData -> Events -> Events parseKeyboardEvent keyboardEvent s = if keyboardEvent ^. keyMotion == Pressed then fromMaybe s $ flip Set.insert s <$> Map.lookup (keyboardEvent ^. keysym ^. keycode) eventsMap else s updateScene :: Scene -> Events -> Scene updateScene scene = foldr applyEvent scene . onlySceneEvents where onlySceneEvents = mapMaybe (^? _SceneEvent) . Set.toList applyEvent (Move MoveLeft) = (position . _1) `over` subtract 10 applyEvent (Move MoveRight) = (position . _1) `over` (+10) applyEvent (Move MoveUp) = (position . _2) `over` subtract 10 applyEvent (Move MoveDown) = (position . _2) `over` (+10) appWire :: Scene -> Wire.Wire Int e IO Events Draw appWire init = proc events -> do rec scene <- Wire.delay init -< scene' let scene' = flip updateScene events scene Wire.returnA -< renderScene scene appLoop :: Renderer -> Wire.Wire Int e IO Events Draw -> IO () appLoop renderer w = do events <- parseEvents <$> pollEvents (Right draw, w') <- Wire.stepWire w 0 (Right events) rendererDrawColor renderer $= V4 0 0 255 255 clear renderer draw renderer present renderer unless (Set.member Quit events) $ appLoop renderer w'
SPY/netwire-sandbox
app/Main.hs
bsd-3-clause
3,669
1
13
758
1,341
708
633
-1
-1
{-# LANGUAGE OverloadedStrings, TupleSections, Arrows, RankNTypes, ScopedTypeVariables #-} module FRP.Yampa.Canvas.Virtual (reactimateVirtualSFinContext) where import FRP.Yampa import Data.Time.Clock import Data.IORef import Control.Concurrent.STM import Graphics.Blank hiding (Event) import qualified Graphics.Blank as Blank ------------------------------------------------------------------- -- | Redraw the entire canvas. renderCanvas :: DeviceContext -> Canvas () -> IO () renderCanvas context drawAction = send context canvas where canvas :: Canvas () canvas = do clearCanvas beginPath () saveRestore drawAction ------------------------------------------------------------------- -- | A specialisation of 'FRP.Yampa.reactimate' to Blank Canvas. -- The arguments are: the Canvas action to get input, the Canvas action to emit output, the signal function to be run, and the device context to use. reactimateVirtualSFinContext :: forall a . Double -- time interval -> Int -- How often to update the screen -> (Blank.Event -> Event a) -> SF (Event a) (Canvas ()) -- only update on *events* -> DeviceContext -> IO () reactimateVirtualSFinContext gap count interpEvent sf context = do c <- newIORef (cycle [1..count]) let getInput :: Bool -> IO (DTime,Maybe (Event a)) getInput canBlock = do let opt_block m = if canBlock then m else m `orElse` return Nothing opt_e <- atomically $ opt_block $ fmap Just $ readTChan (eventQueue context) ev <- case opt_e of Nothing -> return NoEvent Just e -> return (interpEvent e) return (gap, Just ev) putOutput :: Bool -> Canvas () -> IO Bool putOutput changed b = do (i:is) <- readIORef c writeIORef c is if changed && i == 1 then renderCanvas context b >> return False else return False reactimate (return NoEvent) getInput putOutput sf -------------------------------------------------------------------
ku-fpg/protocols
FRP/Yampa/Canvas/Virtual.hs
bsd-3-clause
2,283
0
18
696
499
252
247
42
4
module Network.Orchid.Format.Xml (fXml) where import Text.XML.Light.Output import Data.FileStore (FileStore) import Network.Orchid.Core.Format import Text.Document.Document fXml :: WikiFormat fXml = WikiFormat "xml" "text/xml" xml xml :: FileStore -> FilePath -> FilePath -> String -> IO Output xml _ _ _ src = return $ TextOutput $ either show (ppContent . toXML) $ fromWiki src
sebastiaanvisser/orchid
src/Network/Orchid/Format/Xml.hs
bsd-3-clause
391
0
9
63
125
70
55
12
1
{-# OPTIONS_GHC -fno-warn-partial-type-signatures #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GADTs #-} module Haskell.Ide.Engine.BasePlugin where import Control.Monad import Data.Aeson import Data.Foldable import Data.List import qualified Data.Map as Map import Data.Monoid import qualified Data.Text as T import Development.GitRev (gitCommitCount) import Distribution.System (buildArch) import Distribution.Text (display) import Haskell.Ide.Engine.PluginDescriptor import Haskell.Ide.Engine.PluginUtils import Options.Applicative.Simple (simpleVersion) import qualified Paths_haskell_ide_engine as Meta import Prelude hiding (log) -- --------------------------------------------------------------------- baseDescriptor :: TaggedPluginDescriptor _ baseDescriptor = PluginDescriptor { pdUIShortName = "HIE Base" , pdUIOverview = "Commands for HIE itself, " , pdCommands = buildCommand versionCmd (Proxy :: Proxy "version") "return HIE version" [] (SCtxNone :& RNil) RNil :& buildCommand pluginsCmd (Proxy :: Proxy "plugins") "list available plugins" [] (SCtxNone :& RNil) RNil :& buildCommand commandsCmd (Proxy :: Proxy "commands") "list available commands for a given plugin" [] (SCtxNone :& RNil) ( SParamDesc (Proxy :: Proxy "plugin") (Proxy :: Proxy "the plugin name") SPtText SRequired :& RNil) :& buildCommand commandDetailCmd (Proxy :: Proxy "commandDetail") "list parameters required for a given command" [] (SCtxNone :& RNil) ( SParamDesc (Proxy :: Proxy "plugin") (Proxy :: Proxy "the plugin name") SPtText SRequired :& SParamDesc (Proxy :: Proxy "command") (Proxy :: Proxy "the command name") SPtText SRequired :& RNil) :& RNil , pdExposedServices = [] , pdUsedServices = [] } -- --------------------------------------------------------------------- versionCmd :: CommandFunc T.Text versionCmd = CmdSync $ \_ _ -> return $ IdeResponseOk (T.pack version) pluginsCmd :: CommandFunc IdePlugins pluginsCmd = CmdSync $ \_ _ -> IdeResponseOk . IdePlugins . Map.map (map cmdDesc . pdCommands) <$> getPlugins commandsCmd :: CommandFunc [CommandName] commandsCmd = CmdSync $ \_ req -> do plugins <- getPlugins -- TODO: Use Maybe Monad. What abut error reporting? case Map.lookup "plugin" (ideParams req) of Nothing -> return (missingParameter "plugin") Just (ParamTextP p) -> case Map.lookup p plugins of Nothing -> return $ IdeResponseFail $ IdeError { ideCode = UnknownPlugin , ideMessage = "Can't find plugin:" <> p , ideInfo = toJSON p } Just pl -> return $ IdeResponseOk $ map (cmdName . cmdDesc) (pdCommands pl) Just x -> return $ incorrectParameter "plugin" ("ParamText"::String) x commandDetailCmd :: CommandFunc ExtendedCommandDescriptor commandDetailCmd = CmdSync $ \_ req -> do plugins <- getPlugins case getParams (IdText "plugin" :& IdText "command" :& RNil) req of Left err -> return err Right (ParamText p :& ParamText command :& RNil) -> do case Map.lookup p plugins of Nothing -> return $ IdeResponseError $ IdeError { ideCode = UnknownPlugin , ideMessage = "Can't find plugin:" <> p , ideInfo = toJSON p } Just pl -> case find (\cmd -> command == (cmdName $ cmdDesc cmd) ) (pdCommands pl) of Nothing -> return $ IdeResponseError $ IdeError { ideCode = UnknownCommand , ideMessage = "Can't find command:" <> command , ideInfo = toJSON command } Just detail -> return $ IdeResponseOk (ExtendedCommandDescriptor (cmdDesc detail) p) Right _ -> return $ IdeResponseError $ IdeError { ideCode = InternalError , ideMessage = "commandDetailCmd: ghcโ€™s exhaustiveness checker is broken" , ideInfo = Null } -- --------------------------------------------------------------------- version :: String version = let commitCount = $gitCommitCount in concat $ concat [ [$(simpleVersion Meta.version)] -- Leave out number of commits for --depth=1 clone -- See https://github.com/commercialhaskell/stack/issues/792 , [" (" ++ commitCount ++ " commits)" | commitCount /= ("1"::String) && commitCount /= ("UNKNOWN" :: String)] , [" ", display buildArch] ] -- --------------------------------------------------------------------- replPluginInfo :: Plugins -> Map.Map T.Text (T.Text,UntaggedCommand) replPluginInfo plugins = Map.fromList commands where commands = concatMap extractCommands $ Map.toList plugins extractCommands (pluginName,descriptor) = cmds where cmds = map (\cmd -> (pluginName <> ":" <> (cmdName $ cmdDesc cmd),(pluginName,cmd))) $ pdCommands descriptor -- ---------------------------------------------------------------------
JPMoresmau/haskell-ide-engine
src/Haskell/Ide/Engine/BasePlugin.hs
bsd-3-clause
5,320
0
25
1,364
1,242
669
573
95
5
{-# LANGUAGE OverloadedStrings #-} module Main where import Route import Nix import Conf import Control.Monad.Error () import Control.Monad.IO.Class (liftIO) import Data.ByteString.Lazy.Char8 (pack) import Data.Default (def) import Data.List (isPrefixOf) import Network.HTTP.Types import Network.Wai import Network.Wai.Middleware.RequestLogger import qualified Network.Wai.Handler.Warp as W import System.FilePath import System.Log.Logger import qualified System.Directory as Dir main :: IO () main = do opts <- parseOpts routes <- either fail return (mapM parseRoute (nixrbdRoutes opts)) let addrSource = if nixrbdBehindProxy opts then FromHeader else FromSocket reqLogger <- mkRequestLogger $ def { outputFormat = Apache addrSource } updateGlobalLogger "nixrbd" (setLevel DEBUG) let warpSettings = W.setPort (nixrbdPort opts ) W.defaultSettings infoM "nixrbd" ("Listening on port "++show (nixrbdPort opts)) W.runSettings warpSettings $ reqLogger $ app routes opts app :: [Route] -> Nixrbd -> Application app routes opts req respond = case lookupTarget req routes of (NixHandler p nixpaths, ps') -> do buildRes <- liftIO $ nixBuild opts req p nixpaths ps' either respondFailed serveFile buildRes (StaticPath p, ps') -> do let fp = combine p (joinPath ps') exists <- liftIO $ Dir.doesFileExist fp if not exists then respondNotFound fp else do p' <- liftIO $ Dir.canonicalizePath p fp' <- liftIO $ Dir.canonicalizePath fp if p' `isPrefixOf` fp' then serveFile fp' else respondNotFound fp' (StaticResp s, _) -> stringResp s "" where stringResp s = respond . responseLBS s [("Content-Type","text/plain")] . pack respondFailed err = do liftIO $ errorM "nixrbd" ("Failure: "++show err) stringResp internalServerError500 "Failed building response" respondNotFound fp = do liftIO $ infoM "nixrbd" ("Not found: "++fp) stringResp notFound404 "Not found" serveFile filePath = do filePath' <- liftIO $ Dir.canonicalizePath filePath liftIO $ infoM "nixrbd" ("Serve file: "++filePath') respond $ responseFile status200 [] filePath' Nothing
rickynils/nixrbd
Main.hs
bsd-3-clause
2,169
0
16
417
686
348
338
53
5
{-# LANGUAGE GeneralizedNewtypeDeriving, StandaloneDeriving, DeriveDataTypeable #-} {-# OPTIONS_GHC -Wall -Werror -fno-warn-orphans -cpp #-} {- | Module : $Header$ Description : Working with Shrimp M4 abstract syntax. Copyright : (c) Galois, Inc. Working with Shrimp M4 abstract syntax. -} module SCD.M4.Util where import SCD.SELinux.Syntax as SE import SCD.M4.Syntax as M4 import Data.List ( intercalate ) elementId :: InterfaceElement -> M4Id elementId (InterfaceElement _ _ i _) = i implementationId :: Implementation -> ModuleId implementationId (Implementation m _ _) = m layerModule2Identifier :: IsIdentifier i => LayerModule -> i layerModule2Identifier (l,m) = mkId ((idString l) ++ '_' : idString m) -- | unravel left-to-right. splitId :: String -> [String] splitId xs = case break (=='_') xs of (as,[]) -> [as] (as,_:bs) -> as : splitId bs unsplitId :: [String] -> String unsplitId = intercalate "_" -- | split up again, but with reversed result; -- most specific kind/name first. revSplitId :: String -> [String] revSplitId = go [] where go acc "" = acc go acc xs = case break (=='_') xs of (as,[]) -> as:acc (as,_:bs) -> go (as : acc) bs -- | @dropIdSuffix "t" "foo_bar_t"@ returns @"foo_bar"@, -- snipping out the @t@ suffix. If no such suffix, it -- returns the dropIdSuffix :: String -> String -> String dropIdSuffix t s = case revSplitId s of (x:xs) | t == x -> unsplitId (reverse xs) _ -> s isInstantiatedId :: [String] -> Bool isInstantiatedId forMe = bigBucks `any` forMe where bigBucks ('$':_) = True bigBucks _ = False
GaloisInc/sk-dev-platform
libs/SCD/src/SCD/M4/Util.hs
bsd-3-clause
1,608
0
12
317
466
255
211
35
3
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. ----------------------------------------------------------------- -- Auto-generated by regenClassifiers -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated ----------------------------------------------------------------- {-# LANGUAGE OverloadedStrings #-} module Duckling.Ranking.Classifiers.CS (classifiers) where import Prelude import Duckling.Ranking.Types import qualified Data.HashMap.Strict as HashMap import Data.String classifiers :: Classifiers classifiers = HashMap.fromList []
rfranek/duckling
Duckling/Ranking/Classifiers/CS.hs
bsd-3-clause
825
0
6
105
66
47
19
8
1
{-# LANGUAGE DeriveGeneric #-} module Day11 (part1, part2, test1, testStartState, part1Solution,part2Solution) where import Control.Arrow (second) import Data.Foldable import Data.Graph.AStar import Data.Hashable import qualified Data.HashSet as H import Data.List import Data.Map.Strict (Map) import qualified Data.Map.Strict as Map import Data.Set (Set) import qualified Data.Set as Set import GHC.Generics (Generic) data Gen = Gen String deriving (Eq,Ord,Show,Generic) instance Hashable Gen data Chip = Chip String deriving (Eq,Ord,Show,Generic) instance Hashable Chip type ElevatorFloor = Int data ProbState = ProbState ElevatorFloor (Map Int (Set Gen)) (Map Int (Set Chip)) deriving (Eq,Ord,Show) data HProbState = HProbState ElevatorFloor [(Int,[Gen])] [(Int,[Chip])] deriving (Eq,Ord,Show,Generic) instance Hashable HProbState fromHState :: HProbState -> ProbState fromHState (HProbState e gs cs) = ProbState e (Map.fromList $ map (second Set.fromList) gs) (Map.fromList $ map (second Set.fromList) cs) toHState :: ProbState -> HProbState toHState (ProbState e gs cs) = HProbState e (map (second Set.toList) $ Map.toList gs) (map (second Set.toList) $ Map.toList cs) validFloor :: Set Gen -> Set Chip -> Bool validFloor gs cs | Set.null gs = True | otherwise = all (`Set.member` gs) $ Set.map (\(Chip c) -> Gen c) cs validState :: ProbState -> Bool validState (ProbState _ gs' cs') = and $ zipWith validFloor (Map.elems gs') (Map.elems cs') nextStates :: ProbState -> [ProbState] nextStates (ProbState e gs cs) = filter validState $ concat . concat $ [mixedStates,singleGStates,doubleGStates,singleCStates,doubleCStates] where singleGStates = map (\nE -> map (f nE . (:[])) singleGs) nextElevators doubleGStates = map (\nE -> map (f nE) doubleGs) notDownNextElevators singleCStates = map (\nE -> map (h nE . (:[])) singleCs) nextElevators doubleCStates = map (\nE -> map (h nE) doubleCs) notDownNextElevators mixedStates = map (\nE -> map (\(g,c) -> ProbState nE (Map.adjust (Set.insert g) nE (Map.adjust (Set.delete g) e gs)) (Map.adjust (Set.insert c) nE (Map.adjust (Set.delete c) e cs))) mixed) notDownNextElevators f nE gs' = ProbState nE (foldl' (\m g -> Map.adjust (Set.insert g) nE m) (foldl' (\m g -> Map.adjust (Set.delete g) e m) gs gs') gs') cs h nE cs' = ProbState nE gs (foldl' (\m c -> Map.adjust (Set.insert c) nE m) (foldl' (\m c -> Map.adjust (Set.delete c) e m) cs cs') cs') nextElevators = [nE | nE <- [e-1,e+1], nE >= 0 && nE < 4] notDownNextElevators = [nE | nE <- [e+1], nE >= 0 && nE < 4] singleGs = Set.toList (Map.findWithDefault Set.empty e gs) doubleGs = [[g1,g2] | g1 <- singleGs, g2 <- singleGs, g1 /= g2] singleCs = Set.toList (Map.findWithDefault Set.empty e cs) doubleCs = [[c1,c2] | c1 <- singleCs,c2 <- singleCs, c1 /= c2] mixed = [(g,c) | g@(Gen gStr) <-singleGs, c@(Chip cStr) <- singleCs, gStr == cStr] heuristic :: HProbState -> Int heuristic (HProbState _ gs cs) = movesToTop cs + movesToTop gs where movesToTop = sum . map (\(f,c) -> (3-f) * length c) part1 s e = length <$> aStar (H.fromList . map toHState . nextStates . fromHState) (const . const 1) heuristic (toHState s ==) (toHState e) part2 = part1 part1Solution = part1 inputStartState input part2Solution = part2 input2StartState input2 probStateViz :: ProbState -> IO () probStateViz (ProbState e gs cs) = mapM_ putStrLn floors where floors = map showFloor $ reverse $ sortOn (\(f,_,_) -> f) $ Map.elems $ Map.mapWithKey (\f g -> (f,g,Map.findWithDefault Set.empty f cs)) gs showFloor (f,gfs,cfs) = show f ++ " " ++ (if f == e then "E" else " ") ++ " " ++ foldMap shortG gfs ++ foldMap shortC cfs shortG (Gen g) = g++"G " shortC (Chip c) = c++"M " input2 = ProbState 0 (Map.fromList [(0,Set.fromList [Gen "T", Gen "Pl",Gen "S",Gen "E",Gen "D"]), (1,Set.empty),(2,Set.fromList [Gen"Pr", Gen"R"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "T",Chip "E",Chip "D"]),(1,Set.fromList [Chip "Pl",Chip "S"]),(2,Set.fromList [Chip "Pr",Chip "R"]),(3,Set.empty)]) input2StartState = ProbState 3 (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Gen"T",Gen"Pl",Gen"S",Gen"Pr",Gen"R",Gen"E",Gen"D"])]) (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Chip"T",Chip"Pl",Chip"S",Chip"Pr",Chip"R",Chip"E",Chip"D"])]) inputStartState = ProbState 3 (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Gen"T",Gen"Pl",Gen"S",Gen"Pr",Gen"R"])]) (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Chip"T",Chip"Pl",Chip"S",Chip"Pr",Chip"R"])]) input = ProbState 0 (Map.fromList [(0,Set.fromList [Gen "T", Gen "Pl",Gen "S"]), (1,Set.empty),(2,Set.fromList [Gen"Pr", Gen"R"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "T"]),(1,Set.fromList [Chip "Pl",Chip "S"]),(2,Set.fromList [Chip "Pr",Chip "R"]),(3,Set.empty)]) testStartState = ProbState 3 (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Gen"H",Gen"L"])]) (Map.fromList [(0,Set.empty), (1,Set.empty), (2,Set.empty), (3,Set.fromList [Chip "H",Chip "L"])]) test2 = ProbState 0 (Map.fromList [(0,Set.fromList [Gen "T", Gen "Pl",Gen "S"]), (1,Set.empty),(2,Set.fromList [Gen"Pr", Gen"R"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "T",Chip "Pl"]),(1,Set.fromList [Chip "S"]),(2,Set.fromList [Chip "Pr",Chip "R"]),(3,Set.empty)]) test1 = ProbState 0 (Map.fromList [(0,Set.empty), (1,Set.fromList [Gen "H"]),(2,Set.fromList [Gen"L"]),(3,Set.empty)]) (Map.fromList [(0,Set.fromList [Chip "H",Chip "L"]),(1,Set.empty),(2,Set.empty),(3,Set.empty)])
z0isch/aoc2016
src/Day11.hs
bsd-3-clause
5,992
0
20
1,163
3,051
1,648
1,403
87
2
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE PartialTypeSignatures #-} module Omniscient.Server.Core where import Control.Monad.Reader import Control.Monad.Logger import Control.Monad.Except import Database.Persist.Sql import Servant type OmniscientT m = LoggingT (ReaderT ConnectionPool (ExceptT ServantErr m)) class ( MonadIO m , MonadError ServantErr m , MonadReader ConnectionPool m , MonadLogger m ) => Omni m where instance MonadIO m => Omni (OmniscientT m) db :: Omni app => _ -> app a db = (ask >>=) . liftSqlPersistMPool
bheklilr/omniscient
src/Omniscient/Server/Core.hs
bsd-3-clause
634
0
9
110
156
87
69
-1
-1
{- | Module : Main Description : Test the PuffyTools journal functions Copyright : 2014, Peter Harpending License : BSD3 Maintainer : Peter Harpending <pharpend2@gmail.com> Stability : experimental Portability : Linux -} module Main where import Data.Char import Data.List import PuffyTools.Journal import TestPuffyToolsJournal import Test.Framework import Test.Framework.Providers.QuickCheck2 main :: IO () main = defaultMain tests tests :: [Test] tests = [testGroup "PuffyTools.Journal" [testGroup "Aeson properties" [ testProperty "(encode . decode . encode) = (encode)" prop_encDecEnc , testProperty "(decode . encode . decode . encode) = (decode . encode)" prop_decEncDecEnc , testProperty "(decode . encode . decode . encode)^n = (decode . encode)" prop_dEn ]]]
pharpend/puffytools
test/Test.hs
bsd-3-clause
939
0
10
275
106
60
46
16
1
module Test.QuickCheck.Arbitrary ( -- * Arbitrary and CoArbitrary classes Arbitrary(..) , CoArbitrary(..) -- ** Helper functions for implementing arbitrary , arbitrarySizedIntegral -- :: Num a => Gen a , arbitraryBoundedIntegral -- :: (Bounded a, Integral a) => Gen a , arbitrarySizedBoundedIntegral -- :: (Bounded a, Integral a) => Gen a , arbitrarySizedFractional -- :: Fractional a => Gen a , arbitraryBoundedRandom -- :: (Bounded a, Random a) => Gen a , arbitraryBoundedEnum -- :: (Bounded a, Enum a) => Gen a -- ** Helper functions for implementing shrink , shrinkNothing -- :: a -> [a] , shrinkList -- :: (a -> [a]) -> [a] -> [[a]] , shrinkIntegral -- :: Integral a => a -> [a] , shrinkRealFrac -- :: RealFrac a => a -> [a] -- ** Helper functions for implementing coarbitrary , (><) , coarbitraryIntegral -- :: Integral a => a -> Gen b -> Gen b , coarbitraryReal -- :: Real a => a -> Gen b -> Gen b , coarbitraryShow -- :: Show a => a -> Gen b -> Gen b , coarbitraryEnum -- :: Enum a => a -> Gen b -> Gen b -- ** Generators which use arbitrary , vector -- :: Arbitrary a => Int -> Gen [a] , orderedList -- :: (Ord a, Arbitrary a) => Gen [a] ) where -------------------------------------------------------------------------- -- imports import Test.QuickCheck.Gen {- import Data.Generics ( (:*:)(..) , (:+:)(..) , Unit(..) ) -} import Data.Char ( chr , ord , isLower , isUpper , toLower , isDigit , isSpace ) import Data.Fixed ( Fixed , HasResolution ) import Data.Ratio ( Ratio , (%) , numerator , denominator ) import Data.Complex ( Complex((:+)) ) import System.Random ( Random ) import Data.List ( sort , nub ) import Control.Monad ( liftM , liftM2 , liftM3 , liftM4 , liftM5 ) import Data.Int(Int8, Int16, Int32, Int64) import Data.Word(Word, Word8, Word16, Word32, Word64) -------------------------------------------------------------------------- -- ** class Arbitrary -- | Random generation and shrinking of values. class Arbitrary a where -- | A generator for values of the given type. arbitrary :: Gen a arbitrary = error "no default generator" -- | Produces a (possibly) empty list of all the possible -- immediate shrinks of the given value. shrink :: a -> [a] shrink _ = [] -- instances instance (CoArbitrary a, Arbitrary b) => Arbitrary (a -> b) where arbitrary = promote (`coarbitrary` arbitrary) instance Arbitrary () where arbitrary = return () instance Arbitrary Bool where arbitrary = choose (False,True) shrink True = [False] shrink False = [] instance Arbitrary Ordering where arbitrary = arbitraryBoundedEnum shrink GT = [EQ, LT] shrink LT = [EQ] shrink EQ = [] instance Arbitrary a => Arbitrary (Maybe a) where arbitrary = frequency [(1, return Nothing), (3, liftM Just arbitrary)] shrink (Just x) = Nothing : [ Just x' | x' <- shrink x ] shrink _ = [] instance (Arbitrary a, Arbitrary b) => Arbitrary (Either a b) where arbitrary = oneof [liftM Left arbitrary, liftM Right arbitrary] shrink (Left x) = [ Left x' | x' <- shrink x ] shrink (Right y) = [ Right y' | y' <- shrink y ] instance Arbitrary a => Arbitrary [a] where arbitrary = sized $ \n -> do k <- choose (0,n) sequence [ arbitrary | _ <- [1..k] ] shrink xs = shrinkList shrink xs shrinkList :: (a -> [a]) -> [a] -> [[a]] shrinkList shr xs = concat [ removes k n xs | k <- takeWhile (>0) (iterate (`div`2) n) ] ++ shrinkOne xs where n = length xs shrinkOne [] = [] shrinkOne (x:xs) = [ x':xs | x' <- shr x ] ++ [ x:xs' | xs' <- shrinkOne xs ] removes k n xs | k > n = [] | null xs2 = [[]] | otherwise = xs2 : map (xs1 ++) (removes k (n-k) xs2) where xs1 = take k xs xs2 = drop k xs {- -- "standard" definition for lists: shrink [] = [] shrink (x:xs) = [ xs ] ++ [ x:xs' | xs' <- shrink xs ] ++ [ x':xs | x' <- shrink x ] -} instance (Integral a, Arbitrary a) => Arbitrary (Ratio a) where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac instance (RealFloat a, Arbitrary a) => Arbitrary (Complex a) where arbitrary = liftM2 (:+) arbitrary arbitrary shrink (x :+ y) = [ x' :+ y | x' <- shrink x ] ++ [ x :+ y' | y' <- shrink y ] instance HasResolution a => Arbitrary (Fixed a) where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac instance (Arbitrary a, Arbitrary b) => Arbitrary (a,b) where arbitrary = liftM2 (,) arbitrary arbitrary shrink (x,y) = [ (x',y) | x' <- shrink x ] ++ [ (x,y') | y' <- shrink y ] instance (Arbitrary a, Arbitrary b, Arbitrary c) => Arbitrary (a,b,c) where arbitrary = liftM3 (,,) arbitrary arbitrary arbitrary shrink (x,y,z) = [ (x',y,z) | x' <- shrink x ] ++ [ (x,y',z) | y' <- shrink y ] ++ [ (x,y,z') | z' <- shrink z ] instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d) => Arbitrary (a,b,c,d) where arbitrary = liftM4 (,,,) arbitrary arbitrary arbitrary arbitrary shrink (w,x,y,z) = [ (w',x,y,z) | w' <- shrink w ] ++ [ (w,x',y,z) | x' <- shrink x ] ++ [ (w,x,y',z) | y' <- shrink y ] ++ [ (w,x,y,z') | z' <- shrink z ] instance (Arbitrary a, Arbitrary b, Arbitrary c, Arbitrary d, Arbitrary e) => Arbitrary (a,b,c,d,e) where arbitrary = liftM5 (,,,,) arbitrary arbitrary arbitrary arbitrary arbitrary shrink (v,w,x,y,z) = [ (v',w,x,y,z) | v' <- shrink v ] ++ [ (v,w',x,y,z) | w' <- shrink w ] ++ [ (v,w,x',y,z) | x' <- shrink x ] ++ [ (v,w,x,y',z) | y' <- shrink y ] ++ [ (v,w,x,y,z') | z' <- shrink z ] -- typical instance for primitive (numerical) types instance Arbitrary Integer where arbitrary = arbitrarySizedIntegral shrink = shrinkIntegral instance Arbitrary Int where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int8 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int16 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int32 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Int64 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word8 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word16 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word32 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Word64 where arbitrary = arbitrarySizedBoundedIntegral shrink = shrinkIntegral instance Arbitrary Char where arbitrary = chr `fmap` oneof [choose (0,127), choose (0,255)] shrink c = filter (<. c) $ nub $ ['a','b','c'] ++ [ toLower c | isUpper c ] ++ ['A','B','C'] ++ ['1','2','3'] ++ [' ','\n'] where a <. b = stamp a < stamp b stamp a = ( (not (isLower a) , not (isUpper a) , not (isDigit a)) , (not (a==' ') , not (isSpace a) , a) ) instance Arbitrary Float where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac instance Arbitrary Double where arbitrary = arbitrarySizedFractional shrink = shrinkRealFrac -- ** Helper functions for implementing arbitrary -- | Generates an integral number. The number can be positive or negative -- and its maximum absolute value depends on the size parameter. arbitrarySizedIntegral :: Num a => Gen a arbitrarySizedIntegral = sized $ \n -> let n' = toInteger n in fmap fromInteger (choose (-n', n')) -- | Generates a fractional number. The number can be positive or negative -- and its maximum absolute value depends on the size parameter. arbitrarySizedFractional :: Fractional a => Gen a arbitrarySizedFractional = sized $ \n -> let n' = toInteger n in do a <- choose ((-n') * precision, n' * precision) b <- choose (1, precision) return (fromRational (a % b)) where precision = 9999999999999 :: Integer -- | Generates an integral number. The number is chosen uniformly from -- the entire range of the type. You may want to use -- 'arbitrarySizedBoundedIntegral' instead. arbitraryBoundedIntegral :: (Bounded a, Integral a) => Gen a arbitraryBoundedIntegral = do let mn = minBound mx = maxBound `asTypeOf` mn n <- choose (toInteger mn, toInteger mx) return (fromInteger n `asTypeOf` mn) -- | Generates an element of a bounded type. The element is -- chosen from the entire range of the type. arbitraryBoundedRandom :: (Bounded a, Random a) => Gen a arbitraryBoundedRandom = choose (minBound,maxBound) -- | Generates an element of a bounded enumeration. arbitraryBoundedEnum :: (Bounded a, Enum a) => Gen a arbitraryBoundedEnum = do let mn = minBound mx = maxBound `asTypeOf` mn n <- choose (fromEnum mn, fromEnum mx) return (toEnum n `asTypeOf` mn) -- | Generates an integral number from a bounded domain. The number is -- chosen from the entire range of the type, but small numbers are -- generated more often than big numbers. Inspired by demands from -- Phil Wadler. arbitrarySizedBoundedIntegral :: (Bounded a, Integral a) => Gen a arbitrarySizedBoundedIntegral = sized $ \s -> do let mn = minBound mx = maxBound `asTypeOf` mn bits n | n `quot` 2 == 0 = 0 | otherwise = 1 + bits (n `quot` 2) k = 2^(s*(bits mn `max` bits mx `max` 40) `div` 100) n <- choose (toInteger mn `max` (-k), toInteger mx `min` k) return (fromInteger n `asTypeOf` mn) -- ** Helper functions for implementing shrink -- | Returns no shrinking alternatives. shrinkNothing :: a -> [a] shrinkNothing _ = [] -- | Shrink an integral number. shrinkIntegral :: Integral a => a -> [a] shrinkIntegral x = nub $ [ -x | x < 0, -x > x ] ++ [ x' | x' <- takeWhile (<< x) (0:[ x - i | i <- tail (iterate (`quot` 2) x) ]) ] where -- a << b is "morally" abs a < abs b, but taking care of overflow. a << b = case (a >= 0, b >= 0) of (True, True) -> a < b (False, False) -> a > b (True, False) -> a + b < 0 (False, True) -> a + b > 0 -- | Shrink a fraction. shrinkRealFrac :: RealFrac a => a -> [a] shrinkRealFrac x = nub $ [ -x | x < 0 ] ++ [ x' | x' <- [fromInteger (truncate x)] , x' << x ] where a << b = abs a < abs b -------------------------------------------------------------------------- -- ** CoArbitrary -- | Used for random generation of functions. class CoArbitrary a where -- | Used to generate a function of type @a -> c@. The implementation -- should use the first argument to perturb the random generator -- given as the second argument. the returned generator -- is then used to generate the function result. -- You can often use 'variant' and '><' to implement -- 'coarbitrary'. coarbitrary :: a -> Gen c -> Gen c {- -- GHC definition: coarbitrary{| Unit |} Unit = id coarbitrary{| a :*: b |} (x :*: y) = coarbitrary x >< coarbitrary y coarbitrary{| a :+: b |} (Inl x) = variant 0 . coarbitrary x coarbitrary{| a :+: b |} (Inr y) = variant (-1) . coarbitrary y -} -- | Combine two generator perturbing functions, for example the -- results of calls to 'variant' or 'coarbitrary'. (><) :: (Gen a -> Gen a) -> (Gen a -> Gen a) -> (Gen a -> Gen a) (><) f g gen = do n <- arbitrary (g . variant (n :: Int) . f) gen -- for the sake of non-GHC compilers, I have added definitions -- for coarbitrary here. instance (Arbitrary a, CoArbitrary b) => CoArbitrary (a -> b) where coarbitrary f gen = do xs <- arbitrary coarbitrary (map f xs) gen instance CoArbitrary () where coarbitrary _ = id instance CoArbitrary Bool where coarbitrary False = variant 0 coarbitrary True = variant (-1) instance CoArbitrary Ordering where coarbitrary GT = variant 1 coarbitrary EQ = variant 0 coarbitrary LT = variant (-1) instance CoArbitrary a => CoArbitrary (Maybe a) where coarbitrary Nothing = variant 0 coarbitrary (Just x) = variant (-1) . coarbitrary x instance (CoArbitrary a, CoArbitrary b) => CoArbitrary (Either a b) where coarbitrary (Left x) = variant 0 . coarbitrary x coarbitrary (Right y) = variant (-1) . coarbitrary y instance CoArbitrary a => CoArbitrary [a] where coarbitrary [] = variant 0 coarbitrary (x:xs) = variant (-1) . coarbitrary (x,xs) instance (Integral a, CoArbitrary a) => CoArbitrary (Ratio a) where coarbitrary r = coarbitrary (numerator r,denominator r) instance HasResolution a => CoArbitrary (Fixed a) where coarbitrary = coarbitraryReal instance (RealFloat a, CoArbitrary a) => CoArbitrary (Complex a) where coarbitrary (x :+ y) = coarbitrary x >< coarbitrary y instance (CoArbitrary a, CoArbitrary b) => CoArbitrary (a,b) where coarbitrary (x,y) = coarbitrary x >< coarbitrary y instance (CoArbitrary a, CoArbitrary b, CoArbitrary c) => CoArbitrary (a,b,c) where coarbitrary (x,y,z) = coarbitrary x >< coarbitrary y >< coarbitrary z instance (CoArbitrary a, CoArbitrary b, CoArbitrary c, CoArbitrary d) => CoArbitrary (a,b,c,d) where coarbitrary (x,y,z,v) = coarbitrary x >< coarbitrary y >< coarbitrary z >< coarbitrary v instance (CoArbitrary a, CoArbitrary b, CoArbitrary c, CoArbitrary d, CoArbitrary e) => CoArbitrary (a,b,c,d,e) where coarbitrary (x,y,z,v,w) = coarbitrary x >< coarbitrary y >< coarbitrary z >< coarbitrary v >< coarbitrary w -- typical instance for primitive (numerical) types instance CoArbitrary Integer where coarbitrary = coarbitraryIntegral instance CoArbitrary Int where coarbitrary = coarbitraryIntegral instance CoArbitrary Int8 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int16 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int32 where coarbitrary = coarbitraryIntegral instance CoArbitrary Int64 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word where coarbitrary = coarbitraryIntegral instance CoArbitrary Word8 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word16 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word32 where coarbitrary = coarbitraryIntegral instance CoArbitrary Word64 where coarbitrary = coarbitraryIntegral instance CoArbitrary Char where coarbitrary = coarbitrary . ord instance CoArbitrary Float where coarbitrary = coarbitraryReal instance CoArbitrary Double where coarbitrary = coarbitraryReal -- ** Helpers for implementing coarbitrary -- | A 'coarbitrary' implementation for integral numbers. coarbitraryIntegral :: Integral a => a -> Gen b -> Gen b coarbitraryIntegral = variant -- | A 'coarbitrary' implementation for real numbers. coarbitraryReal :: Real a => a -> Gen b -> Gen b coarbitraryReal x = coarbitrary (toRational x) -- | 'coarbitrary' helper for lazy people :-). coarbitraryShow :: Show a => a -> Gen b -> Gen b coarbitraryShow x = coarbitrary (show x) -- | A 'coarbitrary' implementation for enums. coarbitraryEnum :: Enum a => a -> Gen b -> Gen b coarbitraryEnum = variant . fromEnum -------------------------------------------------------------------------- -- ** arbitrary generators -- these are here and not in Gen because of the Arbitrary class constraint -- | Generates a list of a given length. vector :: Arbitrary a => Int -> Gen [a] vector k = vectorOf k arbitrary -- | Generates an ordered list of a given length. orderedList :: (Ord a, Arbitrary a) => Gen [a] orderedList = sort `fmap` arbitrary -------------------------------------------------------------------------- -- the end.
AlexBaranosky/QuickCheck
Test/QuickCheck/Arbitrary.hs
bsd-3-clause
16,724
0
19
4,338
4,767
2,579
2,188
345
4
{-# LANGUAGE CPP #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeOperators #-} {-# OPTIONS -fno-warn-unused-imports #-} {-# OPTIONS -fno-warn-unused-binds #-} {-# OPTIONS_HADDOCK hide #-} -- | -- Module : Data.Array.Accelerate.Debug -- Copyright : [2008..2014] Manuel M T Chakravarty, Gabriele Keller -- [2009..2014] Trevor L. McDonell -- License : BSD3 -- -- Maintainer : Manuel M T Chakravarty <chak@cse.unsw.edu.au> -- Stability : experimental -- Portability : non-portable (GHC extensions) -- -- Embedded array processing language: debugging support (internal). This module -- provides functionality that is useful for developers of the library. It is -- not meant for library users. -- module Data.Array.Accelerate.Debug ( -- * Dynamic debugging flags dump_sharing, dump_simpl_stats, dump_simpl_iterations, verbose, queryFlag, setFlag, -- * Tracing traceMessage, traceEvent, tracePure, -- * Statistics inline, ruleFired, knownBranch, betaReduce, substitution, simplifierDone, fusionDone, resetSimplCount, simplCount, ) where -- standard libraries import Data.Function ( on ) import Data.IORef import Data.Label import Data.List ( groupBy, sortBy, isPrefixOf ) import Data.Ord ( comparing ) import Numeric import Text.PrettyPrint import System.CPUTime import System.Environment import System.IO.Unsafe ( unsafePerformIO ) import qualified Data.Map as Map import Debug.Trace ( traceIO, traceEventIO ) -- ----------------------------------------------------------------------------- -- Flag option parsing data FlagSpec flag = Option String -- external form flag -- internal form data Flags = Flags { -- debugging _dump_sharing :: !Bool -- sharing recovery phase , _dump_simpl_stats :: !Bool -- statistics form fusion/simplification , _dump_simpl_iterations :: !Bool -- output from each simplifier iteration , _verbose :: !Bool -- additional, uncategorised status messages -- functionality / phase control , _acc_sharing :: !(Maybe Bool) -- recover sharing of array computations , _exp_sharing :: !(Maybe Bool) -- recover sharing of scalar expressions , _fusion :: !(Maybe Bool) -- fuse array expressions , _simplify :: !(Maybe Bool) -- simplify scalar expressions } $(mkLabels [''Flags]) allFlags :: [FlagSpec (Flags -> Flags)] allFlags = map (enable 'd') dflags ++ map (enable 'f') fflags ++ map (disable 'f') fflags where enable p (Option f go) = Option ('-':p:f) (go True) disable p (Option f go) = Option ('-':p:"no-"++f) (go False) -- These @-d\<blah\>@ flags can be reversed with @-dno-\<blah\>@ -- dflags :: [FlagSpec (Bool -> Flags -> Flags)] dflags = [ Option "dump-sharing" (set dump_sharing) -- print sharing recovery trace , Option "dump-simpl-stats" (set dump_simpl_stats) -- dump simplifier stats , Option "dump-simpl-iterations" (set dump_simpl_iterations) -- dump output from each simplifier iteration , Option "verbose" (set verbose) -- print additional information ] -- These @-f\<blah\>@ flags can be reversed with @-fno-\<blah\>@ -- fflags :: [FlagSpec (Bool -> Flags -> Flags)] fflags = [ Option "acc-sharing" (set' acc_sharing) -- sharing of array computations , Option "exp-sharing" (set' exp_sharing) -- sharing of scalar expressions , Option "fusion" (set' fusion) -- fusion of array computations , Option "simplify" (set' simplify) -- scalar expression simplification -- , Option "unfolding-use-threshold" -- the magic cut-off figure for inlining ] where set' f v = set f (Just v) initialise :: IO Flags initialise = parse `fmap` getArgs where defaults = Flags False False False False Nothing Nothing Nothing Nothing parse = foldl parse1 defaults parse1 opts this = case filter (\(Option flag _) -> this `isPrefixOf` flag) allFlags of [Option _ go] -> go opts _ -> opts -- not specified, or ambiguous -- Indicates which tracing messages are to be emitted, and which phases are to -- be run. -- {-# NOINLINE options #-} options :: IORef Flags options = unsafePerformIO $ newIORef =<< initialise -- Query the status of a flag -- queryFlag :: (Flags :-> a) -> IO a queryFlag f = get f `fmap` readIORef options -- Set the status of a debug flag -- setFlag :: (Flags :-> a) -> a -> IO () setFlag f v = modifyIORef' options (set f v) -- Execute an action only if the corresponding flag is set -- when :: (Flags :-> Bool) -> IO () -> IO () #ifdef ACCELERATE_DEBUG when f action = do enabled <- queryFlag f if enabled then action else return () #else when _ _ = return () #endif -- ----------------------------------------------------------------------------- -- Trace messages -- Emit a trace message if the corresponding debug flag is set. -- traceMessage :: (Flags :-> Bool) -> String -> IO () #ifdef ACCELERATE_DEBUG traceMessage f str = when f $ do psec <- getCPUTime let sec = fromIntegral psec * 1E-12 :: Double traceIO $ showFFloat (Just 2) sec (':':str) #else traceMessage _ _ = return () #endif -- Emit a message to the event log if the corresponding debug flag is set -- traceEvent :: (Flags :-> Bool) -> String -> IO () #ifdef ACCELERATE_DEBUG traceEvent f str = when f (traceEventIO str) #else traceEvent _ _ = return () #endif -- Emit a trace message from a pure computation -- tracePure :: (Flags :-> Bool) -> String -> a -> a #ifdef ACCELERATE_DEBUG tracePure f msg next = unsafePerformIO (traceMessage f msg) `seq` next #else tracePure _ _ next = next #endif -- ----------------------------------------------------------------------------- -- Recording statistics ruleFired, inline, knownBranch, betaReduce, substitution :: String -> a -> a inline = annotate Inline ruleFired = annotate RuleFired knownBranch = annotate KnownBranch betaReduce = annotate BetaReduce substitution = annotate Substitution simplifierDone, fusionDone :: a -> a simplifierDone = tick SimplifierDone fusionDone = tick FusionDone -- Add an entry to the statistics counters -- tick :: Tick -> a -> a #ifdef ACCELERATE_DEBUG tick t next = unsafePerformIO (modifyIORef' statistics (simplTick t)) `seq` next #else tick _ next = next #endif -- Add an entry to the statistics counters with an annotation -- annotate :: (Id -> Tick) -> String -> a -> a annotate name ctx = tick (name (Id ctx)) -- Simplifier counts -- ----------------- data SimplStats = Simple {-# UNPACK #-} !Int -- when we don't want detailed stats | Detail { ticks :: {-# UNPACK #-} !Int, -- total ticks details :: !TickCount -- how many of each type } instance Show SimplStats where show = render . pprSimplCount -- Stores the current statistics counters -- {-# NOINLINE statistics #-} statistics :: IORef SimplStats statistics = unsafePerformIO $ newIORef =<< initSimplCount -- Initialise the statistics counters. If we are dumping the stats -- (-ddump-simpl-stats) record extra information, else just a total tick count. -- initSimplCount :: IO SimplStats #ifdef ACCELERATE_DEBUG initSimplCount = do d <- queryFlag dump_simpl_stats return $! if d then Detail { ticks = 0, details = Map.empty } else Simple 0 #else initSimplCount = return $! Simple 0 #endif -- Reset the statistics counters. Do this at the beginning at each HOAS -> de -- Bruijn conversion + optimisation pass. -- resetSimplCount :: IO () #ifdef ACCELERATE_DEBUG resetSimplCount = writeIORef statistics =<< initSimplCount #else resetSimplCount = return () #endif -- Tick a counter -- simplTick :: Tick -> SimplStats -> SimplStats simplTick _ (Simple n) = Simple (n+1) simplTick t (Detail n dts) = Detail (n+1) (dts `addTick` t) -- Pretty print the tick counts. Remarkably reminiscent of GHC style... -- pprSimplCount :: SimplStats -> Doc pprSimplCount (Simple n) = text "Total ticks:" <+> int n pprSimplCount (Detail n dts) = vcat [ text "Total ticks:" <+> int n , text "" , pprTickCount dts ] simplCount :: IO Doc simplCount = pprSimplCount `fmap` readIORef statistics -- Ticks -- ----- type TickCount = Map.Map Tick Int data Id = Id String deriving (Eq, Ord) data Tick = Inline Id | RuleFired Id | KnownBranch Id | BetaReduce Id | Substitution Id -- tick at each iteration | SimplifierDone | FusionDone deriving (Eq, Ord) addTick :: TickCount -> Tick -> TickCount addTick tc t = let x = 1 + Map.findWithDefault 0 t tc in x `seq` Map.insert t x tc pprTickCount :: TickCount -> Doc pprTickCount counts = vcat (map pprTickGroup groups) where groups = groupBy sameTag (Map.toList counts) sameTag = (==) `on` tickToTag . fst pprTickGroup :: [(Tick,Int)] -> Doc pprTickGroup [] = error "pprTickGroup" pprTickGroup group = hang (int groupTotal <+> text groupName) 2 (vcat [ int n <+> pprTickCtx t | (t,n) <- sortBy (flip (comparing snd)) group ]) where groupName = tickToStr (fst (head group)) groupTotal = sum [n | (_,n) <- group] tickToTag :: Tick -> Int tickToTag Inline{} = 0 tickToTag RuleFired{} = 1 tickToTag KnownBranch{} = 2 tickToTag BetaReduce{} = 3 tickToTag Substitution{} = 4 tickToTag SimplifierDone = 99 tickToTag FusionDone = 100 tickToStr :: Tick -> String tickToStr Inline{} = "Inline" tickToStr RuleFired{} = "RuleFired" tickToStr KnownBranch{} = "KnownBranch" tickToStr BetaReduce{} = "BetaReduce" tickToStr Substitution{} = "Substitution" tickToStr SimplifierDone = "SimplifierDone" tickToStr FusionDone = "FusionDone" pprTickCtx :: Tick -> Doc pprTickCtx (Inline v) = pprId v pprTickCtx (RuleFired v) = pprId v pprTickCtx (KnownBranch v) = pprId v pprTickCtx (BetaReduce v) = pprId v pprTickCtx (Substitution v) = pprId v pprTickCtx SimplifierDone = empty pprTickCtx FusionDone = empty pprId :: Id -> Doc pprId (Id s) = text s
kumasento/accelerate
Data/Array/Accelerate/Debug.hs
bsd-3-clause
10,874
0
15
2,940
2,395
1,313
1,082
-1
-1
{-# LANGUAGE GADTs, RecordWildCards, ScopedTypeVariables, FlexibleContexts, FlexibleInstances, DeriveDataTypeable, MultiParamTypeClasses, UndecidableInstances #-} -- | Declaration of exceptions types module YaLedger.Exceptions (throwP, InternalError (..), NoSuchRate (..), InsufficientFunds (..), ReconciliationError (..), DuplicatedRecord (..), NoSuchHold (..), InvalidAccountType (..), NoCorrespondingAccountFound (..), NoSuchTemplate (..), InvalidCmdLine (..), InvalidPath (..), NotAnAccount (..) ) where import Control.Monad.Exception import Control.Monad.State import Data.List (intercalate) import Data.Decimal import YaLedger.Types (Path) import YaLedger.Types.Ledger import YaLedger.Types.Common import YaLedger.Types.Monad showPos :: SourcePos -> String -> String showPos pos msg = msg ++ "\n at " ++ show pos throwP e = do pos <- gets lsPosition throw (e pos) data InternalError = InternalError String SourcePos deriving (Typeable) instance Show InternalError where show (InternalError msg pos) = showPos pos $ "Internal error: " ++ msg instance Exception InternalError instance UncaughtException InternalError data NoSuchRate = NoSuchRate Currency Currency SourcePos deriving (Typeable) instance Show NoSuchRate where show (NoSuchRate c1 c2 pos) = showPos pos $ "No conversion rate defined to convert " ++ show c1 ++ " -> " ++ show c2 instance Exception NoSuchRate data InsufficientFunds = InsufficientFunds String Decimal Currency SourcePos deriving (Typeable) instance Show InsufficientFunds where show (InsufficientFunds account x c pos) = showPos pos $ "Insufficient funds on account " ++ account ++ ": balance would be " ++ show (x :# c) instance Exception InsufficientFunds data ReconciliationError = ReconciliationError String SourcePos deriving (Typeable) instance Show ReconciliationError where show (ReconciliationError msg pos) = showPos pos $ "Reconciliation error: " ++ msg instance Exception ReconciliationError data NoSuchHold = NoSuchHold PostingType Decimal Path SourcePos deriving (Typeable) instance Show NoSuchHold where show (NoSuchHold ptype amt path pos) = showPos pos $ "There is no " ++ show ptype ++ " hold of amount " ++ show amt ++ " on account " ++ intercalate "/" path instance Exception NoSuchHold data DuplicatedRecord = DuplicatedRecord String SourcePos deriving (Typeable) instance Show DuplicatedRecord where show (DuplicatedRecord s pos) = showPos pos $ "Duplicated records:\n" ++ s instance Exception DuplicatedRecord data InvalidAccountType = InvalidAccountType String Decimal AccountGroupType AccountGroupType SourcePos deriving (Typeable) instance Show InvalidAccountType where show (InvalidAccountType name amt t1 t2 pos) = showPos pos $ "Internal error:\n Invalid account type: " ++ name ++ ": " ++ show t1 ++ " instead of " ++ show t2 ++ " (amount: " ++ show amt ++ ")" instance Exception InvalidAccountType data NoCorrespondingAccountFound = NoCorrespondingAccountFound (Delta Amount) CQuery SourcePos deriving (Typeable) instance Show NoCorrespondingAccountFound where show (NoCorrespondingAccountFound delta qry pos) = showPos pos $ "No corresponding account found by query: " ++ show qry ++ "\nwhile need to change some balance: " ++ show delta instance Exception NoCorrespondingAccountFound data NoSuchTemplate = NoSuchTemplate String SourcePos deriving (Typeable) instance Show NoSuchTemplate where show (NoSuchTemplate name pos) = showPos pos $ "No such template was defined: " ++ name instance Exception NoSuchTemplate data InvalidCmdLine = InvalidCmdLine String deriving (Typeable) instance Show InvalidCmdLine where show (InvalidCmdLine e) = "Invalid command line parameter: " ++ e instance Exception InvalidCmdLine data InvalidPath = InvalidPath Path [ChartOfAccounts] SourcePos deriving (Typeable) instance Show InvalidPath where show (InvalidPath path [] pos) = showPos pos $ "No such account: " ++ intercalate "/" path show (InvalidPath path list pos) = showPos pos $ "Ambigous account/group specification: " ++ intercalate "/" path ++ ". Matching are:\n" ++ unlines (map show list) instance Exception InvalidPath data NotAnAccount = NotAnAccount Path SourcePos deriving (Typeable) instance Show NotAnAccount where show (NotAnAccount p pos) = showPos pos $ "This is accounts group, not an account: " ++ intercalate "/" p instance Exception NotAnAccount
portnov/yaledger
YaLedger/Exceptions.hs
bsd-3-clause
4,623
0
15
878
1,156
597
559
115
1
module Data.TrieMap.WordMap.Tests where import Data.TrieMap.WordMap () import Data.Word import qualified Data.TrieMap.TrieKey.Tests as TrieKeyTests import Test.QuickCheck tests :: Property tests = TrieKeyTests.tests "Data.TrieMap.WordMap" (0 :: Word)
lowasser/TrieMap
Data/TrieMap/WordMap/Tests.hs
bsd-3-clause
254
0
6
28
60
39
21
7
1
{-# LANGUAGE CPP, DeriveDataTypeable #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Py.Token -- Copyright : (c) 2009 Bernie Pope -- License : BSD-style -- Maintainer : bjpop@csse.unimelb.edu.au -- Stability : experimental -- Portability : ghc -- -- Lexical tokens for the Python lexer. Contains the superset of tokens from -- version 2 and version 3 of Python (they are mostly the same). ----------------------------------------------------------------------------- module Language.Py.Token -- * The tokens ( Token (..) -- * String conversion , debugTokenString , tokenString -- * Classification , hasLiteral , TokenClass (..) , classifyToken ) where import Language.Py.Pretty import Language.Py.SrcLocation (SrcSpan (..), SrcLocation (..), Span(getSpan)) import Data.Data -- | Lexical tokens. data Token -- Whitespace = IndentToken { tokenSpan :: !SrcSpan } -- ^ Indentation: increase. | DedentToken { tokenSpan :: !SrcSpan } -- ^ Indentation: decrease. | NewlineToken { tokenSpan :: !SrcSpan } -- ^ Newline. | LineJoinToken { tokenSpan :: !SrcSpan } -- ^ Line join (backslash at end of line). -- Comment | CommentToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Single line comment. -- Identifiers | IdentifierToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Identifier. -- Literals | StringToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Literal: string. | ByteStringToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Literal: byte string. | UnicodeStringToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String } -- ^ Literal: unicode string, version 2 only. | IntegerToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenInteger :: !Integer } -- ^ Literal: integer. | LongIntegerToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenInteger :: !Integer } -- ^ Literal: long integer. /Version 2 only/. | FloatToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenDouble :: !Double } -- ^ Literal: floating point. | ImaginaryToken { tokenSpan :: !SrcSpan, tokenLiteral :: !String, tokenDouble :: !Double } -- ^ Literal: imaginary number. -- Keywords | DefToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'def\'. | WhileToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'while\'. | IfToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'if\'. | TrueToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'True\'. | FalseToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'False\'. | ReturnToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'Return\'. | TryToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'try\'. | ExceptToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'except\'. | RaiseToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'raise\'. | InToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'in\'. | IsToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'is\'. | LambdaToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'lambda\'. | ClassToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'class\'. | FinallyToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'finally\'. | NoneToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'None\'. | ForToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'for\'. | FromToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'from\'. | GlobalToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'global\'. | WithToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'with\'. | AsToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'as\'. | ElifToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'elif\'. | YieldToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'yield\'. | AssertToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'assert\'. | ImportToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'import\'. | PassToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'pass\'. | BreakToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'break\'. | ContinueToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'continue\'. | DeleteToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'del\'. | ElseToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'else\'. | NotToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'not\'. | AndToken { tokenSpan :: !SrcSpan } -- ^ Keyword: boolean conjunction \'and\'. | OrToken { tokenSpan :: !SrcSpan } -- ^ Keyword: boolean disjunction \'or\'. -- Version 3.x only: | NonLocalToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'nonlocal\' (Python 3.x only) -- Version 2.x only: | PrintToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'print\'. (Python 2.x only) | ExecToken { tokenSpan :: !SrcSpan } -- ^ Keyword: \'exec\'. (Python 2.x only) -- Delimiters | AtToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: at sign \'\@\'. | LeftRoundBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: left round bracket \'(\'. | RightRoundBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right round bracket \')\'. | LeftSquareBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: left square bracket \'[\'. | RightSquareBracketToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right square bracket \']\'. | LeftBraceToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: left curly bracket \'{\'. | RightBraceToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right curly bracket \'}\'. | DotToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: dot (full stop) \'.\'. | CommaToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: comma \',\'. | SemiColonToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: semicolon \';\'. | ColonToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: colon \':\'. | EllipsisToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: ellipses (three dots) \'...\'. | RightArrowToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: right facing arrow \'->\'. | AssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: assignment \'=\'. | PlusAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: plus assignment \'+=\'. | MinusAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: minus assignment \'-=\'. | MultAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: multiply assignment \'*=\' | DivAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: divide assignment \'/=\'. | ModAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: modulus assignment \'%=\'. | PowAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: power assignment \'**=\'. | BinAndAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-and assignment \'&=\'. | BinOrAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-or assignment \'|=\'. | BinXorAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-xor assignment \'^=\'. | LeftShiftAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-left-shift assignment \'<<=\'. | RightShiftAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: binary-right-shift assignment \'>>=\'. | FloorDivAssignToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: floor-divide assignment \'//=\'. | BackQuoteToken { tokenSpan :: !SrcSpan } -- ^ Delimiter: back quote character \'`\'. -- Operators | PlusToken { tokenSpan :: !SrcSpan } -- ^ Operator: plus \'+\'. | MinusToken { tokenSpan :: !SrcSpan } -- ^ Operator: minus: \'-\'. | MultToken { tokenSpan :: !SrcSpan } -- ^ Operator: multiply \'*\'. | DivToken { tokenSpan :: !SrcSpan } -- ^ Operator: divide \'/\'. | GreaterThanToken { tokenSpan :: !SrcSpan } -- ^ Operator: greater-than \'>\'. | LessThanToken { tokenSpan :: !SrcSpan } -- ^ Operator: less-than \'<\'. | EqualityToken { tokenSpan :: !SrcSpan } -- ^ Operator: equals \'==\'. | GreaterThanEqualsToken { tokenSpan :: !SrcSpan } -- ^ Operator: greater-than-or-equals \'>=\'. | LessThanEqualsToken { tokenSpan :: !SrcSpan } -- ^ Operator: less-than-or-equals \'<=\'. | ExponentToken { tokenSpan :: !SrcSpan } -- ^ Operator: exponential \'**\'. | BinaryOrToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-or \'|\'. | XorToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-xor \'^\'. | BinaryAndToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-and \'&\'. | ShiftLeftToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-shift-left \'<<\'. | ShiftRightToken { tokenSpan :: !SrcSpan } -- ^ Operator: binary-shift-right \'>>\'. | ModuloToken { tokenSpan :: !SrcSpan } -- ^ Operator: modulus \'%\'. | FloorDivToken { tokenSpan :: !SrcSpan } -- ^ Operator: floor-divide \'//\'. | TildeToken { tokenSpan :: !SrcSpan } -- ^ Operator: tilde \'~\'. | NotEqualsToken { tokenSpan :: !SrcSpan } -- ^ Operator: not-equals \'!=\'. | NotEqualsV2Token { tokenSpan :: !SrcSpan } -- ^ Operator: not-equals \'<>\'. Version 2 only. -- Special cases | EOFToken { tokenSpan :: !SrcSpan } -- ^ End of file deriving (Eq, Ord, Show, Typeable, Data) instance Span Token where getSpan = tokenSpan -- | Produce a string from a token containing detailed information. Mainly intended for debugging. debugTokenString :: Token -> String debugTokenString token = render (text (show $ toConstr token) <+> pretty (tokenSpan token) <+> if hasLiteral token then text (tokenLiteral token) else empty) -- | Test if a token contains its literal source text. hasLiteral :: Token -> Bool hasLiteral token = case token of CommentToken {} -> True IdentifierToken {} -> True StringToken {} -> True ByteStringToken {} -> True IntegerToken {} -> True LongIntegerToken {} -> True FloatToken {} -> True ImaginaryToken {} -> True other -> False -- | Classification of tokens data TokenClass = Comment | Number | Identifier | Punctuation | Bracket | Layout | Keyword | String | Operator | Assignment deriving (Show, Eq, Ord) classifyToken :: Token -> TokenClass classifyToken token = case token of IndentToken {} -> Layout DedentToken {} -> Layout NewlineToken {} -> Layout CommentToken {} -> Comment IdentifierToken {} -> Identifier StringToken {} -> String ByteStringToken {} -> String IntegerToken {} -> Number LongIntegerToken {} -> Number FloatToken {} -> Number ImaginaryToken {} -> Number DefToken {} -> Keyword WhileToken {} -> Keyword IfToken {} -> Keyword TrueToken {} -> Keyword FalseToken {} -> Keyword ReturnToken {} -> Keyword TryToken {} -> Keyword ExceptToken {} -> Keyword RaiseToken {} -> Keyword InToken {} -> Keyword IsToken {} -> Keyword LambdaToken {} -> Keyword ClassToken {} -> Keyword FinallyToken {} -> Keyword NoneToken {} -> Keyword ForToken {} -> Keyword FromToken {} -> Keyword GlobalToken {} -> Keyword WithToken {} -> Keyword AsToken {} -> Keyword ElifToken {} -> Keyword YieldToken {} -> Keyword AssertToken {} -> Keyword ImportToken {} -> Keyword PassToken {} -> Keyword BreakToken {} -> Keyword ContinueToken {} -> Keyword DeleteToken {} -> Keyword ElseToken {} -> Keyword NotToken {} -> Keyword AndToken {} -> Keyword OrToken {} -> Keyword NonLocalToken {} -> Keyword PrintToken {} -> Keyword ExecToken {} -> Keyword AtToken {} -> Keyword LeftRoundBracketToken {} -> Bracket RightRoundBracketToken {} -> Bracket LeftSquareBracketToken {} -> Bracket RightSquareBracketToken {} -> Bracket LeftBraceToken {} -> Bracket RightBraceToken {} -> Bracket DotToken {} -> Operator CommaToken {} -> Punctuation SemiColonToken {} -> Punctuation ColonToken {} -> Punctuation EllipsisToken {} -> Keyword -- What kind of thing is an ellipsis? RightArrowToken {} -> Punctuation AssignToken {} -> Assignment PlusAssignToken {} -> Assignment MinusAssignToken {} -> Assignment MultAssignToken {} -> Assignment DivAssignToken {} -> Assignment ModAssignToken {} -> Assignment PowAssignToken {} -> Assignment BinAndAssignToken {} -> Assignment BinOrAssignToken {} -> Assignment BinXorAssignToken {} -> Assignment LeftShiftAssignToken {} -> Assignment RightShiftAssignToken {} -> Assignment FloorDivAssignToken {} -> Assignment BackQuoteToken {} -> Punctuation PlusToken {} -> Operator MinusToken {} -> Operator MultToken {} -> Operator DivToken {} -> Operator GreaterThanToken {} -> Operator LessThanToken {} -> Operator EqualityToken {} -> Operator GreaterThanEqualsToken {} -> Operator LessThanEqualsToken {} -> Operator ExponentToken {} -> Operator BinaryOrToken {} -> Operator XorToken {} -> Operator BinaryAndToken {} -> Operator ShiftLeftToken {} -> Operator ShiftRightToken {} -> Operator ModuloToken {} -> Operator FloorDivToken {} -> Operator TildeToken {} -> Operator NotEqualsToken {} -> Operator NotEqualsV2Token {} -> Operator LineJoinToken {} -> Layout EOFToken {} -> Layout -- maybe a spurious classification. -- | Produce a string from a token which is suitable for printing as Python concrete syntax. -- /Invisible/ tokens yield an empty string. tokenString :: Token -> String tokenString token = case token of IndentToken {} -> "" DedentToken {} -> "" NewlineToken {} -> "" CommentToken {} -> tokenLiteral token IdentifierToken {} -> tokenLiteral token StringToken {} -> tokenLiteral token ByteStringToken {} -> tokenLiteral token IntegerToken {} -> tokenLiteral token LongIntegerToken {} -> tokenLiteral token FloatToken {} -> tokenLiteral token ImaginaryToken {} -> tokenLiteral token DefToken {} -> "def" WhileToken {} -> "while" IfToken {} -> "if" TrueToken {} -> "True" FalseToken {} -> "False" ReturnToken {} -> "return" TryToken {} -> "try" ExceptToken {} -> "except" RaiseToken {} -> "raise" InToken {} -> "in" IsToken {} -> "is" LambdaToken {} -> "lambda" ClassToken {} -> "class" FinallyToken {} -> "finally" NoneToken {} -> "None" ForToken {} -> "for" FromToken {} -> "from" GlobalToken {} -> "global" WithToken {} -> "with" AsToken {} -> "as" ElifToken {} -> "elif" YieldToken {} -> "yield" AssertToken {} -> "assert" ImportToken {} -> "import" PassToken {} -> "pass" BreakToken {} -> "break" ContinueToken {} -> "continue" DeleteToken {} -> "delete" ElseToken {} -> "else" NotToken {} -> "not" AndToken {} -> "and" OrToken {} -> "or" NonLocalToken {} -> "nonlocal" PrintToken {} -> "print" ExecToken {} -> "exec" AtToken {} -> "at" LeftRoundBracketToken {} -> "(" RightRoundBracketToken {} -> ")" LeftSquareBracketToken {} -> "[" RightSquareBracketToken {} -> "]" LeftBraceToken {} -> "{" RightBraceToken {} -> "}" DotToken {} -> "." CommaToken {} -> "," SemiColonToken {} -> ";" ColonToken {} -> ":" EllipsisToken {} -> "..." RightArrowToken {} -> "->" AssignToken {} -> "=" PlusAssignToken {} -> "+=" MinusAssignToken {} -> "-=" MultAssignToken {} -> "*=" DivAssignToken {} -> "/=" ModAssignToken {} -> "%=" PowAssignToken {} -> "**=" BinAndAssignToken {} -> "&=" BinOrAssignToken {} -> "|=" BinXorAssignToken {} -> "^=" LeftShiftAssignToken {} -> "<<=" RightShiftAssignToken {} -> ">>=" FloorDivAssignToken {} -> "//=" BackQuoteToken {} -> "`" PlusToken {} -> "+" MinusToken {} -> "-" MultToken {} -> "*" DivToken {} -> "/" GreaterThanToken {} -> ">" LessThanToken {} -> "<" EqualityToken {} -> "==" GreaterThanEqualsToken {} -> ">=" LessThanEqualsToken {} -> "<=" ExponentToken {} -> "**" BinaryOrToken {} -> "|" XorToken {} -> "^" BinaryAndToken {} -> "&" ShiftLeftToken {} -> "<<" ShiftRightToken {} -> ">>" ModuloToken {} -> "%" FloorDivToken {} -> "//" TildeToken {} -> "~" NotEqualsToken {} -> "!=" NotEqualsV2Token {} -> "<>" LineJoinToken {} -> "\\" EOFToken {} -> ""
codeq/language-py
src/Language/Py/Token.hs
bsd-3-clause
18,123
0
12
5,559
3,683
2,026
1,657
553
95
{-# OPTIONS_HADDOCK hide, prune #-} module Import.BootstrapUtil where import Import bootstrapSelectFieldList :: (Eq a, RenderMessage site FormMessage) => [(Text, a)] -> Field (HandlerT site IO) a bootstrapSelectFieldList opts = Field { fieldParse = parse , fieldView = viewFunc , fieldEnctype = enc } where (Field parse view enc) = selectFieldList opts viewFunc id' name _attrs eitherText required = do let select = view id' name [("class", "form-control")] eitherText required [whamlet| <div .form-group> ^{select} |] -- based on https://www.stackage.org/haddock/lts-8.23/yesod-form-1.4.12/src/Yesod.Form.Fields.html#dayField bootstrapDayField :: Monad m => RenderMessage (HandlerSite m) FormMessage => Field m Day bootstrapDayField = Field { fieldParse = parseHelper $ parseDate . unpack , fieldView = \theId name attrs val isReq -> toWidget [hamlet| <div .form-group> <input .form-control id="#{theId}" name="#{name}" *{attrs} type="date" :isReq:required="" value="#{showVal val}" > |] , fieldEnctype = UrlEncoded } where showVal = either id (pack . show)
achirkin/qua-kit
apps/hs/qua-server/src/Import/BootstrapUtil.hs
mit
1,325
0
14
405
264
146
118
-1
-1
-- -- Copyright (c) 2014 Citrix Systems, Inc. -- -- 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 -- {-# LANGUAGE TypeSynonymInstances,OverlappingInstances,TypeOperators,PatternGuards,ScopedTypeVariables,FlexibleInstances #-} module Vm.Config ( ConfigProperty , diagnose , amtPtActive -- read / write / check for existence of config properties , readConfigProperty , readConfigPropertyDef , saveConfigProperty , saveOrRmConfigProperty , haveConfigProperty , locateConfigProperty , getConfigPropertyName -- Xenvm config out of database config , getXenvmConfig , stringifyXenvmConfig -- list of interesting config properties , vmUuidP, vmName, vmDescription, vmType, vmSlot, vmImagePath, vmPvAddons, vmPvAddonsVersion , vmStartOnBoot, vmStartOnBootPriority, vmKeepAlive, vmProvidesNetworkBackend, vmTimeOffset , vmAmtPt, vmCryptoUser, vmCryptoKeyDirs, vmStartup , vmNotify, vmHvm, vmPae, vmAcpi, vmApic, vmViridian, vmNx, vmSound, vmMemory, vmHap, vmSmbiosPt , vmDisplay, vmBoot, vmCmdLine, vmKernel, vmInitrd, vmAcpiPt, vmVcpus, vmGpu , vmKernelExtract, vmInitrdExtract , vmMemoryStaticMax , vmMemoryMin , vmVideoram, vmHibernated, vmHidden, vmMeasured, vmShutdownPriority, vmProvidesGraphicsFallback , vmPorticaStatus, vmPassthroughMmio, vmPassthroughIo, vmHiddenInUi , vmFlaskLabel, vmCoresPerSocket, vmAutoS3Wake, vmSeamlessId, vmStartFromSuspendImage , vmExtraHvms, vmExtraXenvm, vmDisks, vmNics, vmPcis, vmDisk, vmNic, vmPci, vmQemuDmPath, vmQemuDmTimeout , vmTrackDependencies, vmSeamlessMouseLeft, vmSeamlessMouseRight , vmOs, vmControlPlatformPowerState , vmFirewallRules , vmSeamlessTraffic , vmOemAcpiFeatures, vmUsbEnabled, vmUsbAutoPassthrough, vmUsbControl, vmStubdom, vmCpuid , vmUsbGrabDevices , vmGreedyPcibackBind , vmRunPostCreate, vmRunPreDelete, vmRunOnStateChange, vmRunOnAcpiStateChange , vmRunPreBoot , vmRunInsteadofStart , vmDomstoreReadAccess, vmDomstoreWriteAccess , vmShowSwitcher, vmWirelessControl, vmNativeExperience , vmXciCpuidSignature , vmS3Mode , vmS4Mode , vmVsnd, vmVkbd, vmVfb, vmV4v , vmRealm , vmSyncUuid , vmIcbinnPath , vmOvfTransportIso , vmReady , vmProvidesDefaultNetworkBackend , vmRestrictDisplayDepth , vmRestrictDisplayRes , vmPreserveOnReboot , vmBootSentinel , vmHpet, vmHpetDefault , vmTimerMode, vmTimerModeDefault , vmNestedHvm , vmSerial ) where import Control.Arrow import Control.Monad hiding (join) import Control.Applicative import Data.Bits import Data.Char import Data.String import Data.List import Data.Maybe import qualified Data.Text.Lazy as TL import qualified Data.Map as M import Directory import Text.Printf import System.FilePath.Posix import Tools.Log import Tools.File import Tools.Misc import Tools.Future import Tools.IfM import Rpc.Core import Vm.Types import Vm.Policies import XenMgr.Db import XenMgr.Host import XenMgr.Notify import XenMgr.Rpc import XenMgr.Config import Rpc.Autogen.XenmgrConst ------------------------ -- Configuration Tree -- ------------------------ type Location = String type Value = String -- UUID as well instance Marshall Uuid where dbRead x = dbReadStr x >>= return . fromString dbWrite x v = dbWriteStr x (show v) -- VM type can be marshalled instance Marshall VmType where dbRead x = dbReadStr x >>= return . fromS where fromS "svm" = Svm fromS "pvm" = Svm fromS tag = ServiceVm tag dbWrite x v = dbWriteStr x (toS v) where toS Svm = "svm" toS (ServiceVm tag) = tag instance Marshall XbDeviceID where dbRead p = XbDeviceID <$> dbRead p dbWrite p (XbDeviceID v) = dbWrite p v instance EnumMarshall DiskDeviceType where enumMarshallMap = [ (DiskDeviceTypeDisk , "disk" ) , (DiskDeviceTypeCdRom, "cdrom") ] instance EnumMarshall DiskMode where enumMarshallMap = [ (Vm.Types.ReadOnly , "r") , (Vm.Types.ReadWrite, "w") ] instance EnumMarshall DiskType where enumMarshallMap = [ (DiskImage , "file") , (PhysicalDevice , "phy" ) , (QemuCopyOnWrite, "qcow") , (ExternalVdi , "vdi" ) , (Aio , "aio" ) , (VirtualHardDisk, "vhd" ) ] instance EnumMarshall DiskSnapshotMode where enumMarshallMap = [ (SnapshotTemporary , "temporary" ) , (SnapshotTemporaryEncrypted, "temporary-encrypted" ) , (SnapshotCoalesce , "coalesce" ) , (SnapshotScripted , "scripted" ) , (SnapshotScriptedAuthor , "scripted-author" ) , (SnapshotScriptedNoSnapshot, "scripted-no-snapshot") ] instance EnumMarshall ManagedDiskType where enumMarshallMap = [ (UnmanagedDisk, eMANAGED_DISKTYPE_NONE) , (SystemDisk, eMANAGED_DISKTYPE_SYSTEM) , (ApplicationDisk, eMANAGED_DISKTYPE_APPLICATION) , (UserDisk, eMANAGED_DISKTYPE_USER) ] instance EnumMarshall S3Mode where enumMarshallMap = [ (S3Pv, eS3_MODE_PV) , (S3Ignore, eS3_MODE_IGNORE) , (S3Restart, eS3_MODE_RESTART) , (S3Snapshot, eS3_MODE_SNAPSHOT) ] instance EnumMarshall S4Mode where enumMarshallMap = [ (S4Pv, eS4_MODE_PV) , (S4Ignore, eS4_MODE_IGNORE) , (S4Restart, eS4_MODE_RESTART) , (S4Snapshot, eS4_MODE_SNAPSHOT) ] instance Marshall DiskMode where {dbRead = dbReadEnum; dbWrite = dbWriteEnum} instance Marshall DiskType where {dbRead = dbReadEnum; dbWrite = dbWriteEnum} instance Marshall DiskSnapshotMode where {dbRead = dbReadEnum; dbWrite = dbWriteEnum} instance Marshall DiskDeviceType where {dbRead = dbReadEnum; dbWrite = dbWriteEnum} instance Marshall ManagedDiskType where {dbRead = dbReadEnum; dbWrite = dbWriteEnum} instance Marshall S3Mode where {dbRead = dbReadEnum; dbWrite = dbWriteEnum} instance Marshall S4Mode where {dbRead = dbReadEnum; dbWrite = dbWriteEnum} instance Marshall Sha1Sum where dbRead = fmap (read . ("0x" ++)) . dbReadStr dbWrite x = dbWriteStr x . printf "%040x" instance Marshall a => Marshall (Maybe a) where dbRead = dbMaybeRead dbWrite = dbMaybeWrite -- Disk definition info can be marshalled instance Marshall Disk where dbRead x = do path <- dbRead (x ++ "/path" ) typ <- dbRead (x ++ "/type" ) mtyp <- dbReadWithDefault UnmanagedDisk (x ++ "/managed-disktype" ) mode <- dbRead (x ++ "/mode" ) dev <- dbRead (x ++ "/device" ) devt <- dbRead (x ++ "/devtype" ) snap <- dbRead (x ++ "/snapshot") sha1Sum <- dbRead (x ++ "/sha1sum" ) shared <- dbReadWithDefault False (x ++ "/shared") enable <- dbReadWithDefault True (x ++ "/enable") return $ Disk { diskPath = path , diskType = typ , diskMode = mode , diskDevice = dev , diskDeviceType = devt , diskSnapshotMode = snap , diskSha1Sum = sha1Sum , diskShared = shared , diskManagedType = mtyp , diskEnabled = enable } dbWrite x v = do current <- dbRead x dbWrite (x ++ "/path" ) (diskPath v) dbWrite (x ++ "/type" ) (diskType v) let mmt UnmanagedDisk = Nothing; mmt x = Just x dbMaybeWrite (x ++ "/managed-disktype") (mmt $ diskManagedType v) dbWrite (x ++ "/mode" ) (diskMode v) dbWrite (x ++ "/device" ) (diskDevice v) dbWrite (x ++ "/devtype" ) (diskDeviceType v) dbWrite (x ++ "/snapshot") (diskSnapshotMode v) dbWrite (x ++ "/sha1sum" ) (diskSha1Sum v) dbWrite (x ++ "/shared" ) (diskShared v) when (diskEnabled v /= diskEnabled current) $ dbWrite (x ++ "/enable") (diskEnabled v) -- NIC definition can be marshalled instance Marshall NicDef where dbRead x = do ids <- dbReadStr (x ++ "/id" ) net <- dbMaybeRead (x ++ "/network" ) uuid <- dbMaybeRead (x ++ "/backend-uuid") bname <- dbMaybeRead (x ++ "/backend-name") enable <- dbReadWithDefault True (x ++ "/enable" ) wifi <- dbReadWithDefault False (x ++ "/wireless-driver") mac <- dbMaybeRead (x ++ "/mac" ) let nicid = case ids of "" -> 0 s -> read s :: Int return $ NicDef { nicdefId = XbDeviceID nicid , nicdefNetwork = fromMaybe fallbackNetwork (fmap networkFromStr net) , nicdefWirelessDriver = wifi , nicdefBackendUuid = case uuid of Just "" -> Nothing _ -> fmap fromString uuid , nicdefBackendName = case bname of Just "" -> Nothing _ -> fmap id bname , nicdefBackendDomid = Nothing , nicdefEnable = enable , nicdefMac = mac } dbWrite x v = do current <- dbRead x let XbDeviceID nid = nicdefId v dbWriteStr (x ++ "/id") (show nid) when (nicdefEnable v /= nicdefEnable current) $ dbWrite (x ++ "/enable") (nicdefEnable v) dbWrite (x ++ "/network") (networkToStr $ nicdefNetwork v) case nicdefWirelessDriver v of False -> dbRm (x ++ "/wireless-driver") True -> dbWrite (x ++ "/wireless-driver") True case nicdefBackendUuid v of Nothing -> dbRm (x ++ "/backend-uuid") Just id -> dbWrite (x ++ "/backend-uuid") id case nicdefBackendName v of Nothing -> dbRm (x ++ "/backend-name") Just id -> dbWrite (x ++ "/backend-name") id case nicdefMac v of Nothing -> dbRm (x ++ "/mac") Just m -> dbWrite (x ++ "/mac") m -- Portica status is marshallable instance Marshall PorticaStatus where -- But this is dangerous, if the order of elements in PorticaStatus changes. dbRead x = PorticaStatus <$> (maybe False id <$> dbMaybeRead (x ++ "/portica-installed")) <*> (maybe False id <$> dbMaybeRead (x ++ "/portica-enabled")) dbWrite x (PorticaStatus installed enabled) = do dbWrite (x ++ "/portica-installed") installed dbWrite (x ++ "/portica-enabled") enabled -- A path to database from given VM dbPath :: Uuid -> Location dbPath uuid = "/vm/" ++ show uuid -- Convert a property path by getting rid of dots convert :: Location -> Location convert = map f where f '.' = '/' f x = x -- Join paths using a separator / join :: [String] -> String join = concat . intersperse "/" data ConfigProperty = ConfigProperty { property_name :: String , property_location :: Uuid -> String } property :: String -> ConfigProperty property name = ConfigProperty { property_name = name , property_location = \uuid -> join [dbPath uuid, convert name] } -- Locate a named property within a VM of given uuid locate :: ConfigProperty -> Uuid -> Location locate p uuid = property_location p uuid locateConfigProperty = property ------------------------ -- Individual properties ------------------------ -- Core Ones vmUuidP = property "uuid" vmName = property "name" vmDescription = property "description" vmSlot = property "slot" vmType = property "type" vmImagePath = property "image_path" vmPvAddons = property "pv-addons-installed" vmPvAddonsVersion = property "pv-addons-version" vmStartOnBoot = property "start_on_boot" vmStartOnBootPriority = property "start_on_boot_priority" vmStartFromSuspendImage = property "start-from-suspend-image" vmShutdownPriority = property "shutdown-priority" vmKeepAlive = property "keep-alive" vmProvidesNetworkBackend = property "provides-network-backend" vmProvidesDefaultNetworkBackend = property "provides-default-network-backend" vmProvidesGraphicsFallback = property "provides-graphics-fallback" vmTimeOffset = property "time-offset" vmAmtPt = property "amt-pt" vmHibernated = property "hibernated" vmHidden = property "hidden" vmHiddenInUi = property "hidden-in-ui" vmAutoS3Wake = property "auto-s3-wake" vmMeasured = property "measured" vmSeamlessId = property "seamless-id" vmTrackDependencies = property "track-dependencies" vmSeamlessMouseLeft = property "seamless-mouse-left" vmSeamlessMouseRight = property "seamless-mouse-right" vmOs = property "os" vmControlPlatformPowerState = property "control-platform-power-state" vmSeamlessTraffic = property "seamless-traffic" vmOemAcpiFeatures = property "oem-acpi-features" vmUsbEnabled = property "usb-enabled" vmUsbAutoPassthrough = property "usb-auto-passthrough" vmUsbControl = property "usb-control" vmUsbGrabDevices = property "usb-grab-devices" vmStubdom = property "stubdom" vmCpuid = property "cpuid" vmXciCpuidSignature = property "xci-cpuid-signature" vmGreedyPcibackBind = property "greedy-pciback-bind" vmRunPostCreate = property "run-post-create" vmRunPreDelete = property "run-pre-delete" vmRunPreBoot = property "run-pre-boot" vmRunInsteadofStart = property "run-insteadof-start" vmRunOnStateChange = property "run-on-state-change" vmRunOnAcpiStateChange = property "run-on-acpi-state-change" vmDomstoreReadAccess = property "domstore-read-access" vmDomstoreWriteAccess = property "domstore-write-access" vmShowSwitcher = property "show-switcher" vmWirelessControl = property "wireless-control" vmNativeExperience = property "native-experience" vmS3Mode = property "s3-mode" vmS4Mode = property "s4-mode" vmRealm = property "realm" vmSyncUuid = property "sync-uuid" vmIcbinnPath = property "icbinn-path" vmOvfTransportIso = property "ovf-transport-iso" vmReady = property "ready" vmRestrictDisplayDepth = property "restrict-display-depth" vmRestrictDisplayRes = property "restrict-display-res" vmPreserveOnReboot = property "preserve-on-reboot" vmBootSentinel = property "boot-sentinel" -- this one is stored directly under /vm node as two entries portica-installed and portica-enabled vmPorticaStatus = ConfigProperty { property_name = "portica-status" , property_location = dbPath} -- Crypto Ones vmCryptoUser = property "crypto-user" vmCryptoKeyDirs = property "crypto-key-dirs" -- Ones in CONFIG subtree vmNotify = property "config.notify" vmHvm = property "config.hvm" vmPae = property "config.pae" vmAcpi = property "config.acpi" vmApic = property "config.apic" vmViridian = property "config.viridian" vmHap = property "config.hap" vmNx = property "config.nx" vmSound = property "config.sound" vmMemory = property "config.memory" vmMemoryStaticMax = property "config.memory-static-max" vmMemoryMin = property "config.memory-min" vmDisplay = property "config.display" vmBoot = property "config.boot" vmCmdLine = property "config.cmdline" vmKernel = property "config.kernel" vmKernelExtract = property "config.kernel-extract" vmInitrd = property "config.initrd" vmInitrdExtract = property "config.initrd-extract" vmAcpiPt = property "config.acpi-pt" vmVcpus = property "config.vcpus" vmSmbiosPt = property "config.smbios-pt" vmVideoram = property "config.videoram" vmPassthroughMmio = property "config.passthrough-mmio" vmPassthroughIo = property "config.passthrough-io" vmStartup = property "config.startup" vmFlaskLabel = property "config.flask-label" vmCoresPerSocket = property "config.cores-per-socket" vmQemuDmPath = property "config.qemu-dm-path" vmQemuDmTimeout = property "config.qemu-dm-timeout" vmVsnd = property "config.vsnd" vmVkbd = property "config.vkbd" vmVfb = property "config.vfb" vmV4v = property "config.v4v" vmHpet = property "config.hpet" vmHpetDefault = True vmTimerMode = property "config.timer-mode" vmTimerModeDefault = (1 :: Int) vmNestedHvm = property "config.nestedhvm" vmSerial = property "config.serial" -- Composite ones and lists vmExtraHvms = property "config.extra-hvm" vmExtraXenvm = property "config.extra-xenvm" vmDisks = property "config.disk" vmNics = property "config.nic" vmPcis = property "config.pci" vmGpu = property "gpu" vmExtraHvm num = property $ "config.extra-hvm." ++ show num vmDisk num = property $ "config.disk." ++ show num vmNic num = property $ "config.nic." ++ show num vmPci num = property $ "config.pci." ++ show num vmFirewallRules= property "v4v-firewall-rules" -- Read and Save a single property -- example usage, to save a list of disks : saveP uuid vmDisks [disk1, disk2, disk3].. -- getConfigPropertyName :: ConfigProperty -> String getConfigPropertyName = property_name -- Check if property exists before reading it readConfigProperty :: (MonadRpc e m, Marshall a) => Uuid -> ConfigProperty -> m (Maybe a) readConfigProperty uuid p = dbMaybeRead (locate p uuid) vmExists :: (MonadRpc e m) => Uuid -> m Bool vmExists uuid = dbExists (dbPath uuid) saveConfigProperty :: (MonadRpc e m, Marshall a) => Uuid -> ConfigProperty -> a -> m () saveConfigProperty uuid p v = whenM (vmExists uuid) $ dbMaybeRead (locate p uuid) >>= maybeSave where -- only save when the value is different, do nothing when it is equal. also save when it does not exist maybeSave Nothing = save maybeSave (Just currentV) | currentV == v = return () | otherwise = save save = do dbWrite (locate p uuid) v notifyVmConfigChanged uuid saveOrRmConfigProperty :: (MonadRpc e m, Marshall a) => Uuid -> ConfigProperty -> Maybe a -> m () saveOrRmConfigProperty uuid p Nothing = dbRm (locate p uuid) saveOrRmConfigProperty uuid p (Just v) = saveConfigProperty uuid p v haveConfigProperty :: (MonadRpc e m) => Uuid -> ConfigProperty -> m Bool haveConfigProperty uuid p = dbExists (locate p uuid) -- Read config property with default value if it doesn't exist readConfigPropertyDef :: (MonadRpc e m, Marshall a) => Uuid -> ConfigProperty -> a -> m a readConfigPropertyDef uuid p def = fromMaybe def <$> readConfigProperty uuid p type Problem = String -- Find problems with config if any diagnose :: VmConfig -> [Problem] diagnose cfg | vmcfgGraphics cfg == HDX, not (vmcfgPvAddons cfg) = [ "VM has HDX enabled, but PV addons are not installed" ] | otherwise = [ ] ------------------------------------------ -- Create a config file for running XENVM ------------------------------------------ -- Xenvm config is a simple list of strings in the format of key=value newtype XenvmConfig = XenvmConfig [ Param ] type Param = String type UserID = String type VhdName = String type DiskSpec = Param type NicSpec = Param type PciSpec = Param amtPtActive :: Uuid -> Rpc Bool amtPtActive uuid = do -- Amt PT is active if a) system amt pt is activated b) vm amt pt is activated (&&) <$> haveSystemAmtPt <*> readConfigPropertyDef uuid vmAmtPt False stringifyXenvmConfig :: XenvmConfig -> String stringifyXenvmConfig (XenvmConfig params) = unlines params -- Gets a xenvm config, given domain ID of networking domain. getXenvmConfig :: VmConfig -> Rpc XenvmConfig getXenvmConfig cfg = fmap (XenvmConfig . concat) . mapM (force <=< future) $ [prelude, diskSpecs cfg, nicSpecs cfg, pciSpecs cfg , map ("extra-hvm="++) <$> extraHvmSpecs uuid , miscSpecs cfg] where uuid = vmcfgUuid cfg -- First section of xenvm config file prelude = do Just uuid <- readConfigProperty uuid vmUuidP :: Rpc (Maybe Uuid) let kernel = maybe [] (\path -> ["kernel="++path]) (vmcfgKernelPath cfg) let name = maybeToList $ ("name="++) <$> (vmcfgName cfg) return $ [ "uuid=" ++ (show uuid) , "power-management=2" , "startup=poweroff" , "extra-local-watch=power-state" , "on_restart=preserve" , "qemu-dm-path=" ++ (vmcfgQemuDmPath cfg) , "qemu-dm-timeout=" ++ show (vmcfgQemuDmTimeout cfg) , "xci-cpuid-signature=" ++ (if vmcfgXciCpuidSignature cfg then "true" else "false") ] ++ oem_acpi ++ name ++ kernel oem_acpi | vmcfgOemAcpiFeatures cfg = [ "oem-features=1" ] | otherwise = [ ] -- Next section: information about disk drives allDisks = vmcfgDisks validDisks = filterM isDiskValid . allDisks isDiskValid :: Disk -> Rpc Bool isDiskValid disk = case diskType disk of VirtualHardDisk -> liftIO . doesFileExist $ diskPath disk _ -> return True diskSpecs :: VmConfig -> Rpc [DiskSpec] diskSpecs cfg = mapM (diskSpec uuid crypto_dirs) =<< disks where disks = filter diskEnabled <$> validDisks cfg crypto_dirs = vmcfgCryptoKeyDirs cfg uuid = vmcfgUuid cfg diskSpec :: Uuid -> [FilePath] -> Disk -> Rpc DiskSpec diskSpec uuid crypto_dirs d = do let crypto = cryptoSpec uuid crypto_dirs d return $ "disk=" ++ printf "%s:%s:%s:%s:%s:%s:%s" (diskPath d) (enumMarshall $ diskType d) (diskDevice d) (enumMarshall $ diskMode d) (enumMarshall $ diskDeviceType d) snapshot crypto where snapshot = maybe "" enumMarshall (diskSnapshotMode d) -- Next section: information about Network Interfaces nicSpecs :: VmConfig -> Rpc [NicSpec] nicSpecs cfg = do amt <- amtPtActive (vmcfgUuid cfg) maybeHostmac <- liftIO eth0Mac -- Get the configuration file entries ... (fmap.map) (\nic -> "vif=" ++ nicSpec cfg amt maybeHostmac nic (net_domid nic)) . -- ... for all the nics which are defined & enabled & pass the policy check filterM policyCheck . filter nicdefEnable $ vmcfgNics cfg where net_domid nic = fromMaybe 0 (nicdefBackendDomid nic) networks nic = filter (\n -> niHandle n == nicdefNetwork nic) (vmcfgNetworks cfg) isWireless nic = case networks nic of [] -> False (n:_) -> niIsWireless n policyCheck nic | isWireless nic = policyQueryWifiNetworking (vmcfgUuid cfg) | otherwise = policyQueryWiredNetworking (vmcfgUuid cfg) nicSpec :: VmConfig -> Bool -> Maybe Mac -> NicDef -> DomainID -> String nicSpec cfg amt eth0Mac nic networkDomID = let entries = [ "id=" ++ show (nicdefId nic) ] ++ network ++ bridge ++ backend ++ wireless ++ vmMac in concat $ intersperse "," entries where netinfo :: Maybe NetworkInfo netinfo = case filter (\net -> niHandle net == nicdefNetwork nic) (vmcfgNetworks cfg) of (ni:_) -> Just ni _ -> Nothing -- path to network daemon 'network' object network = ["network=" ++ (TL.unpack $ strObjectPath $ networkObjectPath $ nicdefNetwork nic)] -- bridge name, only necessary for emulated net interfaces as qemu manages them bridge = maybe [] (\bn -> ["bridge=" ++ bn]) bridgename bridgename= niBridgeName `fmap` netinfo -- force backend domid for NIC if specified backend = ["backend-domid=" ++ show networkDomID] -- HACK: don't put device as wireless for linuxes, as we have no pv driver for that wireless | nicdefWirelessDriver nic , vmcfgOs cfg /= Linux = ["wireless=true"] | otherwise = [ ] -- use mac specified in configuration as first priority vmMac | Just mac <- nicdefMac nic = ["mac=" ++ mac] -- otherwise, -- If AMT is active, we set the VM mac to be equal to original eth0 mac (that is, before -- the bits on it got swizzled during boot) | Just mac <- eth0Mac, amt == True = ["mac=" ++ unswizzleMac mac] -- Otherwise we do not touch the VM mac and let xenvm choose | otherwise = [ ] unswizzleMac :: Mac -> Mac unswizzleMac mac = let bytes = macToBytes mac h = (head bytes) .&. 253 in bytesToMac $ h : tail bytes data Display = VNC | Other -- Next section: information about PCI Passthrough Devices pciSpecs :: VmConfig -> Rpc [PciSpec] pciSpecs cfg = do let devices = vmcfgPciPtDevices cfg uuid = vmcfgUuid cfg display_str <- readConfigProperty uuid vmDisplay let display = case display_str of Just ('v':'n':'c':_) -> VNC _ -> Other xengfx <- liftIO $ ifM (doesFileExist "/config/xengfx") (return "extra-hvm=xengfx=") (return "extra-hvm=std-vga=") return $ -- and get specs from them map (\dev -> "pci=0,bind," ++ stringAddr dev ++ fslot dev ++ msi dev) devices -- plus some vga info depending on vm type ++ vgaopts xengfx (vmcfgGraphics cfg) (vmcfgVgpuMode cfg) display where stringAddr (PciPtDev d _ _ _) = printf "%04x:%02x:%02x.%x" (pciDomain addr) (pciBus addr) (pciSlot addr) (pciFunc addr) where addr = devAddr d -- Xenvm requires guest_slot=blabla to be passed if we want to force the pci device slot in guest -- to specific value fslot (PciPtDev _ PciSlotDontCare _ _) = "" fslot (PciPtDev d PciSlotMatchHost _ _) = printf ",guest_slot=%d" (pciSlot . devAddr $ d) fslot (PciPtDev d (PciSlotUse s) _ _) = printf ",guest_slot=%d" s msi d | pciPtMsiTranslate d = ",msitranslate=1" | otherwise = "" -- Some additional info depending on type of vm vgaopts xengfx = vgaopts' where vgaopts' HDX Nothing _ = [ "extra-hvm=gfx_passthru=" ] vgaopts' HDX (Just vgpu) _ | null (vgpuPciPtDevices vgpu) = [ "extra-hvm=vgpu", xengfx, "extra-hvm=surfman=" ] | otherwise = [ "extra-hvm=gfx_passthru=", "extra-hvm=surfman=" ] vgaopts' VGAEmu _ VNC = [ xengfx ] vgaopts' VGAEmu _ _ = [ xengfx, "extra-hvm=surfman=" ] -- Extra HVM parameters from database extraHvmSpecs :: Uuid -> Rpc [Param] extraHvmSpecs uuid = readConfigPropertyDef uuid vmExtraHvms [] cpuidResponses :: VmConfig -> [String] cpuidResponses cfg = map option (vmcfgCpuidResponses cfg) where option (CpuidResponse r) = printf "cpuid=%s" r -- Additional misc stuff in xenvm config miscSpecs :: VmConfig -> Rpc [Param] miscSpecs cfg = do t <- timeOffset v <- videoram other <- otherXenvmParams -- these bits depend on appropriate policy being set to true cdromA <- policyQueryCdAccess uuid cdromR <- policyQueryCdRecording uuid bsgs <- liftIO $ getHostBSGDevices let cdexcl_opt = case vmcfgCdExclusive cfg of True -> "-exclusive" _ -> "" let cdromParams = map cdromParam bsgs cdromParam (BSGDevice a b c d) = let bsg_str = "/dev/bsg/" ++ (concat . intersperse ":" $ map show [a,b,c,d]) in case (cdromA,cdromR) of -- no cdrom (False, _) -> "" -- full access to cdrom (True, True) -> "extra-hvm=cdrom-pt" ++ cdexcl_opt ++ "=" ++ bsg_str -- readonly access to cdrom (True, False) -> "extra-hvm=cdrom-pt-ro" ++ cdexcl_opt ++ "=" ++ bsg_str let empty = pure [] snd <- ifM (policyQueryAudioAccess uuid) sound empty audioRec <- ifM (policyQueryAudioRecording uuid) empty (pure ["extra-hvm=disable-audio-rec="]) vcpus <- readConfigPropertyDef uuid vmVcpus (1::Int) coresPS <- readConfigPropertyDef uuid vmCoresPerSocket vcpus stubdom_ <- liftIO stubdom usb <- usb_opts hpet_ <- hpet timer_mode_ <- timer_mode nested_ <- nested let coresPSpms = if coresPS > 1 then ["cores-per-socket=" ++ show coresPS] else ["cores-per-socket=" ++ show vcpus] return $ t ++ v ++ cdromParams ++ ["memory="++show (vmcfgMemoryMib cfg) ] ++ ["memory-max="++show (vmcfgMemoryStaticMaxMib cfg) ] ++ smbios_pt ++ snd ++ audioRec ++ coresPSpms ++ biosStrs ++ stubdom_ ++ cpuidResponses cfg ++ usb ++ platform ++ other ++ hpet_ ++ timer_mode_ ++ nested_ where uuid = vmcfgUuid cfg -- omit if not specified timeOffset = maybeToList . fmap ("time-offset="++) <$> readConfigProperty uuid vmTimeOffset -- 16 meg if not specified videoram = do hvm <- readConfigPropertyDef uuid vmHvm False let defaultVideoram = if hvm then 16 else 0 (\ram -> ["videoram="++ram]) . fromMaybe (show defaultVideoram) <$> readConfigProperty uuid vmVideoram hpet = (i <$> readConfigPropertyDef uuid vmHpet vmHpetDefault) >>= \ v -> return ["hpet=" ++ show v] where i True = 1 i _ = 0 timer_mode = readConfigPropertyDef uuid vmTimerMode vmTimerModeDefault >>= \ v -> return ["timer-mode=" ++ show v] nested = readConfigPropertyDef uuid vmNestedHvm False >>= \ v -> if v then return ["nested=true"] else return [] smbios_pt = case (vmcfgSmbiosOemTypesPt cfg) of [] -> [] types -> [ "smbios-oem-types-pt=" ++ intercalate "," (map show types) , "smbios-pt=true" ] -- Activate sound sound = maybeToList . fmap ("sound="++) <$> readConfigProperty uuid vmSound stubdom | not (vmcfgStubdom cfg) = return [] | otherwise = (\u -> ["stubdom="++show u]) <$> uuidGen usb_opts | not (vmcfgUsbEnabled cfg) = return ["usb=false"] | otherwise = return [] platform = x (vmcfgRestrictDisplayDepth cfg) "platform=restrictdisplaydepth=1" ++ x (vmcfgRestrictDisplayRes cfg) "platform=restrictdisplayres=1" where x cond s = if cond then [s] else [] -- Other config keys taken directly from .config subtree which we delegate directly -- to xenvm passToXenvmProperties = [ ("notify" , vmNotify) , ("hvm" , vmHvm) , ("pae" , vmPae) , ("acpi" , vmAcpi) , ("apic" , vmApic) , ("viridian" , vmViridian) , ("nx" , vmNx) , ("display" , vmDisplay) , ("boot" , vmBoot) , ("cmdline" , vmCmdLine) , ("initrd" , vmInitrd) , ("acpi-pt" , vmAcpiPt) , ("vcpus" , vmVcpus) , ("hap" , vmHap) , ("vsnd" , vmVsnd) , ("vkbd" , vmVkbd) , ("vfb" , vmVfb) , ("v4v" , vmV4v) , ("passthrough-io" , vmPassthroughIo) , ("passthrough-mmio", vmPassthroughMmio) , ("startup" , vmStartup) , ("flask-label" , vmFlaskLabel) , ("serial" , vmSerial) ] biosStrs = [ "bios-string=xenvendor-manufacturer=Citrix" , "bios-string=xenvendor-product=XenClient " ++ version , "bios-string=xenvendor-seamless-hint=" ++ if vmcfgSeamlessSupport cfg then "1" else "0" ] where XcVersion version = vmcfgXcVersion cfg otherXenvmParams = concat <$> sequence [ reverse . catMaybes <$> mapM g passToXenvmProperties , extra_xenvm , smbios_sysinfo ] where g (name,prop) = fmap (\v -> name ++ "=" ++ v) <$> readConfigProperty uuid prop -- additional parameters passed through config/extra-xenvm/... key extra_xenvm :: Rpc [Param] extra_xenvm = readConfigPropertyDef uuid vmExtraXenvm [] -- smbios host stuff smbios_sysinfo :: Rpc [Param] smbios_sysinfo = go =<< readConfigPropertyDef uuid vmAcpiPt False where go False = return [] go _ = liftIO $ sequence [ ("bios-string=oem-installation-manufacturer=" ++) <$> getHostSystemManufacturer ] cryptoSpec :: Uuid -> [FilePath] -> Disk -> String cryptoSpec uuid crypto_dirs disk | diskType disk /= VirtualHardDisk = "" | null crypto_dirs = "" | otherwise = printf ":key-dir=%s" (concat . intersperse "," $ crypto_dirs)
jean-edouard/manager
xenmgr/Vm/Config.hs
gpl-2.0
35,446
0
26
10,971
7,869
4,142
3,727
640
12
module HyLoRes.Core.SMP.Worker( Worker, WorkerId, workerIdToInt, WorkerChans(..), runWorker, param, params, channels, channel, workerId, cycleCount, incCycleCount, onClauseSet, onClauseSet_, fromClauseSet, onClausesIndex_, getDirective, unsatDetected, postProcessNew ) where import Prelude hiding ( log, cycle ) import Control.Applicative ( (<$>) ) import Data.List ( sortBy , foldl') import Data.Maybe import Control.Concurrent.Chan import Control.Monad.State import Control.Monad.Reader import Control.Concurrent.MVar import qualified Data.Set as Set import qualified Data.EnumSet as ESet import HyLoRes.Clause.BasicClause ( BasicClause ) import HyLoRes.Clause.FullClause ( FullClause, specialize, ClauseId ) import HyLoRes.Clause ( size ) import HyLoRes.Formula.TypeLevel ( Spec(..) ) import HyLoRes.ClauseSet.InUse (InUseClauseSet, allClauses) import HyLoRes.Formula ( At, Opaque ) import HyLoRes.ClauseSet ( ClauseSet ) import qualified HyLoRes.ClauseSet as CS import HyLoRes.Subsumption.CASSubsumptionTrie ( CASSubsumptionTrie ) import qualified HyLoRes.Subsumption.CASSubsumptionTrie as ST import HyLoRes.Subsumption.ClausesByFormulaIndex ( ClausesByFormulaIndex ) import qualified HyLoRes.Subsumption.ClausesByFormulaIndex as CbFI import Data.IORef import HyLoRes.Core.Worker.Base ( Result(..), CycleCount, Directive(..) ) import HyLoRes.Core.SMP.Base ( WorkerId, workerIdToInt, ChWorkerToMain, ChWorkerToDispatcher, MsgWorkerToDispatcher(..), ChDispatcherToWorker, MsgDispatcherToWorker(..) ) import HyLoRes.Config ( Params (..) ) import HyLoRes.Logger ( MonadLogger, LoggerT, runLoggerT, log, LoggerEvent(..) ) import HyLoRes.Statistics ( StatisticsT, runStatisticsT, MonadStatistics, StatsValues ) import HyLoRes.FrontEnd.PrettyPrint ( logSubsumptions, logBwSubsumptions ) import HyLoRes.Util ( compareUsing ) data WorkerChans = WC {toMain :: ChWorkerToMain, fromDispatcher :: ChDispatcherToWorker, toDispatcher :: ChWorkerToDispatcher} newtype Worker a = WR {unWR :: ReaderT Params ( ReaderT WorkerChans ( ReaderT WorkerId ( LoggerT ( StatisticsT ( StateT WorkerState ( StateT (IORef CASSubsumptionTrie)( ReaderT (MVar ClausesByFormulaIndex) IO))))))) a} deriving (Functor, Monad, MonadIO, MonadStatistics, MonadLogger) data WorkerState = S{ cycle :: CycleCount, clauseSet :: ClauseSet, clausesSize :: Int, -- Used to calculate the number of -- clauses removed from -- from Clauses on each cycle (because -- of ParUnit, this can be arbitrarly -- large) clsIds :: Set.Set ClauseId } -- Used to store clauses Ids received -- from dispatcher to avoid duplicates readFromDispatcher :: Bool -> Worker MsgDispatcherToWorker readFromDispatcher ok_to_block = do chans <- channels emptyChan <- liftIO $ isEmptyChan (fromDispatcher chans) if (ok_to_block || not emptyChan) then liftIO $ readChan (fromDispatcher chans) else return $ D2W_CLAUSES [] sendToDispatcher :: Int -> [BasicClause] -> Worker () sendToDispatcher processed new = do chans <- channels liftIO $ writeChan (toDispatcher chans) (NEW processed new) sendInUseToDispatcher :: InUseClauseSet -> Worker () sendInUseToDispatcher inUse = do chans <- channels liftIO $ writeChan (toDispatcher chans) (INUSE (allClauses inUse)) sendToMain :: Result -> Worker () sendToMain result = do chans <- channels liftIO $ writeChan (toMain chans) result isEq :: FullClause (At Opaque) -> Bool isEq cl = case specialize cl of AtNom c -> size c == 1 _ -> False isRelDiam :: FullClause (At Opaque) -> Bool isRelDiam cl = case specialize cl of AtDiamNom{} -> True _ -> False subsumptionCheck :: FullClause (At Opaque) -> Worker Bool subsumptionCheck fcl = do tr <- trie subsumed <- liftIO $ subsumes fcl tr if subsumed then return False else do checkBW <- param bwSubsIsOn when checkBW $ do mvar <- cbIndex cbf <- liftIO $ takeMVar mvar let (bwSubs,cbf') = CbFI.addToIndexLookupSubs fcl cbf let bws = ESet.toList bwSubs -- removedCls <- mapM (onClauseSet . CS.removeClauseById) bws logBwSubsumptions fcl bws let cbf'' = foldl' (flip CbFI.removeFromIndex) cbf' (catMaybes removedCls) liftIO $ putMVar mvar cbf'' return True subsumes :: FullClause (At Opaque) -> IORef CASSubsumptionTrie-> IO (Bool) subsumes cl tr = -- If the clause is Eq or a Rel Diam add it to trie -- and always return False since those clauses are sent to -- more than one Worker and all of them should process it do if isEq cl || isRelDiam cl then do ST.add cl tr return False else do subsumed <- ST.subsumes tr cl if subsumed then return True else do ST.add cl tr return False runWorker :: Worker a -> WorkerChans -> WorkerId -> Params -> StatsValues -> IORef CASSubsumptionTrie -> MVar ClausesByFormulaIndex -> IO a runWorker w wc wId p s st cbi = (`runReaderT` cbi) . (`evalStateT` st) . (`evalStateT` initialState) . (`runStatisticsT` s) . (`runLoggerT` (logPref, loggerCfg p)) . (`runReaderT` wId) . (`runReaderT` wc) . (`runReaderT` p) . unWR $ w where initialState = S{cycle = 0, clauseSet = CS.empty (clausesOrd p), clausesSize = 0, clsIds = Set.empty} logPref = concat ["[", show wId, "]: "] onClauseSet_ :: (ClauseSet -> ClauseSet) -> Worker () onClauseSet_ f = WR (lift . lift . lift . lift . lift $ m) where m = modify $ \s -> s{clauseSet = f (clauseSet s)} onClauseSet :: (ClauseSet -> (ClauseSet, a)) -> Worker a onClauseSet f = WR (lift . lift . lift . lift . lift $ m) where m = do s <- get let (cs',r) = f (clauseSet s) put s{clauseSet = cs'} return r onClausesIndex_ :: (ClausesByFormulaIndex -> ClausesByFormulaIndex) -> Worker () onClausesIndex_ f = do mvar <- cbIndex cbf <- liftIO $ takeMVar mvar liftIO $ putMVar mvar (f cbf) fromClauseSet :: (ClauseSet -> a) -> Worker a fromClauseSet f = WR (lift . lift . lift . lift . lift $ gets (f . clauseSet)) cycleCount :: Worker CycleCount cycleCount = WR (lift . lift . lift . lift . lift $ gets cycle) trie :: Worker (IORef CASSubsumptionTrie) trie = WR (lift . lift . lift .lift . lift . lift $ get) cbIndex :: Worker (MVar ClausesByFormulaIndex) cbIndex = WR (lift . lift . lift . lift . lift . lift . lift $ ask) incCycleCount :: Worker () incCycleCount = WR (lift . lift . lift . lift . lift $ modify addOne) where addOne s = s{cycle = 1 + cycle s} savedClausesSize :: Worker Int savedClausesSize = WR (lift . lift . lift . lift . lift $ gets clausesSize) resetSavedClausesSize :: Int -> Worker () resetSavedClausesSize n = WR (lift . lift . lift . lift . lift $ m) where m = modify $ \s -> s{clausesSize = n + CS.clausesSize (clauseSet s)} --clausesIds :: Worker (Set.Set ClauseId) --clausesIds = WR (lift . lift . lift . lift . lift $ gets clsIds ) --addClauseId :: ClauseId -> Worker () --addClauseId clId = WR (lift . lift . lift . lift . lift $ m) -- where m = modify $ \s -> s{clsIds = Set.insert clId (clsIds s)} params :: Worker Params params = WR ask param :: (Params -> a) -> Worker a param f = f <$> params getDirective :: Worker Directive getDirective = do ok_to_block <- fromClauseSet CS.nothingInClauses msg_from_disp <- readFromDispatcher ok_to_block case msg_from_disp of GET_INUSE -> do in_use <- fromClauseSet CS.inUse sendInUseToDispatcher in_use return Abort -- D2W_CLAUSES new_clauses -> do -- sort by size so potential subsumers are added first let sorted_new = sortBy (compareUsing size) new_clauses -- we reset the saved clauses size, taking into -- into account the number of new clauses. this -- value is later used during postprocessing to -- infer the number of clauses actually processed resetSavedClausesSize (length new_clauses) (survived, subsumed) <- partitionM subsumptionCheck sorted_new logSubsumptions subsumed clauses_is_empty <- fromClauseSet CS.nothingInClauses if clauses_is_empty && null survived then return $ AllSubsumed else return $ Continue survived unsatDetected :: Worker () unsatDetected = sendToMain UNSAT postProcessNew :: Worker () postProcessNew = do new <- fromClauseSet CS.new log L_Comm $ concat ["New : ", show new] -- -- clauses_size_on_start <- savedClausesSize current_clauses_size <- fromClauseSet CS.clausesSize let processed_clauses = clauses_size_on_start - current_clauses_size -- log L_Comm $ concat ["Processed clauses : ", show $ processed_clauses] sendToDispatcher processed_clauses new -- onClauseSet_ CS.emptyNew channels :: Worker WorkerChans channels = WR (lift ask) channel :: (WorkerChans -> a) -> Worker a channel f = f <$> channels workerId :: Worker WorkerId workerId = WR (lift . lift $ ask) partitionM :: Monad m => (a -> m Bool) -> [a] -> m ([a],[a]) partitionM p xs = sequence (map p' xs) >>= return . partitionEithers where p' a = do r <- p a; return $ if r then Left a else Right a partitionEithers :: [Either a b] -> ([a],[b]) partitionEithers = foldr (either left right) ([],[]) where left a (l, r) = (a:l, r) right a (l, r) = (l, a:r)
nevrenato/HyLoRes_Source
src/HyLoRes/Core/SMP/Worker.hs
gpl-2.0
11,625
1
23
4,231
2,926
1,550
1,376
214
3
module ExprDoLastNotExpr2 where main = do let x = 0
roberth/uu-helium
test/staticerrors/ExprDoLastNotExpr2.hs
gpl-3.0
52
0
9
10
18
10
8
-1
-1
{-# LANGUAGE TemplateHaskell #-} -- |Template Haskell preprocessing module CO4.Frontend.THPreprocess ( preprocessDecs, noSignatureExpression, noSignaturePattern, noSignatureDeclarations) where import Control.Monad (liftM) import Data.List (foldl') import qualified Data.Map as M import Data.Generics (everywhere,everywhereM,mkT,mkM) import Language.Haskell.TH import CO4.Unique (MonadUnique,newString) import CO4.Names (nilName,consName) import CO4.Util (extM') type TypeSynonyms = M.Map Name ([TyVarBndr], Type) preprocessDecs :: MonadUnique u => [Dec] -> u [Dec] preprocessDecs decs = everywhereM ( extM' (return . onDecs) $ extM' onPat $ extM' onMatch $ extM' onClause $ extM' (return . onExpandedType synonyms) $ mkM onExp ) decs where synonyms = M.fromList $ concatMap synonym decs synonym (TySynD name vars t) = let t' = everywhere (mkT onType) t in [(name, (vars,t'))] synonym _ = [] onExp :: MonadUnique u => Exp -> u Exp onExp a = noInfixAppExpression a >>= noNestedPatternsInLambdaParameters >>= return . noParensExpression . noListExpression . noTupleExpression . noSignatureExpression . noCondExpression . noFunAppOperator onPat :: MonadUnique u => Pat -> u Pat onPat a = noWildcardPattern a >>= return . noParensPattern . noInfixPattern . noListPattern . noTuplePattern . noSignaturePattern onMatch :: MonadUnique u => Match -> u Match onMatch = noNestedPatternsInMatch onClause :: MonadUnique u => Clause -> u Clause onClause = noNestedPatternsInClauseParameters onExpandedType :: TypeSynonyms -> Type -> Type onExpandedType synonyms = expandTypeSynonyms synonyms . onType onType :: Type -> Type onType = noTupleType onDecs :: [Dec] -> [Dec] onDecs = noTypeSynonyms -- Preprocessors on `Exp` ------------------------------------------------ -- |Transforms infix applications to prefix applications noInfixAppExpression :: MonadUnique u => Exp -> u Exp noInfixAppExpression exp = case exp of InfixE (Just a) op (Just b) -> return $ AppE (AppE op a) b InfixE (Just a) op Nothing -> do u <- newTHName "noInfixApp" return $ LamE [VarP u] $ AppE (AppE op a) $ VarE u InfixE Nothing op (Just b) -> do u <- newTHName "noInfixApp" return $ LamE [VarP u] $ AppE (AppE op $ VarE u) b InfixE Nothing op Nothing -> do u <- newTHName "noInfixApp" v <- newTHName "noInfixApp" return $ LamE [VarP u,VarP v] $ AppE (AppE op $ VarE u) $ VarE v UInfixE a op b -> noInfixAppExpression $ InfixE (Just a) op (Just b) _ -> return exp -- |Removes parens expressions noParensExpression :: Exp -> Exp noParensExpression e = case e of ParensE e -> e _ -> e noListExpression :: Exp -> Exp noListExpression exp = case exp of ListE xs -> foldr (\x -> AppE $ AppE (ConE consName) x) (ConE nilName) xs _ -> exp noTupleExpression :: Exp -> Exp noTupleExpression exp = case exp of TupE xs -> foldl AppE (ConE $ tupleDataName $ length xs) xs _ -> exp noSignatureExpression :: Exp -> Exp noSignatureExpression exp = case exp of SigE e _ -> e _ -> exp noCondExpression :: Exp -> Exp noCondExpression exp = case exp of CondE c t f -> CaseE c [ Match (ConP 'True []) (NormalB t) [] , Match (ConP 'False []) (NormalB f) [] ] _ -> exp noFunAppOperator :: Exp -> Exp noFunAppOperator exp = case exp of AppE (AppE (VarE op) f) x | op == '($) || op == mkName "$" -> AppE f x _ -> exp -- |Transforms nested patterns in arguments of lambda expressions into case expressions -- over those arguments noNestedPatternsInLambdaParameters :: MonadUnique u => Exp -> u Exp noNestedPatternsInLambdaParameters exp = case exp of LamE ps e -> do (ps',e') <- onlyVariablePatterns ps e return $ LamE ps' e' _ -> return exp -- Preprocessors on `Pat` ------------------------------------------------ -- |Removes parens patterns noParensPattern :: Pat -> Pat noParensPattern p = case p of ParensP p -> p _ -> p -- |Transforms infix patterns to contructor patterns noInfixPattern :: Pat -> Pat noInfixPattern pat = case pat of InfixP p1 n p2 -> ConP n [p1,p2] UInfixP p1 n p2 -> noInfixPattern $ InfixP p1 n p2 _ -> pat -- |Removes wildcard patterns by introducting new pattern variables noWildcardPattern :: MonadUnique u => Pat -> u Pat noWildcardPattern pat = case pat of WildP -> liftM VarP $ newTHName "wildcard" _ -> return pat noListPattern :: Pat -> Pat noListPattern pat = case pat of ListP xs -> foldr (\x y -> ConP consName [x,y]) (ConP nilName []) xs _ -> pat noTuplePattern :: Pat -> Pat noTuplePattern pat = case pat of TupP xs -> ConP (tupleDataName $ length xs) xs _ -> pat noSignaturePattern :: Pat -> Pat noSignaturePattern pat = case pat of SigP p _ -> p _ -> pat -- Preprocessors on `Match` ------------------------------------------------ -- |Transforms nested patterns in matches into case expressions over those arguments noNestedPatternsInMatch :: MonadUnique u => Match -> u Match noNestedPatternsInMatch (Match pat (NormalB body) decs) = do (pat',body') <- noNestedPatterns pat body return $ Match pat' (NormalB body') decs where noNestedPatterns (VarP p) exp = return (VarP p, exp) noNestedPatterns (ConP c ps) exp = do (ps',exp') <- onlyVariablePatterns ps exp return (ConP c ps', exp') -- Preprocessors on `Clause` ------------------------------------------------ -- |Transforms nested patterns in arguments of function clauses into case expressions -- over those arguments noNestedPatternsInClauseParameters :: MonadUnique u => Clause -> u Clause noNestedPatternsInClauseParameters (Clause ps (NormalB e) d) = do (ps',e') <- onlyVariablePatterns ps e return $ Clause ps' (NormalB e') d -- Preprocessors on `Type` ------------------------------------------------ noTupleType :: Type -> Type noTupleType ty = case ty of TupleT i -> ConT (tupleTypeName i) _ -> ty expandTypeSynonyms :: TypeSynonyms -> Type -> Type expandTypeSynonyms synonyms t = case collectAppT t of (ConT con):args -> case M.lookup con synonyms of Nothing -> t Just (vars,t') -> if length args < length vars then t else let expanded = foldl' apply t' $ zip vars args in everywhere (mkT $ expandTypeSynonyms synonyms) expanded _ -> t where collectAppT (AppT a b) = (collectAppT a) ++ [b] collectAppT t = [t] apply t (PlainTV v,t') = everywhere (mkT applyInType) t where applyInType (VarT v') | v == v' = t' applyInType x = x -- Preprocessors on `[Dec]` ------------------------------------------------ noSignatureDeclarations :: [Dec] -> [Dec] noSignatureDeclarations = filter (not . isSig) where isSig (SigD {}) = True isSig _ = False noTypeSynonyms :: [Dec] -> [Dec] noTypeSynonyms = filter (not . isSynonym) where isSynonym (TySynD {}) = True isSynonym _ = False -- Utilities ------------------------------------------------------------------ onlyVariablePatterns :: MonadUnique u => [Pat] -> Exp -> u ([Pat],Exp) onlyVariablePatterns [] exp = return ([],exp) onlyVariablePatterns [VarP p] exp = return ([VarP p],exp) onlyVariablePatterns [p] exp = do n <- newTHName "varPat" return ([VarP n], CaseE (VarE n) [Match p (NormalB exp) []]) onlyVariablePatterns (p:ps) exp = do (ps',e') <- onlyVariablePatterns ps exp (p',e'') <- onlyVariablePatterns [p] e' return (p' ++ ps', e'') newTHName :: MonadUnique u => String -> u Name newTHName name = liftM mkName $ newString name
apunktbau/co4
src/CO4/Frontend/THPreprocess.hs
gpl-3.0
8,105
0
17
2,106
2,604
1,309
1,295
167
6
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE LambdaCase #-} module CO4.Algorithms.HigherOrderInstantiation (hoInstantiation) where import Control.Monad.Reader import Control.Monad.State.Strict hiding (State) import qualified Data.Map as M import Data.List (nub,partition,(\\)) import Data.Maybe (fromMaybe,mapMaybe) import CO4.Language import CO4.Util (programDeclarations,programFromDeclarations,removeSignature) import CO4.Unique (MonadUnique,newName,originalName) import CO4.Algorithms.Instantiator import qualified CO4.Algorithms.HindleyMilner as HM import CO4.Algorithms.Free (free) import CO4.Algorithms.Util (eraseTypedNames,collapseApplications,collapseAbstractions) import CO4.TypesUtil import CO4.Names import CO4.Config (MonadConfig,Config(ImportPrelude),is,instantiationDepth,fromConfigs) import CO4.Prelude (unparsedNames) data Env = Env { -- |Bindings of higher order expressions hoBindings :: M.Map Name Expression -- |Not instantiable declarations , notInstantiable :: [Declaration] -- |Current instantiation depth , depth :: Int } type CacheKey = (Name,[Expression]) type CacheValue = Name type Cache = M.Map CacheKey CacheValue data State = State { cache :: Cache , instances :: [Binding] } newtype Instantiator u a = Instantiator { runInstantiator :: ReaderT Env (StateT State u) a } deriving (Functor, Applicative, Monad, MonadReader Env, MonadState State, MonadUnique, MonadConfig) writeInstance :: MonadUnique u => Binding -> Instantiator u () writeInstance instance_ = modify (\state -> state { instances = (instances state) ++ [instance_] }) writeCacheItem :: MonadUnique u => CacheKey -> CacheValue -> Instantiator u () writeCacheItem key value = modify (\state -> state { cache = M.insert key value $ cache state }) hoBinding :: Monad u => Name -> Instantiator u (Maybe Expression) hoBinding name = asks hoBindings >>= return . M.lookup name instance (MonadUnique u,MonadConfig u) => MonadInstantiator (Instantiator u) where instantiateVar (EVar name) = liftM (fromMaybe $ EVar name) $ hoBinding name instantiateApp (EApp (EVar f) args) = hoBinding f >>= \case Nothing -> return (EApp $ EVar f) `ap` instantiate args Just (ELam params e) -> do args' <- mapM instantiateExpression args let ( foParameters , foArguments , hoParameters , hoArguments ) = splitByOrder $ zip params args' freeInHoArguments <- liftM (nub . concat) $ mapM freeNames hoArguments let instanceParameters = foParameters ++ freeInHoArguments instanceArguments = foArguments ++ map EVar freeInHoArguments gets (M.lookup (f, hoArguments) . cache) >>= \case Nothing -> do instanceName <- newName $ fromName (originalName f) ++ "HOInstance" writeCacheItem (f, hoArguments) instanceName let newBindings = zip hoParameters hoArguments instanceRHS = ELam instanceParameters e instantiateExpInModifiedEnv f newBindings instanceRHS >>= writeInstance . Binding instanceName return $ EApp (EVar instanceName) instanceArguments Just instance_ -> return $ EApp (EVar instance_) instanceArguments Just e -> instantiateApp $ EApp e args instantiateApp (EApp f args) = return EApp `ap` instantiate f `ap` instantiate args splitByOrder :: [(Name,Expression)] -> ([Name],[Expression],[Name],[Expression]) splitByOrder = foldl (\(foParam,foArg,hoParam,hoArg) (parameter,argument) -> if hasFunType parameter then (foParam,foArg,hoParam ++ [parameter],hoArg ++ [argument]) else (foParam ++ [parameter],foArg ++ [argument],hoParam,hoArg) ) ([],[],[],[]) where hasFunType (NTyped _ s) = isFunType $ typeOfScheme s isInstantiable :: Declaration -> Bool isInstantiable declaration = case declaration of DBind (Binding n _) -> isHigherOrder n _ -> False where isHigherOrder (NTyped _ scheme) = let paramTypes = argumentTypes $ typeOfScheme scheme in any isFunType paramTypes -- |Program must not contain local abstractions hoInstantiation :: (MonadConfig u,MonadUnique u) => Program -> u Program hoInstantiation program = do maxDepth <- fromConfigs instantiationDepth typedProgram <- HM.schemes program let (instantiable,rest) = partition isInstantiable $ programDeclarations typedProgram initBindings = map (\(DBind (Binding n e)) -> (n,e)) instantiable initEnv = Env (M.fromList initBindings) rest maxDepth initState = State M.empty [] instantiableNames = map (untypedName . fst) initBindings (p',state) <- runStateT (runReaderT (runInstantiator $ instantiate rest) initEnv) initState return $ eraseTypedNames $ collapseApplications $ collapseAbstractions $ flip (foldl $ flip removeSignature) instantiableNames $ programFromDeclarations $ p' ++ (map DBind $ instances state) freeNames :: (MonadUnique u,MonadConfig u) => Expression -> Instantiator u [Name] freeNames exp = let frees = free exp toplevelName (DBind (Binding name _)) = Just name toplevelName _ = Nothing in do parsedToplevelNames <- liftM (mapMaybe toplevelName) $ asks notInstantiable toplevelNames <- is ImportPrelude >>= \case True -> return $ parsedToplevelNames ++ unparsedNames False -> return $ parsedToplevelNames instanceNames <- liftM (map boundName) $ gets instances return $ frees \\ (toplevelNames ++ instanceNames) instantiateExpInModifiedEnv :: (MonadUnique u, MonadConfig u, Namelike n) => n -> [(Name,Expression)] -> Expression -> Instantiator u Expression instantiateExpInModifiedEnv fName newBindings = let modifyEnv env = if depth env == 0 then error $ "Algorithms.Instantiation: reached maximum depth while instantiating '" ++ fromName fName ++ "'" else env { depth = depth env - 1 , hoBindings = M.union (M.fromList newBindings) (hoBindings env) } in local modifyEnv . instantiateExpression
apunktbau/co4
src/CO4/Algorithms/HigherOrderInstantiation.hs
gpl-3.0
6,669
0
23
1,817
1,886
992
894
120
3
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="fr-FR"> <title>Plug-n-Hack | ZAP Extension</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indice</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Rechercher</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/plugnhack/src/main/javahelp/org/zaproxy/zap/extension/plugnhack/resources/help_fr_FR/helpset_fr_FR.hs
apache-2.0
978
80
68
159
421
213
208
-1
-1
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="tr-TR"> <title>SOAP Tarayฤฑcฤฑsฤฑ | ZAP Uzantฤฑsฤฑ</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>ฤฐรงerikler</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Dizin</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Arama</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favoriler</label> <type>javax.help.FavoritesView</type> </view> </helpset>
veggiespam/zap-extensions
addOns/soap/src/main/javahelp/org/zaproxy/zap/extension/soap/resources/help_tr_TR/helpset_tr_TR.hs
apache-2.0
983
80
66
160
428
216
212
-1
-1
module Propellor.Property.OS ( cleanInstallOnce, Confirmation(..), preserveNetwork, preserveResolvConf, preserveRootSshAuthorized, oldOSRemoved, ) where import Propellor import qualified Propellor.Property.Debootstrap as Debootstrap import qualified Propellor.Property.Ssh as Ssh import qualified Propellor.Property.Network as Network import qualified Propellor.Property.User as User import qualified Propellor.Property.File as File import qualified Propellor.Property.Reboot as Reboot import Propellor.Property.Mount import Propellor.Property.Chroot.Util (stdPATH) import System.Posix.Files (rename, fileExist) import Control.Exception (throw) -- | Replaces whatever OS was installed before with a clean installation -- of the OS that the Host is configured to have. -- -- This is experimental; use with caution! -- -- This can replace one Linux distribution with different one. -- But, it can also fail and leave the system in an unbootable state. -- -- To avoid this property being accidentially used, you have to provide -- a Confirmation containing the name of the host that you intend to apply -- the property to. -- -- This property only runs once. The cleanly installed system will have -- a file </etc/propellor-cleaninstall>, which indicates it was cleanly -- installed. -- -- The files from the old os will be left in </old-os> -- -- After the OS is installed, and if all properties of the host have -- been successfully satisfied, the host will be rebooted to properly load -- the new OS. -- -- You will typically want to run some more properties after the clean -- install succeeds, to bootstrap from the cleanly installed system to -- a fully working system. For example: -- -- > & os (System (Debian Unstable) "amd64") -- > & cleanInstallOnce (Confirmed "foo.example.com") -- > `onChange` propertyList "fixing up after clean install" -- > [ preserveNetwork -- > , preserveResolvConf -- > , preserveRootSshAuthorized -- > , Apt.update -- > -- , Grub.boots "/dev/sda" -- > -- `requires` Grub.installed Grub.PC -- > -- , oldOsRemoved (Confirmed "foo.example.com") -- > ] -- > & Hostname.sane -- > & Apt.installed ["linux-image-amd64"] -- > & Apt.installed ["ssh"] -- > & User.hasSomePassword "root" -- > & User.accountFor "joey" -- > & User.hasSomePassword "joey" -- > -- rest of system properties here cleanInstallOnce :: Confirmation -> Property NoInfo cleanInstallOnce confirmation = check (not <$> doesFileExist flagfile) $ go `requires` confirmed "clean install confirmed" confirmation where go = finalized `requires` -- easy to forget and system may not boot without shadow pw! User.shadowConfig True `requires` -- reboot at end if the rest of the propellor run succeeds Reboot.atEnd True (/= FailedChange) `requires` propellorbootstrapped `requires` flipped `requires` osbootstrapped osbootstrapped = withOS (newOSDir ++ " bootstrapped") $ \o -> case o of (Just d@(System (Debian _) _)) -> debootstrap d (Just u@(System (Ubuntu _) _)) -> debootstrap u _ -> error "os is not declared to be Debian or Ubuntu" debootstrap targetos = ensureProperty $ -- Ignore the os setting, and install debootstrap from -- source, since we don't know what OS we're running in yet. Debootstrap.built' Debootstrap.sourceInstall newOSDir targetos Debootstrap.DefaultConfig -- debootstrap, I wish it was faster.. -- TODO eatmydata to speed it up -- Problem: Installing eatmydata on some random OS like -- Fedora may be difficult. Maybe configure dpkg to not -- sync instead? -- This is the fun bit. flipped = property (newOSDir ++ " moved into place") $ liftIO $ do -- First, unmount most mount points, lazily, so -- they don't interfere with moving things around. devfstype <- fromMaybe "devtmpfs" <$> getFsType "/dev" mnts <- filter (`notElem` ("/": trickydirs)) <$> mountPoints -- reverse so that deeper mount points come first forM_ (reverse mnts) umountLazy renamesout <- map (\d -> (d, oldOSDir ++ d, pure $ d `notElem` (oldOSDir:newOSDir:trickydirs))) <$> dirContents "/" renamesin <- map (\d -> let dest = "/" ++ takeFileName d in (d, dest, not <$> fileExist dest)) <$> dirContents newOSDir createDirectoryIfMissing True oldOSDir massRename (renamesout ++ renamesin) removeDirectoryRecursive newOSDir -- Prepare environment for running additional properties, -- overriding old OS's environment. void $ setEnv "PATH" stdPATH True void $ unsetEnv "LANG" -- Remount /dev, so that block devices etc are -- available for other properties to use. unlessM (mount devfstype devfstype "/dev") $ do warningMessage $ "failed mounting /dev using " ++ devfstype ++ "; falling back to MAKEDEV generic" void $ boolSystem "sh" [Param "-c", Param "cd /dev && /sbin/MAKEDEV generic"] -- Mount /sys too, needed by eg, grub-mkconfig. unlessM (mount "sysfs" "sysfs" "/sys") $ warningMessage "failed mounting /sys" -- And /dev/pts, used by apt. unlessM (mount "devpts" "devpts" "/dev/pts") $ warningMessage "failed mounting /dev/pts" return MadeChange propellorbootstrapped = property "propellor re-debootstrapped in new os" $ return NoChange -- re-bootstrap propellor in /usr/local/propellor, -- (using git repo bundle, privdata file, and possibly -- git repo url, which all need to be arranged to -- be present in /old-os's /usr/local/propellor) -- TODO finalized = property "clean OS installed" $ do liftIO $ writeFile flagfile "" return MadeChange flagfile = "/etc/propellor-cleaninstall" trickydirs = -- /tmp can contain X's sockets, which prevent moving it -- so it's left as-is. [ "/tmp" -- /proc is left mounted , "/proc" ] -- Performs all the renames. If any rename fails, rolls back all -- previous renames. Thus, this either successfully performs all -- the renames, or does not change the system state at all. massRename :: [(FilePath, FilePath, IO Bool)] -> IO () massRename = go [] where go _ [] = return () go undo ((from, to, test):rest) = ifM test ( tryNonAsync (rename from to) >>= either (rollback undo) (const $ go ((to, from):undo) rest) , go undo rest ) rollback undo e = do mapM_ (uncurry rename) undo throw e data Confirmation = Confirmed HostName confirmed :: Desc -> Confirmation -> Property NoInfo confirmed desc (Confirmed c) = property desc $ do hostname <- asks hostName if hostname /= c then do warningMessage "Run with a bad confirmation, not matching hostname." return FailedChange else return NoChange -- | </etc/network/interfaces> is configured to bring up the network -- interface that currently has a default route configured, using -- the same (static) IP address. preserveNetwork :: Property NoInfo preserveNetwork = go `requires` Network.cleanInterfacesFile where go = property "preserve network configuration" $ do ls <- liftIO $ lines <$> readProcess "ip" ["route", "list", "scope", "global"] case words <$> headMaybe ls of Just ("default":"via":_:"dev":iface:_) -> ensureProperty $ Network.static iface _ -> do warningMessage "did not find any default ipv4 route" return FailedChange -- | </etc/resolv.conf> is copied from the old OS preserveResolvConf :: Property NoInfo preserveResolvConf = check (fileExist oldloc) $ property (newloc ++ " copied from old OS") $ do ls <- liftIO $ lines <$> readFile oldloc ensureProperty $ newloc `File.hasContent` ls where newloc = "/etc/resolv.conf" oldloc = oldOSDir ++ newloc -- | </root/.ssh/authorized_keys> has added to it any ssh keys that -- were authorized in the old OS. Any other contents of the file are -- retained. preserveRootSshAuthorized :: Property NoInfo preserveRootSshAuthorized = check (fileExist oldloc) $ property (newloc ++ " copied from old OS") $ do ks <- liftIO $ lines <$> readFile oldloc ensureProperties (map (Ssh.authorizedKey (User "root")) ks) where newloc = "/root/.ssh/authorized_keys" oldloc = oldOSDir ++ newloc -- Removes the old OS's backup from </old-os> oldOSRemoved :: Confirmation -> Property NoInfo oldOSRemoved confirmation = check (doesDirectoryExist oldOSDir) $ go `requires` confirmed "old OS backup removal confirmed" confirmation where go = property "old OS backup removed" $ do liftIO $ removeDirectoryRecursive oldOSDir return MadeChange oldOSDir :: FilePath oldOSDir = "/old-os" newOSDir :: FilePath newOSDir = "/new-os"
shosti/propellor
src/Propellor/Property/OS.hs
bsd-2-clause
8,501
79
20
1,583
1,637
881
756
126
3
-- | -- Module : Data.Packer.Unsafe -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : experimental -- Portability : unknown -- -- Access to lower primitive that allow to use Packing and Unpacking, -- on mmap type of memory. Potentially unsafe, as it can't check if -- any of value passed are valid. -- module Data.Packer.Unsafe ( runPackingAt , runUnpackingAt ) where import Data.Word import Data.Packer.Internal import Foreign.Ptr import Foreign.ForeignPtr import Control.Monad import Control.Exception import Control.Concurrent.MVar (takeMVar, newMVar) -- | Run packing on an arbitrary buffer with a size. -- -- This is available, for example to run on mmap typed memory, and this is highly unsafe, -- as the user need to make sure the pointer and size passed to this function are correct. runPackingAt :: Ptr Word8 -- ^ Pointer to the beginning of the memory -> Int -- ^ Size of the memory -> Packing a -- ^ Packing action -> IO (a, Int) -- ^ Number of bytes filled runPackingAt ptr sz action = do mvar <- newMVar 0 (a, (Memory _ leftSz)) <- (runPacking_ action) (ptr,mvar) (Memory ptr sz) --(PackSt _ holes (Memory _ leftSz)) <- execStateT (runPacking_ action) (PackSt ptr 0 $ Memory ptr sz) holes <- takeMVar mvar when (holes > 0) (throwIO $ HoleInPacking holes) return (a, sz - leftSz) -- | Run unpacking on an arbitrary buffer with a size. -- -- This is available, for example to run on mmap typed memory, and this is highly unsafe, -- as the user need to make sure the pointer and size passed to this function are correct. runUnpackingAt :: ForeignPtr Word8 -- ^ The initial block of memory -> Int -- ^ Starting offset in the block of memory -> Int -- ^ Size -> Unpacking a -- ^ Unpacking action -> IO a runUnpackingAt fptr offset sz action = withForeignPtr fptr $ \ptr -> let m = Memory (ptr `plusPtr` offset) sz in fmap fst ((runUnpacking_ action) (fptr,m) m)
erikd/hs-packer
Data/Packer/Unsafe.hs
bsd-2-clause
2,120
0
13
542
345
193
152
29
1
{-# LANGUAGE Trustworthy #-} {-# LANGUAGE CPP , RankNTypes , MagicHash , UnboxedTuples , ScopedTypeVariables #-} {-# OPTIONS_GHC -Wno-deprecations #-} -- kludge for the Control.Concurrent.QSem, Control.Concurrent.QSemN -- and Control.Concurrent.SampleVar imports. ----------------------------------------------------------------------------- -- | -- Module : Control.Concurrent -- Copyright : (c) The University of Glasgow 2001 -- License : BSD-style (see the file libraries/base/LICENSE) -- -- Maintainer : libraries@haskell.org -- Stability : experimental -- Portability : non-portable (concurrency) -- -- A common interface to a collection of useful concurrency -- abstractions. -- ----------------------------------------------------------------------------- module Control.Concurrent ( -- * Concurrent Haskell -- $conc_intro -- * Basic concurrency operations ThreadId, myThreadId, forkIO, forkFinally, forkIOWithUnmask, killThread, throwTo, -- ** Threads with affinity forkOn, forkOnWithUnmask, getNumCapabilities, setNumCapabilities, threadCapability, -- * Scheduling -- $conc_scheduling yield, -- ** Blocking -- $blocking -- ** Waiting threadDelay, threadWaitRead, threadWaitWrite, threadWaitConnect, threadWaitAccept, threadWaitReadSTM, threadWaitWriteSTM, -- * Communication abstractions module Control.Concurrent.MVar, module Control.Concurrent.Chan, module Control.Concurrent.QSem, module Control.Concurrent.QSemN, -- * Bound Threads -- $boundthreads rtsSupportsBoundThreads, forkOS, forkOSWithUnmask, isCurrentThreadBound, runInBoundThread, runInUnboundThread, -- * Weak references to ThreadIds mkWeakThreadId, -- * GHC's implementation of concurrency -- |This section describes features specific to GHC's -- implementation of Concurrent Haskell. -- ** Haskell threads and Operating System threads -- $osthreads -- ** Terminating the program -- $termination -- ** Pre-emption -- $preemption -- ** Deadlock -- $deadlock ) where import Control.Exception.Base as Exception import GHC.Conc hiding (threadWaitRead, threadWaitWrite, threadWaitReadSTM, threadWaitWriteSTM) import GHC.IO ( unsafeUnmask, catchException ) import GHC.IORef ( newIORef, readIORef, writeIORef ) import GHC.Base import System.Posix.Types ( Fd, Channel ) import Foreign.StablePtr import Foreign.C.Types import qualified GHC.Conc import Control.Concurrent.MVar import Control.Concurrent.Chan import Control.Concurrent.QSem import Control.Concurrent.QSemN {- $conc_intro The concurrency extension for Haskell is described in the paper /Concurrent Haskell/ <http://www.haskell.org/ghc/docs/papers/concurrent-haskell.ps.gz>. Concurrency is \"lightweight\", which means that both thread creation and context switching overheads are extremely low. Scheduling of Haskell threads is done internally in the Haskell runtime system, and doesn't make use of any operating system-supplied thread packages. However, if you want to interact with a foreign library that expects your program to use the operating system-supplied thread package, you can do so by using 'forkOS' instead of 'forkIO'. Haskell threads can communicate via 'MVar's, a kind of synchronised mutable variable (see "Control.Concurrent.MVar"). Several common concurrency abstractions can be built from 'MVar's, and these are provided by the "Control.Concurrent" library. In GHC, threads may also communicate via exceptions. -} {- $conc_scheduling Scheduling may be either pre-emptive or co-operative, depending on the implementation of Concurrent Haskell (see below for information related to specific compilers). In a co-operative system, context switches only occur when you use one of the primitives defined in this module. This means that programs such as: > main = forkIO (write 'a') >> write 'b' > where write c = putChar c >> write c will print either @aaaaaaaaaaaaaa...@ or @bbbbbbbbbbbb...@, instead of some random interleaving of @a@s and @b@s. In practice, cooperative multitasking is sufficient for writing simple graphical user interfaces. -} {- $blocking Different Haskell implementations have different characteristics with regard to which operations block /all/ threads. Using GHC without the @-threaded@ option, all foreign calls will block all other Haskell threads in the system, although I\/O operations will not. With the @-threaded@ option, only foreign calls with the @unsafe@ attribute will block all other threads. -} -- | Fork a thread and call the supplied function when the thread is about -- to terminate, with an exception or a returned value. The function is -- called with asynchronous exceptions masked. -- -- > forkFinally action and_then = -- > mask $ \restore -> -- > forkIO $ try (restore action) >>= and_then -- -- This function is useful for informing the parent when a child -- terminates, for example. -- -- @since 4.6.0.0 forkFinally :: IO a -> (Either SomeException a -> IO ()) -> IO ThreadId forkFinally action and_then = mask $ \restore -> forkIO $ try (restore action) >>= and_then -- --------------------------------------------------------------------------- -- Bound Threads {- $boundthreads #boundthreads# Support for multiple operating system threads and bound threads as described below is currently only available in the GHC runtime system if you use the /-threaded/ option when linking. Other Haskell systems do not currently support multiple operating system threads. A bound thread is a haskell thread that is /bound/ to an operating system thread. While the bound thread is still scheduled by the Haskell run-time system, the operating system thread takes care of all the foreign calls made by the bound thread. To a foreign library, the bound thread will look exactly like an ordinary operating system thread created using OS functions like @pthread_create@ or @CreateThread@. Bound threads can be created using the 'forkOS' function below. All foreign exported functions are run in a bound thread (bound to the OS thread that called the function). Also, the @main@ action of every Haskell program is run in a bound thread. Why do we need this? Because if a foreign library is called from a thread created using 'forkIO', it won't have access to any /thread-local state/ - state variables that have specific values for each OS thread (see POSIX's @pthread_key_create@ or Win32's @TlsAlloc@). Therefore, some libraries (OpenGL, for example) will not work from a thread created using 'forkIO'. They work fine in threads created using 'forkOS' or when called from @main@ or from a @foreign export@. In terms of performance, 'forkOS' (aka bound) threads are much more expensive than 'forkIO' (aka unbound) threads, because a 'forkOS' thread is tied to a particular OS thread, whereas a 'forkIO' thread can be run by any OS thread. Context-switching between a 'forkOS' thread and a 'forkIO' thread is many times more expensive than between two 'forkIO' threads. Note in particular that the main program thread (the thread running @Main.main@) is always a bound thread, so for good concurrency performance you should ensure that the main thread is not doing repeated communication with other threads in the system. Typically this means forking subthreads to do the work using 'forkIO', and waiting for the results in the main thread. -} -- | 'True' if bound threads are supported. -- If @rtsSupportsBoundThreads@ is 'False', 'isCurrentThreadBound' -- will always return 'False' and both 'forkOS' and 'runInBoundThread' will -- fail. rtsSupportsBoundThreads :: Bool rtsSupportsBoundThreads = True {- | Like 'forkIO', this sparks off a new thread to run the 'IO' computation passed as the first argument, and returns the 'ThreadId' of the newly created thread. However, 'forkOS' creates a /bound/ thread, which is necessary if you need to call foreign (non-Haskell) libraries that make use of thread-local state, such as OpenGL (see "Control.Concurrent#boundthreads"). Using 'forkOS' instead of 'forkIO' makes no difference at all to the scheduling behaviour of the Haskell runtime system. It is a common misconception that you need to use 'forkOS' instead of 'forkIO' to avoid blocking all the Haskell threads when making a foreign call; this isn't the case. To allow foreign calls to be made without blocking all the Haskell threads (with GHC), it is only necessary to use the @-threaded@ option when linking your program, and to make sure the foreign import is not marked @unsafe@. -} forkOS :: IO () -> IO ThreadId foreign export java forkOS_entry :: StablePtr (IO ()) -> IO () foreign import java "@static base.control.Concurrent.forkOS_entry" forkOS_entry_reimported :: StablePtr (IO ()) -> IO () forkOS_entry :: StablePtr (IO ()) -> IO () forkOS_entry stableAction = do action <- deRefStablePtr stableAction action foreign import java "@static eta.runtime.concurrent.Concurrent.forkOS_createThread" forkOS_createThread :: StablePtr (IO ()) -> IO CInt failNonThreaded :: IO a failNonThreaded = fail $ "RTS doesn't support multiple OS threads " ++"(use ghc -threaded when linking)" forkOS action0 | rtsSupportsBoundThreads = do mv <- newEmptyMVar b <- Exception.getMaskingState let -- async exceptions are masked in the child if they are masked -- in the parent, as for forkIO (see #1048). forkOS_createThread -- creates a thread with exceptions masked by default. action1 = case b of Unmasked -> unsafeUnmask action0 MaskedInterruptible -> action0 MaskedUninterruptible -> uninterruptibleMask_ action0 action_plus = Exception.catch action1 childHandler entry <- newStablePtr (myThreadId >>= putMVar mv >> action_plus) err <- forkOS_createThread entry when (err /= 0) $ fail "Cannot create OS thread." tid <- takeMVar mv freeStablePtr entry return tid | otherwise = failNonThreaded -- | Like 'forkIOWithUnmask', but the child thread is a bound thread, -- as with 'forkOS'. forkOSWithUnmask :: ((forall a . IO a -> IO a) -> IO ()) -> IO ThreadId forkOSWithUnmask io = forkOS (io unsafeUnmask) -- | Returns 'True' if the calling thread is /bound/, that is, if it is -- safe to use foreign libraries that rely on thread-local state from the -- calling thread. isCurrentThreadBound :: IO Bool isCurrentThreadBound = IO $ \ s# -> case isCurrentThreadBound# s# of (# s2#, flg #) -> (# s2#, isTrue# (flg /=# 0#) #) {- | Run the 'IO' computation passed as the first argument. If the calling thread is not /bound/, a bound thread is created temporarily. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. You can wrap a series of foreign function calls that rely on thread-local state with @runInBoundThread@ so that you can use them without knowing whether the current thread is /bound/. -} runInBoundThread :: IO a -> IO a runInBoundThread action | rtsSupportsBoundThreads = do bound <- isCurrentThreadBound if bound then action else do ref <- newIORef undefined let action_plus = Exception.try action >>= writeIORef ref bracket (newStablePtr action_plus) freeStablePtr (\cEntry -> forkOS_entry_reimported cEntry >> readIORef ref) >>= unsafeResult | otherwise = failNonThreaded {- | Run the 'IO' computation passed as the first argument. If the calling thread is /bound/, an unbound thread is created temporarily using 'forkIO'. @runInBoundThread@ doesn't finish until the 'IO' computation finishes. Use this function /only/ in the rare case that you have actually observed a performance loss due to the use of bound threads. A program that doesn't need its main thread to be bound and makes /heavy/ use of concurrency (e.g. a web server), might want to wrap its @main@ action in @runInUnboundThread@. Note that exceptions which are thrown to the current thread are thrown in turn to the thread that is executing the given computation. This ensures there's always a way of killing the forked thread. -} runInUnboundThread :: IO a -> IO a runInUnboundThread action = do bound <- isCurrentThreadBound if bound then do mv <- newEmptyMVar mask $ \restore -> do tid <- forkIO $ Exception.try (restore action) >>= putMVar mv let wait = takeMVar mv `catchException` \(e :: SomeException) -> Exception.throwTo tid e >> wait wait >>= unsafeResult else action unsafeResult :: Either SomeException a -> IO a unsafeResult = either Exception.throwIO return -- --------------------------------------------------------------------------- -- threadWaitRead/threadWaitWrite -- | Block the current thread until data is available to read on the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitRead', use -- 'GHC.Conc.closeFdWith'. threadWaitRead :: Channel -> IO () threadWaitRead fd = GHC.Conc.threadWaitRead fd -- | Block the current thread until data can be written to the -- given file descriptor (GHC only). -- -- This will throw an 'IOError' if the file descriptor was closed -- while this thread was blocked. To safely close a file descriptor -- that has been used with 'threadWaitWrite', use -- 'GHC.Conc.closeFdWith'. threadWaitWrite :: Channel -> IO () threadWaitWrite fd = GHC.Conc.threadWaitWrite fd -- | Returns an STM action that can be used to wait for data -- to read from a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitReadSTM :: Channel -> IO (STM (), IO ()) threadWaitReadSTM fd = GHC.Conc.threadWaitReadSTM fd -- | Returns an STM action that can be used to wait until data -- can be written to a file descriptor. The second returned value -- is an IO action that can be used to deregister interest -- in the file descriptor. -- -- @since 4.7.0.0 threadWaitWriteSTM :: Channel -> IO (STM (), IO ()) threadWaitWriteSTM fd = GHC.Conc.threadWaitWriteSTM fd -- --------------------------------------------------------------------------- -- More docs {- $osthreads #osthreads# In GHC, threads created by 'forkIO' are lightweight threads, and are managed entirely by the GHC runtime. Typically Haskell threads are an order of magnitude or two more efficient (in terms of both time and space) than operating system threads. The downside of having lightweight threads is that only one can run at a time, so if one thread blocks in a foreign call, for example, the other threads cannot continue. The GHC runtime works around this by making use of full OS threads where necessary. When the program is built with the @-threaded@ option (to link against the multithreaded version of the runtime), a thread making a @safe@ foreign call will not block the other threads in the system; another OS thread will take over running Haskell threads until the original call returns. The runtime maintains a pool of these /worker/ threads so that multiple Haskell threads can be involved in external calls simultaneously. The "System.IO" library manages multiplexing in its own way. On Windows systems it uses @safe@ foreign calls to ensure that threads doing I\/O operations don't block the whole runtime, whereas on Unix systems all the currently blocked I\/O requests are managed by a single thread (the /IO manager thread/) using a mechanism such as @epoll@ or @kqueue@, depending on what is provided by the host operating system. The runtime will run a Haskell thread using any of the available worker OS threads. If you need control over which particular OS thread is used to run a given Haskell thread, perhaps because you need to call a foreign library that uses OS-thread-local state, then you need bound threads (see "Control.Concurrent#boundthreads"). If you don't use the @-threaded@ option, then the runtime does not make use of multiple OS threads. Foreign calls will block all other running Haskell threads until the call returns. The "System.IO" library still does multiplexing, so there can be multiple threads doing I\/O, and this is handled internally by the runtime using @select@. -} {- $termination In a standalone GHC program, only the main thread is required to terminate in order for the process to terminate. Thus all other forked threads will simply terminate at the same time as the main thread (the terminology for this kind of behaviour is \"daemonic threads\"). If you want the program to wait for child threads to finish before exiting, you need to program this yourself. A simple mechanism is to have each child thread write to an 'MVar' when it completes, and have the main thread wait on all the 'MVar's before exiting: > myForkIO :: IO () -> IO (MVar ()) > myForkIO io = do > mvar <- newEmptyMVar > forkFinally io (\_ -> putMVar mvar ()) > return mvar Note that we use 'forkFinally' to make sure that the 'MVar' is written to even if the thread dies or is killed for some reason. A better method is to keep a global list of all child threads which we should wait for at the end of the program: > children :: MVar [MVar ()] > children = unsafePerformIO (newMVar []) > > waitForChildren :: IO () > waitForChildren = do > cs <- takeMVar children > case cs of > [] -> return () > m:ms -> do > putMVar children ms > takeMVar m > waitForChildren > > forkChild :: IO () -> IO ThreadId > forkChild io = do > mvar <- newEmptyMVar > childs <- takeMVar children > putMVar children (mvar:childs) > forkFinally io (\_ -> putMVar mvar ()) > > main = > later waitForChildren $ > ... The main thread principle also applies to calls to Haskell from outside, using @foreign export@. When the @foreign export@ed function is invoked, it starts a new main thread, and it returns when this main thread terminates. If the call causes new threads to be forked, they may remain in the system after the @foreign export@ed function has returned. -} {- $preemption GHC implements pre-emptive multitasking: the execution of threads are interleaved in a random fashion. More specifically, a thread may be pre-empted whenever it allocates some memory, which unfortunately means that tight loops which do no allocation tend to lock out other threads (this only seems to happen with pathological benchmark-style code, however). The rescheduling timer runs on a 20ms granularity by default, but this may be altered using the @-i\<n\>@ RTS option. After a rescheduling \"tick\" the running thread is pre-empted as soon as possible. One final note: the @aaaa@ @bbbb@ example may not work too well on GHC (see Scheduling, above), due to the locking on a 'System.IO.Handle'. Only one thread may hold the lock on a 'System.IO.Handle' at any one time, so if a reschedule happens while a thread is holding the lock, the other thread won't be able to run. The upshot is that the switch from @aaaa@ to @bbbbb@ happens infrequently. It can be improved by lowering the reschedule tick period. We also have a patch that causes a reschedule whenever a thread waiting on a lock is woken up, but haven't found it to be useful for anything other than this example :-) -} {- $deadlock GHC attempts to detect when threads are deadlocked using the garbage collector. A thread that is not reachable (cannot be found by following pointers from live objects) must be deadlocked, and in this case the thread is sent an exception. The exception is either 'BlockedIndefinitelyOnMVar', 'BlockedIndefinitelyOnSTM', 'NonTermination', or 'Deadlock', depending on the way in which the thread is deadlocked. Note that this feature is intended for debugging, and should not be relied on for the correct operation of your program. There is no guarantee that the garbage collector will be accurate enough to detect your deadlock, and no guarantee that the garbage collector will run in a timely enough manner. Basically, the same caveats as for finalizers apply to deadlock detection. There is a subtle interaction between deadlock detection and finalizers (as created by 'Foreign.Concurrent.newForeignPtr' or the functions in "System.Mem.Weak"): if a thread is blocked waiting for a finalizer to run, then the thread will be considered deadlocked and sent an exception. So preferably don't do this, but if you have no alternative then it is possible to prevent the thread from being considered deadlocked by making a 'StablePtr' pointing to it. Don't forget to release the 'StablePtr' later with 'freeStablePtr'. -}
rahulmutt/ghcvm
libraries/base/Control/Concurrent.hs
bsd-3-clause
22,020
91
12
4,957
1,230
724
506
-1
-1
{-# LANGUAGE ForeignFunctionInterface, EmptyDataDecls, ScopedTypeVariables, DeriveDataTypeable, GADTs #-} module CommonFFI where import Prelude hiding (catch) import qualified Data.ByteString as S import qualified Data.ByteString.Unsafe as S import qualified Data.ByteString.Lazy as L import Foreign.Marshal.Utils import Foreign import Foreign.C.String import Data.Data import Control.Exception import Control.Monad import qualified Data.ByteString.UTF8 as U import qualified Data.Aeson.Encode as E import GHC.Conc import JSONGeneric import Common data UrwebContext data Result a = EndUserFailure EndUserFailure | InternalFailure String | Success a deriving (Data, Typeable) -- here's how you parse this: first, you try parsing using -- the expected result type. If that doesn't work, try parsing -- using EndUserFailure. And then finally, parse as string. -- XXX this doesn't work if we have something that legitimately -- needs to return a string, although we can force fix that -- by adding a wrapper... result :: IO a -> IO (Result a) result m = liftM Success m `catches` [ Handler (return . EndUserFailure) , Handler (return . InternalFailure . (show :: SomeException -> String)) ] -- incoming string doesn't have to be Haskell managed -- outgoing string is on Urweb allocated memory, and -- is the unique outgoing one serialize :: Data a => Ptr UrwebContext -> IO a -> IO CString serialize ctx m = lazyByteStringToUrWebCString ctx . E.encode . toJSON =<< result m peekUTF8String :: CString -> IO String peekUTF8String = liftM U.toString . S.packCString lazyByteStringToUrWebCString :: Ptr UrwebContext -> L.ByteString -> IO CString lazyByteStringToUrWebCString ctx bs = do let s = S.concat (L.toChunks bs) -- XXX S.concat is really bad! Bad Edward! S.unsafeUseAsCStringLen s $ \(c,n) -> do x <- uw_malloc ctx (n+1) copyBytes x c n poke (plusPtr x n) (0 :: Word8) return x {- This is the right way to do it, which doesn't - involve copying everything, but it might be overkill -- XXX This would be a useful helper function for bytestring to have. let l = fromIntegral (L.length bs' + 1) -- XXX overflow x <- uw_malloc ctx l let f x c = ... foldlChunks f x -} foreign import ccall "urweb.h uw_malloc" uw_malloc :: Ptr UrwebContext -> Int -> IO (Ptr a) foreign export ccall ensureIOManagerIsRunning :: IO ()
diflying/logitext
CommonFFI.hs
bsd-3-clause
2,463
0
14
513
491
271
220
-1
-1
{- | Module : $Header$ Description : Import data generated by hol2hets into a DG Copyright : (c) Jonathan von Schroeder, DFKI GmbH 2010 License : GPLv2 or higher, see LICENSE.txt Maintainer : jonathan.von_schroeder@dfki.de Stability : experimental Portability : portable -} module Isabelle.Isa2DG where import Static.GTheory import Static.DevGraph import Static.DgUtils import Static.History import Static.ComputeTheory import Static.AnalysisStructured (insLink) import Logic.Prover import Logic.ExtSign import Logic.Grothendieck import Logic.Logic (ide) import Common.LibName import Common.Id import Common.AS_Annotation import Common.IRI (simpleIdToIRI) import Isabelle.Logic_Isabelle import Isabelle.IsaSign import Isabelle.IsaImport (importIsaDataIO, IsaData) import Driver.Options import qualified Data.Map as Map import Data.Graph.Inductive.Graph (Node) import Data.List (intercalate) import Data.Maybe (catMaybes) import Control.Monad (unless, when) import Control.Concurrent (forkIO, killThread) import Common.Utils import System.Exit import System.Directory import System.FilePath _insNodeDG :: Sign -> [Named Sentence] -> String -> DGraph -> (DGraph, Node) _insNodeDG sig sens n dg = let gt = G_theory Isabelle Nothing (makeExtSign Isabelle sig) startSigId (toThSens sens) startThId labelK = newInfoNodeLab (makeName (simpleIdToIRI (mkSimpleId n))) (newNodeInfo DGEmpty) gt k = getNewNodeDG dg insN = [InsertNode (k, labelK)] newDG = changesDGH dg insN labCh = [SetNodeLab labelK (k, labelK { globalTheory = computeLabelTheory Map.empty newDG (k, labelK) })] newDG1 = changesDGH newDG labCh in (newDG1, k) analyzeMessages :: Int -> [String] -> IO () analyzeMessages _ [] = return () analyzeMessages i (x : xs) = do case x of 'v' : i' : ':' : msg -> when (read [i'] < i) $ putStr $ msg ++ "\n" _ -> putStr $ x ++ "\n" analyzeMessages i xs anaThyFile :: HetcatsOpts -> FilePath -> IO (Maybe (LibName, LibEnv)) anaThyFile opts path = do fp <- canonicalizePath path tempFile <- getTempFile "" (takeBaseName fp) fifo <- getTempFifo (takeBaseName fp) exportScript' <- fmap (</> "export.sh") $ getEnvDef "HETS_ISA_TOOLS" "./Isabelle/export" exportScript <- canonicalizePath exportScript' e1 <- doesFileExist exportScript unless e1 $ fail "Export script not available! Maybe you need to specify HETS_ISA_TOOLS" (l, close) <- readFifo fifo tid <- forkIO $ analyzeMessages (verbose opts) (lines . concat $ l) (ex, sout, err) <- executeProcess exportScript [fp, tempFile, fifo] "" close killThread tid removeFile fifo case ex of ExitFailure _ -> do removeFile tempFile soutF <- getTempFile sout (takeBaseName fp ++ ".sout") errF <- getTempFile err (takeBaseName fp ++ ".serr") fail $ "Export Failed! - Export script died prematurely. See " ++ soutF ++ " and " ++ errF ++ " for details." ExitSuccess -> do ret <- anaIsaFile opts tempFile removeFile tempFile return ret mkNode :: (DGraph, Map.Map String (Node, Sign)) -> IsaData -> (DGraph, Map.Map String (Node, Sign)) mkNode (dg, m) (name, header', imps, keywords', uses', body) = let sens = map (\ sen -> let name' = case sen of Locale n' _ _ _ -> "locale " ++ qname n' Class n' _ _ _ -> "class " ++ qname n' Datatypes dts -> "datatype " ++ intercalate "_" (map (qname . datatypeName) dts) Consts cs -> "consts " ++ intercalate "_" (map (\ (n', _, _) -> n') cs) TypeSynonym n' _ _ _ -> "type_synonym " ++ qname n' Axioms axs -> "axioms " ++ intercalate "_" (map (qname . axiomName) axs) Lemma _ _ _ l -> "lemma " ++ (intercalate "_" . map qname . catMaybes $ map propsName l) Definition n' _ _ _ _ _ -> "definition " ++ show n' Fun _ _ _ _ _ fsigs -> "fun " ++ intercalate "_" (map (\ (n', _, _, _) -> n') fsigs) _ -> "" in makeNamed name' sen) body sgns = Map.foldWithKey (\ k a l -> if elem k imps then snd a : l else l) [] m sgn = foldl union_sig (emptySign { imports = imps, header = header', keywords = keywords', uses = uses' }) sgns (dg', n) = _insNodeDG sgn sens name dg m' = Map.insert name (n, sgn) m dgRet = foldr (\ imp dg'' -> case Map.lookup imp m of Just (n', s') -> let gsig = G_sign Isabelle (makeExtSign Isabelle s') startSigId incl = gEmbed2 gsig $ mkG_morphism Isabelle (ide sgn) in insLink dg'' incl globalDef DGLinkImports n' n Nothing -> dg'') dg' imps in (dgRet, m') anaIsaFile :: HetcatsOpts -> FilePath -> IO (Maybe (LibName, LibEnv)) anaIsaFile _ path = do theories <- importIsaDataIO path let name = "Imported Theory" (dg, _) = foldl mkNode (emptyDG, Map.empty) theories le = Map.insert (emptyLibName name) dg Map.empty return $ Just (emptyLibName name, computeLibEnvTheories le)
nevrenato/HetsAlloy
Isabelle/Isa2DG.hs
gpl-2.0
5,569
0
25
1,739
1,720
885
835
127
12
-- Set up the data structures provided by 'Vectorise.Builtins'. module Vectorise.Builtins.Initialise ( -- * Initialisation initBuiltins, initBuiltinVars ) where import GhcPrelude import Vectorise.Builtins.Base import BasicTypes import TysPrim import DsMonad import TysWiredIn import DataCon import TyCon import Class import CoreSyn import Type import NameEnv import Name import Id import FastString import Outputable import Control.Monad import Data.Array -- |Create the initial map of builtin types and functions. -- initBuiltins :: DsM Builtins initBuiltins = do { -- 'PArray: representation type for parallel arrays ; parrayTyCon <- externalTyCon (fsLit "PArray") -- 'PData': type family mapping array element types to array representation types -- Not all backends use `PDatas`. ; pdataTyCon <- externalTyCon (fsLit "PData") ; pdatasTyCon <- externalTyCon (fsLit "PDatas") -- 'PR': class of basic array operators operating on 'PData' types ; prClass <- externalClass (fsLit "PR") ; let prTyCon = classTyCon prClass -- 'PRepr': type family mapping element types to representation types ; preprTyCon <- externalTyCon (fsLit "PRepr") -- 'PA': class of basic operations on arrays (parametrised by the element type) ; paClass <- externalClass (fsLit "PA") ; let paTyCon = classTyCon paClass [paDataCon] = tyConDataCons paTyCon paPRSel = classSCSelId paClass 0 -- Functions on array representations ; replicatePDVar <- externalVar (fsLit "replicatePD") ; replicate_vars <- mapM externalVar (suffixed "replicatePA" aLL_DPH_PRIM_TYCONS) ; emptyPDVar <- externalVar (fsLit "emptyPD") ; empty_vars <- mapM externalVar (suffixed "emptyPA" aLL_DPH_PRIM_TYCONS) ; packByTagPDVar <- externalVar (fsLit "packByTagPD") ; packByTag_vars <- mapM externalVar (suffixed "packByTagPA" aLL_DPH_PRIM_TYCONS) ; let combineNamesD = [("combine" ++ show i ++ "PD") | i <- [2..mAX_DPH_COMBINE]] ; let combineNamesA = [("combine" ++ show i ++ "PA") | i <- [2..mAX_DPH_COMBINE]] ; combines <- mapM externalVar (map mkFastString combineNamesD) ; combines_vars <- mapM (mapM externalVar) $ map (\name -> suffixed name aLL_DPH_PRIM_TYCONS) combineNamesA ; let replicatePD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS replicate_vars) emptyPD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS empty_vars) packByTagPD_PrimVars = mkNameEnv (zip aLL_DPH_PRIM_TYCONS packByTag_vars) combinePDVars = listArray (2, mAX_DPH_COMBINE) combines combinePD_PrimVarss = listArray (2, mAX_DPH_COMBINE) [ mkNameEnv (zip aLL_DPH_PRIM_TYCONS vars) | vars <- combines_vars] -- 'Scalar': class moving between plain unboxed arrays and 'PData' representations ; scalarClass <- externalClass (fsLit "Scalar") -- N-ary maps ('zipWith' family) ; scalar_map <- externalVar (fsLit "scalar_map") ; scalar_zip2 <- externalVar (fsLit "scalar_zipWith") ; scalar_zips <- mapM externalVar (numbered "scalar_zipWith" 3 mAX_DPH_SCALAR_ARGS) ; let scalarZips = listArray (1, mAX_DPH_SCALAR_ARGS) (scalar_map : scalar_zip2 : scalar_zips) -- Types and functions for generic type representations ; voidTyCon <- externalTyCon (fsLit "Void") ; voidVar <- externalVar (fsLit "void") ; fromVoidVar <- externalVar (fsLit "fromVoid") ; sum_tcs <- mapM externalTyCon (numbered "Sum" 2 mAX_DPH_SUM) ; let sumTyCons = listArray (2, mAX_DPH_SUM) sum_tcs ; wrapTyCon <- externalTyCon (fsLit "Wrap") ; pvoidVar <- externalVar (fsLit "pvoid") ; pvoidsVar <- externalVar (fsLit "pvoids#") -- Types and functions for closure conversion ; closureTyCon <- externalTyCon (fsLit ":->") ; closureVar <- externalVar (fsLit "closure") ; liftedClosureVar <- externalVar (fsLit "liftedClosure") ; applyVar <- externalVar (fsLit "$:") ; liftedApplyVar <- externalVar (fsLit "liftedApply") ; closures <- mapM externalVar (numbered "closure" 1 mAX_DPH_SCALAR_ARGS) ; let closureCtrFuns = listArray (1, mAX_DPH_SCALAR_ARGS) closures -- Types and functions for selectors ; sel_tys <- mapM externalType (numbered "Sel" 2 mAX_DPH_SUM) ; sels_tys <- mapM externalType (numbered "Sels" 2 mAX_DPH_SUM) ; sels_length <- mapM externalFun (numbered_hash "lengthSels" 2 mAX_DPH_SUM) ; sel_replicates <- mapM externalFun (numbered_hash "replicateSel" 2 mAX_DPH_SUM) ; sel_tags <- mapM externalFun (numbered "tagsSel" 2 mAX_DPH_SUM) ; sel_elements <- mapM mk_elements [(i,j) | i <- [2..mAX_DPH_SUM], j <- [0..i-1]] ; let selTys = listArray (2, mAX_DPH_SUM) sel_tys selsTys = listArray (2, mAX_DPH_SUM) sels_tys selsLengths = listArray (2, mAX_DPH_SUM) sels_length selReplicates = listArray (2, mAX_DPH_SUM) sel_replicates selTagss = listArray (2, mAX_DPH_SUM) sel_tags selElementss = array ((2, 0), (mAX_DPH_SUM, mAX_DPH_SUM)) sel_elements -- Distinct local variable ; liftingContext <- liftM (\u -> mkSysLocalOrCoVar (fsLit "lc") u intPrimTy) newUnique ; return $ Builtins { parrayTyCon = parrayTyCon , pdataTyCon = pdataTyCon , pdatasTyCon = pdatasTyCon , preprTyCon = preprTyCon , prClass = prClass , prTyCon = prTyCon , paClass = paClass , paTyCon = paTyCon , paDataCon = paDataCon , paPRSel = paPRSel , replicatePDVar = replicatePDVar , replicatePD_PrimVars = replicatePD_PrimVars , emptyPDVar = emptyPDVar , emptyPD_PrimVars = emptyPD_PrimVars , packByTagPDVar = packByTagPDVar , packByTagPD_PrimVars = packByTagPD_PrimVars , combinePDVars = combinePDVars , combinePD_PrimVarss = combinePD_PrimVarss , scalarClass = scalarClass , scalarZips = scalarZips , voidTyCon = voidTyCon , voidVar = voidVar , fromVoidVar = fromVoidVar , sumTyCons = sumTyCons , wrapTyCon = wrapTyCon , pvoidVar = pvoidVar , pvoidsVar = pvoidsVar , closureTyCon = closureTyCon , closureVar = closureVar , liftedClosureVar = liftedClosureVar , applyVar = applyVar , liftedApplyVar = liftedApplyVar , closureCtrFuns = closureCtrFuns , selTys = selTys , selsTys = selsTys , selsLengths = selsLengths , selReplicates = selReplicates , selTagss = selTagss , selElementss = selElementss , liftingContext = liftingContext } } where suffixed :: String -> [Name] -> [FastString] suffixed pfx ns = [mkFastString (pfx ++ "_" ++ (occNameString . nameOccName) n) | n <- ns] -- Make a list of numbered strings in some range, eg foo3, foo4, foo5 numbered :: String -> Int -> Int -> [FastString] numbered pfx m n = [mkFastString (pfx ++ show i) | i <- [m..n]] numbered_hash :: String -> Int -> Int -> [FastString] numbered_hash pfx m n = [mkFastString (pfx ++ show i ++ "#") | i <- [m..n]] mk_elements :: (Int, Int) -> DsM ((Int, Int), CoreExpr) mk_elements (i,j) = do { v <- externalVar $ mkFastString ("elementsSel" ++ show i ++ "_" ++ show j ++ "#") ; return ((i, j), Var v) } -- |Get the mapping of names in the Prelude to names in the DPH library. -- initBuiltinVars :: Builtins -> DsM [(Var, Var)] -- FIXME: must be replaced by VECTORISE pragmas!!! initBuiltinVars (Builtins { }) = do cvars <- mapM externalVar cfs return $ zip (map dataConWorkId cons) cvars where (cons, cfs) = unzip preludeDataCons preludeDataCons :: [(DataCon, FastString)] preludeDataCons = [mk_tup n (mkFastString $ "tup" ++ show n) | n <- [2..5]] where mk_tup n name = (tupleDataCon Boxed n, name) -- Auxiliary look up functions ----------------------------------------------- -- |Lookup a variable given its name and the module that contains it. externalVar :: FastString -> DsM Var externalVar fs = dsLookupDPHRdrEnv (mkVarOccFS fs) >>= dsLookupGlobalId -- |Like `externalVar` but wrap the `Var` in a `CoreExpr`. externalFun :: FastString -> DsM CoreExpr externalFun fs = Var <$> externalVar fs -- |Lookup a 'TyCon' in 'Data.Array.Parallel.Prim', given its name. -- Panic if there isn't one. externalTyCon :: FastString -> DsM TyCon externalTyCon fs = dsLookupDPHRdrEnv (mkTcOccFS fs) >>= dsLookupTyCon -- |Lookup some `Type` in 'Data.Array.Parallel.Prim', given its name. externalType :: FastString -> DsM Type externalType fs = do tycon <- externalTyCon fs return $ mkTyConApp tycon [] -- |Lookup a 'Class' in 'Data.Array.Parallel.Prim', given its name. externalClass :: FastString -> DsM Class externalClass fs = do { tycon <- dsLookupDPHRdrEnv (mkClsOccFS fs) >>= dsLookupTyCon ; case tyConClass_maybe tycon of Nothing -> pprPanic "Vectorise.Builtins.Initialise" $ text "Data.Array.Parallel.Prim." <> ftext fs <+> text "is not a type class" Just cls -> return cls }
shlevy/ghc
compiler/vectorise/Vectorise/Builtins/Initialise.hs
bsd-3-clause
10,351
1
17
3,306
2,269
1,204
1,065
164
2
{-# language OverloadedStrings #-} {-# language PackageImports #-} module Main where -------------------------------------------------------------------------------- -- Imports -------------------------------------------------------------------------------- import "base" System.Environment ( getArgs ) import "base" Data.Semigroup ( (<>) ) import "HUnit" Test.HUnit.Base ( assertEqual ) import "test-framework" Test.Framework ( defaultMainWithOpts, interpretArgsOrExit, Test, testGroup ) import "test-framework-hunit" Test.Framework.Providers.HUnit ( testCase ) import "terminal-progress-bar" System.ProgressBar import qualified "text" Data.Text.Lazy as TL import "time" Data.Time.Clock ( UTCTime(..), NominalDiffTime ) -------------------------------------------------------------------------------- -- Test suite -------------------------------------------------------------------------------- main :: IO () main = do opts <- interpretArgsOrExit =<< getArgs defaultMainWithOpts tests opts tests :: [Test] tests = [ testGroup "Label padding" [ eqTest "no labels" "[]" mempty mempty 0 $ Progress 0 0 () , eqTest "pre" "pre []" (msg "pre") mempty 0 $ Progress 0 0 () , eqTest "post" "[] post" mempty (msg "post") 0 $ Progress 0 0 () , eqTest "pre & post" "pre [] post" (msg "pre") (msg "post") 0 $ Progress 0 0 () ] , testGroup "Bar fill" [ eqTest "empty" "[....]" mempty mempty 6 $ Progress 0 1 () , eqTest "almost half" "[=>..]" mempty mempty 6 $ Progress 49 100 () , eqTest "half" "[==>.]" mempty mempty 6 $ Progress 1 2 () , eqTest "almost full" "[===>]" mempty mempty 6 $ Progress 99 100 () , eqTest "full" "[====]" mempty mempty 6 $ Progress 1 1 () , eqTest "overfull" "[====]" mempty mempty 6 $ Progress 2 1 () ] , testGroup "Labels" [ testGroup "Percentage" [ eqTest " 0%" " 0% [....]" percentage mempty 11 $ Progress 0 1 () , eqTest "100%" "100% [====]" percentage mempty 11 $ Progress 1 1 () , eqTest " 50%" " 50% [==>.]" percentage mempty 11 $ Progress 1 2 () , eqTest "200%" "200% [====]" percentage mempty 11 $ Progress 2 1 () , labelTest "0 work todo" percentage (Progress 10 0 ()) "100%" ] , testGroup "Exact" [ eqTest "0/0" "0/0 [....]" exact mempty 10 $ Progress 0 0 () , eqTest "1/1" "1/1 [====]" exact mempty 10 $ Progress 1 1 () , eqTest "1/2" "1/2 [==>.]" exact mempty 10 $ Progress 1 2 () , eqTest "2/1" "2/1 [====]" exact mempty 10 $ Progress 2 1 () , labelTest "0 work todo" exact (Progress 10 0 ()) "10/0" ] , testGroup "Label Semigroup" [ eqTest "exact <> msg <> percentage" "1/2 - 50% [===>...]" (exact <> msg " - " <> percentage) mempty 20 $ Progress 1 2 () ] , testGroup "rendeRuration" [ renderDurationTest 42 "42" , renderDurationTest (5 * 60 + 42) "05:42" , renderDurationTest (8 * 60 * 60 + 5 * 60 + 42) "08:05:42" , renderDurationTest (123 * 60 * 60 + 59 * 60 + 59) "123:59:59" ] ] ] labelTest :: String -> Label () -> Progress () -> TL.Text -> Test labelTest testName label progress expected = testCase testName $ assertEqual expectationError expected $ runLabel label progress someTiming renderDurationTest :: NominalDiffTime -> TL.Text -> Test renderDurationTest dt expected = testCase ("renderDuration " <> show dt) $ assertEqual expectationError expected $ renderDuration dt eqTest :: String -> TL.Text -> Label () -> Label () -> Int -> Progress () -> Test eqTest name expected mkPreLabel mkPostLabel width progress = testCase name $ assertEqual expectationError expected actual where actual = renderProgressBar style progress someTiming style :: Style () style = defStyle { stylePrefix = mkPreLabel , stylePostfix = mkPostLabel , styleWidth = ConstantWidth width } someTime :: UTCTime someTime = UTCTime (toEnum 0) 0 someTiming :: Timing someTiming = Timing someTime someTime expectationError :: String expectationError = "Expected result doesn't match actual result"
ngzax/urbit
pkg/hs/terminal-progress-bar/test/test.hs
mit
4,236
0
16
1,021
1,207
620
587
73
1
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ru-RU"> <title>ะ˜ะฝั‚ะตั€ั„ะตะนัะฝั‹ะน ัะบะฐะฝะตั€ | ะ ะฐััˆะธั€ะตะฝะธะต ZAP </title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>ะกะพะดะตั€ะถะฐะฝะธะต</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>ะ˜ะฝะดะตะบั</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>ะŸะพะธัะบ</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>ะ˜ะทะฑั€ะฐะฝะฝะพะต</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/frontendscanner/src/main/javahelp/org/zaproxy/zap/extension/frontendscanner/resources/help_ru_RU/helpset_ru_RU.hs
apache-2.0
1,042
78
66
160
519
260
259
-1
-1
{- | The public face of Template Haskell For other documentation, refer to: <http://www.haskell.org/haskellwiki/Template_Haskell> -} module Language.Haskell.TH( -- * The monad and its operations Q, runQ, -- ** Administration: errors, locations and IO reportError, -- :: String -> Q () reportWarning, -- :: String -> Q () report, -- :: Bool -> String -> Q () recover, -- :: Q a -> Q a -> Q a location, -- :: Q Loc Loc(..), runIO, -- :: IO a -> Q a -- ** Querying the compiler -- *** Reify reify, -- :: Name -> Q Info reifyModule, thisModule, Info(..), ModuleInfo(..), InstanceDec, ParentName, Arity, Unlifted, -- *** Name lookup lookupTypeName, -- :: String -> Q (Maybe Name) lookupValueName, -- :: String -> Q (Maybe Name) -- *** Fixity lookup reifyFixity, -- *** Instance lookup reifyInstances, isInstance, -- *** Roles lookup reifyRoles, -- *** Annotation lookup reifyAnnotations, AnnLookup(..), -- * Typed expressions TExp, unType, -- * Names Name, NameSpace, -- Abstract -- ** Constructing names mkName, -- :: String -> Name newName, -- :: String -> Q Name -- ** Deconstructing names nameBase, -- :: Name -> String nameModule, -- :: Name -> Maybe String namePackage, -- :: Name -> Maybe String nameSpace, -- :: Name -> Maybe NameSpace -- ** Built-in names tupleTypeName, tupleDataName, -- Int -> Name unboxedTupleTypeName, unboxedTupleDataName, -- :: Int -> Name -- * The algebraic data types -- | The lowercase versions (/syntax operators/) of these constructors are -- preferred to these constructors, since they compose better with -- quotations (@[| |]@) and splices (@$( ... )@) -- ** Declarations Dec(..), Con(..), Clause(..), Strict(..), Foreign(..), Callconv(..), Safety(..), Pragma(..), Inline(..), RuleMatch(..), Phases(..), RuleBndr(..), AnnTarget(..), FunDep(..), FamFlavour(..), TySynEqn(..), Fixity(..), FixityDirection(..), defaultFixity, maxPrecedence, -- ** Expressions Exp(..), Match(..), Body(..), Guard(..), Stmt(..), Range(..), Lit(..), -- ** Patterns Pat(..), FieldExp, FieldPat, -- ** Types Type(..), TyVarBndr(..), TyLit(..), Kind, Cxt, Pred, Syntax.Role(..), FamilyResultSig(..), Syntax.InjectivityAnn(..), -- * Library functions -- ** Abbreviations InfoQ, ExpQ, DecQ, DecsQ, ConQ, TypeQ, TyLitQ, CxtQ, PredQ, MatchQ, ClauseQ, BodyQ, GuardQ, StmtQ, RangeQ, StrictTypeQ, VarStrictTypeQ, PatQ, FieldPatQ, RuleBndrQ, TySynEqnQ, -- ** Constructors lifted to 'Q' -- *** Literals intPrimL, wordPrimL, floatPrimL, doublePrimL, integerL, rationalL, charL, stringL, stringPrimL, charPrimL, -- *** Patterns litP, varP, tupP, conP, uInfixP, parensP, infixP, tildeP, bangP, asP, wildP, recP, listP, sigP, viewP, fieldPat, -- *** Pattern Guards normalB, guardedB, normalG, normalGE, patG, patGE, match, clause, -- *** Expressions dyn, varE, conE, litE, appE, uInfixE, parensE, staticE, infixE, infixApp, sectionL, sectionR, lamE, lam1E, lamCaseE, tupE, condE, multiIfE, letE, caseE, appsE, listE, sigE, recConE, recUpdE, stringE, fieldExp, -- **** Ranges fromE, fromThenE, fromToE, fromThenToE, -- ***** Ranges with more indirection arithSeqE, fromR, fromThenR, fromToR, fromThenToR, -- **** Statements doE, compE, bindS, letS, noBindS, parS, -- *** Types forallT, varT, conT, appT, arrowT, infixT, uInfixT, parensT, equalityT, listT, tupleT, sigT, litT, promotedT, promotedTupleT, promotedNilT, promotedConsT, -- **** Type literals numTyLit, strTyLit, -- **** Strictness isStrict, notStrict, strictType, varStrictType, -- **** Class Contexts cxt, classP, equalP, normalC, recC, infixC, forallC, -- *** Kinds varK, conK, tupleK, arrowK, listK, appK, starK, constraintK, -- *** Roles nominalR, representationalR, phantomR, inferR, -- *** Top Level Declarations -- **** Data valD, funD, tySynD, dataD, newtypeD, -- **** Class classD, instanceD, sigD, standaloneDerivD, defaultSigD, -- **** Role annotations roleAnnotD, -- **** Type Family / Data Family dataFamilyD, openTypeFamilyD, closedTypeFamilyD, dataInstD, familyNoKindD, familyKindD, closedTypeFamilyNoKindD, closedTypeFamilyKindD, newtypeInstD, tySynInstD, typeFam, dataFam, tySynEqn, injectivityAnn, noSig, kindSig, tyVarSig, -- **** Foreign Function Interface (FFI) cCall, stdCall, cApi, prim, javaScript, unsafe, safe, forImpD, -- **** Pragmas ruleVar, typedRuleVar, pragInlD, pragSpecD, pragSpecInlD, pragSpecInstD, pragRuleD, pragAnnD, pragLineD, -- * Pretty-printer Ppr(..), pprint, pprExp, pprLit, pprPat, pprParendType ) where import Language.Haskell.TH.Syntax as Syntax import Language.Haskell.TH.Lib import Language.Haskell.TH.Ppr
AlexanderPankiv/ghc
libraries/template-haskell/Language/Haskell/TH.hs
bsd-3-clause
5,474
0
5
1,564
1,056
739
317
87
0
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="id-ID"> <title>Kembali</title> <maps> <homeID>top</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Konten</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Indeks</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Telusuri</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorit</label> <type>javax.help.FavoritesView</type> </view> </helpset>
thc202/zap-extensions
addOns/revisit/src/main/javahelp/org/zaproxy/zap/extension/revisit/resources/help_id_ID/helpset_id_ID.hs
apache-2.0
951
77
66
155
404
205
199
-1
-1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NondecreasingIndentation #-} {-# LANGUAGE PatternGuards #-} import Test.Cabal.Workdir import Test.Cabal.Script import Test.Cabal.Server import Test.Cabal.Monad import Distribution.Verbosity (normal, verbose, Verbosity) import Distribution.Simple.Configure (getPersistBuildConfig) import Distribution.Simple.Utils (getDirectoryContentsRecursive) import Options.Applicative import Control.Concurrent.MVar import Control.Concurrent import Control.Concurrent.Async import Control.Exception import Control.Monad import qualified Control.Exception as E import GHC.Conc (numCapabilities) import Data.List import Data.Monoid import Text.Printf import qualified System.Clock as Clock import System.IO import System.FilePath import System.Exit import System.Process (callProcess, showCommandForUser) -- | Record for arguments that can be passed to @cabal-tests@ executable. data MainArgs = MainArgs { mainArgThreads :: Int, mainArgTestPaths :: [String], mainArgHideSuccesses :: Bool, mainArgVerbose :: Bool, mainArgQuiet :: Bool, mainArgDistDir :: Maybe FilePath, mainCommonArgs :: CommonArgs } -- | optparse-applicative parser for 'MainArgs' mainArgParser :: Parser MainArgs mainArgParser = MainArgs <$> option auto ( help "Number of threads to run" <> short 'j' <> showDefault <> value numCapabilities <> metavar "INT") <*> many (argument str (metavar "FILE")) <*> switch ( long "hide-successes" <> help "Do not print test cases as they are being run" ) <*> switch ( long "verbose" <> short 'v' <> help "Be verbose" ) <*> switch ( long "quiet" <> short 'q' <> help "Only output stderr on failure" ) <*> optional (option str ( help "Dist directory we were built with" <> long "builddir" <> metavar "DIR")) <*> commonArgParser main :: IO () main = do -- By default, stderr is not buffered. This isn't really necessary -- for us, and it causes problems on Windows, see: -- https://github.com/appveyor/ci/issues/1364 hSetBuffering stderr LineBuffering -- Parse arguments args <- execParser (info mainArgParser mempty) let verbosity = if mainArgVerbose args then verbose else normal -- To run our test scripts, we need to be able to run Haskell code -- linked against the Cabal library under test. The most efficient -- way to get this information is by querying the *host* build -- system about the information. -- -- Fortunately, because we are using a Custom setup, our Setup -- script is bootstrapped against the Cabal library we're testing -- against, so can use our dependency on Cabal to read out the build -- info *for this package*. -- -- NB: Currently assumes that per-component build is NOT turned on -- for Custom. dist_dir <- case mainArgDistDir args of Just dist_dir -> return dist_dir Nothing -> guessDistDir when (verbosity >= verbose) $ hPutStrLn stderr $ "Using dist dir: " ++ dist_dir lbi <- getPersistBuildConfig dist_dir -- Get ready to go! senv <- mkScriptEnv verbosity lbi let runTest runner path = runner Nothing [] path $ ["--builddir", dist_dir, path] ++ renderCommonArgs (mainCommonArgs args) case mainArgTestPaths args of [path] -> do -- Simple runner (real_path, real_args) <- runTest (runnerCommand senv) path hPutStrLn stderr $ showCommandForUser real_path real_args callProcess real_path real_args hPutStrLn stderr "OK" user_paths -> do -- Read out tests from filesystem hPutStrLn stderr $ "threads: " ++ show (mainArgThreads args) test_scripts <- if null user_paths then findTests else return user_paths -- NB: getDirectoryContentsRecursive is lazy IO, but it -- doesn't handle directories disappearing gracefully. Fix -- this! (single_tests, multi_tests) <- evaluate (partitionTests test_scripts) let all_tests = multi_tests ++ single_tests margin = maximum (map length all_tests) + 2 hPutStrLn stderr $ "tests to run: " ++ show (length all_tests) -- TODO: Get parallelization out of multitests by querying -- them for their modes and then making a separate worker -- for each. But for now, just run them earlier to avoid -- them straggling at the end work_queue <- newMVar all_tests unexpected_fails_var <- newMVar [] unexpected_passes_var <- newMVar [] chan <- newChan let logAll msg = writeChan chan (ServerLogMsg AllServers msg) logEnd = writeChan chan ServerLogEnd -- NB: don't use withAsync as we do NOT want to cancel this -- on an exception async_logger <- async (withFile "cabal-tests.log" WriteMode $ outputThread verbosity chan) -- Make sure we pump out all the logs before quitting (\m -> finally m (logEnd >> wait async_logger)) $ do -- NB: Need to use withAsync so that if the main thread dies -- (due to ctrl-c) we tear down all of the worker threads. let go server = do let split [] = return ([], Nothing) split (y:ys) = return (ys, Just y) logMeta msg = writeChan chan $ ServerLogMsg (ServerMeta (serverProcessId server)) msg mb_work <- modifyMVar work_queue split case mb_work of Nothing -> return () Just path -> do when (verbosity >= verbose) $ logMeta $ "Running " ++ path start <- getTime r <- runTest (runOnServer server) path end <- getTime let time = end - start code = serverResultExitCode r status | code == ExitSuccess = "OK" | code == ExitFailure skipExitCode = "SKIP" | code == ExitFailure expectedBrokenExitCode = "KNOWN FAIL" | code == ExitFailure unexpectedSuccessExitCode = "UNEXPECTED OK" | otherwise = "FAIL" unless (mainArgHideSuccesses args && status /= "FAIL") $ do logMeta $ path ++ replicate (margin - length path) ' ' ++ status ++ if time >= 0.01 then printf " (%.2fs)" time else "" when (status == "FAIL") $ do -- TODO: ADT let description | mainArgQuiet args = serverResultStderr r | otherwise = "$ " ++ serverResultCommand r ++ "\n" ++ "stdout:\n" ++ serverResultStdout r ++ "\n" ++ "stderr:\n" ++ serverResultStderr r ++ "\n" logMeta $ description ++ "*** unexpected failure for " ++ path ++ "\n\n" modifyMVar_ unexpected_fails_var $ \paths -> return (path:paths) when (status == "UNEXPECTED OK") $ modifyMVar_ unexpected_passes_var $ \paths -> return (path:paths) go server mask $ \restore -> do -- Start as many threads as requested by -j to spawn -- GHCi servers and start running tests off of the -- run queue. -- NB: we don't use 'withAsync' because it's more -- convenient to generate n threads this way (and when -- one fails, we can cancel everyone at once.) as <- replicateM (mainArgThreads args) (async (restore (withNewServer chan senv go))) restore (mapM_ wait as) `E.catch` \e -> do -- Be patient, because if you ^C again, you might -- leave some zombie GHCi processes around! logAll "Shutting down GHCi sessions (please be patient)..." -- Start cleanup on all threads concurrently. mapM_ (async . cancel) as -- Wait for the threads to finish cleaning up. NB: -- do NOT wait on the cancellation asynchronous actions; -- these complete when the message is *delivered*, not -- when cleanup is done. rs <- mapM waitCatch as -- Take a look at the returned exit codes, and figure out -- if something errored in an unexpected way. This -- could mean there's a zombie. forM_ rs $ \r -> case r of Left err | Just ThreadKilled <- fromException err -> return () | otherwise -> logAll ("Unexpected failure on GHCi exit: " ++ show e) _ -> return () -- Propagate the exception throwIO (e :: SomeException) unexpected_fails <- takeMVar unexpected_fails_var unexpected_passes <- takeMVar unexpected_passes_var if not (null (unexpected_fails ++ unexpected_passes)) then do unless (null unexpected_passes) . logAll $ "UNEXPECTED OK: " ++ intercalate " " unexpected_passes unless (null unexpected_fails) . logAll $ "UNEXPECTED FAIL: " ++ intercalate " " unexpected_fails exitFailure else logAll "OK" findTests :: IO [FilePath] findTests = getDirectoryContentsRecursive "." partitionTests :: [FilePath] -> ([FilePath], [FilePath]) partitionTests = go [] [] where go ts ms [] = (ts, ms) go ts ms (f:fs) = -- NB: Keep this synchronized with isTestFile case takeExtensions f of ".test.hs" -> go (f:ts) ms fs ".multitest.hs" -> go ts (f:ms) fs _ -> go ts ms fs outputThread :: Verbosity -> Chan ServerLogMsg -> Handle -> IO () outputThread verbosity chan log_handle = go "" where go prev_hdr = do v <- readChan chan case v of ServerLogEnd -> return () ServerLogMsg t msg -> do let ls = lines msg pre s c | verbosity >= verbose -- Didn't use printf as GHC 7.4 -- doesn't understand % 7s. = replicate (7 - length s) ' ' ++ s ++ " " ++ c : " " | otherwise = "" hdr = case t of AllServers -> "" ServerMeta s -> pre s ' ' ServerIn s -> pre s '<' ServerOut s -> pre s '>' ServerErr s -> pre s '!' ws = replicate (length hdr) ' ' mb_hdr l | hdr == prev_hdr = ws ++ l | otherwise = hdr ++ l ls' = case ls of [] -> [] r:rs -> mb_hdr r : map (ws ++) rs logmsg = unlines ls' hPutStr stderr logmsg hPutStr log_handle logmsg go hdr -- Cribbed from tasty type Time = Double getTime :: IO Time getTime = do t <- Clock.getTime Clock.Monotonic let ns = realToFrac $ Clock.toNanoSecs t return $ ns / 10 ^ (9 :: Int)
mydaum/cabal
cabal-testsuite/main/cabal-tests.hs
bsd-3-clause
12,985
0
40
5,513
2,435
1,203
1,232
218
10
{-# LANGUAGE CPP #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE NondecreasingIndentation #-} -- | A GHC run-server, which supports running multiple GHC scripts -- without having to restart from scratch. module Test.Cabal.Server ( Server, serverProcessId, ServerLogMsg(..), ServerLogMsgType(..), ServerResult(..), withNewServer, runOnServer, runMain, ) where import Test.Cabal.Script import Prelude hiding (log) import Control.Concurrent.MVar import Control.Concurrent import Control.Concurrent.Async import System.Process import System.IO import System.Exit import Data.List import Distribution.Simple.Program.Db import Distribution.Simple.Program import Control.Exception import qualified Control.Exception as E import Control.Monad import Data.IORef import Data.Maybe import Distribution.Verbosity import System.Process.Internals #if mingw32_HOST_OS import qualified System.Win32.Process as Win32 #endif -- TODO: Compare this implementation with -- https://github.com/ndmitchell/ghcid/blob/master/src/Language/Haskell/Ghcid.hs -- which does something similar -- ----------------------------------------------------------------- -- -- Public API -- ----------------------------------------------------------------- -- -- | A GHCi server session, which we can ask to run scripts. -- It operates in a *fixed* runner environment as specified -- by 'serverScriptEnv'. data Server = Server { serverStdin :: Handle, serverStdout :: Handle, serverStderr :: Handle, serverProcessHandle :: ProcessHandle, serverProcessId :: ProcessId, serverScriptEnv :: ScriptEnv, -- | Accumulators which we use to keep tracking -- of stdout/stderr we've incrementally read out. In the event -- of an error we'll use this to give diagnostic information. serverStdoutAccum :: MVar [String], serverStderrAccum :: MVar [String], serverLogChan :: Chan ServerLogMsg } -- | Portable representation of process ID; just a string rendered -- number. type ProcessId = String data ServerLogMsg = ServerLogMsg ServerLogMsgType String | ServerLogEnd data ServerLogMsgType = ServerOut ProcessId | ServerErr ProcessId | ServerIn ProcessId | ServerMeta ProcessId | AllServers data ServerResult = ServerResult { -- Result serverResultExitCode :: ExitCode, serverResultCommand :: String, serverResultStdout :: String, serverResultStderr :: String } -- | With 'ScriptEnv', create a new GHCi 'Server' session. -- When @f@ returns, the server is terminated and no longer -- valid. withNewServer :: Chan ServerLogMsg -> ScriptEnv -> (Server -> IO a) -> IO a withNewServer chan senv f = bracketWithInit (startServer chan senv) initServer stopServer f -- | Like 'bracket', but with an initialization function on the resource -- which will be called, unmasked, on the resource to transform it -- in some way. If the initialization function throws an exception, the cleanup -- handler will get invoked with the original resource; if it succeeds, the -- cleanup handler will get invoked with the transformed resource. -- The cleanup handler must be able to handle both cases. -- -- This can help avoid race conditions in certain situations: with -- normal use of 'bracket', the resource acquisition function -- MUST return immediately after the resource is acquired. If it -- performs any interruptible actions afterwards, it could be -- interrupted and the exception handler not called. bracketWithInit :: IO a -> (a -> IO a) -> (a -> IO b) -> (a -> IO c) -> IO c bracketWithInit before initialize after thing = mask $ \restore -> do a0 <- before a <- restore (initialize a0) `onException` after a0 r <- restore (thing a) `onException` after a _ <- after a return r -- | Run an hs script on the GHCi server, returning the 'ServerResult' of -- executing the command. -- -- * The script MUST have an @hs@ or @lhs@ filename; GHCi -- will reject non-Haskell filenames. -- -- * If the script is not well-typed, the returned output -- will be of GHC's compile errors. -- -- * Inside your script, do not rely on 'getProgName' having -- a sensible value. -- -- * Current working directory and environment overrides -- are currently not implemented. -- runOnServer :: Server -> Maybe FilePath -> [(String, Maybe String)] -> FilePath -> [String] -> IO ServerResult runOnServer s mb_cwd env_overrides script_path args = do -- TODO: cwd not implemented when (isJust mb_cwd) $ error "runOnServer change directory not implemented" -- TODO: env_overrides not implemented unless (null env_overrides) $ error "runOnServer set environment not implemented" -- Set arguments returned by System.getArgs write s $ ":set args " ++ show args -- Output start sigil (do it here so we pick up compilation -- failures) write s $ "System.IO.hPutStrLn System.IO.stdout " ++ show start_sigil write s $ "System.IO.hPutStrLn System.IO.stderr " ++ show start_sigil _ <- readUntilSigil s start_sigil IsOut _ <- readUntilSigil s start_sigil IsErr -- Drain the output produced by the script as we are running so that -- we do not deadlock over a full pipe. withAsync (readUntilEnd s IsOut) $ \a_exit_out -> do withAsync (readUntilSigil s end_sigil IsErr) $ \a_err -> do -- NB: No :set prog; don't rely on this value in test scripts, -- we pass it in via the arguments -- NB: load drops all bindings, which is GOOD. Avoid holding onto -- garbage. write s $ ":load " ++ script_path -- Create a ref which will record the exit status of the command -- NB: do this after :load so it doesn't get dropped write s $ "ref <- Data.IORef.newIORef (System.Exit.ExitFailure 1)" -- TODO: What if an async exception gets raised here? At the -- moment, there is no way to recover until we get to the top-level -- bracket; then stopServer which correctly handles this case. -- If you do want to be able to abort this computation but KEEP -- USING THE SERVER SESSION, you will need to have a lot more -- sophisticated logic. write s $ "Test.Cabal.Server.runMain ref Main.main" -- Output end sigil. -- NB: We're line-oriented, so we MUST add an extra newline -- to ensure that we see the end sigil. write s $ "System.IO.hPutStrLn System.IO.stdout " ++ show "" write s $ "System.IO.hPutStrLn System.IO.stderr " ++ show "" write s $ "Data.IORef.readIORef ref >>= \\e -> " ++ " System.IO.hPutStrLn System.IO.stdout (" ++ show end_sigil ++ " ++ \" \" ++ show e)" write s $ "System.IO.hPutStrLn System.IO.stderr " ++ show end_sigil (code, out) <- wait a_exit_out err <- wait a_err -- Give the user some indication about how they could run the -- command by hand. (real_path, real_args) <- runnerCommand (serverScriptEnv s) mb_cwd env_overrides script_path args return ServerResult { serverResultExitCode = code, serverResultCommand = showCommandForUser real_path real_args, serverResultStdout = out, serverResultStderr = err } -- | Helper function which we use in the GHCi session to communicate -- the exit code of the process. runMain :: IORef ExitCode -> IO () -> IO () runMain ref m = do E.catch (m >> writeIORef ref ExitSuccess) serverHandler where serverHandler :: SomeException -> IO () serverHandler e = do -- TODO: Probably a few more cases you could handle; -- e.g., StackOverflow should return 2; also signals. writeIORef ref $ case fromException e of Just exit_code -> exit_code -- Only rethrow for non ExitFailure exceptions _ -> ExitFailure 1 case fromException e :: Maybe ExitCode of Just _ -> return () _ -> throwIO e -- ----------------------------------------------------------------- -- -- Initialize/tear down -- ----------------------------------------------------------------- -- -- | Start a new GHCi session. startServer :: Chan ServerLogMsg -> ScriptEnv -> IO Server startServer chan senv = do (prog, _) <- requireProgram verbosity ghcProgram (runnerProgramDb senv) let ghc_args = runnerGhcArgs senv ++ ["--interactive", "-v0", "-ignore-dot-ghci"] proc_spec = (proc (programPath prog) ghc_args) { create_group = True, -- Closing fds is VERY important to avoid -- deadlock; we won't see the end of a -- stream until everyone gives up. close_fds = True, std_in = CreatePipe, std_out = CreatePipe, std_err = CreatePipe } -- printRawCommandAndArgsAndEnv (runnerVerbosity senv) (programPath prog) ghc_args Nothing when (verbosity >= verbose) $ writeChan chan (ServerLogMsg AllServers (showCommandForUser (programPath prog) ghc_args)) (Just hin, Just hout, Just herr, proch) <- createProcess proc_spec out_acc <- newMVar [] err_acc <- newMVar [] tid <- myThreadId return Server { serverStdin = hin, serverStdout = hout, serverStderr = herr, serverProcessHandle = proch, serverProcessId = show tid, serverLogChan = chan, serverStdoutAccum = out_acc, serverStderrAccum = err_acc, serverScriptEnv = senv } where verbosity = runnerVerbosity senv -- | Unmasked initialization for the server initServer :: Server -> IO Server initServer s0 = do -- NB: withProcessHandle reads an MVar and is interruptible #if mingw32_HOST_OS pid <- withProcessHandle (serverProcessHandle s0) $ \ph -> case ph of OpenHandle x -> fmap show (Win32.getProcessId x) ClosedHandle _ -> return (serverProcessId s0) #else pid <- withProcessHandle (serverProcessHandle s0) $ \ph -> case ph of OpenHandle x -> return (show x) -- TODO: handle OpenExtHandle? _ -> return (serverProcessId s0) #endif let s = s0 { serverProcessId = pid } -- We will read/write a line at a time, including for -- output; our demarcation tokens are an entire line. forM_ [serverStdin, serverStdout, serverStderr] $ \f -> do hSetBuffering (f s) LineBuffering hSetEncoding (f s) utf8 write s ":set prompt \"\"" write s "System.IO.hSetBuffering System.IO.stdout System.IO.LineBuffering" return s -- | Stop a GHCi session. stopServer :: Server -> IO () stopServer s = do -- This is quite a bit of funny business. -- On Linux, terminateProcess will send a SIGINT, which -- GHCi will swallow and actually only use to terminate -- whatever computation is going on at that time. So we -- have to follow up with an actual :quit command to -- finish it up (if you delete it, the processes will -- hang around). On Windows, this will just actually kill -- the process so the rest should be unnecessary. mb_exit <- getProcessExitCode (serverProcessHandle s) let hardKiller = do threadDelay 2000000 -- 2sec log ServerMeta s $ "Terminating..." terminateProcess (serverProcessHandle s) softKiller = do -- Ask to quit. If we're in the middle of a computation, -- this will buffer up (unless the program is intercepting -- stdin, but that should NOT happen.) ignore $ write s ":quit" -- NB: it's important that we used create_group. We -- run this AFTER write s ":quit" because if we C^C -- sufficiently early in GHCi startup process, GHCi -- will actually die, and then hClose will fail because -- the ":quit" command was buffered up but never got -- flushed. interruptProcessGroupOf (serverProcessHandle s) log ServerMeta s $ "Waiting..." -- Close input BEFORE waiting, close output AFTER waiting. -- If you get either order wrong, deadlock! hClose (serverStdin s) -- waitForProcess has race condition -- https://github.com/haskell/process/issues/46 waitForProcess $ serverProcessHandle s let drain f = do r <- hGetContents (f s) _ <- evaluate (length r) hClose (f s) return r withAsync (drain serverStdout) $ \a_out -> do withAsync (drain serverStderr) $ \a_err -> do r <- case mb_exit of Nothing -> do log ServerMeta s $ "Terminating GHCi" race hardKiller softKiller Just exit -> do log ServerMeta s $ "GHCi died unexpectedly" return (Right exit) -- Drain the output buffers rest_out <- wait a_out rest_err <- wait a_err if r /= Right ExitSuccess && r /= Right (ExitFailure (-2)) -- SIGINT; happens frequently for some reason then do withMVar (serverStdoutAccum s) $ \acc -> mapM_ (info ServerOut s) (reverse acc) info ServerOut s rest_out withMVar (serverStderrAccum s) $ \acc -> mapM_ (info ServerErr s) (reverse acc) info ServerErr s rest_err info ServerMeta s $ (case r of Left () -> "GHCi was forcibly terminated" Right exit -> "GHCi exited with " ++ show exit) ++ if verbosity < verbose then " (use -v for more information)" else "" else log ServerOut s rest_out log ServerMeta s $ "Done" return () where verbosity = runnerVerbosity (serverScriptEnv s) -- Using the procedure from -- https://www.schoolofhaskell.com/user/snoyberg/general-haskell/exceptions/catching-all-exceptions ignore :: IO () -> IO () ignore m = withAsync m $ \a -> void (waitCatch a) -- ----------------------------------------------------------------- -- -- Utility functions -- ----------------------------------------------------------------- -- log :: (ProcessId -> ServerLogMsgType) -> Server -> String -> IO () log ctor s msg = when (verbosity >= verbose) $ info ctor s msg where verbosity = runnerVerbosity (serverScriptEnv s) info :: (ProcessId -> ServerLogMsgType) -> Server -> String -> IO () info ctor s msg = writeChan chan (ServerLogMsg (ctor (serverProcessId s)) msg) where chan = serverLogChan s -- | Write a string to the prompt of the GHCi server. write :: Server -> String -> IO () write s msg = do log ServerIn s $ msg hPutStrLn (serverStdin s) msg hFlush (serverStdin s) -- line buffering should get it, but just for good luck accumulate :: MVar [String] -> String -> IO () accumulate acc msg = modifyMVar_ acc (\msgs -> return (msg:msgs)) flush :: MVar [String] -> IO [String] flush acc = modifyMVar acc (\msgs -> return ([], reverse msgs)) data OutOrErr = IsOut | IsErr serverHandle :: Server -> OutOrErr -> Handle serverHandle s IsOut = serverStdout s serverHandle s IsErr = serverStderr s serverAccum :: Server -> OutOrErr -> MVar [String] serverAccum s IsOut = serverStdoutAccum s serverAccum s IsErr = serverStderrAccum s outOrErrMsgType :: OutOrErr -> (ProcessId -> ServerLogMsgType) outOrErrMsgType IsOut = ServerOut outOrErrMsgType IsErr = ServerErr -- | Consume output from the GHCi server until we hit a "start -- sigil" (indicating that the subsequent output is for the -- command we want.) Call this only immediately after you -- send a command to GHCi to emit the start sigil. readUntilSigil :: Server -> String -> OutOrErr -> IO String readUntilSigil s sigil outerr = do l <- hGetLine (serverHandle s outerr) log (outOrErrMsgType outerr) s l if sigil `isPrefixOf` l -- NB: on Windows there might be extra goo at end then intercalate "\n" `fmap` flush (serverAccum s outerr) else do accumulate (serverAccum s outerr) l readUntilSigil s sigil outerr -- | Consume output from the GHCi server until we hit the -- end sigil. Return the consumed output as well as the -- exit code (which is at the end of the sigil). readUntilEnd :: Server -> OutOrErr -> IO (ExitCode, String) readUntilEnd s outerr = go [] where go rs = do l <- hGetLine (serverHandle s outerr) log (outOrErrMsgType outerr) s l if end_sigil `isPrefixOf` l -- NB: NOT unlines, we don't want the trailing newline! then do exit <- evaluate (parseExit l) _ <- flush (serverAccum s outerr) -- TODO: don't toss this out return (exit, intercalate "\n" (reverse rs)) else do accumulate (serverAccum s outerr) l go (l:rs) parseExit l = read (drop (length end_sigil) l) -- | The start and end sigils. This should be chosen to be -- reasonably unique, so that test scripts don't accidentally -- generate them. If these get spuriously generated, we will -- probably deadlock. start_sigil, end_sigil :: String start_sigil = "BEGIN Test.Cabal.Server" end_sigil = "END Test.Cabal.Server"
mydaum/cabal
cabal-testsuite/Test/Cabal/Server.hs
bsd-3-clause
17,705
0
25
4,781
3,193
1,651
1,542
245
5
{- Type name: qualified names for register types Part of Mackerel: a strawman device definition DSL for Barrelfish Copyright (c) 2011, ETH Zurich. All rights reserved. This file is distributed under the terms in the attached LICENSE file. If you do not find this file, copies can be found by writing to: ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. -} module TypeName where import MackerelParser {-------------------------------------------------------------------- --------------------------------------------------------------------} -- Fully-qualified name of a type data Name = Name String String deriving (Show, Eq) fromParts :: String -> String -> Name fromParts dev typename = Name dev typename fromRef :: AST -> String -> Name fromRef (TypeRef tname (Just dname)) _ = Name dname tname fromRef (TypeRef tname Nothing) dname = Name dname tname toString :: Name -> String toString (Name d t) = d ++ "." ++ t devName :: Name -> String devName (Name d _) = d typeName :: Name -> String typeName (Name _ t) = t is_builtin_type :: Name -> Bool is_builtin_type (Name _ "uint8") = True is_builtin_type (Name _ "uint16") = True is_builtin_type (Name _ "uint32") = True is_builtin_type (Name _ "uint64") = True is_builtin_type _ = False null :: Name null = Name "" ""
daleooo/barrelfish
tools/mackerel/TypeName.hs
mit
1,384
0
9
293
304
158
146
23
1
{- In order to test Hackage, we need to be able to send check for confirmation emails. In this module we provide a simple interface to do that. Currently we use mailinator, but the API is designed to be agnostic to the specific mail service used. -} module MailUtils ( Email(..) , testEmailAddress , checkEmail , getEmail , emailWithSubject , waitForEmailWithSubject ) where import Control.Concurrent (threadDelay) import Data.Maybe import Network.URI import Network.HTTP hiding (user) import qualified Text.XML.Light as XML import HttpUtils import Util testEmailAddress :: String -> String testEmailAddress user = user ++ "@mailinator.com" data Email = Email { emailTitle :: String , emailLink :: URI , emailSender :: String , emailDate :: String } deriving Show checkEmail :: String -> IO [Email] checkEmail user = do raw <- execRequest NoAuth (getRequest rssUrl) let rss = XML.onlyElems (XML.parseXML raw) items = concatMap (XML.filterElementsName $ simpleName "item") rss return (map parseEmail items) where rssUrl = "http://www.mailinator.com/feed?to=" ++ user parseEmail :: XML.Element -> Email parseEmail e = let [title] = XML.filterElementsName (simpleName "title") e [link] = XML.filterElementsName (simpleName "link") e [sender] = XML.filterElementsName (simpleName "creator") e [date] = XML.filterElementsName (simpleName "date") e in Email { emailTitle = XML.strContent title , emailLink = fromJust . parseURI . XML.strContent $ link , emailSender = XML.strContent sender , emailDate = XML.strContent date } simpleName :: String -> XML.QName -> Bool simpleName n = (== n) . XML.qName emailWithSubject :: String -> String -> IO (Maybe Email) emailWithSubject user subject = do emails <- checkEmail user return . listToMaybe . filter ((== subject) . emailTitle) $ emails waitForEmailWithSubject :: String -> String -> IO Email waitForEmailWithSubject user subject = f 10 where f :: Int -> IO Email f n = do info $ "Waiting for confirmation email at " ++ testEmailAddress user mEmail <- emailWithSubject user subject case mEmail of Just email -> return email Nothing | n == 0 -> die "Didn't get confirmation email" | otherwise -> do info "No confirmation email yet; will try again in 30 sec" threadDelay (30 * 1000000) f (n - 1) getEmail :: Email -> IO String getEmail email = execRequest NoAuth (getRequest url) where msgid = fromJust . lookup "msgid" . parseQuery . uriQuery . emailLink $ email url = "http://mailinator.com/rendermail.jsp?msgid=" ++ msgid ++ "&text=true"
ocharles/hackage-server
tests/MailUtils.hs
bsd-3-clause
2,821
0
17
717
744
383
361
62
2
module GenUtils ( trace, assocMaybe, assocMaybeErr, arrElem, arrCond, memoise, Maybe(..), MaybeErr(..), mapMaybe, mapMaybeFail, maybeToBool, maybeToObj, maybeMap, joinMaybe, mkClosure, foldb, mapAccumL, sortWith, sort, cjustify, ljustify, rjustify, space, copy, combinePairs, formatText ) where import Data.Array -- 1.3 import Data.Ix -- 1.3 import Debug.Trace ( trace ) -- ------------------------------------------------------------------------- -- Here are two defs that everyone seems to define ... -- HBC has it in one of its builtin modules infix 1 =: -- 1.3 type Assoc a b = (a,b) -- 1.3 (=:) a b = (a,b) mapMaybe :: (a -> Maybe b) -> [a] -> [b] mapMaybe f [] = [] mapMaybe f (a:r) = case f a of Nothing -> mapMaybe f r Just b -> b : mapMaybe f r -- This version returns nothing, if *any* one fails. mapMaybeFail f (x:xs) = case f x of Just x' -> case mapMaybeFail f xs of Just xs' -> Just (x':xs') Nothing -> Nothing Nothing -> Nothing mapMaybeFail f [] = Just [] maybeToBool :: Maybe a -> Bool maybeToBool (Just _) = True maybeToBool _ = False maybeToObj :: Maybe a -> a maybeToObj (Just a) = a maybeToObj _ = error "Trying to extract object from a Nothing" maybeMap :: (a -> b) -> Maybe a -> Maybe b maybeMap f (Just a) = Just (f a) maybeMap f Nothing = Nothing joinMaybe :: (a -> a -> a) -> Maybe a -> Maybe a -> Maybe a joinMaybe _ Nothing Nothing = Nothing joinMaybe _ (Just g) Nothing = Just g joinMaybe _ Nothing (Just g) = Just g joinMaybe f (Just g) (Just h) = Just (f g h) data MaybeErr a err = Succeeded a | Failed err deriving (Eq,Show{-was:Text-}) -- @mkClosure@ makes a closure, when given a comparison and iteration loop. -- Be careful, because if the functional always makes the object different, -- This will never terminate. mkClosure :: (a -> a -> Bool) -> (a -> a) -> a -> a mkClosure eq f = match . iterate f where match (a:b:c) | a `eq` b = a match (_:c) = match c -- fold-binary. -- It combines the element of the list argument in balanced mannerism. foldb :: (a -> a -> a) -> [a] -> a foldb f [] = error "can't reduce an empty list using foldb" foldb f [x] = x foldb f l = foldb f (foldb' l) where foldb' (x:y:x':y':xs) = f (f x y) (f x' y') : foldb' xs foldb' (x:y:xs) = f x y : foldb' xs foldb' xs = xs -- Merge two ordered lists into one ordered list. mergeWith :: (a -> a -> Bool) -> [a] -> [a] -> [a] mergeWith _ [] ys = ys mergeWith _ xs [] = xs mergeWith le (x:xs) (y:ys) | x `le` y = x : mergeWith le xs (y:ys) | otherwise = y : mergeWith le (x:xs) ys insertWith :: (a -> a -> Bool) -> a -> [a] -> [a] insertWith _ x [] = [x] insertWith le x (y:ys) | x `le` y = x:y:ys | otherwise = y:insertWith le x ys -- Sorting is something almost every program needs, and this is the -- quickest sorting function I know of. sortWith :: (a -> a -> Bool) -> [a] -> [a] sortWith le [] = [] sortWith le lst = foldb (mergeWith le) (splitList lst) where splitList (a1:a2:a3:a4:a5:xs) = insertWith le a1 (insertWith le a2 (insertWith le a3 (insertWith le a4 [a5]))) : splitList xs splitList [] = [] splitList (r:rs) = [foldr (insertWith le) [r] rs] sort :: (Ord a) => [a] -> [a] sort = sortWith (<=) -- Gofer-like stuff: cjustify, ljustify, rjustify :: Int -> String -> String cjustify n s = space halfm ++ s ++ space (m - halfm) where m = n - length s halfm = m `div` 2 ljustify n s = s ++ space (max 0 (n - length s)) rjustify n s = space (max 0 (n - length s)) ++ s space :: Int -> String space n = copy n ' ' copy :: Int -> a -> [a] -- make list of n copies of x copy n x = take n xs where xs = x:xs combinePairs :: (Ord a) => [(a,b)] -> [(a,[b])] combinePairs xs = combine [ (a,[b]) | (a,b) <- sortWith (\ (a,_) (b,_) -> a <= b) xs] where combine [] = [] combine ((a,b):(c,d):r) | a == c = combine ((a,b++d) : r) combine (a:r) = a : combine r assocMaybe :: (Eq a) => [(a,b)] -> a -> Maybe b assocMaybe env k = case [ val | (key,val) <- env, k == key] of [] -> Nothing (val:vs) -> Just val assocMaybeErr :: (Eq a) => [(a,b)] -> a -> MaybeErr b String assocMaybeErr env k = case [ val | (key,val) <- env, k == key] of [] -> Failed "assoc: " (val:vs) -> Succeeded val deSucc (Succeeded e) = e mapAccumL :: (a -> b -> (c,a)) -> a -> [b] -> ([c],a) mapAccumL f s [] = ([],s) mapAccumL f s (b:bs) = (c:cs,s'') where (c,s') = f s b (cs,s'') = mapAccumL f s' bs -- Now some utilities involving arrays. -- Here is a version of @elem@ that uses partial application -- to optimise lookup. arrElem :: (Ix a) => [a] -> a -> Bool arrElem obj = \x -> inRange size x && arr ! x where size = (maximum obj,minimum obj) arr = listArray size [ i `elem` obj | i <- range size ] -- Here is the functional version of a multi-way conditional, -- again using arrays, of course. Remember @b@ can be a function ! -- Note again the use of partiual application. arrCond :: (Ix a) => (a,a) -- the bounds -> [(Assoc [a] b)] -- the simple lookups -> [(Assoc (a -> Bool) b)] -- the functional lookups -> b -- the default -> a -> b -- the (functional) result arrCond bds pairs fnPairs def = (!) arr' where arr' = array bds [ t =: head ([ r | (p, r) <- pairs, elem t p ] ++ [ r | (f, r) <- fnPairs, f t ] ++ [ def ]) | t <- range bds ] memoise :: (Ix a) => (a,a) -> (a -> b) -> a -> b memoise bds f = (!) arr where arr = array bds [ t =: f t | t <- range bds ] -- Quite neat this. Formats text to fit in a column. formatText :: Int -> [String] -> [String] formatText n = map unwords . cutAt n [] where cutAt :: Int -> [String] -> [String] -> [[String]] cutAt m wds [] = [reverse wds] cutAt m wds (wd:rest) = if len <= m || null wds then cutAt (m-(len+1)) (wd:wds) rest else reverse wds : cutAt n [] (wd:rest) where len = length wd
ezyang/ghc
testsuite/tests/programs/andy_cherry/GenUtils.hs
bsd-3-clause
6,771
0
17
2,313
2,740
1,465
1,275
149
3
{-# LANGUAGE RecordWildCards #-} module T9436 where data T = T { x :: Int } f :: T -> Int f (T' { .. }) = x + 1
ezyang/ghc
testsuite/tests/rename/should_fail/T9436.hs
bsd-3-clause
115
0
8
33
50
29
21
5
1
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE Strict #-} -- | The most primitive ("core") aspects of the AST. Split out of -- "Futhark.IR.Syntax" in order for -- "Futhark.IR.Rep" to use these definitions. This -- module is re-exported from "Futhark.IR.Syntax" and -- there should be no reason to include it explicitly. module Futhark.IR.Syntax.Core ( module Language.Futhark.Core, module Futhark.IR.Primitive, -- * Types Commutativity (..), Uniqueness (..), NoUniqueness (..), ShapeBase (..), Shape, Ext (..), ExtSize, ExtShape, Rank (..), ArrayShape (..), Space (..), SpaceId, TypeBase (..), Type, ExtType, DeclType, DeclExtType, Diet (..), ErrorMsg (..), ErrorMsgPart (..), errorMsgArgTypes, -- * Attributes Attr (..), Attrs (..), oneAttr, inAttrs, withoutAttrs, -- * Values PrimValue (..), -- * Abstract syntax tree Ident (..), Certs (..), SubExp (..), Param (..), DimIndex (..), Slice (..), dimFix, sliceIndices, sliceDims, unitSlice, fixSlice, sliceSlice, PatElemT (..), -- * Flat (LMAD) slices FlatSlice (..), FlatDimIndex (..), flatSliceDims, flatSliceStrides, ) where import Control.Category import Control.Monad.State import Data.Bifoldable import Data.Bifunctor import Data.Bitraversable import qualified Data.Map.Strict as M import Data.Maybe import qualified Data.Set as S import Data.String import Data.Traversable (fmapDefault, foldMapDefault) import Futhark.IR.Primitive import Language.Futhark.Core import Prelude hiding (id, (.)) -- | Whether some operator is commutative or not. The 'Monoid' -- instance returns the least commutative of its arguments. data Commutativity = Noncommutative | Commutative deriving (Eq, Ord, Show) instance Semigroup Commutativity where (<>) = min instance Monoid Commutativity where mempty = Commutative -- | The size of an array type as a list of its dimension sizes, with -- the type of sizes being parametric. newtype ShapeBase d = Shape {shapeDims :: [d]} deriving (Eq, Ord, Show) instance Functor ShapeBase where fmap = fmapDefault instance Foldable ShapeBase where foldMap = foldMapDefault instance Traversable ShapeBase where traverse f = fmap Shape . traverse f . shapeDims instance Semigroup (ShapeBase d) where Shape l1 <> Shape l2 = Shape $ l1 `mappend` l2 instance Monoid (ShapeBase d) where mempty = Shape mempty -- | The size of an array as a list of subexpressions. If a variable, -- that variable must be in scope where this array is used. type Shape = ShapeBase SubExp -- | Something that may be existential. data Ext a = Ext Int | Free a deriving (Eq, Ord, Show) instance Functor Ext where fmap = fmapDefault instance Foldable Ext where foldMap = foldMapDefault instance Traversable Ext where traverse _ (Ext i) = pure $ Ext i traverse f (Free v) = Free <$> f v -- | The size of this dimension. type ExtSize = Ext SubExp -- | Like t'Shape' but some of its elements may be bound in a local -- environment instead. These are denoted with integral indices. type ExtShape = ShapeBase ExtSize -- | The size of an array type as merely the number of dimensions, -- with no further information. newtype Rank = Rank Int deriving (Show, Eq, Ord) -- | A class encompassing types containing array shape information. class (Monoid a, Eq a, Ord a) => ArrayShape a where -- | Return the rank of an array with the given size. shapeRank :: a -> Int -- | @stripDims n shape@ strips the outer @n@ dimensions from -- @shape@. stripDims :: Int -> a -> a -- | Check whether one shape if a subset of another shape. subShapeOf :: a -> a -> Bool instance ArrayShape (ShapeBase SubExp) where shapeRank (Shape l) = length l stripDims n (Shape dims) = Shape $ drop n dims subShapeOf = (==) instance ArrayShape (ShapeBase ExtSize) where shapeRank (Shape l) = length l stripDims n (Shape dims) = Shape $ drop n dims subShapeOf (Shape ds1) (Shape ds2) = -- Must agree on Free dimensions, and ds1 may not be existential -- where ds2 is Free. Existentials must also be congruent. length ds1 == length ds2 && evalState (and <$> zipWithM subDimOf ds1 ds2) M.empty where subDimOf (Free se1) (Free se2) = return $ se1 == se2 subDimOf (Ext _) (Free _) = return False subDimOf (Free _) (Ext _) = return True subDimOf (Ext x) (Ext y) = do extmap <- get case M.lookup y extmap of Just ywas | ywas == x -> return True | otherwise -> return False Nothing -> do put $ M.insert y x extmap return True instance Semigroup Rank where Rank x <> Rank y = Rank $ x + y instance Monoid Rank where mempty = Rank 0 instance ArrayShape Rank where shapeRank (Rank x) = x stripDims n (Rank x) = Rank $ x - n subShapeOf = (==) -- | The memory space of a block. If 'DefaultSpace', this is the "default" -- space, whatever that is. The exact meaning of the 'SpaceId' -- depends on the backend used. In GPU kernels, for example, this is -- used to distinguish between constant, global and shared memory -- spaces. In GPU-enabled host code, it is used to distinguish -- between host memory ('DefaultSpace') and GPU space. data Space = DefaultSpace | Space SpaceId | -- | A special kind of memory that is a statically sized -- array of some primitive type. Used for private memory -- on GPUs. ScalarSpace [SubExp] PrimType deriving (Show, Eq, Ord) -- | A string representing a specific non-default memory space. type SpaceId = String -- | A fancier name for @()@ - encodes no uniqueness information. data NoUniqueness = NoUniqueness deriving (Eq, Ord, Show) instance Semigroup NoUniqueness where NoUniqueness <> NoUniqueness = NoUniqueness instance Monoid NoUniqueness where mempty = NoUniqueness -- | The type of a value. When comparing types for equality with -- '==', shapes must match. data TypeBase shape u = Prim PrimType | -- | Token, index space, element type, and uniqueness. Acc VName Shape [Type] u | Array PrimType shape u | Mem Space deriving (Show, Eq, Ord) instance Bitraversable TypeBase where bitraverse f g (Array t shape u) = Array t <$> f shape <*> g u bitraverse _ _ (Prim pt) = pure $ Prim pt bitraverse _ g (Acc arrs ispace ts u) = Acc arrs ispace ts <$> g u bitraverse _ _ (Mem s) = pure $ Mem s instance Bifunctor TypeBase where bimap = bimapDefault instance Bifoldable TypeBase where bifoldMap = bifoldMapDefault -- | A type with shape information, used for describing the type of -- variables. type Type = TypeBase Shape NoUniqueness -- | A type with existentially quantified shapes - used as part of -- function (and function-like) return types. Generally only makes -- sense when used in a list. type ExtType = TypeBase ExtShape NoUniqueness -- | A type with shape and uniqueness information, used declaring -- return- and parameters types. type DeclType = TypeBase Shape Uniqueness -- | An 'ExtType' with uniqueness information, used for function -- return types. type DeclExtType = TypeBase ExtShape Uniqueness -- | Information about which parts of a value/type are consumed. For -- example, we might say that a function taking three arguments of -- types @([int], *[int], [int])@ has diet @[Observe, Consume, -- Observe]@. data Diet = -- | Consumes this value. Consume | -- | Only observes value in this position, does -- not consume. A result may alias this. Observe | -- | As 'Observe', but the result will not -- alias, because the parameter does not carry -- aliases. ObservePrim deriving (Eq, Ord, Show) -- | An identifier consists of its name and the type of the value -- bound to the identifier. data Ident = Ident { identName :: VName, identType :: Type } deriving (Show) instance Eq Ident where x == y = identName x == identName y instance Ord Ident where x `compare` y = identName x `compare` identName y -- | A list of names used for certificates in some expressions. newtype Certs = Certs {unCerts :: [VName]} deriving (Eq, Ord, Show) instance Semigroup Certs where Certs x <> Certs y = Certs (x <> y) instance Monoid Certs where mempty = Certs mempty -- | A subexpression is either a scalar constant or a variable. One -- important property is that evaluation of a subexpression is -- guaranteed to complete in constant time. data SubExp = Constant PrimValue | Var VName deriving (Show, Eq, Ord) -- | A function or lambda parameter. data Param dec = Param { -- | Attributes of the parameter. When constructing a parameter, -- feel free to just pass 'mempty'. paramAttrs :: Attrs, -- | Name of the parameter. paramName :: VName, -- | Function parameter decoration. paramDec :: dec } deriving (Ord, Show, Eq) instance Foldable Param where foldMap = foldMapDefault instance Functor Param where fmap = fmapDefault instance Traversable Param where traverse f (Param attr name dec) = Param attr name <$> f dec -- | How to index a single dimension of an array. data DimIndex d = -- | Fix index in this dimension. DimFix d | -- | @DimSlice start_offset num_elems stride@. DimSlice d d d deriving (Eq, Ord, Show) instance Functor DimIndex where fmap f (DimFix i) = DimFix $ f i fmap f (DimSlice i j s) = DimSlice (f i) (f j) (f s) instance Foldable DimIndex where foldMap f (DimFix d) = f d foldMap f (DimSlice i j s) = f i <> f j <> f s instance Traversable DimIndex where traverse f (DimFix d) = DimFix <$> f d traverse f (DimSlice i j s) = DimSlice <$> f i <*> f j <*> f s -- | A list of 'DimIndex's, indicating how an array should be sliced. -- Whenever a function accepts a 'Slice', that slice should be total, -- i.e, cover all dimensions of the array. Deviators should be -- indicated by taking a list of 'DimIndex'es instead. newtype Slice d = Slice {unSlice :: [DimIndex d]} deriving (Eq, Ord, Show) instance Traversable Slice where traverse f = fmap Slice . traverse (traverse f) . unSlice instance Functor Slice where fmap = fmapDefault instance Foldable Slice where foldMap = foldMapDefault -- | If the argument is a 'DimFix', return its component. dimFix :: DimIndex d -> Maybe d dimFix (DimFix d) = Just d dimFix _ = Nothing -- | If the slice is all 'DimFix's, return the components. sliceIndices :: Slice d -> Maybe [d] sliceIndices = mapM dimFix . unSlice -- | The dimensions of the array produced by this slice. sliceDims :: Slice d -> [d] sliceDims = mapMaybe dimSlice . unSlice where dimSlice (DimSlice _ d _) = Just d dimSlice DimFix {} = Nothing -- | A slice with a stride of one. unitSlice :: Num d => d -> d -> DimIndex d unitSlice offset n = DimSlice offset n 1 -- | Fix the 'DimSlice's of a slice. The number of indexes must equal -- the length of 'sliceDims' for the slice. fixSlice :: Num d => Slice d -> [d] -> [d] fixSlice = fixSlice' . unSlice where fixSlice' (DimFix j : mis') is' = j : fixSlice' mis' is' fixSlice' (DimSlice orig_k _ orig_s : mis') (i : is') = (orig_k + i * orig_s) : fixSlice' mis' is' fixSlice' _ _ = [] -- | Further slice the 'DimSlice's of a slice. The number of slices -- must equal the length of 'sliceDims' for the slice. sliceSlice :: Num d => Slice d -> Slice d -> Slice d sliceSlice (Slice jslice) (Slice islice) = Slice $ sliceSlice' jslice islice where sliceSlice' (DimFix j : js') is' = DimFix j : sliceSlice' js' is' sliceSlice' (DimSlice j _ s : js') (DimFix i : is') = DimFix (j + (i * s)) : sliceSlice' js' is' sliceSlice' (DimSlice j _ s0 : js') (DimSlice i n s1 : is') = DimSlice (j + (s0 * i)) n (s0 * s1) : sliceSlice' js' is' sliceSlice' _ _ = [] data FlatDimIndex d = FlatDimIndex d -- ^ Number of elements in dimension d -- ^ Stride of dimension deriving (Eq, Ord, Show) instance Traversable FlatDimIndex where traverse f (FlatDimIndex n s) = FlatDimIndex <$> f n <*> f s instance Functor FlatDimIndex where fmap = fmapDefault instance Foldable FlatDimIndex where foldMap = foldMapDefault data FlatSlice d = FlatSlice d [FlatDimIndex d] deriving (Eq, Ord, Show) instance Traversable FlatSlice where traverse f (FlatSlice offset is) = FlatSlice <$> f offset <*> traverse (traverse f) is instance Functor FlatSlice where fmap = fmapDefault instance Foldable FlatSlice where foldMap = foldMapDefault flatSliceDims :: FlatSlice d -> [d] flatSliceDims (FlatSlice _ ds) = map dimSlice ds where dimSlice (FlatDimIndex n _) = n flatSliceStrides :: FlatSlice d -> [d] flatSliceStrides (FlatSlice _ ds) = map dimStride ds where dimStride (FlatDimIndex _ s) = s -- | An element of a pattern - consisting of a name and an addditional -- parametric decoration. This decoration is what is expected to -- contain the type of the resulting variable. data PatElemT dec = PatElem { -- | The name being bound. patElemName :: VName, -- | Pat element decoration. patElemDec :: dec } deriving (Ord, Show, Eq) instance Functor PatElemT where fmap = fmapDefault instance Foldable PatElemT where foldMap = foldMapDefault instance Traversable PatElemT where traverse f (PatElem name dec) = PatElem name <$> f dec -- | An error message is a list of error parts, which are concatenated -- to form the final message. newtype ErrorMsg a = ErrorMsg [ErrorMsgPart a] deriving (Eq, Ord, Show) instance IsString (ErrorMsg a) where fromString = ErrorMsg . pure . fromString -- | A part of an error message. data ErrorMsgPart a = -- | A literal string. ErrorString String | -- | A run-time value. ErrorVal PrimType a deriving (Eq, Ord, Show) instance IsString (ErrorMsgPart a) where fromString = ErrorString instance Functor ErrorMsg where fmap f (ErrorMsg parts) = ErrorMsg $ map (fmap f) parts instance Foldable ErrorMsg where foldMap f (ErrorMsg parts) = foldMap (foldMap f) parts instance Traversable ErrorMsg where traverse f (ErrorMsg parts) = ErrorMsg <$> traverse (traverse f) parts instance Functor ErrorMsgPart where fmap = fmapDefault instance Foldable ErrorMsgPart where foldMap = foldMapDefault instance Traversable ErrorMsgPart where traverse _ (ErrorString s) = pure $ ErrorString s traverse f (ErrorVal t a) = ErrorVal t <$> f a -- | How many non-constant parts does the error message have, and what -- is their type? errorMsgArgTypes :: ErrorMsg a -> [PrimType] errorMsgArgTypes (ErrorMsg parts) = mapMaybe onPart parts where onPart ErrorString {} = Nothing onPart (ErrorVal t _) = Just t -- | A single attribute. data Attr = AttrName Name | AttrInt Integer | AttrComp Name [Attr] deriving (Ord, Show, Eq) instance IsString Attr where fromString = AttrName . fromString -- | Every statement is associated with a set of attributes, which can -- have various effects throughout the compiler. newtype Attrs = Attrs {unAttrs :: S.Set Attr} deriving (Ord, Show, Eq, Monoid, Semigroup) -- | Construct 'Attrs' from a single 'Attr'. oneAttr :: Attr -> Attrs oneAttr = Attrs . S.singleton -- | Is the given attribute to be found in the attribute set? inAttrs :: Attr -> Attrs -> Bool inAttrs attr (Attrs attrs) = attr `S.member` attrs -- | @x `withoutAttrs` y@ gives @x@ except for any attributes also in @y@. withoutAttrs :: Attrs -> Attrs -> Attrs withoutAttrs (Attrs x) (Attrs y) = Attrs $ x `S.difference` y
HIPERFIT/futhark
src/Futhark/IR/Syntax/Core.hs
isc
15,736
0
17
3,480
3,915
2,120
1,795
327
4
module WykopStream ( indexStream , module WykopTypes ) where import WykopTypes import WykopUtils indexStream :: Keys -> Maybe Int -> IO (Maybe [Entry]) indexStream k page = get k [] (mPageToGet page) "stream/index"
mikusp/hwykop
WykopStream.hs
mit
231
0
10
49
74
40
34
7
1
{-# htermination minFM :: FiniteMap Int b -> Maybe Int #-} import FiniteMap
ComputationWithBoundedResources/ara-inference
doc/tpdb_trs/Haskell/full_haskell/FiniteMap_minFM_5.hs
mit
76
0
3
13
5
3
2
1
0
module Problem6 where main :: IO () main = print $ squareSums [1..100] - sumSquares [1..100] squareSums :: Integral n => [n] -> n squareSums xs = (sum xs) ^ 2 sumSquares :: Integral n => [n] -> n sumSquares xs = sum $ map (^2) xs
DevJac/haskell-project-euler
src/Problem6.hs
mit
236
0
8
53
120
63
57
7
1
module Robot ( Bearing(East,North,South,West) , bearing , coordinates , mkRobot , move ) where data Bearing = North | East | South | West deriving (Eq, Show) data Robot = Dummy bearing :: Robot -> Bearing bearing robot = error "You need to implement this function." coordinates :: Robot -> (Integer, Integer) coordinates robot = error "You need to implement this function." mkRobot :: Bearing -> (Integer, Integer) -> Robot mkRobot direction coordinates = error "You need to implement this function." move :: Robot -> String -> Robot move robot instructions = error "You need to implement this function."
exercism/xhaskell
exercises/practice/robot-simulator/src/Robot.hs
mit
687
0
7
181
169
97
72
22
1
-- ะญะบัะฟะพั€ั‚ะธั€ะพะฒะฐะฝะธะต -- http://www.haskell.org/onlinereport/haskell2010/haskellch5.html#x11-1000005.2 module Chapter5.Section52 where -- exports โ†’ ( export1 , โ€ฆ , exportn [ , ] ) (n โ‰ฅ 0) -- -- export โ†’ qvar -- | qtycon [(..) | ( cname1 , โ€ฆ , cnamen )] (n โ‰ฅ 0) -- | qtycls [(..) | ( var1 , โ€ฆ , varn )] (n โ‰ฅ 0) -- | module modid -- -- cname โ†’ var | con -- ะŸะพ ัƒะผะพะปั‡ะฐะฝะธัŽ ัะบัะฟะพั€ั‚ะธั€ัƒัŽั‚ัั ะฒัั ะพะฑะปะฐัั‚ัŒ ะฒะธะดะธะผะพัั‚ะธ ะผะพะดัƒะปั data TheTest = A | B
mrLSD/HaskellTutorials
src/Chapter5/Section52.hs
mit
539
0
5
109
27
21
6
2
0
{-# LANGUAGE RebindableSyntax, OverloadedStrings, CPP, TypeOperators #-} module Cochon.View where import Prelude hiding ((>>), return) import qualified Data.Foldable as Foldable import Data.Monoid import Data.String import Data.Text (Text) import qualified Data.Text as T import Data.Void import Lens.Family2 import React hiding (key) import qualified React import React.DOM import React.GHCJS import React.Rebindable import Cochon.Controller import Cochon.Imports import Cochon.Model import Cochon.Reactify import Distillation.Distiller import Distillation.Scheme import Evidences.Tm import Kit.BwdFwd import Kit.ListZip import NameSupply.NameSupply import ProofState.Edition.ProofContext import ProofState.Structure.Developments -- handlers constTransition :: trans -> MouseEvent -> Maybe trans constTransition = const . Just handleEntryToggle :: Name -> MouseEvent -> Maybe TermTransition handleEntryToggle = constTransition . ToggleTerm handleEntryGoTo :: Name -> MouseEvent -> Maybe TermTransition handleEntryGoTo = constTransition . GoToTerm handleToggleAnnotate :: Name -> MouseEvent -> Maybe TermTransition handleToggleAnnotate = constTransition . ToggleAnnotate -- TODO(joel) - stop faking this handleAddConstructor :: Name -> MouseEvent -> Maybe TermTransition handleAddConstructor _ _ = Nothing -- handleToggleEntry :: Name -> MouseEvent -> Maybe Transition -- handleToggleEntry name _ = Just $ ToggleEntry name -- handleToggleEntry = constTransition . ToggleEntry -- TODO(joel) this and handleEntryClick duplicate functionality -- handleGoTo :: Name -> MouseEvent -> Maybe Transition -- handleGoTo = constTransition . GoTo -- views page_ :: InteractionState -> ReactNode a page_ initialState = let cls = smartClass { React.name = "Page" , transition = \(state, trans) -> (dispatch trans state, Nothing) , initialState = initialState , renderFn = \() state -> pageLayout_ $ do editView_ (state^.proofCtx) messages_ (state^.messages) -- testing only -- locally $ paramLayout_ -- (ctName dataTac) -- (do text_ (ctMessage dataTac) -- tacticFormat_ (ctDesc dataTac) -- ) } in classLeaf cls () messages_ :: [UserMessage] -> ReactNode Transition messages_ = classLeaf $ smartClass { React.name = "Messages" , transition = \(state, trans) -> (state, Just trans) , renderFn = \msgs _ -> messagesLayout_ $ forReact msgs message_ } message_ :: UserMessage -> ReactNode Transition message_ = classLeaf $ smartClass { React.name = "Message" , transition = \(state, trans) -> (state, Just trans) , renderFn = \(UserMessage parts) _ -> locally $ messageLayout_ $ forReact parts messagePart_ } messagePart_ :: UserMessagePart -> ReactNode Void messagePart_ (UserMessagePart text maybeName stack maybeTerm severity) = messagePartLayout_ text (fromString (show severity)) -- Top-level views: -- * develop / debug / chiusano edit -- * node history (better: node focus?) -- * edit editView_ :: Bwd ProofContext -> ReactNode Transition editView_ = classLeaf $ smartClass { React.name = "Edit View" , transition = \(state, trans) -> (state, Just trans) , renderFn = \pc _ -> case pc of B0 -> "Red alert - empty proof context" (_ :< pc@(PC _ dev _)) -> locally $ dev_ pc dev } dev_ :: ProofContext -> Dev Bwd -> ReactNode TermTransition dev_ pc (Dev entries tip nSupply suspendState) = devLayout_ $ do fromString (show suspendState) entriesLayout_ $ forReact entries (entry_ pc) entry_ :: ProofContext -> Entry Bwd -> ReactNode TermTransition entry_ pc (EEntity ref lastName entity ty meta) = entryEntityLayout_ $ do entryHeaderLayout_ $ do ref_ pc ref metadata_ meta intm_ pc (SET :>: ty) entity_ pc entity entry_ pc (EModule name dev purpose meta) = entryModuleLayout_ $ do moduleHeaderLayout_ $ do locally $ name_ name purpose_ purpose metadata_ meta dev_ pc dev intm_ :: ProofContext -> (TY :>: INTM) -> ReactNode TermTransition intm_ pc tm = case runProofState (distillHere tm) pc of Left err -> "ERR: runProofState" Right (inTmRn :=>: _, _) -> dInTmRN_ inTmRn ref_ :: ProofContext -> REF -> ReactNode TermTransition ref_ pc (name := rKind :<: ty) = refLayout_ $ do locally $ name_ name -- TODO rKind intm_ pc (SET :>: ty) name_ :: Name -> ReactNode Void name_ n = nameLayout_ (forReact n namePiece_) namePiece_ :: (String, Int) -> ReactNode Void namePiece_ (str, n) = namePieceLayout_ (T.pack str) (T.pack (show n)) purpose_ :: ModulePurpose -> ReactNode a purpose_ p = fromString (show p) metadata_ :: Metadata -> ReactNode a metadata_ m = fromString (show m) entity_ :: ProofContext -> Entity Bwd -> ReactNode TermTransition entity_ pc (Parameter pKind) = parameterLayout_ (fromString (show pKind)) entity_ pc (Definition dKind dev) = definitionLayout_ $ do dev_ pc dev case dKind of LETG -> "LETG" PROG sch -> case runProofState (distillSchemeHere sch) pc of Left err -> "PROGERR" Right (sch', _) -> "PROG" <> scheme_ sch'
kwangkim/pigment
src-web/hs/Cochon/View.hs
mit
5,329
0
17
1,209
1,440
759
681
114
3
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.SVGMaskElement (js_getMaskUnits, getMaskUnits, js_getMaskContentUnits, getMaskContentUnits, js_getX, getX, js_getY, getY, js_getWidth, getWidth, js_getHeight, getHeight, SVGMaskElement, castToSVGMaskElement, gTypeSVGMaskElement) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"maskUnits\"]" js_getMaskUnits :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedEnumeration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.maskUnits Mozilla SVGMaskElement.maskUnits documentation> getMaskUnits :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedEnumeration) getMaskUnits self = liftIO ((js_getMaskUnits (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"maskContentUnits\"]" js_getMaskContentUnits :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedEnumeration) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.maskContentUnits Mozilla SVGMaskElement.maskContentUnits documentation> getMaskContentUnits :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedEnumeration) getMaskContentUnits self = liftIO ((js_getMaskContentUnits (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"x\"]" js_getX :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.x Mozilla SVGMaskElement.x documentation> getX :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getX self = liftIO ((js_getX (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"y\"]" js_getY :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.y Mozilla SVGMaskElement.y documentation> getY :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getY self = liftIO ((js_getY (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"width\"]" js_getWidth :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.width Mozilla SVGMaskElement.width documentation> getWidth :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getWidth self = liftIO ((js_getWidth (unSVGMaskElement self)) >>= fromJSRef) foreign import javascript unsafe "$1[\"height\"]" js_getHeight :: JSRef SVGMaskElement -> IO (JSRef SVGAnimatedLength) -- | <https://developer.mozilla.org/en-US/docs/Web/API/SVGMaskElement.height Mozilla SVGMaskElement.height documentation> getHeight :: (MonadIO m) => SVGMaskElement -> m (Maybe SVGAnimatedLength) getHeight self = liftIO ((js_getHeight (unSVGMaskElement self)) >>= fromJSRef)
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/SVGMaskElement.hs
mit
3,686
36
11
526
847
483
364
59
1
{-# LANGUAGE PatternSynonyms #-} -- For HasCallStack compatibility {-# LANGUAGE ImplicitParams, ConstraintKinds, KindSignatures #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} module JSDOM.Generated.Storage (key, key_, keyUnsafe, keyUnchecked, getItem, getItem_, getItemUnsafe, getItemUnchecked, setItem, removeItem, clear, getLength, Storage(..), gTypeStorage) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, realToFrac, fmap, Show, Read, Eq, Ord, Maybe(..)) import qualified Prelude (error) import Data.Typeable (Typeable) import Data.Traversable (mapM) import Language.Javascript.JSaddle (JSM(..), JSVal(..), JSString, strictEqual, toJSVal, valToStr, valToNumber, valToBool, js, jss, jsf, jsg, function, asyncFunction, new, array, jsUndefined, (!), (!!)) import Data.Int (Int64) import Data.Word (Word, Word64) import JSDOM.Types import Control.Applicative ((<$>)) import Control.Monad (void) import Control.Lens.Operators ((^.)) import JSDOM.EventTargetClosures (EventName, unsafeEventName, unsafeEventNameAsync) import JSDOM.Enums -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> key :: (MonadDOM m, FromJSString result) => Storage -> Word -> m (Maybe result) key self index = liftDOM ((self ^. jsf "key" [toJSVal index]) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> key_ :: (MonadDOM m) => Storage -> Word -> m () key_ self index = liftDOM (void (self ^. jsf "key" [toJSVal index])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> keyUnsafe :: (MonadDOM m, HasCallStack, FromJSString result) => Storage -> Word -> m result keyUnsafe self index = liftDOM (((self ^. jsf "key" [toJSVal index]) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.key Mozilla Storage.key documentation> keyUnchecked :: (MonadDOM m, FromJSString result) => Storage -> Word -> m result keyUnchecked self index = liftDOM ((self ^. jsf "key" [toJSVal index]) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItem :: (MonadDOM m, ToJSString key, FromJSString result) => Storage -> key -> m (Maybe result) getItem self key = liftDOM ((self ! key) >>= fromMaybeJSString) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItem_ :: (MonadDOM m, ToJSString key) => Storage -> key -> m () getItem_ self key = liftDOM (void (self ! key)) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItemUnsafe :: (MonadDOM m, ToJSString key, HasCallStack, FromJSString result) => Storage -> key -> m result getItemUnsafe self key = liftDOM (((self ! key) >>= fromMaybeJSString) >>= maybe (Prelude.error "Nothing to return") return) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.getItem Mozilla Storage.getItem documentation> getItemUnchecked :: (MonadDOM m, ToJSString key, FromJSString result) => Storage -> key -> m result getItemUnchecked self key = liftDOM ((self ! key) >>= fromJSValUnchecked) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.setItem Mozilla Storage.setItem documentation> setItem :: (MonadDOM m, ToJSString key, ToJSString data') => Storage -> key -> data' -> m () setItem self key data' = liftDOM (void (self ^. jsf "setItem" [toJSVal key, toJSVal data'])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.removeItem Mozilla Storage.removeItem documentation> removeItem :: (MonadDOM m, ToJSString key) => Storage -> key -> m () removeItem self key = liftDOM (void (self ^. jsf "removeItem" [toJSVal key])) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.clear Mozilla Storage.clear documentation> clear :: (MonadDOM m) => Storage -> m () clear self = liftDOM (void (self ^. jsf "clear" ())) -- | <https://developer.mozilla.org/en-US/docs/Web/API/Storage.length Mozilla Storage.length documentation> getLength :: (MonadDOM m) => Storage -> m Word getLength self = liftDOM (round <$> ((self ^. js "length") >>= valToNumber))
ghcjs/jsaddle-dom
src/JSDOM/Generated/Storage.hs
mit
4,607
0
14
776
1,190
663
527
-1
-1
{-# LANGUAGE LambdaCase #-} module Control.Monad.Evented where import Control.Monad.IO.Class import Control.Monad.Trans.Class newtype EventT m b = EventT { runEventT :: m (Either b (EventT m b)) } -------------------------------------------------------------------------------- -- Constructors -------------------------------------------------------------------------------- done :: Monad m => a -> EventT m a done = EventT . return . Left next :: Monad m => EventT m a -> EventT m a next = EventT . return . Right -------------------------------------------------------------------------------- -- Combinators -------------------------------------------------------------------------------- -- | Waits a number of frames. wait :: Monad m => Int -> EventT m () wait 0 = done () wait n = next $ wait $ n - 1 -- | Runs both evented computations (left and then right) each frame and returns -- the first computation that completes. withEither :: Monad m => EventT m a -> EventT m b -> EventT m (Either a b) withEither ea eb = lift ((,) <$> runEventT ea <*> runEventT eb) >>= \case (Left a,_) -> done $ Left a (_,Left b) -> done $ Right b (Right a, Right b) -> next $ withEither a b -- | Runs all evented computations (left to right) on each frame and returns -- the first computation that completes. withAny :: Monad m => [EventT m a] -> EventT m a withAny ts0 = do es <- lift $ mapM runEventT ts0 case foldl f (Right []) es of Right ts -> next $ withAny ts Left a -> done a where f (Left a) _ = Left a f (Right ts) (Right t) = Right $ ts ++ [t] f _ (Left a) = Left a -------------------------------------------------------------------------------- -- Instances -------------------------------------------------------------------------------- instance Monad m => Functor (EventT m) where fmap f (EventT g) = EventT $ g >>= \case Right ev -> return $ Right $ fmap f ev Left c -> return $ Left $ f c instance Monad m => Applicative (EventT m) where pure = done ef <*> ex = do f <- ef x <- ex return $ f x instance Monad m => Monad (EventT m) where (EventT g) >>= fev = EventT $ g >>= \case Right ev -> return $ Right $ ev >>= fev Left c -> runEventT $ fev c return = done instance MonadTrans EventT where lift f = EventT $ f >>= return . Left instance MonadIO m => MonadIO (EventT m) where liftIO = lift . liftIO
schell/odin
src/Control/Monad/Evented.hs
mit
2,453
0
12
544
826
412
414
47
4
{-# LANGUAGE Rank2Types, TypeFamilies #-} module TestInference where import Data.AEq import Numeric.Log import Control.Monad.Bayes.Class import Control.Monad.Bayes.Enumerator import Control.Monad.Bayes.Sampler import Control.Monad.Bayes.Population import Control.Monad.Bayes.Inference.SMC import Sprinkler sprinkler :: MonadInfer m => m Bool sprinkler = Sprinkler.soft -- | Count the number of particles produced by SMC checkParticles :: Int -> Int -> IO Int checkParticles observations particles = sampleIOfixed (fmap length (runPopulation $ smcMultinomial observations particles Sprinkler.soft)) checkParticlesSystematic :: Int -> Int -> IO Int checkParticlesSystematic observations particles = sampleIOfixed (fmap length (runPopulation $ smcSystematic observations particles Sprinkler.soft)) checkTerminateSMC :: IO [(Bool, Log Double)] checkTerminateSMC = sampleIOfixed (runPopulation $ smcMultinomial 2 5 sprinkler) checkPreserveSMC :: Bool checkPreserveSMC = (enumerate . collapse . smcMultinomial 2 2) sprinkler ~== enumerate sprinkler
adscib/monad-bayes
test/TestInference.hs
mit
1,082
0
11
156
261
142
119
25
1
-- | Reexports all @Manager@ utilities. module Control.TimeWarp.Manager ( module Control.TimeWarp.Manager.Job ) where import Control.TimeWarp.Manager.Job
serokell/time-warp
src/Control/TimeWarp/Manager.hs
mit
180
0
5
41
25
18
7
3
0
{-# LANGUAGE OverloadedStrings #-} import Data.List import System.CPUTime notWhole :: Double -> Bool notWhole x = fromIntegral (round x) /= x cat :: Double -> Double -> Double cat l m | m < 0 = 3.1 | l == 0 = 3.1 | notWhole l = 3.1 | notWhole m = 3.1 | otherwise = read (show (round l) ++ show (round m)) f :: Double -> String f x = show (round x) scoreDiv :: (Eq a, Fractional a) => a -> a -> a scoreDiv az bz | bz == 0 = 99999 | otherwise = (/) az bz ops = [cat, (+), (-), (*), scoreDiv] calc :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op2 (op1 a' b') c' == 20] calc2 :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc2 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op2 a' (op1 b' c') == 20] calc3 :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc3 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 (op1 a' b') (op2 c' d') == 20] calc4 :: Double -> Double -> Double -> Double -> [(Double, Double, Double, Double)] calc4 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 (op2 (op1 a' b') c') d' == 20] calc5 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 (op2 a' (op1 b' c')) d' == 20] calc6 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 a' (op2 (op1 b' c') d') == 20] calc7 a b c d = [ (a',b',c',d') | [a',b',c',d'] <- nub(permutations [a,b,c,d]), op1 <- ops, op2 <- ops, op3 <- ops, op3 a' (op2 b' (op1 c' d')) == 20] only_calc = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, not (null $ calc a b c d), null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc2 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, not (null $ calc2 a b c d), null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc3 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, not (null $ calc3 a b c d), null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc4 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, not (null $ calc4 a b c d), null $ calc5 a b c d, null $ calc6 a b c d, null $ calc7 a b c d ] only_calc5 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, not (null $ calc5 a b c d), null $ calc6 a b c d, null $ calc7 a b c d ] only_calc6 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, not (null $ calc6 a b c d), null $ calc7 a b c d ] only_calc7 = [ [a, b, c, d] | a <- [1..6], b <- [1..6], c <- [1..12], d <- [1..20], a <= b, b <= c, c <= d, null $ calc a b c d, null $ calc2 a b c d, null $ calc3 a b c d, null $ calc4 a b c d, null $ calc5 a b c d, null $ calc6 a b c d, not (null $ calc7 a b c d )] main = do print "*****************************___only_calc" t1 <- getCPUTime mapM_ print only_calc print " " print "*****************************___only_calc2" mapM_ print only_calc2 print " " print "*****************************___only_calc3" mapM_ print only_calc3 print " " print "*****************************___only_calc4" mapM_ print only_calc4 print " " print "*****************************___only_calc5" mapM_ print only_calc5 print " " print "*****************************___only_calc6" mapM_ print only_calc6 print " " print "*****************************___only_calc7" mapM_ print only_calc7 t2 <- getCPUTime let t = fromIntegral (t2-t1) * 1e-12 print t print " "
dschalk/score3
analysis_A.hs
mit
6,109
0
13
2,726
2,973
1,527
1,446
122
1
-------------------------------------------------------------------- -- File Name: xmonad.hs -- Purpose: Configure the Xmonad tiled window manager -- Creation Date: Sat Jul 07 07:13:31 CDT 2016 -- Last Modified: Sun Jan 22 17:21:02 CST 2017 -- Created By: Ivan Guerra <Ivan.E.Guerra-1@ou.edu> -------------------------------------------------------------------- import XMonad import XMonad.Hooks.DynamicLog import XMonad.Hooks.ManageDocks import XMonad.Hooks.SetWMName import Graphics.X11.ExtraTypes.XF86 (xF86XK_AudioLowerVolume, xF86XK_AudioRaiseVolume, xF86XK_AudioMute, xF86XK_MonBrightnessDown, xF86XK_MonBrightnessUp) import XMonad.Util.Run(spawnPipe) import XMonad.Util.EZConfig(additionalKeys) import XMonad.Actions.CycleWS import XMonad.Layout.BorderResize import System.IO main = do xmproc <- spawnPipe "xmobar" xmonad $ defaultConfig { manageHook = manageDocks <+> manageHook defaultConfig , layoutHook = avoidStruts $ layoutHook defaultConfig , handleEventHook = handleEventHook defaultConfig <+> docksEventHook , logHook = dynamicLogWithPP xmobarPP { ppOutput = hPutStrLn xmproc , ppTitle = xmobarColor "#bdbdbd" "" . shorten 50 } , modMask = mod4Mask -- Rebind Mod to the Windows key , terminal = "xfce4-terminal" -- Set the default terminal to the Xfce terminal , normalBorderColor = "black" , focusedBorderColor = "#bdbdbd" , startupHook = setWMName "LG3D" <+> spawn "compton --backend glx -fcC" } `additionalKeys` [ ((mod4Mask .|. controlMask, xK_l), spawn "slock") -- Call slock to lock the screen , ((mod4Mask .|. controlMask, xK_b), spawn "chromium") -- Launch a Chromium browser instance , ((mod4Mask .|. controlMask, xK_g), spawn "emacs") -- Launch an Emacs instance , ((mod4Mask, xK_Right), nextWS) -- Map Mod and right key to move to next workspace , ((mod4Mask, xK_Left), prevWS) -- Map Mod and left key to move to previous workspace , ((0 , xF86XK_AudioLowerVolume), spawn "amixer set Master 4-") -- use the function keys to decrease the volume , ((0 , xF86XK_AudioRaiseVolume), spawn "amixer set Master 4+") -- use the function keys to increase the volume , ((0, xF86XK_MonBrightnessDown), spawn "xbacklight -10") -- use the function keys to decrease screen brightness , ((0, xF86XK_MonBrightnessUp), spawn "xbacklight +10") -- use the function keys to increase screen brightness , ((mod4Mask .|. controlMask, xK_F4), spawn "sudo shutdown -h now") -- shutdown the machine , ((mod4Mask .|. controlMask, xK_F5), spawn "sudo shutdown -r now") -- restart the machine ]
ivan-guerra/config_files
xmonad.hs
mit
3,086
0
15
917
464
284
180
36
1
import System.IO import Data.List import Debug.Trace enumerate = zip [0..] discatenate :: [a] -> [[a]] discatenate xs = map (\a -> [a]) xs format :: (Int, Int) -> String format (i, n) = "Case #" ++ (show (i + 1)) ++ ": " ++ (show n) rsort :: (Ord a) => [a] -> [a] rsort = reverse . sort split :: [Int] -> Int -> [Int] split [] _ = [] split (x:xs) 0 = let small = x `div` 2 big = x - small in big : small : xs split (x:xs) n = x : (split xs (n - 1)) advance :: [Int] -> [Int] advance xs = map (\x -> x - 1) xs removeFinished :: [Int] -> [Int] removeFinished = filter (>0) step :: (Int, [[Int]]) -> (Int, [[Int]]) step (count, xss) = (count + 1, newXss) where len = length xss indices = [0..(len-1)] splits = nub $ concatMap (\xs -> map (rsort . (split xs)) [0..(length xs)]) xss advances = map advance xss together = map removeFinished $ splits ++ advances newXss = if any null together then [] else together solveCase :: ([Int], [String]) -> ([Int], [String]) solveCase (results, input) = (results ++ [result], drop 2 input) where num = read $ head input :: Int plates = rsort $ map read $ words (input !! 1) :: [Int] (result, _) = until (\(_, xs) -> null xs) step (0, [plates]) solveCases :: [String] -> [Int] solveCases input = result where (result, _) = until (\(_, is) -> null is) solveCase ([], input) main = do input <- openFile "d.in" ReadMode >>= hGetContents >>= return . lines let numCases = read $ head input :: Int let solved = solveCases $ tail input mapM_ putStrLn $ map format (enumerate solved)
davidrusu/Google-Code-Jam
2015/qualifiers/B/brute.hs
mit
1,663
0
15
450
843
463
380
43
2
--matchTypes.hs module MatchTypes where import Data.List (sort) i :: Num a => a i = 1 f :: RealFrac a => a f = 1.0 freud :: Ord a => a -> a freud x = x freud' :: Int -> Int freud' x = x myX = 1 :: Int sigmund :: Int -> Int sigmund x = myX sigmund' :: Int -> Int sigmund' x = myX jung :: [Int] -> Int jung xs = head (sort xs) young :: Ord a => [a] -> a young xs = head (sort xs) mySort :: [Char] -> [Char] mySort = sort signifier :: [Char] -> Char signifier xs = head (mySort xs)
deciduously/Haskell-First-Principles-Exercises
2-Defining and combining/6-Typeclasses/code/matchTypes.hs
mit
491
0
7
125
246
132
114
23
1
{-| Module : IREvaluator Description : EBNF IR evaluation Copyright : (c) chop-lang, 2015 License : MIT Maintainer : carterhinsley@gmail.com -} module IREvaluator ( PTerminal , PToken(..) , PAST , evaluate , createEvaluator ) where import Data.Text (Text(..)) import IRGenerator ( IRTerminal(..) , IRToken(..) , IRAlternation , IRContent , IRForm , IR ) data EToken = ETContainer EContent | ETTerminal ETerminal deriving (Eq, Show) type EAlternation = [EToken] type EContent = [EAlternation] type EForm = (Text, EContent) type ER = [EForm] -- | A product AST terminal, its first element being a descriptor of the -- terminal and its second element being the terminal content. type PTerminal = (Text, Text) -- | A product AST token, either containing another product AST or comprising -- a PTerminal. data PToken = PTContainer PAST | PTTerminal PTerminal deriving (Eq, Show) -- | The final product AST of the parsing process. type PAST = [PToken] -- | Accept an EBNF IR and some source text and product a product AST. evaluate :: IR -> Text -> PAST -- | Accept an EBNF IR and produce an evaluator representation. createEvaluator :: IR -> ER
chop-lang/parsebnf
src/IREvaluator.hs
mit
1,309
0
6
358
210
135
75
27
0
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-} module Main where import Action import Control.Applicative import Control.Concurrent import Control.Lens import Control.Monad import Control.Monad.IO.Class import Control.Monad.State import Data.ByteString.Char8 (pack, unpack, ByteString) import qualified Data.Map as M import Data.Maybe (fromJust, isNothing) import Debug.Trace import MainHelper import Mana import qualified Snap import Snap hiding (writeBS, state) import Snap.Util.FileServe (serveDirectory) import State import System.Log.Logger import Cards -- debugging purposes --writeBS str = trace (take 50 $ show str) (Snap.writeBS str) writeBS :: ByteString -> Snap () writeBS = Snap.writeBS type GSHandler = MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> Snap () setupGame :: GameState -> IO GameState setupGame = execStateT defaultGame' where defaultGame' = do forM_ [1..7] $ \_ -> drawCard 1 forM_ [1..6] $ \_ -> drawCard 0 processGameState nickDeck :: String nickDeck = "20 x Swamp\n40 x Tenacious Dead" --nickDeck = "3 x Battle Sliver\n11 x Mountain\n12 x Forest\n2 x Blur Sliver\n2 x Groundshaker Sliver\n3 x Manaweft Sliver\n2 x Megantic Sliver\n3 x Predatory Sliver\n4 x Striking Sliver\n3 x Thorncaster Sliver\n3 x Giant Growth\n3 x Fog\n2 x Naturalize\n3 x Shock\n4 x Enlarge" --mitchellDeck = "30 x Mountain\n6 x Regathan Firecat\n8 x Lava Axe\n6 x Battle Sliver\n4 x Blur Sliver\n4 x Shock\n4 x Thunder Strike" mitchellDeck :: String mitchellDeck = "13 x Mountain\n1 x Canyon Minotaur\n1 x Dragon Hatchling\n2 x Goblin Shortcutter\n2 x Pitchburn Devils\n2 x Regathan Firecat\n3 x Chandra's Outrage\n2 x Lava Axe\n1 x Seismic Stomp\n1 x Shock\n2 x Thunder Strike" main :: IO () main = do updateGlobalLogger "Game" (setLevel DEBUG) updateGlobalLogger "MVar" (setLevel DEBUG) stateMVar <- newEmptyMVar input <- newMVar (Nothing, IOReqPriority 0) output <- newEmptyMVar :: IO (MVar GameAction) gameState <- setupGame =<< buildGame stateMVar input output "Nicholas" nickDeck "Mitchell" mitchellDeck debugM "MVar" "main putting initial game state" putMVar stateMVar gameState threadID <- spawnLogicThread stateMVar output input tID <- newMVar threadID quickHttpServe $ site stateMVar input output tID site :: MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> MVar ThreadId -> Snap () site stateMVar input output tID = ifTop (writeBS "Magic: the Gathering, yo!") <|> route [("gameBoard", gameBoardHandler stateMVar input output) ,("clickCard", clickCardHandler stateMVar input output) ,("useAbility", useAbilityHandler stateMVar input output) ,("pass", passPriority stateMVar input output) ,("targetPlayer", targetPlayerHandler stateMVar input output) ,("chooseColor", chooseColorHandler stateMVar input output) ,("decideYes", youMayHandler DecideYes stateMVar input output) ,("decideNo", youMayHandler DecideNo stateMVar input output) ,("debug", printState stateMVar) ,("/static", serveDirectory "./M14/") ,("/client", serveDirectory "../magic-spieler/web-client/") ,("/newGame", newGame tID stateMVar input output) -- ,("/setupPlayer", runHandler setupPlayer state) ] printState :: MVar GameState -> Snap () printState stateMVar = liftIO $ print =<< readMVar stateMVar clickCardHandler :: GSHandler clickCardHandler state input output = do noInput <- liftIO $ isEmptyMVar input if noInput then writeBS "Waiting on server..." else do params <- getParams let lookups = do pID <- "playerID" `M.lookup` params cID <- "cardID" `M.lookup` params return (head pID, head cID) case lookups of Nothing -> writeBS "Error! Please pass in playerID, cardID" Just (playerID :: ByteString, cardID :: ByteString) -> clickCard state input output (read $ unpack playerID) (read $ unpack cardID) clickCard :: MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> Int -> Int -> Snap () clickCard stateMVar input output playerID cardID = do s <- liftIO $ readMVar stateMVar inputVal@(_, ioreq) <- liftIO $ takeMVar input case ioreq of IOReqChooseBlocker -> if playerID == (s^.currentPlayerID) then do writeBS "You can't block yourself!" liftIO $ putMVar input inputVal else doAction input output (DeclareIsBlocker playerID cardID) IOReqChooseBlockee blockerID | playerID == (s^.currentPlayerID) -> do writeBS "You can't block yourself!" liftIO $ putMVar input inputVal | cardID `notElem` (s^.attackers) -> do writeBS "That isn't attacking. Choose who to block." liftIO $ putMVar input inputVal | otherwise -> doAction input output (DeclareBlocker playerID (blockerID, cardID)) IOReqPriority _ -> doAction input output $ actionForClick playerID (s^.card cardID) s IOReqTargeting pID pred cID -> let valid = evalState (pred cID (CardTarget cardID)) s in if valid then doAction input output (TargetCard playerID cardID) else do writeBS "Invalid target choice. Pick another target." liftIO $ putMVar input inputVal _ -> error $ "Unknown IORequest " ++ show ioreq doAction :: MVar (Maybe String, IORequest) -> MVar GameAction -> GameAction -> Snap () doAction input output action = do -- Sanity checks inputEmpty <- liftIO (isEmptyMVar input) outputEmpty <- liftIO (isEmptyMVar output) unless inputEmpty $ error ("doAction " ++ show action ++ " - input not empty") unless outputEmpty $ error ("doAction " ++ show action ++ " - output not empty") liftIO $ debugM "MVar" "doAction putting output MVar" liftIO $ putMVar output action liftIO $ debugM "MVar" "doAction reading input MVar" (maybeError, ioreq) <- liftIO $ readMVar input case maybeError of Just err -> writeBS (pack err) Nothing -> let message = case ioreq of IOReqPriority _ -> "OK" IOReqTargeting _ _ _ -> "Select a target" IOReqBlocking _ _ -> "IOReqBlocking - shouldn't be used..." IOReqChooseBlocker -> "Choose a blocker" IOReqChooseBlockee _ -> "Choose who to block" IOReqChooseCard _ _ -> "Choose a card" IOReqChooseColor _ -> "Choose a color" IOReqYouMay _ _ -> "Choose an option" in writeBS message useAbilityHandler :: MVar GameState -> MVar (Maybe String, IORequest) -> MVar GameAction -> Snap () useAbilityHandler stateMvar input output = do params <- getParams liftIO $ debugM "MVar" "useAbilityHandler reading state MVar, taking input MVar" state <- liftIO $ readMVar stateMvar ioreq <- liftIO $ tryTakeMVar input let lookups = do pID <- "playerID" `M.lookup` params cID <- "cardID" `M.lookup` params aID <- "abilityID" `M.lookup` params return ((read . unpack . head) pID, (read . unpack . head) cID, (read . unpack . head) aID) case ioreq of Nothing -> writeBS "Ability use canceled, waiting on server..." Just ioreq'@(_, IOReqPriority _) -> case lookups of Nothing -> do writeBS "Invalid call to useAbility" liftIO $ putMVar input ioreq' Just (pID, cID, aID) -> do let cardAbilities = state^.card cID.abilities maybeAbility = cardAbilities^?ix aID case maybeAbility of Nothing -> do writeBS "Invalid ability index - programmer error" liftIO $ putMVar input ioreq' Just ability -> -- liftIO $ -- putMVar output (DoAbility pID cID ability) doAction input output (DoAbility pID cID ability) _ -> error "Unknown IORequest in useAbilityHandler" chooseColorHandler :: GSHandler chooseColorHandler _ input output = do params <- getParams liftIO $ debugM "MVar" "chooseColorHandler reading state MVar, taking input MVar" ioreq <- liftIO $ tryTakeMVar input let lookups = do pID <- "playerID" `M.lookup` params color <- "color" `M.lookup` params return ((read . unpack . head) pID, (unpack . head) color) case ioreq of Just ioreq'@(_, IOReqChooseColor reqID) -> case lookups of Nothing -> writeBS "Invalid call to chooseColor" Just (pID, colorString) -> let color = parseManaCost colorString in if (pID /= reqID) || length color /= 1 then do writeBS "Please choose exactly 1 color." liftIO $ putMVar input ioreq' else doAction input output (ChooseColor $ head color) Just ioreq' -> do writeBS "Not looking for a color right now." liftIO $ putMVar input ioreq' Nothing -> writeBS "Not looking for a color right now." youMayHandler :: GameAction -> GSHandler youMayHandler action _ input output = do params <- getParams liftIO $ debugM "MVar" "youMayHandler reading state MVar, taking input MVar" ioreq <- liftIO $ tryTakeMVar input let maybePID = do pID <- "playerID" `M.lookup` params return $ (read . unpack . head) pID case ioreq of Just ioreq'@(_, IOReqYouMay reqID _) -> case maybePID of Nothing -> writeBS "Invalid call to decide{Yes,No}" Just pID -> if (pID /= reqID) then do writeBS "It is not your decision." liftIO $ putMVar input ioreq' else doAction input output action Just ioreq' -> do writeBS "Not looking for a decision right now." liftIO $ putMVar input ioreq' Nothing -> writeBS "Not looking for a decision right now." targetPlayerHandler :: GSHandler targetPlayerHandler stateMVar input output = do params <- getParams liftIO $ debugM "MVar" "targetPlayerHandler reading state MVar, taking input MVar" state <- liftIO $ readMVar stateMVar ioreq <- liftIO $ tryTakeMVar input let lookups = do pID <- "sourceID" `M.lookup` params tID <- "targetID" `M.lookup` params return ((read . unpack . head) pID, (read . unpack . head) tID) case ioreq of Just ioreq'@(_, IOReqTargeting _ pred cID) -> case lookups of Nothing -> writeBS "Invalid call to targetPlayer" Just (pID, tID) -> let valid = evalState (pred cID (PlayerTarget tID)) state in if not valid then do writeBS "Invalid Choice" liftIO $ putMVar input ioreq' else doAction input output (TargetPlayer pID tID) Just ioreq' -> do writeBS "Not looking for a target right now." liftIO $ putMVar input ioreq' Nothing -> writeBS "Not looking for a target right now." attacker :: Integer attacker = 0 -- TODO - how to do this? errorAction :: GameAction errorAction = PayCost 0 0 (ManaCost $ replicate 9001 B) actionForClick :: Int -> Card -> GameState -> GameAction actionForClick pID c s | c^.cardID `elem` s^.playerWithID pID.hand = PlayCard pID (c^.cardID) | Land `elem` (c^.cardType) = DoAbility pID (c^.cardID) (head $ c^.abilities) | Creature `elem` (c^.cardType) = if s^.currentPlayerID == pID then DeclareAttacker pID (c^.cardID) else errorAction --DeclareBlocker pID (c^.cardID, attacker) | otherwise = errorAction gameBoardHandler :: GSHandler gameBoardHandler stateMVar _ _ = do state <- liftIO (readMVar stateMVar) xml <- liftIO $ toXML state writeBS . pack $ xml passPriority :: GSHandler passPriority stateMVar input output = do params <- getParams liftIO $ debugM "MVar" "passPriority reading state MVar, taking input MVar" s <- liftIO $ readMVar stateMVar (_, ioreq) <- liftIO $ readMVar input let callingPIDList = "playerID" `M.lookup` params if isNothing callingPIDList then writeBS "Error - No pID sent with \"pass\" command" else do let callingPID = read . unpack . head . fromJust $ callingPIDList case ioreq of IOReqPriority pID -> if callingPID == pID then do _ <- liftIO $ takeMVar input doAction input output (PassAction callingPID) else writeBS "Please wait for your opponent." IOReqChooseBlocker -> if s^.currentPlayerID /= callingPID then do _ <- liftIO $ takeMVar input doAction input output (PassAction callingPID) else writeBS "Please wait for your opponent." _ -> writeBS $ pack $ "You can't pass - waiting on " ++ show ioreq newGame :: MVar ThreadId -> GSHandler newGame tID state input output = do params <- getParams let lookups = do p1Name <- "p1Name" `M.lookup` params p1Deck <- "p1Deck" `M.lookup` params p2Name <- "p2Name" `M.lookup` params p2Deck <- "p2Deck" `M.lookup` params return (p1Name, p1Deck, p2Name, p2Deck) case lookups of Nothing -> writeBS "Incorrect call to newGame" Just (p1Name, p1Deck, p2Name, p2Deck) -> liftIO $ do threadID <- takeMVar tID killThread threadID _ <- tryTakeMVar input _ <- tryTakeMVar output _ <- tryTakeMVar state putMVar input (Nothing, IOReqPriority 0) gameState <- setupGame =<< buildGame state input output (unpack $ head p1Name) (unpack $ head p1Deck) (unpack $ head p2Name) (unpack $ head p2Deck) putMVar state gameState threadID' <- spawnLogicThread state output input putMVar tID threadID'
mplamann/magic-spieler
src/SnapServer.hs
mit
14,387
0
21
4,216
3,758
1,832
1,926
-1
-1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE NoImplicitPrelude #-} module Rx.Disposable ( emptyDisposable , dispose , disposeCount , disposeErrorCount , newDisposable , newBooleanDisposable , newSingleAssignmentDisposable , toList , wrapDisposable , wrapDisposableIO , BooleanDisposable , Disposable , SingleAssignmentDisposable , SetDisposable (..) , ToDisposable (..) , IDisposable (..) , DisposeResult ) where import Prelude.Compat import Control.Arrow (first) import Control.Exception (SomeException, try) import Control.Monad (liftM, void) -- import Data.List (foldl') import Data.Typeable (Typeable) import Control.Concurrent.MVar (MVar, modifyMVar, newMVar, putMVar, readMVar, swapMVar, takeMVar) -------------------------------------------------------------------------------- type DisposableDescription = String data DisposeResult = DisposeBranch DisposableDescription DisposeResult | DisposeLeaf DisposableDescription (Maybe SomeException) | DisposeResult [DisposeResult] deriving (Show, Typeable) newtype Disposable = Disposable [IO DisposeResult] deriving (Typeable) newtype BooleanDisposable = BooleanDisposable (MVar Disposable) deriving (Typeable) newtype SingleAssignmentDisposable = SingleAssignmentDisposable (MVar (Maybe Disposable)) deriving (Typeable) -------------------------------------------------------------------------------- class IDisposable d where disposeVerbose :: d -> IO DisposeResult class ToDisposable d where toDisposable :: d -> Disposable class SetDisposable d where setDisposable :: d -> Disposable -> IO () -------------------------------------------------------------------------------- instance Monoid DisposeResult where mempty = DisposeResult [] (DisposeResult as) `mappend` (DisposeResult bs) = DisposeResult (as `mappend` bs) a@(DisposeResult coll) `mappend` b = DisposeResult (coll ++ [b]) a `mappend` b@(DisposeResult coll) = DisposeResult (a:coll) a `mappend` b = DisposeResult [a, b] -------------------- instance Monoid Disposable where mempty = Disposable [] (Disposable as) `mappend` (Disposable bs) = Disposable (as `mappend` bs) instance IDisposable Disposable where disposeVerbose (Disposable actions) = mconcat `fmap` sequence actions instance ToDisposable Disposable where toDisposable = id -------------------- instance IDisposable BooleanDisposable where disposeVerbose (BooleanDisposable disposableVar) = do disposable <- readMVar disposableVar disposeVerbose disposable instance ToDisposable BooleanDisposable where toDisposable booleanDisposable = Disposable [disposeVerbose booleanDisposable] instance SetDisposable BooleanDisposable where setDisposable (BooleanDisposable currentVar) disposable = do oldDisposable <- swapMVar currentVar disposable void $ disposeVerbose oldDisposable -------------------- instance IDisposable SingleAssignmentDisposable where disposeVerbose (SingleAssignmentDisposable disposableVar) = do mdisposable <- readMVar disposableVar maybe (return mempty) disposeVerbose mdisposable instance ToDisposable SingleAssignmentDisposable where toDisposable singleAssignmentDisposable = Disposable [disposeVerbose singleAssignmentDisposable] instance SetDisposable SingleAssignmentDisposable where setDisposable (SingleAssignmentDisposable disposableVar) disposable = do mdisposable <- takeMVar disposableVar case mdisposable of Nothing -> putMVar disposableVar (Just disposable) Just _ -> error $ "ERROR: called 'setDisposable' more " ++ "than once on SingleAssignmentDisposable" -------------------------------------------------------------------------------- foldDisposeResult :: (DisposableDescription -> Maybe SomeException -> acc -> acc) -> (DisposableDescription -> acc -> acc) -> ([acc] -> acc) -> acc -> DisposeResult -> acc foldDisposeResult fLeaf _ _ acc (DisposeLeaf desc mErr) = fLeaf desc mErr acc foldDisposeResult fLeaf fBranch fList acc (DisposeBranch desc disposeResult) = fBranch desc (foldDisposeResult fLeaf fBranch fList acc disposeResult) foldDisposeResult fLeaf fBranch fList acc (DisposeResult ds) = let acc1 = map (foldDisposeResult fLeaf fBranch fList acc) ds in fList acc1 disposeCount :: DisposeResult -> Int disposeCount = foldDisposeResult (\_ _ acc -> acc + 1) (const id) sum 0 {-# INLINE disposeCount #-} disposeErrorCount :: DisposeResult -> Int disposeErrorCount = foldDisposeResult (\_ mErr acc -> acc + maybe 0 (const 1) mErr) (const id) sum 0 {-# INLINE disposeErrorCount #-} toList :: DisposeResult -> [([DisposableDescription], Maybe SomeException)] toList = foldDisposeResult (\desc res acc -> (([desc], res) : acc)) (\desc acc -> map (first (desc :)) acc) concat [] dispose :: IDisposable disposable => disposable -> IO () dispose = void . disposeVerbose {-# INLINE dispose #-} emptyDisposable :: IO Disposable emptyDisposable = return mempty {-# INLINE emptyDisposable #-} newDisposable :: DisposableDescription -> IO () -> IO Disposable newDisposable desc disposingAction = do disposeResultVar <- newMVar Nothing return $ Disposable [modifyMVar disposeResultVar $ \disposeResult -> case disposeResult of Just result -> return (Just result, result) Nothing -> do disposingResult <- try disposingAction let result = DisposeLeaf desc (either Just (const Nothing) disposingResult) return (Just result, result)] wrapDisposableIO :: DisposableDescription -> IO Disposable -> IO Disposable wrapDisposableIO desc getDisposable = do disposeResultVar <- newMVar Nothing return $ Disposable [modifyMVar disposeResultVar $ \disposeResult -> case disposeResult of Just result -> return (Just result, result) Nothing -> do disposable <- getDisposable innerResult <- disposeVerbose disposable let result = DisposeBranch desc innerResult return (Just result, result)] {-# INLINE wrapDisposableIO #-} wrapDisposable :: DisposableDescription -> Disposable -> IO Disposable wrapDisposable desc = wrapDisposableIO desc . return {-# INLINE wrapDisposable #-} newBooleanDisposable :: IO BooleanDisposable newBooleanDisposable = liftM BooleanDisposable (newMVar mempty) {-# INLINE newBooleanDisposable #-} newSingleAssignmentDisposable :: IO SingleAssignmentDisposable newSingleAssignmentDisposable = liftM SingleAssignmentDisposable (newMVar Nothing) {-# INLINE newSingleAssignmentDisposable #-}
roman/Haskell-Reactive-Extensions
rx-disposable/src/Rx/Disposable.hs
mit
7,151
0
24
1,571
1,660
865
795
170
2
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-} module GHCJS.DOM.JSFFI.Generated.AudioDestinationNode (js_getMaxChannelCount, getMaxChannelCount, AudioDestinationNode, castToAudioDestinationNode, gTypeAudioDestinationNode) where import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord) import Data.Typeable (Typeable) import GHCJS.Types (JSRef(..), JSString, castRef) import GHCJS.Foreign (jsNull) import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..)) import GHCJS.Marshal (ToJSRef(..), FromJSRef(..)) import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..)) import Control.Monad.IO.Class (MonadIO(..)) import Data.Int (Int64) import Data.Word (Word, Word64) import GHCJS.DOM.Types import Control.Applicative ((<$>)) import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName) import GHCJS.DOM.Enums foreign import javascript unsafe "$1[\"maxChannelCount\"]" js_getMaxChannelCount :: JSRef AudioDestinationNode -> IO Word -- | <https://developer.mozilla.org/en-US/docs/Web/API/AudioDestinationNode.maxChannelCount Mozilla AudioDestinationNode.maxChannelCount documentation> getMaxChannelCount :: (MonadIO m) => AudioDestinationNode -> m Word getMaxChannelCount self = liftIO (js_getMaxChannelCount (unAudioDestinationNode self))
plow-technologies/ghcjs-dom
src/GHCJS/DOM/JSFFI/Generated/AudioDestinationNode.hs
mit
1,460
6
9
152
358
228
130
23
1
module Language.Binal.Util.TyKind where import Control.Monad.State import qualified Data.List as List import qualified Data.HashMap.Strict as HashMap import Language.Binal.Types import qualified Language.Binal.Util.Gen as Gen freeVariables :: TyKind -> [Variable] freeVariables (VarTy i) = [i] freeVariables (RecTy i ty) = filter (/=i) (freeVariables ty) freeVariables SymTy = [] freeVariables StrTy = [] freeVariables NumTy = [] freeVariables BoolTy = [] freeVariables (ArrTy x y) = freeVariables x ++ freeVariables y freeVariables (ListTy xs) = concatMap freeVariables xs freeVariables (EitherTy xs) = concatMap freeVariables xs freeVariables (ObjectTy _ m) = concatMap freeVariables (HashMap.elems m) freeVariables (MutableTy ty) = freeVariables ty extractVarTy :: TyKind -> Maybe Variable extractVarTy (VarTy i) = Just i extractVarTy _ = Nothing extractListTy :: TyKind -> Maybe [TyKind] extractListTy (ListTy xs) = Just xs extractListTy _ = Nothing flatListTy' :: [TyKind] -> [TyKind] flatListTy' [] = [] flatListTy' xs = do case last xs of ListTy [] -> xs ListTy ys -> init xs ++ flatListTy' ys _ -> xs flatListTy :: TyKind -> TyKind flatListTy (VarTy i) = VarTy i flatListTy (RecTy i ty) = RecTy i (flatListTy ty) flatListTy SymTy = SymTy flatListTy StrTy = StrTy flatListTy NumTy = NumTy flatListTy BoolTy = BoolTy flatListTy (ArrTy ty1 ty2) = ArrTy (flatListTy ty1) (flatListTy ty2) flatListTy (ListTy tys) = case flatListTy' tys of [ty] -> ty tys' -> ListTy tys' flatListTy (EitherTy xs) = EitherTy (map flatListTy xs) flatListTy (ObjectTy i m) = ObjectTy i (HashMap.map flatListTy m) flatListTy (MutableTy ty) = MutableTy (flatListTy ty) flatEitherTy' :: Variable -> [TyKind] -> [TyKind] flatEitherTy' _ [] = [] flatEitherTy' i xs = do List.nub (concatMap (\x -> case x of VarTy j | i == j -> [] | otherwise -> [VarTy j] ty -> [ty]) xs) flatEitherTy :: Variable -> TyKind -> TyKind flatEitherTy i (EitherTy xs) = case flatEitherTy' i xs of [ty] -> ty tys -> EitherTy tys flatEitherTy _ ty = ty showTy' :: TyKind -> State (HashMap.HashMap Variable String, [String]) String showTy' (VarTy i) = do (mp, varList) <- get case HashMap.lookup i mp of Just s -> return ('\'':s) Nothing -> do let (v, varList') = case varList of [] -> (show i, []) (s:ss) -> (s, ss) let mp' = HashMap.insert i v mp put (mp', varList') return ('\'':v) showTy' (RecTy i ty) = do x <- showTy' (VarTy i) y <- showTy' ty return ("(recur " ++ x ++ " " ++ y ++ ")") showTy' SymTy = return "symbol" showTy' StrTy = return "string" showTy' NumTy = return "number" showTy' BoolTy = return "bool" showTy' (ArrTy ty1 ty2) = do ty1S <- showTy' ty1 ty2S <- showTy' ty2 case (length (lines ty1S), length (lines ty2S)) of (1, 1) -> return ("(-> " ++ ty1S ++ " " ++ ty2S ++ ")") _ -> return ("(-> " ++ drop 4 (Gen.indent 4 ty1S) ++ "\n" ++ Gen.indent 4 ty2S ++ ")") showTy' (ListTy xs) = do ss <- mapM showTy' xs if all (\x -> 1 == length (lines x)) ss then return ("(" ++ unwords ss ++ ")") else return ("(" ++ drop 1 (Gen.indent 1 (unlines ss)) ++ ")") showTy' (EitherTy xs) = do ss <- mapM showTy' xs if all (\x -> 1 == length (lines x)) ss then return ("(| " ++ unwords ss ++ ")") else return ("(| " ++ drop 3 (Gen.indent 3 (unlines ss)) ++ ")") showTy' (ObjectTy _ m) | HashMap.null m = return "(obj)" | otherwise = do let maxLen = foldr1 max (map length (HashMap.keys m)) ss <- mapM (\(key, val) -> do x <- showTy' val return ["\n", key, drop (length key) (Gen.indent (maxLen + 1) x)]) (HashMap.toList m) return ("(obj " ++ drop 5 (Gen.indent 5 (tail (concat (concat ss)))) ++ ")") showTy' (MutableTy ty) = do s <- showTy' ty case length (lines s) of 1 -> do return ("(mutable " ++ s ++ ")") _ -> do return ("(mutable" ++ drop 8 (Gen.indent 9 s) ++ ")") showTy :: TyKind -> String showTy ty = evalState (showTy' ty) (HashMap.empty, map (\ch -> [ch]) ['a'..'z']) showTy2 :: TyKind -> TyKind -> (String, String) showTy2 ty1 ty2 = evalState (do { x <- showTy' ty1; y <- showTy' ty2; return (x, y) }) (HashMap.empty, map (\ch -> [ch]) ['a'..'z']) traverseVarTyM :: Monad m => (TyKind -> m ()) -> TyKind -> m () traverseVarTyM f ty@(VarTy _) = f ty traverseVarTyM _ SymTy = return () traverseVarTyM _ StrTy = return () traverseVarTyM _ NumTy = return () traverseVarTyM _ BoolTy = return () traverseVarTyM f (ArrTy ty1 ty2) = traverseVarTyM f ty1 >> traverseVarTyM f ty2 traverseVarTyM f (ListTy tys) = mapM_ (traverseVarTyM f) tys traverseVarTyM f (EitherTy tys) = mapM_ (traverseVarTyM f) tys traverseVarTyM f (ObjectTy _ x) = mapM_ (traverseVarTyM f) (HashMap.elems x) traverseVarTyM f (RecTy _ ty) = traverseVarTyM f ty traverseVarTyM f (MutableTy ty) = traverseVarTyM f ty
pasberth/binal1
Language/Binal/Util/TyKind.hs
mit
5,038
36
20
1,205
2,234
1,121
1,113
125
7
{-# LANGUAGE RecordWildCards #-} module Game.Graphics.Font ( FontText(..) , Font, loadFont , drawFontText ) where import Graphics.Rendering.FTGL import Game.Graphics.AffineTransform (AffineTransform, withTransformRasterGl) data FontText = FontText { getFont :: Font , getString :: String } loadFont :: String -> IO Font loadFont = createPixmapFont drawFontText :: AffineTransform -> FontText -> IO Bool drawFontText trans FontText{..} = do setFontFaceSize getFont 24 72 withTransformRasterGl trans $ renderFont getFont getString Front return True
caryoscelus/graphics
src/Game/Graphics/Font.hs
mit
625
0
8
147
149
82
67
18
1
{-# LANGUAGE BangPatterns, ConstraintKinds, FlexibleContexts, GeneralizedNewtypeDeriving, MultiParamTypeClasses, StandaloneDeriving, TupleSections #-} {- | Module : Data.Graph.Unordered.Algorithms.Clustering Description : Graph partitioning Copyright : (c) Ivan Lazar Miljenovic License : MIT Maintainer : Ivan.Miljenovic@gmail.com -} module Data.Graph.Unordered.Algorithms.Clustering (bgll ,EdgeMergeable ) where import Data.Graph.Unordered import Data.Graph.Unordered.Internal import Control.Arrow (first, (***)) import Control.Monad (void) import Data.Bool (bool) import Data.Function (on) import Data.Hashable (Hashable) import Data.HashMap.Strict (HashMap) import qualified Data.HashMap.Strict as HM import Data.List (delete, foldl', foldl1', group, maximumBy, sort) import Data.Maybe (fromMaybe, mapMaybe) import Data.Proxy (Proxy (Proxy)) -- ----------------------------------------------------------------------------- -- | Find communities in weighted graphs using the algorithm by -- Blondel, Guillaume, Lambiotte and Lefebvre in their paper -- <http://arxiv.org/abs/0803.0476 Fast unfolding of communities in large networks>. bgll :: (ValidGraph et n, EdgeMergeable et, Fractional el, Ord el) => Graph et n nl el -> [[n]] bgll g = maybe [nodes g] nodes (recurseUntil pass g') where pass = fmap phaseTwo . phaseOne -- HashMap doesn't allow directly mapping the keys g' = Gr { nodeMap = HM.fromList . map ((: []) *** void) . HM.toList $ nodeMap g , edgeMap = HM.map (first (fmap (: []))) (edgeMap g) , nextEdge = nextEdge g } data CGraph et n el = CG { comMap :: HashMap Community (Set [n]) , cGraph :: Graph et [n] Community el } deriving (Show, Read) deriving instance (Eq n, Eq el, Eq (et [n])) => Eq (CGraph et n el) newtype Community = C Word deriving (Eq, Ord, Show, Read, Enum, Bounded, Hashable) type ValidC et n el = (ValidGraph et n, EdgeMergeable et, Fractional el, Ord el) phaseOne :: (ValidC et n el) => Graph et [n] nl el -> Maybe (CGraph et n el) phaseOne = recurseUntil moveAll . initCommunities initCommunities :: (ValidC et n el) => Graph et [n] nl el -> CGraph et n el initCommunities g = CG { comMap = cm , cGraph = Gr { nodeMap = nm' , edgeMap = edgeMap g , nextEdge = nextEdge g } } where nm = nodeMap g ((_,cm),nm') = mapAccumWithKeyL go (C minBound, HM.empty) nm go (!c,!cs) ns al = ( (succ c, HM.insert c (HM.singleton ns ()) cs) , c <$ al ) moveAll :: (ValidC et n el) => CGraph et n el -> Maybe (CGraph et n el) moveAll cg = uncurry (bool Nothing . Just) $ foldl' go (cg,False) (nodes (cGraph cg)) where go pr@(cg',_) = maybe pr (,True) . tryMove cg' tryMove :: (ValidC et n el) => CGraph et n el -> [n] -> Maybe (CGraph et n el) tryMove cg ns = moveTo <$> bestMove cg ns where cm = comMap cg g = cGraph cg currentC = getC g ns currentCNs = cm HM.! currentC moveTo c = CG { comMap = HM.adjust (HM.insert ns ()) c cm' , cGraph = nmapFor (const c) g ns } where currentCNs' = HM.delete ns currentCNs cm' | HM.null currentCNs' = HM.delete currentC cm | otherwise = HM.adjust (const currentCNs') currentC cm bestMove :: (ValidC et n el) => CGraph et n el -> [n] -> Maybe Community bestMove cg n | null vs = Nothing | null cs = Nothing | maxDQ <= 0 = Nothing | otherwise = Just maxC where g = cGraph cg c = getC g n vs = neighbours g n cs = delete c . map head . group . sort . map (getC g) $ vs (maxC, maxDQ) = maximumBy (compare`on`snd) . map ((,) <*> diffModularity cg n) $ cs getC :: (ValidC et n el) => Graph et [n] Community el -> [n] -> Community getC g = fromMaybe (error "Node doesn't have a community!") . nlab g -- This is the ๐™Q function. Assumed that @i@ is not within the community @c@. diffModularity :: (ValidC et n el) => CGraph et n el -> [n] -> Community -> el diffModularity cg i c = ((sumIn + kiIn)/m2 - sq ((sumTot + ki)/m2)) - (sumIn/m2 - sq (sumTot/m2) - sq (ki/m2)) where g = cGraph cg nm = nodeMap g em = edgeMap g -- Nodes within the community cNs = fromMaybe HM.empty (HM.lookup c (comMap cg)) -- Edges solely within the community cEMap = HM.filter (all (`HM.member`cNs) . edgeNodes . fst) em -- All edges incident with C incEs = HM.filter (any (`HM.member`cNs) . edgeNodes . fst) em -- Twice the weight of all edges in the graph (take into account both directions) m2 = eTot em -- Sum of weights of all edges within the community sumIn = eTot cEMap -- Sum of weights of all edges incident with the community sumTot = eTot incEs iAdj = maybe HM.empty fst $ HM.lookup i nm ki = kTot . HM.intersection em $ iAdj kiIn = kTot . HM.intersection incEs $ iAdj -- 2* because the EdgeMap only contains one copy of each edge. eTot = (2*) . kTot kTot = (2*) . sum . map snd . HM.elems sq x = x * x phaseTwo :: (ValidC et n el) => CGraph et n el -> Graph et [n] () el phaseTwo cg = mkGraph ns es where nsCprs = map ((,) <*> concat . HM.keys) . HM.elems $ comMap cg nsToC = HM.fromList . concatMap (\(vs,c) -> map (,c) (HM.keys vs)) $ nsCprs emNCs = HM.map (first (fmap (nsToC HM.!))) (edgeMap (cGraph cg)) es = compressEdgeMap Proxy emNCs ns = map (,()) (map snd nsCprs) -- eM' = map toCE -- . groupBy ((==)`on`fst) -- . sortBy (compare`on`fst) -- . map (first edgeNodes) -- . HM.elems -- $ edgeMap (cGraph cg) -- d -- toCE es = let ([u,v],_) = head es -- in (u,v, sum (map snd es)) -- The resultant (n,n) pairings will be unique compressEdgeMap :: (ValidC et n el) => Proxy et -> EdgeMap et [n] el -> [([n],[n],el)] compressEdgeMap p em = concatMap (\(u,vels) -> map (uncurry $ mkE u) (HM.toList vels)) (HM.toList esUndir) where -- Mapping on edge orders as created esDir = foldl1' (HM.unionWith (HM.unionWith (+))) . map ((\(u,v,el) -> HM.singleton u (HM.singleton v el)) . edgeTriple) $ HM.elems em esUndir = fst $ foldl' checkOpp (HM.empty, esDir) (HM.keys esDir) mkE u v el | el < 0 = (v,u,applyOpposite p el) | otherwise = (u,v,el) checkOpp (esU,esD) u | HM.null uVs = (esU , esD' ) | otherwise = (esU', esD'') where uVs = esD HM.! u -- So we don't worry about loops. esD' = HM.delete u esD uAdj = mapMaybe (\v -> fmap (v,) . HM.lookup u =<< (HM.lookup v esD')) (HM.keys (esD' `HM.intersection` uVs)) esD'' = foldl' (flip $ HM.adjust (HM.delete u)) esD' (map fst uAdj) uVs' = foldl' toE uVs uAdj toE m (v,el) = HM.insertWith (+) v (applyOpposite p el) m esU' = HM.insert u uVs' esU class (EdgeType et) => EdgeMergeable et where applyOpposite :: (Fractional el) => Proxy et -> el -> el instance EdgeMergeable DirEdge where applyOpposite _ = negate instance EdgeMergeable UndirEdge where applyOpposite _ = id -- ----------------------------------------------------------------------------- -- StateL was copied from the source of Data.Traversable in base-4.8.1.0 mapAccumWithKeyL :: (a -> k -> v -> (a, y)) -> a -> HashMap k v -> (a, HashMap k y) mapAccumWithKeyL f a m = runStateL (HM.traverseWithKey f' m) a where f' k v = StateL $ \s -> f s k v -- left-to-right state transformer newtype StateL s a = StateL { runStateL :: s -> (s, a) } instance Functor (StateL s) where fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v) instance Applicative (StateL s) where pure x = StateL (\ s -> (s, x)) StateL kf <*> StateL kv = StateL $ \ s -> let (s', f) = kf s (s'', v) = kv s' in (s'', f v) -- ----------------------------------------------------------------------------- recurseUntil :: (a -> Maybe a) -> a -> Maybe a recurseUntil f = fmap go . f where go a = maybe a go (f a)
ivan-m/unordered-graphs
src/Data/Graph/Unordered/Algorithms/Clustering.hs
mit
8,702
0
17
2,685
3,031
1,611
1,420
141
1
-- | Exercises for chapter 3. module Chapter03 ( xs0, xs1, xs2, xs3, t0, t1, twice, palindrome, double, pair, swap, second ) where -- * Exercise 1 xs0 :: [Int] xs0 = [0, 1] -- Define the values below and give them types. -- | TODO: define as @['a','b','c']@ xs1 = undefined -- | TODO: define as @('a','b','c')@ t0 = undefined -- | TODO: define as @[(False,'0'),(True,'1')]@ xs2 = undefined -- | TODO: define as @([False,True],['0','1'])@ t1 = undefined -- | TODO: define as @[tail,init,reverse]@ xs3 = undefined -- * Exercise 2 -- Define the values below and give them types. -- | Returns the second element of a list. -- -- TODO: give it a type and implement. second xs = undefined -- | Swap the elements of a tuple. -- -- TODO: give it a type and implement. swap (x,y) = undefined -- | Constructs a pair with the given elements, in the order in which the -- parameters appear. -- -- TODO: give it a type and implement. pair x y = undefined -- | Multiplies the given argument by 2. -- -- TODO: give it a type and implement. double x = undefined -- | Determine wether the given list is a palindrome. -- -- TODO: give it a type and implement. palindrome xs = undefined -- | Apply the given function twice to the given argument. -- -- TODO: give it a type and implement. twice f x = undefined
EindhovenHaskellMeetup/meetup
courses/programming-in-haskell/pih-exercises/src/Chapter03.hs
mit
1,312
0
6
266
173
114
59
15
1
module CFDI.Types.ProductDescription where import CFDI.Chainable import CFDI.Types.Type import Data.Text (Text, pack, unpack) import Text.Regex (mkRegex) import Text.Regex.Posix (matchTest) newtype ProductDescription = ProductDescription Text deriving (Eq, Show) instance Chainable ProductDescription where chain (ProductDescription d) = d instance Type ProductDescription where parseExpr str | matchTest regExp str = Right . ProductDescription $ pack str | otherwise = Left $ DoesNotMatchExpr "[^|]{1,1000}" where regExp = mkRegex "^(.|รก|รฉ|รญ|รณ|รบ|รฑ|ร|ร‰|ร|ร“|รš|ร‘){1,1000}$" render (ProductDescription d) = unpack d
yusent/cfdis
src/CFDI/Types/ProductDescription.hs
mit
667
0
9
112
177
94
83
15
0
{-# LANGUAGE PackageImports, RecordWildCards #-} module GameState where import "GLFW-b" Graphics.UI.GLFW as GLFW import Graphics.Gloss.Rendering import Graphics.Gloss.Data.Color import Graphics.Gloss.Data.Picture import Control.Applicative import qualified Data.List as L import Math.Geometry.Grid.Hexagonal import Math.Geometry.Grid.HexagonalInternal import Math.Geometry.GridMap ((!)) import Board import Drawing import Textures -- | Definition for the game state data type. data GameState = GameState { tileMapState :: TileMap , mapPosition :: (Float, Float) , mapZoom :: Float , civColor :: Color , nextUnitInLine :: Maybe TileCoord , blinkAnimation :: (Float, Bool) } deriving Show -- | The main function to render the game state. renderView :: TextureMap -> GameState -> Picture renderView txMap gS@GameState{..} = views where (x, y) = mapPosition views = translate x y $ scale mapZoom mapZoom $ pictures (map (tilePicture txMap gS) tiles) -- | Renders a picture for a single tile. tilePicture :: TextureMap -> GameState -> TileCoord -- ^ The coordinate of the tile to be rendered. -> Picture tilePicture txMap gS@GameState{..} t = translate x y $ pictures [ tileView txMap tile , (improvementView txMap . tileImprovement) tile , (resourceView txMap . tileResource) tile , (unitView txMap gS t . tileUnit) tile ] where tile = tileMapState ! t (x, y) = tileLocationCenter t grey = makeColor (x/(x+y+0.2)) 1 (y/(x+y+0.2)) 1 -- | Basic drawing of a unit. unitView :: TextureMap -> GameState -> TileCoord -> Maybe Unit -> Picture unitView _ _ _ Nothing = Blank unitView txMap GameState{..} coord (Just Unit{..}) = pictures [ case unitKind of Settler -> "settler" `from` txMap Worker -> "worker" `from` txMap -- Worker -> color (blinky red) $ "worker" `from` txMap _ -> Blank , color (blinky civColor) $ thickCircle 80 10 ] where s = 50 blinky :: Color -> Color blinky c = case nextUnitInLine of Just x -> if coord == x then setAlpha c (fst blinkAnimation) else c _ -> c ------------------------------ -- Game state change functions ------------------------------ -- | The default settings of a game state. It is semi-random. initGameState :: IO GameState initGameState = do randomTMap <- randomTileMap -- example units added let tMap = replaceUnit (0,0) (Just $ Unit Settler 1 True) $ replaceUnit (2,3) (Just $ Unit Worker 1 True) $ replaceImprovement (0,0) (Just City) randomTMap return $ GameState tMap (0,0) 0.6 blue (Just (0,0)) (1.0, False) -- | Moves map to the opposite direction of the key, by the float number given. moveMap :: (Float, Float) -- ^ Indicates directions coming from getCursorKeyDirections. -> Float -- ^ Translation offset. -> GameState -- ^ Game state to be changed. -> GameState -- ^ New game state. moveMap (x,y) i gs@GameState{..} = gs { mapPosition = (x' + x * i, y' + y * i) } where (x', y') = mapPosition -- | Moves the unit in the given coordinate according to the key. moveUnitWithKey :: Maybe TileCoord -- ^ The coordinate of the unit to be moved. -> [Key] -- ^ The direction keys to determine the direction. -> GameState -- ^ Game state to be changed. -> GameState -- ^ New game state. moveUnitWithKey mCoord [k] gS@GameState{..} = case mCoord of Nothing -> gS Just c -> gS { tileMapState = moveUnitToDirection c dir tileMapState , nextUnitInLine = findNextUnitInLine $ deactivateNextUnitInLine c tileMapState } where dir = keyToDirection k moveUnitWithKey _ _ gS = gS -- | Assigns a hexagonal direction to the keys W,E,D,X,Z,A. -- Note that this is a partial function and it fails on other keys. keyToDirection :: Key -> HexDirection keyToDirection k = case k of Key'W -> Northwest Key'E -> Northeast Key'D -> East Key'X -> Southeast Key'Z -> Southwest Key'A -> West _ -> error "No hexagonal direction assigned for this key." -- | Takes keys about turn action and changes the game state. turnAction :: [Key] -- ^ Should only contain space. -> GameState -> GameState turnAction [Key'Space] gS@GameState{..} = case nextUnitInLine of Just c -> let newTMap = deactivateNextUnitInLine c tileMapState in gS { tileMapState = newTMap , nextUnitInLine = findNextUnitInLine newTMap } _ -> gS -- end turn or activate all units again turnAction _ gS = gS -- | Changes zoom scale in the game state with respect to a coefficient. changeScale :: Float -- ^ The coefficient to respond to. -> GameState -- ^ Game state to be changed. -> GameState -- ^ New game state. changeScale coeff gS@GameState{..} = gS { mapZoom = limited } where newZoom = mapZoom * ((coeff + 100.0) / 100) limited | newZoom < 0.2 = 0.2 | newZoom > 0.9 = 0.9 | otherwise = newZoom -- | Set state for blink animation. blink :: GameState -> GameState blink gS@GameState{..} = gS { blinkAnimation = y } where (x, inc) = blinkAnimation op = if inc then (+) else (-) i = 0.05 -- offset y = case () of _ | x < 0.3 && not inc -> (x + i, True) | x > 0.9 && inc -> (x - i, False) | otherwise -> (x `op` i, inc)
joom/civ
src/GameState.hs
mit
5,819
0
15
1,755
1,441
793
648
123
7
{-# LANGUAGE TypeOperators #-} module AtomIndex where import qualified Data.IntMap as IM import qualified Data.Map as M import Data.Functor import Data.Strict.Tuple import Types import Arches import Indices type AtomIndex = (M.Map Atom Int :!: IM.IntMap (IM.IntMap (IM.IntMap Int)) :!: IM.IntMap Atom :!: Counter) maxIndex :: AtomIndex -> AtomI maxIndex (_ :!: _ :!: _ :!: i) = Index (pred i) emptyIndex :: AtomIndex emptyIndex = (M.empty :!: IM.empty :!: IM.empty :!: 1) indexBin :: AtomIndex -> Binary -> Maybe BinI indexBin (m :!: _ :!: _ :!: _) b = Index <$> BinAtom b `M.lookup` m indexSrc :: AtomIndex -> Source -> Maybe SrcI indexSrc (m :!: _ :!: _ :!: _) s = Index <$> SrcAtom s `M.lookup` m indexBug :: AtomIndex -> Bug -> Maybe BugI indexBug (m :!: _ :!: _ :!: _) b = Index <$> BugAtom b `M.lookup` m indexInst :: AtomIndex -> Inst -> Maybe InstI indexInst (m :!: im :!: _ :!: _) (Inst (Index b1) (Index b2) (Arch arch)) = do im' <- arch `IM.lookup` im im'' <- b1 `IM.lookup` im' i <- b2 `IM.lookup` im'' return $ Index i indexAtom :: AtomIndex -> Atom -> Maybe AtomI indexAtom ai@(m :!: _ :!: _ :!: _) (InstAtom i) = genIndex <$> indexInst ai i indexAtom (m :!: _ :!: _ :!: _) a = Index <$> a `M.lookup` m addBin :: AtomIndex -> Binary -> (AtomIndex, BinI) addBin a2i@(m :!: im :!: m' :!: c) b = case indexBin a2i b of Just i -> (a2i, i) Nothing -> (((BinAtom b `M.insert` c) m :!: im :!: (c `IM.insert` BinAtom b) m' :!: succ c), Index c) addSrc :: AtomIndex -> Source -> (AtomIndex, SrcI) addSrc a2i@(m :!: im :!: m' :!: c) b = case indexSrc a2i b of Just i -> (a2i, i) Nothing -> (((SrcAtom b `M.insert` c) m :!: im :!: (c `IM.insert` SrcAtom b) m' :!: succ c), Index c) addBug :: AtomIndex -> Bug -> (AtomIndex, BugI) addBug a2i@(m :!: im :!: m' :!: c) b = case indexBug a2i b of Just i -> (a2i, i) Nothing -> (((BugAtom b `M.insert` c) m :!: im :!: (c `IM.insert` BugAtom b) m':!: succ c), Index c) addInst :: AtomIndex -> Inst -> (AtomIndex, InstI) addInst a2i@(m :!: im :!: m' :!: c) i' = case indexInst a2i i' of Just i -> (a2i, i) Nothing -> (( m :!: addInst2IM i' c im :!: (c `IM.insert` InstAtom i') m' :!: succ c ), Index c) addInst2IM (Inst (Index b1) (Index b2) (Arch a)) c = IM.insertWith (IM.unionWith IM.union) a $ IM.singleton b1 $ IM.singleton b2 c lookupBin :: AtomIndex -> BinI -> Binary lookupBin (_ :!: _ :!: m :!: _) (Index i) = (\(BinAtom b) -> b) (m IM.! i) lookupSrc :: AtomIndex -> SrcI -> Source lookupSrc (_ :!: _ :!: m :!: _) (Index i) = (\(SrcAtom b) -> b) (m IM.! i) lookupBug :: AtomIndex -> BugI -> Bug lookupBug (_ :!: _ :!: m :!: _) (Index i) = (\(BugAtom b) -> b) (m IM.! i) lookupInst :: AtomIndex -> InstI -> Inst lookupInst (_ :!: _ :!: m :!: _) (Index i) = (\(InstAtom b) -> b) (m IM.! i) lookupAtom :: AtomIndex -> AtomI -> Atom lookupAtom (_ :!: _ :!: m :!: _) (Index i) = m IM.! i lookupAny :: AtomIndex -> Index a -> Atom lookupAny (_ :!: _ :!: m :!: _) (Index i) = m IM.! i
nomeata/sat-britney
AtomIndex.hs
gpl-2.0
3,654
0
16
1,305
1,555
817
738
76
2
{-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE TypeSynonymInstances #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE PatternGuards #-} -- | -- Copyright : (c) 2010-2012 Simon Meier & Benedikt Schmidt -- License : GPL v3 (see LICENSE) -- -- Maintainer : Simon Meier <iridcode@gmail.com> -- Portability : GHC only -- -- Types and operations for handling sorted first-order logic module Theory.Model.Formula ( -- * Formulas Connective(..) , Quantifier(..) , ProtoFormula(..) , Formula , SyntacticFormula , LNFormula , ProtoLNFormula , SyntacticLNFormula , LFormula , quantify , openFormula , openFormulaPrefix , toLNFormula -- , unquantify -- ** More convenient constructors , lfalse , ltrue , (.&&.) , (.||.) , (.==>.) , (.<=>.) , exists , forall , hinted -- ** General Transformations , mapAtoms , foldFormula , traverseFormulaAtom -- ** Pretty-Printing , prettyLNFormula , prettySyntacticLNFormula ) where import Prelude hiding (negate) import GHC.Generics (Generic) import Data.Binary -- import Data.Foldable (Foldable, foldMap) import Data.Data -- import Data.Monoid hiding (All) -- import Data.Traversable import Control.Basics import Control.DeepSeq import Control.Monad.Fresh import qualified Control.Monad.Trans.PreciseFresh as Precise import Theory.Model.Atom import Text.PrettyPrint.Highlight import Theory.Text.Pretty import Term.LTerm import Term.Substitution ------------------------------------------------------------------------------ -- Types ------------------------------------------------------------------------------ -- | Logical connectives. data Connective = And | Or | Imp | Iff deriving( Eq, Ord, Show, Enum, Bounded, Data, Typeable, Generic, NFData, Binary ) -- | Quantifiers. data Quantifier = All | Ex deriving( Eq, Ord, Show, Enum, Bounded, Data, Typeable, Generic, NFData, Binary ) -- | First-order formulas in locally nameless representation with hints for the -- names/sorts of quantified variables and syntactic sugar in atoms. data ProtoFormula syn s c v = Ato (ProtoAtom syn (VTerm c (BVar v))) | TF !Bool | Not (ProtoFormula syn s c v) | Conn !Connective (ProtoFormula syn s c v) (ProtoFormula syn s c v) | Qua !Quantifier s (ProtoFormula syn s c v) deriving ( Generic) -- | First-order formulas in locally nameless representation with hints for the -- names/sorts of quantified variables. type Formula s c v = ProtoFormula Unit2 s c v type SyntacticFormula s c v = ProtoFormula SyntacticSugar s c v -- Folding ---------- -- | Fold a formula. {-# INLINE foldFormula #-} foldFormula :: (ProtoAtom syn (VTerm c (BVar v)) -> b) -> (Bool -> b) -> (b -> b) -> (Connective -> b -> b -> b) -> (Quantifier -> s -> b -> b) -> (ProtoFormula syn s c v) -> b foldFormula fAto fTF fNot fConn fQua = go where go (Ato a) = fAto a go (TF b) = fTF b go (Not p) = fNot (go p) go (Conn c p q) = fConn c (go p) (go q) go (Qua qua x p) = fQua qua x (go p) -- | Fold a formula. {-# INLINE foldFormulaScope #-} foldFormulaScope :: (Integer -> ProtoAtom syn (VTerm c (BVar v)) -> b) -> (Bool -> b) -> (b -> b) -> (Connective -> b -> b -> b) -> (Quantifier -> s -> b -> b) -> ProtoFormula syn s c v -> b foldFormulaScope fAto fTF fNot fConn fQua = go 0 where go !i (Ato a) = fAto i a go _ (TF b) = fTF b go !i (Not p) = fNot (go i p) go !i (Conn c p q) = fConn c (go i p) (go i q) go !i (Qua qua x p) = fQua qua x (go (succ i) p) -- Instances ------------ {- instance Functor (Formula s c) where fmap f = foldFormula (Ato . fmap (fmap (fmap (fmap f)))) TF Not Conn Qua -} deriving instance (NFData c, NFData v, NFData s) => NFData (ProtoFormula SyntacticSugar s c v) deriving instance (Binary c, Binary v, Binary s) => Binary (ProtoFormula SyntacticSugar s c v) deriving instance (NFData c, NFData v, NFData s) => NFData (ProtoFormula Unit2 s c v) deriving instance (Binary c, Binary v, Binary s) => Binary (ProtoFormula Unit2 s c v) instance (Foldable syn) => Foldable (ProtoFormula syn s c) where foldMap f = foldFormula (foldMap (foldMap (foldMap (foldMap f)))) mempty id (const mappend) (const $ const id) -- | traverse formula down to the term level traverseFormula :: (Ord v, Ord c, Ord v', Applicative f, Traversable syn) => (v -> f v') -> ProtoFormula syn s c v -> f (ProtoFormula syn s c v') traverseFormula f = foldFormula (liftA Ato . traverse (traverseTerm (traverse (traverse f)))) (pure . TF) (liftA Not) (liftA2 . Conn) ((liftA .) . Qua) -- | traverse formula up to atom level traverseFormulaAtom :: Applicative f => (ProtoAtom syn1 (VTerm c1 (BVar v1)) -> f (ProtoFormula syn2 s c2 v2)) -> ProtoFormula syn1 s c1 v1 -> f (ProtoFormula syn2 s c2 v2) traverseFormulaAtom fAt = foldFormula (fAt) (pure . TF) (liftA Not) (liftA2 . Conn) ((liftA .) . Qua) {- instance Traversable (Formula a s) where traverse f = foldFormula (liftA Ato . traverseAtom (traverseTerm (traverseLit (traverseBVar f)))) (pure . TF) (liftA Not) (liftA2 . Conn) ((liftA .) . Qua) -} -- Abbreviations ---------------- infixl 3 .&&. infixl 2 .||. infixr 1 .==>. infix 1 .<=>. -- | Logically true. ltrue :: ProtoFormula syn a s v ltrue = TF True -- | Logically false. lfalse :: ProtoFormula syn a s v lfalse = TF False (.&&.), (.||.), (.==>.), (.<=>.) :: ProtoFormula syn a s v -> ProtoFormula syn a s v -> ProtoFormula syn a s v (.&&.) = Conn And (.||.) = Conn Or (.==>.) = Conn Imp (.<=>.) = Conn Iff ------------------------------------------------------------------------------ -- Dealing with bound variables ------------------------------------------------------------------------------ -- | @LFormula@ are FOL formulas with sorts abused to denote both a hint for -- the name of the bound variable, as well as the variable's actual sort. type LFormula c = Formula (String, LSort) c LVar type ProtoLFormula syn c = ProtoFormula syn (String, LSort) c LVar type LNFormula = Formula (String, LSort) Name LVar type ProtoLNFormula syn = ProtoLFormula syn Name type SyntacticLNFormula = ProtoLNFormula SyntacticSugar -- | Change the representation of atoms. mapAtoms :: (Integer -> ProtoAtom syn (VTerm c (BVar v)) -> ProtoAtom syn1 (VTerm c1 (BVar v1))) -> ProtoFormula syn s c v -> ProtoFormula syn1 s c1 v1 mapAtoms f = foldFormulaScope (\i a -> Ato $ f i a) TF Not Conn Qua -- | @openFormula f@ returns @Just (v,Q,f')@ if @f = Q v. f'@ modulo -- alpha renaming and @Nothing otherwise@. @v@ is always chosen to be fresh. openFormula :: (MonadFresh m, Ord c, Functor syn) => ProtoLFormula syn c -> Maybe (Quantifier, m (LVar, ProtoLFormula syn c)) openFormula (Qua qua (n,s) fm) = Just ( qua , do x <- freshLVar n s return $ (x, mapAtoms (\i a -> fmap (mapLits (subst x i)) a) fm) ) where subst x i (Var (Bound i')) | i == i' = Var $ Free x subst _ _ l = l openFormula _ = Nothing mapLits :: (Ord a, Ord b) => (a -> b) -> Term a -> Term b mapLits f t = case viewTerm t of Lit l -> lit . f $ l FApp o as -> fApp o (map (mapLits f) as) -- | @openFormulaPrefix f@ returns @Just (vs,Q,f')@ if @f = Q v_1 .. v_k. f'@ -- modulo alpha renaming and @Nothing otherwise@. @vs@ is always chosen to be -- fresh. openFormulaPrefix :: (MonadFresh m, Ord c, Functor syn) => ProtoLFormula syn c -> m ([LVar], Quantifier, ProtoLFormula syn c) openFormulaPrefix f0 = case openFormula f0 of Nothing -> error $ "openFormulaPrefix: no outermost quantifier" Just (q, open) -> do (x, f) <- open go q [x] f where go q xs f = case openFormula f of Just (q', open') | q' == q -> do (x', f') <- open' go q (x' : xs) f' -- no further quantifier of the same kind => return result _ -> return (reverse xs, q, f) -- Instances ------------ deriving instance Eq LNFormula deriving instance Show LNFormula deriving instance Ord LNFormula deriving instance Eq SyntacticLNFormula deriving instance Show SyntacticLNFormula deriving instance Ord SyntacticLNFormula deriving instance Data SyntacticLNFormula instance HasFrees LNFormula where foldFrees f = foldMap (foldFrees f) foldFreesOcc _ _ = const mempty -- we ignore occurences in Formulas for now mapFrees f = traverseFormula (mapFrees f) instance HasFrees SyntacticLNFormula where foldFrees f = foldMap (foldFrees f) foldFreesOcc _ _ = const mempty -- we ignore occurences in Formulas for now mapFrees f = traverseFormula (mapFrees f) instance Apply LNFormula where apply subst = mapAtoms (const $ apply subst) instance Apply SyntacticLNFormula where apply subst = mapAtoms (const $ apply subst ) ------------------------------------------------------------------------------ -- Formulas modulo E and modulo AC ------------------------------------------------------------------------------ -- | Introduce a bound variable for a free variable. quantify :: (Ord c, Ord v, Functor syn) => v -> ProtoFormula syn s c v -> ProtoFormula syn s c v quantify x = mapAtoms (\i a -> fmap (mapLits (fmap (>>= subst i))) a) where subst i v | v == x = Bound i | otherwise = Free v -- | Create a universal quantification with a sort hint for the bound variable. forall :: (Ord c, Ord v, Functor syn) => s -> v -> ProtoFormula syn s c v -> ProtoFormula syn s c v forall hint x = Qua All hint . quantify x -- | Create a existential quantification with a sort hint for the bound variable. exists :: (Ord c, Ord v, Functor syn) => s -> v -> ProtoFormula syn s c v -> ProtoFormula syn s c v exists hint x = Qua Ex hint . quantify x -- | Transform @forall@ and @exists@ into functions that operate on logical variables hinted :: ((String, LSort) -> LVar -> a) -> LVar -> a hinted f v@(LVar n s _) = f (n,s) v -- | Convert to LNFormula, if possible. -- toLNFormula :: Formula s c0 (ProtoAtom s0 t0) -> Maybe (Formula s c0 (Atom t0)) toLNFormula :: ProtoFormula syn s c v -> Maybe (Formula s c v) toLNFormula = traverseFormulaAtom (liftA Ato . f) where f x | (Syntactic _) <- x = Nothing | otherwise = Just (toAtom x) ------------------------------------------------------------------------------ -- Pretty printing ------------------------------------------------------------------------------ -- | Pretty print a formula. prettyLFormula :: (HighlightDocument d, MonadFresh m, Ord c, Functor syn) => (ProtoAtom syn (VTerm c LVar) -> d) -- ^ Function for pretty printing atoms -> ProtoLFormula syn c -- ^ Formula to pretty print. -> m d -- ^ Pretty printed formula. prettyLFormula ppAtom = pp where extractFree (Free v) = v extractFree (Bound i) = error $ "prettyFormula: illegal bound variable '" ++ show i ++ "'" pp (Ato a) = return $ ppAtom (fmap (mapLits (fmap extractFree)) a) pp (TF True) = return $ operator_ "โŠค" -- "T" pp (TF False) = return $ operator_ "โŠฅ" -- "F" pp (Not p) = do p' <- pp p return $ operator_ "ยฌ" <> opParens p' -- text "ยฌ" <> parens (pp a) -- return $ operator_ "not" <> opParens p' -- text "ยฌ" <> parens (pp a) pp (Conn op p q) = do p' <- pp p q' <- pp q return $ sep [opParens p' <-> ppOp op, opParens q'] where ppOp And = opLAnd ppOp Or = opLOr ppOp Imp = opImp ppOp Iff = opIff pp fm@(Qua _ _ _) = scopeFreshness $ do (vs,qua,fm') <- openFormulaPrefix fm d' <- pp fm' return $ sep [ ppQuant qua <> ppVars vs <> operator_ "." , nest 1 d'] where ppVars = fsep . map (text . show) ppQuant All = opForall ppQuant Ex = opExists -- | Pretty print a logical formula prettyLNFormula :: HighlightDocument d => LNFormula -> d prettyLNFormula fm = Precise.evalFresh (prettyLFormula prettyNAtom fm) (avoidPrecise fm) -- | Pretty print a logical formula prettySyntacticLNFormula :: HighlightDocument d => SyntacticLNFormula -> d prettySyntacticLNFormula fm = Precise.evalFresh (prettyLFormula prettySyntacticNAtom fm) (avoidPrecise fm)
tamarin-prover/tamarin-prover
lib/theory/src/Theory/Model/Formula.hs
gpl-3.0
13,502
0
18
3,850
3,773
1,979
1,794
237
11
import Data.List replaceChars :: Char -> Char -> Char -> Char replaceChars whatC withC c = if c == whatC then withC else c interestFields :: [String] -> [Int] -> [String] interestFields s takeWhat = undefined isR200 :: [String] -> Bool isR200 s = (head s) == "R200" processLine :: String -> String processLine s = if isR200 sInWords then unwords (interestFields sInWords [1,2,3] ) else [] where sInWords = words ( map (replaceChars '|' ' ') s ) processString :: String -> [String] processString s = map processLine (lines $ s) main :: IO () main = do str <- readFile "merged.txt" putStrLn (intercalate "\r\n" (processString $ str))
graninas/Haskell-Algorithms
Materials/Haskell ะฒ ั€ะตะฐะปัŒะฝะพะผ ะผะธั€ะต - ะกั‚ะฐั‚ัŒั/parser 0.2.hs
gpl-3.0
666
0
11
143
264
138
126
16
2
module Main where import Control.Parallel.Strategies --import Y2015.R1A.A (solve, parse) import Y2015.R1A.B (solve, parse) -- import Y2015.R1A.C (solve, parse) main :: IO () main = getContents >>= putStr . unlines . showSolutions . parMap rdeepseq (show . solve) . parse . tail . lines showSolutions :: [String] -> [String] showSolutions = zipWith (++) ["Case #" ++ show i ++ ": " | i <- [1::Int ..]]
joranvar/GoogleCodeJam
Main.hs
gpl-3.0
411
0
11
75
137
78
59
8
1
module Main where import Control.Applicative import Control.Arrow import Data.List (splitAt, find) import Data.Monoid ((<>)) import System.Random(randomRIO) import Data.Function (on, (&)) -- | Define the main data structure data Suit = Spade | Heart | Club | Diamond deriving (Eq, Ord, Enum, Show) data Pip = Ace | Two | Three | Four | Five | Six | Seven | Eight | Nine | Ten | Jack | Queen | King deriving (Eq, Ord, Enum, Show) data Card = Card { _suit :: Suit , _pip :: Pip } deriving (Eq, Ord, Show) -- | Make Card enumerable pour facilment construct instance Enum Card where toEnum = (`div` 13) &&& (`mod` 13) >>> toEnum *** toEnum >>> uncurry Card fromEnum = _suit &&& _pip >>> fromEnum *** fromEnum >>> \(x, y) -> 13 * x + y -- | Just make a shabby non-type-safe data structure considering the balence of use and cost type Deck = [Card] data EOBoard = EOBoard { _foundations :: [Deck] , _columns :: [Deck] , _reserves :: [Deck] } deriving (Eq, Ord, Show) -- | Tricky method to get all the constructor of a enum pack :: Deck pack = Card <$> enumFrom Spade <*> enumFrom Ace -- | Trival def, useless, but this can be odd when reach Ace or King pCard, sCard :: Card -> Card pCard = succ sCard = pred -- | Trival def for judge isAce, isKing :: Card -> Bool isAce = _pip >>> (==) Ace isKing = _pip >>> (==) King -- | The un-rec single-step shuffle moveRamdonElemtes :: ([a], [a]) -> IO ([a], [a]) moveRamdonElemtes (ss, as@(_ : _)) = takeN <$> randomRIO (0,length as - 1) <*> pure as where takeN n = splitAt n >>> (\(xs, (y : ys)) -> ((y : ss), xs <> ys)) moveRamdonElemtes (ss, []) = pure (ss, []) -- | shuffle a deck by the global RandomGEN shuffle :: [a] -> IO [a] shuffle as = fst <$> shuffle' ([], as) where shuffle' (ss, as@(_ : _)) = moveRamdonElemtes (ss,as) >>= shuffle' shuffle' (ss, [] ) = pure (ss,[]) -- | split a list into given parts, generic splitAt multiSplit :: [Int] -> [a] -> [[a]] multiSplit (s:ss) = splitAt s >>> second (multiSplit ss) >>> uncurry (:) multiSplit [] = pure -- | Generate a EOBoard whose state is the start of the 8-off eODeal :: IO EOBoard eODeal = let packSplit = (multiSplit $ replicate 8 6 <> replicate 3 1) >>> splitAt 8 >>> uncurry (EOBoard $ replicate 4 []) in packSplit <$> shuffle pack -- | Detect if a deck in the fundations can be auto-added by the given deck in the columns overlayDetect :: Deck -> Deck -> Bool overlayDetect (c : cs) (xc:xcs) = if isKing c then False else (_suit c) == (_suit xc) && (succ $ _pip c) == (_pip xc) overlayDetect [] (xc:xcs) = isAce xc overlayDetect _ [] = False -- | Replace the nth elem of the list with given one replaceWith :: [a] -> Int -> a -> [a] replaceWith xs i y = (take i xs) ++ (y : (drop (i+1) xs)) -- | a.k.a. autoplay, i.e.,automaticly doing the possible columns-to-foundations move toFoundations :: EOBoard -> EOBoard toFoundations e = let (ef,(ec,er)) = _foundations &&& _columns &&& _reserves $ e possibleMoves = curry (uncurry (overlayDetect `on` snd) &&& id) <$> zip [0..] ef <*> zip [0..] ec in case snd <$> find fst possibleMoves of Just ((i, d1), (j, (hd2 : d2))) -> toFoundations $ EOBoard (replaceWith ef i (hd2:d1)) (replaceWith ec j d2) er otherwise -> e main :: IO () main = toFoundations <$> eODeal >>= print
suzumiyasmith/KDJL
KDJL.hs
gpl-3.0
3,413
0
16
805
1,278
713
565
62
2
module Model where import ClassyPrelude.Yesod import Database.Persist.Quasi import Yesod.Auth.HashDB (HashDBUser(..)) -- You can define all of your database entities in the entities file. -- You can find more information on persistent and how to declare entities -- at: -- http://www.yesodweb.com/book/persistent/ share [mkPersist sqlSettings, mkMigrate "migrateAll"] $(persistFileWith lowerCaseSettings "config/models") instance HashDBUser User where userPasswordHash = userPassword setPasswordHash h p = p { userPassword = Just h }
Drezil/neat
Model.hs
gpl-3.0
549
0
8
81
97
55
42
-1
-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.Games.Rooms.Get -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Get the data for a room. -- -- /See:/ <https://developers.google.com/games/services/ Google Play Game Services API Reference> for @games.rooms.get@. module Network.Google.Resource.Games.Rooms.Get ( -- * REST Resource RoomsGetResource -- * Creating a Request , roomsGet , RoomsGet -- * Request Lenses , rgConsistencyToken , rgRoomId , rgLanguage ) where import Network.Google.Games.Types import Network.Google.Prelude -- | A resource alias for @games.rooms.get@ method which the -- 'RoomsGet' request conforms to. type RoomsGetResource = "games" :> "v1" :> "rooms" :> Capture "roomId" Text :> QueryParam "consistencyToken" (Textual Int64) :> QueryParam "language" Text :> QueryParam "alt" AltJSON :> Get '[JSON] Room -- | Get the data for a room. -- -- /See:/ 'roomsGet' smart constructor. data RoomsGet = RoomsGet' { _rgConsistencyToken :: !(Maybe (Textual Int64)) , _rgRoomId :: !Text , _rgLanguage :: !(Maybe Text) } deriving (Eq,Show,Data,Typeable,Generic) -- | Creates a value of 'RoomsGet' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'rgConsistencyToken' -- -- * 'rgRoomId' -- -- * 'rgLanguage' roomsGet :: Text -- ^ 'rgRoomId' -> RoomsGet roomsGet pRgRoomId_ = RoomsGet' { _rgConsistencyToken = Nothing , _rgRoomId = pRgRoomId_ , _rgLanguage = Nothing } -- | The last-seen mutation timestamp. rgConsistencyToken :: Lens' RoomsGet (Maybe Int64) rgConsistencyToken = lens _rgConsistencyToken (\ s a -> s{_rgConsistencyToken = a}) . mapping _Coerce -- | The ID of the room. rgRoomId :: Lens' RoomsGet Text rgRoomId = lens _rgRoomId (\ s a -> s{_rgRoomId = a}) -- | The preferred language to use for strings returned by this method. rgLanguage :: Lens' RoomsGet (Maybe Text) rgLanguage = lens _rgLanguage (\ s a -> s{_rgLanguage = a}) instance GoogleRequest RoomsGet where type Rs RoomsGet = Room type Scopes RoomsGet = '["https://www.googleapis.com/auth/games", "https://www.googleapis.com/auth/plus.login"] requestClient RoomsGet'{..} = go _rgRoomId _rgConsistencyToken _rgLanguage (Just AltJSON) gamesService where go = buildClient (Proxy :: Proxy RoomsGetResource) mempty
rueshyna/gogol
gogol-games/gen/Network/Google/Resource/Games/Rooms/Get.hs
mpl-2.0
3,302
0
14
824
484
285
199
71
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.Dataflow.Projects.Locations.Jobs.Debug.SendCapture -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Send encoded debug capture data for component. -- -- /See:/ <https://cloud.google.com/dataflow Dataflow API Reference> for @dataflow.projects.locations.jobs.debug.sendCapture@. module Network.Google.Resource.Dataflow.Projects.Locations.Jobs.Debug.SendCapture ( -- * REST Resource ProjectsLocationsJobsDebugSendCaptureResource -- * Creating a Request , projectsLocationsJobsDebugSendCapture , ProjectsLocationsJobsDebugSendCapture -- * Request Lenses , pljdscXgafv , pljdscJobId , pljdscUploadProtocol , pljdscLocation , pljdscAccessToken , pljdscUploadType , pljdscPayload , pljdscProjectId , pljdscCallback ) where import Network.Google.Dataflow.Types import Network.Google.Prelude -- | A resource alias for @dataflow.projects.locations.jobs.debug.sendCapture@ method which the -- 'ProjectsLocationsJobsDebugSendCapture' request conforms to. type ProjectsLocationsJobsDebugSendCaptureResource = "v1b3" :> "projects" :> Capture "projectId" Text :> "locations" :> Capture "location" Text :> "jobs" :> Capture "jobId" Text :> "debug" :> "sendCapture" :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] SendDebugCaptureRequest :> Post '[JSON] SendDebugCaptureResponse -- | Send encoded debug capture data for component. -- -- /See:/ 'projectsLocationsJobsDebugSendCapture' smart constructor. data ProjectsLocationsJobsDebugSendCapture = ProjectsLocationsJobsDebugSendCapture' { _pljdscXgafv :: !(Maybe Xgafv) , _pljdscJobId :: !Text , _pljdscUploadProtocol :: !(Maybe Text) , _pljdscLocation :: !Text , _pljdscAccessToken :: !(Maybe Text) , _pljdscUploadType :: !(Maybe Text) , _pljdscPayload :: !SendDebugCaptureRequest , _pljdscProjectId :: !Text , _pljdscCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'ProjectsLocationsJobsDebugSendCapture' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'pljdscXgafv' -- -- * 'pljdscJobId' -- -- * 'pljdscUploadProtocol' -- -- * 'pljdscLocation' -- -- * 'pljdscAccessToken' -- -- * 'pljdscUploadType' -- -- * 'pljdscPayload' -- -- * 'pljdscProjectId' -- -- * 'pljdscCallback' projectsLocationsJobsDebugSendCapture :: Text -- ^ 'pljdscJobId' -> Text -- ^ 'pljdscLocation' -> SendDebugCaptureRequest -- ^ 'pljdscPayload' -> Text -- ^ 'pljdscProjectId' -> ProjectsLocationsJobsDebugSendCapture projectsLocationsJobsDebugSendCapture pPljdscJobId_ pPljdscLocation_ pPljdscPayload_ pPljdscProjectId_ = ProjectsLocationsJobsDebugSendCapture' { _pljdscXgafv = Nothing , _pljdscJobId = pPljdscJobId_ , _pljdscUploadProtocol = Nothing , _pljdscLocation = pPljdscLocation_ , _pljdscAccessToken = Nothing , _pljdscUploadType = Nothing , _pljdscPayload = pPljdscPayload_ , _pljdscProjectId = pPljdscProjectId_ , _pljdscCallback = Nothing } -- | V1 error format. pljdscXgafv :: Lens' ProjectsLocationsJobsDebugSendCapture (Maybe Xgafv) pljdscXgafv = lens _pljdscXgafv (\ s a -> s{_pljdscXgafv = a}) -- | The job id. pljdscJobId :: Lens' ProjectsLocationsJobsDebugSendCapture Text pljdscJobId = lens _pljdscJobId (\ s a -> s{_pljdscJobId = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). pljdscUploadProtocol :: Lens' ProjectsLocationsJobsDebugSendCapture (Maybe Text) pljdscUploadProtocol = lens _pljdscUploadProtocol (\ s a -> s{_pljdscUploadProtocol = a}) -- | The [regional endpoint] -- (https:\/\/cloud.google.com\/dataflow\/docs\/concepts\/regional-endpoints) -- that contains the job specified by job_id. pljdscLocation :: Lens' ProjectsLocationsJobsDebugSendCapture Text pljdscLocation = lens _pljdscLocation (\ s a -> s{_pljdscLocation = a}) -- | OAuth access token. pljdscAccessToken :: Lens' ProjectsLocationsJobsDebugSendCapture (Maybe Text) pljdscAccessToken = lens _pljdscAccessToken (\ s a -> s{_pljdscAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). pljdscUploadType :: Lens' ProjectsLocationsJobsDebugSendCapture (Maybe Text) pljdscUploadType = lens _pljdscUploadType (\ s a -> s{_pljdscUploadType = a}) -- | Multipart request metadata. pljdscPayload :: Lens' ProjectsLocationsJobsDebugSendCapture SendDebugCaptureRequest pljdscPayload = lens _pljdscPayload (\ s a -> s{_pljdscPayload = a}) -- | The project id. pljdscProjectId :: Lens' ProjectsLocationsJobsDebugSendCapture Text pljdscProjectId = lens _pljdscProjectId (\ s a -> s{_pljdscProjectId = a}) -- | JSONP pljdscCallback :: Lens' ProjectsLocationsJobsDebugSendCapture (Maybe Text) pljdscCallback = lens _pljdscCallback (\ s a -> s{_pljdscCallback = a}) instance GoogleRequest ProjectsLocationsJobsDebugSendCapture where type Rs ProjectsLocationsJobsDebugSendCapture = SendDebugCaptureResponse type Scopes ProjectsLocationsJobsDebugSendCapture = '["https://www.googleapis.com/auth/cloud-platform", "https://www.googleapis.com/auth/compute", "https://www.googleapis.com/auth/compute.readonly", "https://www.googleapis.com/auth/userinfo.email"] requestClient ProjectsLocationsJobsDebugSendCapture'{..} = go _pljdscProjectId _pljdscLocation _pljdscJobId _pljdscXgafv _pljdscUploadProtocol _pljdscAccessToken _pljdscUploadType _pljdscCallback (Just AltJSON) _pljdscPayload dataflowService where go = buildClient (Proxy :: Proxy ProjectsLocationsJobsDebugSendCaptureResource) mempty
brendanhay/gogol
gogol-dataflow/gen/Network/Google/Resource/Dataflow/Projects/Locations/Jobs/Debug/SendCapture.hs
mpl-2.0
7,181
0
23
1,684
958
558
400
152
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.GamesConfiguration.AchievementConfigurations.Update -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- -- Update the metadata of the achievement configuration with the given ID. -- -- /See:/ <https://developers.google.com/games/ Google Play Game Services Publishing API Reference> for @gamesConfiguration.achievementConfigurations.update@. module Network.Google.Resource.GamesConfiguration.AchievementConfigurations.Update ( -- * REST Resource AchievementConfigurationsUpdateResource -- * Creating a Request , achievementConfigurationsUpdate , AchievementConfigurationsUpdate -- * Request Lenses , acuXgafv , acuUploadProtocol , acuAchievementId , acuAccessToken , acuUploadType , acuPayload , acuCallback ) where import Network.Google.GamesConfiguration.Types import Network.Google.Prelude -- | A resource alias for @gamesConfiguration.achievementConfigurations.update@ method which the -- 'AchievementConfigurationsUpdate' request conforms to. type AchievementConfigurationsUpdateResource = "games" :> "v1configuration" :> "achievements" :> Capture "achievementId" Text :> QueryParam "$.xgafv" Xgafv :> QueryParam "upload_protocol" Text :> QueryParam "access_token" Text :> QueryParam "uploadType" Text :> QueryParam "callback" Text :> QueryParam "alt" AltJSON :> ReqBody '[JSON] AchievementConfiguration :> Put '[JSON] AchievementConfiguration -- | Update the metadata of the achievement configuration with the given ID. -- -- /See:/ 'achievementConfigurationsUpdate' smart constructor. data AchievementConfigurationsUpdate = AchievementConfigurationsUpdate' { _acuXgafv :: !(Maybe Xgafv) , _acuUploadProtocol :: !(Maybe Text) , _acuAchievementId :: !Text , _acuAccessToken :: !(Maybe Text) , _acuUploadType :: !(Maybe Text) , _acuPayload :: !AchievementConfiguration , _acuCallback :: !(Maybe Text) } deriving (Eq, Show, Data, Typeable, Generic) -- | Creates a value of 'AchievementConfigurationsUpdate' with the minimum fields required to make a request. -- -- Use one of the following lenses to modify other fields as desired: -- -- * 'acuXgafv' -- -- * 'acuUploadProtocol' -- -- * 'acuAchievementId' -- -- * 'acuAccessToken' -- -- * 'acuUploadType' -- -- * 'acuPayload' -- -- * 'acuCallback' achievementConfigurationsUpdate :: Text -- ^ 'acuAchievementId' -> AchievementConfiguration -- ^ 'acuPayload' -> AchievementConfigurationsUpdate achievementConfigurationsUpdate pAcuAchievementId_ pAcuPayload_ = AchievementConfigurationsUpdate' { _acuXgafv = Nothing , _acuUploadProtocol = Nothing , _acuAchievementId = pAcuAchievementId_ , _acuAccessToken = Nothing , _acuUploadType = Nothing , _acuPayload = pAcuPayload_ , _acuCallback = Nothing } -- | V1 error format. acuXgafv :: Lens' AchievementConfigurationsUpdate (Maybe Xgafv) acuXgafv = lens _acuXgafv (\ s a -> s{_acuXgafv = a}) -- | Upload protocol for media (e.g. \"raw\", \"multipart\"). acuUploadProtocol :: Lens' AchievementConfigurationsUpdate (Maybe Text) acuUploadProtocol = lens _acuUploadProtocol (\ s a -> s{_acuUploadProtocol = a}) -- | The ID of the achievement used by this method. acuAchievementId :: Lens' AchievementConfigurationsUpdate Text acuAchievementId = lens _acuAchievementId (\ s a -> s{_acuAchievementId = a}) -- | OAuth access token. acuAccessToken :: Lens' AchievementConfigurationsUpdate (Maybe Text) acuAccessToken = lens _acuAccessToken (\ s a -> s{_acuAccessToken = a}) -- | Legacy upload protocol for media (e.g. \"media\", \"multipart\"). acuUploadType :: Lens' AchievementConfigurationsUpdate (Maybe Text) acuUploadType = lens _acuUploadType (\ s a -> s{_acuUploadType = a}) -- | Multipart request metadata. acuPayload :: Lens' AchievementConfigurationsUpdate AchievementConfiguration acuPayload = lens _acuPayload (\ s a -> s{_acuPayload = a}) -- | JSONP acuCallback :: Lens' AchievementConfigurationsUpdate (Maybe Text) acuCallback = lens _acuCallback (\ s a -> s{_acuCallback = a}) instance GoogleRequest AchievementConfigurationsUpdate where type Rs AchievementConfigurationsUpdate = AchievementConfiguration type Scopes AchievementConfigurationsUpdate = '["https://www.googleapis.com/auth/androidpublisher"] requestClient AchievementConfigurationsUpdate'{..} = go _acuAchievementId _acuXgafv _acuUploadProtocol _acuAccessToken _acuUploadType _acuCallback (Just AltJSON) _acuPayload gamesConfigurationService where go = buildClient (Proxy :: Proxy AchievementConfigurationsUpdateResource) mempty
brendanhay/gogol
gogol-games-configuration/gen/Network/Google/Resource/GamesConfiguration/AchievementConfigurations/Update.hs
mpl-2.0
5,738
0
18
1,285
782
455
327
119
1
func = ($) where {-# INLINE ($) #-} ($) = id
lspitzner/brittany
data/Test40.hs
agpl-3.0
50
0
4
16
19
12
7
3
1
{- | Module : $Header$ Description : The tempuhs server executable Copyright : (c) plaimi 2014 License : AGPL-3 Maintainer : tempuhs@plaimi.net -} module Main where import Tempuhs.Server.CLI ( cli, ) main :: IO () -- | 'main' starts the server with options from the command line. main = cli
plaimi/tempuhs-server
src-exec/Main.hs
agpl-3.0
317
0
6
76
33
21
12
6
1
-- These are the tests for our api. The only real interesting part is the -- 'main' function, were we specific that the test database is different -- from the production database. {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE InstanceSigs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} module Main (main) where import Control.Monad.IO.Class (liftIO) import Control.Monad.Logger (NoLoggingT(..)) import Data.Aeson (ToJSON, encode) import Data.ByteString (ByteString) import Database.Persist ((>=.), deleteWhere) import Database.Persist.Sql (toSqlKey) import Database.Persist.Sqlite (runMigration, runSqlConn, withSqliteConn) import Network.HTTP.Types.Method (methodPost, methodPut) import Network.Wai (Application) import Network.Wai.Test (SResponse) import Servant.Server (serve) import Test.Hspec (Spec, describe, hspec, it) import Test.Hspec.Wai ( WaiExpectation, WaiSession, delete, get, matchBody, request , shouldRespondWith, with ) import Lib (BlogPost(..), EntityField(..), blogPostApiProxy, migrateAll, server) -- | These are our actual unit tests. They should be relatively -- straightforward. -- -- This function is using 'app', which in turn accesses our testing -- database. spec :: IO Application -> Spec spec app = with app $ do describe "GET blogpost" $ do it "responds with 200 after inserting something" $ do postJson "/create" testBlogPost `shouldRespondWith` 201 get "/read/1" `shouldRespondWithJson` (200, testBlogPost) it "responds with 404 because nothing has been inserted" $ do get "/read/1" `shouldRespondWith` 404 describe "PUT blogpost" $ do it "responds with 204 even when key doesn't exist in DB" $ do putJson "/update/1" testBlogPost `shouldRespondWith` 204 it "can't GET after PUT" $ do putJson "/update/1" testBlogPost `shouldRespondWith` 204 get "/read/1" `shouldRespondWith` 404 describe "DELETE blogpost" $ do it "responds with 204 even when key doesn't exist in DB" $ do delete "/delete/1" `shouldRespondWith` 204 it "GET after DELETE returns 404" $ do postJson "/create" testBlogPost `shouldRespondWith` 201 get "/read/1" `shouldRespondWith` 200 delete "/delete/1" `shouldRespondWith` 204 get "/read/1" `shouldRespondWith` 404 where -- Send a type that can be turned into JSON (@a@) to the Wai -- 'Application' at the 'ByteString' url. This returns a 'SResponse' -- in the 'WaiSession' monad. This is similar to the 'post' function. postJson :: (ToJSON a) => ByteString -> a -> WaiSession SResponse postJson path = request methodPost path [("Content-Type", "application/json")] . encode -- Similar to 'postJson'. putJson :: (ToJSON a) => ByteString -> a -> WaiSession SResponse putJson path = request methodPut path [("Content-Type", "application/json")] . encode -- Similar to 'shouldRespondWith', but converts the second argument to -- JSON before it compares with the 'SResponse'. shouldRespondWithJson :: (ToJSON a) => WaiSession SResponse -> (Integer, a) -> WaiExpectation shouldRespondWithJson req (expectedStatus, expectedValue) = let matcher = (fromInteger expectedStatus) { matchBody = Just $ encode expectedValue } in shouldRespondWith req matcher -- An example blog post to use in tests. testBlogPost :: BlogPost testBlogPost = BlogPost "title" "content" -- | This is almost identical to the 'defaultMain' defined in "Lib", except -- that is it running against "testing.sqlite" instead of -- "production.sqlite". main :: IO () main = runNoLoggingT $ withSqliteConn "testing.sqlite" $ \conn -> do liftIO $ runSqlConn (runMigration migrateAll) conn liftIO $ putStrLn "\napi running on port 8080..." liftIO $ hspec $ spec $ do -- Before running each test, we have to remove all of the -- existing blog posts from the database. This ensures that -- it doesn't matter which order the tests are run in. runSqlConn (deleteWhere [BlogPostId >=. toSqlKey 0]) conn return . serve blogPostApiProxy $ server conn
cdepillabout/testing-code-that-accesses-db-in-haskell
with-db/testing-db/test/Test.hs
apache-2.0
4,579
0
17
1,069
843
463
380
73
1
{-# LANGUAGE PackageImports #-} {-# LANGUAGE PatternSynonyms #-} {-# LANGUAGE RebindableSyntax #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE NoImplicitPrelude #-} {- 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. -} module Internal.Color where import qualified "codeworld-api" CodeWorld as CW import Internal.Num import Internal.Truth import qualified "base" Prelude as P import "base" Prelude ((.)) -- | A color. -- -- Colors can be described in several ways: -- -- 1. Using common color names: 'red', 'blue', 'yellow', 'green', -- 'orange', 'purple', 'pink', 'black', 'white', 'brown', and -- 'gray'. -- 2. Transforming other colors with functions such as 'light', -- 'dark', 'bright', 'dull', 'translucent', and 'mixed'. -- 3. Constructing colors from coordinates in a color space, such -- as 'RGB', 'RGBA', or 'HSL'. -- -- Note that transparency is included in a color. Common color -- names and the 'RGB' and 'HSL' constructors only produce opaque -- colors, but 'RGBA' and the 'translucent' function work with -- transparency. newtype Color = Color {toCWColor :: CW.Color} deriving (P.Eq) -- | A synonym for 'Color', using the non-US spelling. type Colour = Color {-# RULES "equality/color" forall (x :: Color). (==) x = (P.==) x #-} pattern RGBA :: (Number, Number, Number, Number) -> Color pattern RGBA components <- (toRGBA -> components) where RGBA components = let (r, g, b, a) = components in Color ( CW.RGBA (toDouble r) (toDouble g) (toDouble b) (toDouble a) ) -- Utility function for RGB pattern synonym. toRGBA :: Color -> (Number, Number, Number, Number) toRGBA (Color (CW.RGBA r g b a)) = (fromDouble r, fromDouble g, fromDouble b, fromDouble a) pattern RGB :: (Number, Number, Number) -> Color pattern RGB components <- (toRGB -> P.Just components) where RGB components = let (r, g, b) = components in Color ( CW.RGBA (toDouble r) (toDouble g) (toDouble b) (toDouble 1) ) -- Utility function for RGB pattern synonym. toRGB :: Color -> P.Maybe (Number, Number, Number) toRGB (Color (CW.RGBA r g b (fromDouble -> 1))) = P.Just (fromDouble r, fromDouble g, fromDouble b) toRGB _ = P.Nothing pattern HSL :: (Number, Number, Number) -> Color pattern HSL components <- (toHSL -> P.Just components) where HSL components = fromHSL components -- Utility functions for HSL pattern synonym. toHSL :: Color -> P.Maybe (Number, Number, Number) toHSL c@(RGBA (_, _, _, 1)) = P.Just (hue c, saturation c, luminosity c) toHSL _ = P.Nothing fromHSL :: (Number, Number, Number) -> Color fromHSL (h, s, l) = Color (CW.HSL (toDouble (pi * h / 180)) (toDouble s) (toDouble l)) -- | Produces a color by mixing other colors in equal proportion. -- -- The order of colors is unimportant. Colors may be mixed in uneven -- proportions by listing a color more than once, such as -- @mixed([red, red, orange])@. mixed :: [Color] -> Color mixed = Color . CW.mixed . P.map toCWColor -- | Increases the luminosity of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @lighter(c, 1)@ is always white, regardless of @c@. -- * @lighter(c, 0)@ is the same as @c@. -- * @lighter(c, -1)@ is always black, regardless of @c@. lighter :: (Color, Number) -> Color lighter (c, d) = Color (CW.lighter (toDouble d) (toCWColor c)) -- | Produces a lighter shade of the given color. -- -- This function may be nested more than once to produce an even -- lighter shade, as in @light(light(blue))@. light :: Color -> Color light = Color . CW.light . toCWColor -- | Decreases the luminosity of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @darker(c, 1)@ is always black, regardless of @c@. -- * @darker(c, 0)@ is the same as @c@. -- * @darker(c, -1)@ is always white, regardless of @c@. darker :: (Color, Number) -> Color darker (c, d) = Color (CW.darker (toDouble d) (toCWColor c)) -- | Produces a darker shade of the given color. -- -- This function may be nested more than once to produce an even -- darker shade, as in @dark(dark(green))@. dark :: Color -> Color dark = Color . CW.dark . toCWColor -- | Increases the saturation of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @brighter(c, 1)@ is a fully saturated version of @c@. -- * @brighter(c, 0)@ is the same as @c@. -- * @brighter(c, -1)@ is just a shade of gray with no color. brighter :: (Color, Number) -> Color brighter (c, d) = Color (CW.brighter (toDouble d) (toCWColor c)) -- | Produces a brighter shade of the given color; that is, less -- gray and more colorful. -- -- This function may be nested more than once to produce an even -- brighter shade, as in @bright(bright(yellow))@. bright :: Color -> Color bright = Color . CW.bright . toCWColor -- | Decreases the saturation of a color by the given amount. -- -- The amount should be between -1 and 1, where: -- -- * @duller(c, 1)@ is just a shade of gray with no color. -- * @duller(c, 0)@ is the same as @c@. -- * @duller(c, -1)@ is a fully saturated version of @c@. duller :: (Color, Number) -> Color duller (c, d) = Color (CW.duller (toDouble d) (toCWColor c)) -- | Produces a duller shade of the given color; that is, more -- gray and less colorful. -- -- This function may be nested more than once to produce an even -- duller shade, as in @dull(dull(purple))@. dull :: Color -> Color dull = Color . CW.dull . toCWColor -- | Produces a partially transparent color. -- -- This function may be nested more than once to produce an even -- more transparent color, as in @translucent(translucent(brown))@. translucent :: Color -> Color translucent = Color . CW.translucent . toCWColor -- | An infinite list of various colors. -- -- The list is chosen to contain a variety of different hues as -- spread out as possible to create colorful effects. assortedColors :: [Color] assortedColors = P.map Color CW.assortedColors hue, saturation, luminosity, alpha :: Color -> Number hue = (180 *) . (/ pi) . fromDouble . CW.hue . toCWColor saturation = fromDouble . CW.saturation . toCWColor luminosity = fromDouble . CW.luminosity . toCWColor alpha = fromDouble . CW.alpha . toCWColor -- New style colors -- | The color white white :: Color white = Color CW.white -- | The color black black :: Color black = Color CW.black -- | The color gray gray :: Color gray = Color CW.gray -- | The color grey -- -- This is the same color as 'gray', but with a non-US -- spelling. grey :: Color grey = Color CW.grey -- | The color red red :: Color red = Color CW.red -- | The color orange orange :: Color orange = Color CW.orange -- | The color yellow yellow :: Color yellow = Color CW.yellow -- | The color green green :: Color green = Color CW.green -- | The color blue blue :: Color blue = Color CW.blue -- | The color purple purple :: Color purple = Color CW.purple -- | The color pink pink :: Color pink = Color CW.pink -- | The color brown brown :: Color brown = Color CW.brown
google/codeworld
codeworld-base/src/Internal/Color.hs
apache-2.0
7,724
0
12
1,613
1,446
834
612
108
1
{-# LANGUAGE MultiParamTypeClasses #-} -- |Collections which support efficient bulk insertion. module Data.Collections.BulkInsertable where import qualified Data.Set as S -- |The class of data structures to which can be appended. class BulkInsertable a b where bulkInsert :: a -> b -> b instance Ord a => BulkInsertable [a] (S.Set a) where bulkInsert xs ys = S.fromList xs `S.union` ys instance Ord a => BulkInsertable (S.Set a) (S.Set a) where bulkInsert = S.union instance BulkInsertable [a] [a] where bulkInsert = (++)
jtapolczai/Hephaestos
Data/Collections/BulkInsertable.hs
apache-2.0
541
0
8
99
156
86
70
11
0
{-# LANGUAGE CPP #-} {-# LANGUAGE OverloadedStrings #-} #include "version-compatibility-macros.h" -- | Common symbols composed out of the ASCII subset of Unicode. For non-ASCII -- symbols, see "Prettyprinter.Symbols.Unicode". module Prettyprinter.Symbols.Ascii where import Prettyprinter.Internal -- | >>> squotes "ยท" -- 'ยท' squotes :: Doc ann -> Doc ann squotes = enclose squote squote -- | >>> dquotes "ยท" -- "ยท" dquotes :: Doc ann -> Doc ann dquotes = enclose dquote dquote -- | >>> parens "ยท" -- (ยท) parens :: Doc ann -> Doc ann parens = enclose lparen rparen -- | >>> angles "ยท" -- <ยท> angles :: Doc ann -> Doc ann angles = enclose langle rangle -- | >>> brackets "ยท" -- [ยท] brackets :: Doc ann -> Doc ann brackets = enclose lbracket rbracket -- | >>> braces "ยท" -- {ยท} braces :: Doc ann -> Doc ann braces = enclose lbrace rbrace -- | >>> squote -- ' squote :: Doc ann squote = Char '\'' -- | >>> dquote -- " dquote :: Doc ann dquote = Char '"' -- | >>> lparen -- ( lparen :: Doc ann lparen = Char '(' -- | >>> rparen -- ) rparen :: Doc ann rparen = Char ')' -- | >>> langle -- < langle :: Doc ann langle = Char '<' -- | >>> rangle -- > rangle :: Doc ann rangle = Char '>' -- | >>> lbracket -- [ lbracket :: Doc ann lbracket = Char '[' -- | >>> rbracket -- ] rbracket :: Doc ann rbracket = Char ']' -- | >>> lbrace -- { lbrace :: Doc ann lbrace = Char '{' -- | >>> rbrace -- } rbrace :: Doc ann rbrace = Char '}' -- | >>> semi -- ; semi :: Doc ann semi = Char ';' -- | >>> colon -- : colon :: Doc ann colon = Char ':' -- | >>> comma -- , comma :: Doc ann comma = Char ',' -- | >>> "a" <> space <> "b" -- a b -- -- This is mostly used via @'<+>'@, -- -- >>> "a" <+> "b" -- a b space :: Doc ann space = Char ' ' -- | >>> dot -- . dot :: Doc ann dot = Char '.' -- | >>> slash -- / slash :: Doc ann slash = Char '/' -- | >>> backslash -- \\ backslash :: Doc ann backslash = "\\" -- | >>> equals -- = equals :: Doc ann equals = Char '=' -- | >>> pipe -- | pipe :: Doc ann pipe = Char '|' -- $setup -- -- (Definitions for the doctests) -- -- >>> :set -XOverloadedStrings -- >>> import Data.Semigroup -- >>> import Prettyprinter.Render.Text -- >>> import Prettyprinter.Util
quchen/prettyprinter
prettyprinter/src/Prettyprinter/Symbols/Ascii.hs
bsd-2-clause
2,232
0
6
508
531
299
232
54
1
{- This module is used to preprocess the AST before we - actually use it -} module DuckTest.AST.Preprocess (preprocess) where import DuckTest.Internal.Common import DuckTest.AST.Util import DuckTest.AST.BinaryOperators import qualified Data.Map as Map dunderFunctions :: Map String String dunderFunctions = Map.fromList [ ("len", "__len__"), ("str", "__str__"), ("int", "__int__") ] preprocess :: [Statement e] -> [Statement e] preprocess = map (mapExpressions proc) where proc (BinaryOp op@(In _) ex1 ex2 pos) = {- The in operator is backwards -} mapExpressions proc $ Call (Dot ex2 (Ident (toDunderName op) pos) pos) [ArgExpr ex1 pos] pos proc (BinaryOp op ex1 ex2 pos) = {- Convert all binary operators to their actual function calls - to make things easier -} mapExpressions proc $ Call (Dot ex1 (Ident (toDunderName op) pos) pos) [ArgExpr ex2 pos] pos proc ex@(Call (Var (Ident str _) _) [ArgExpr ex1 _] pos) {- Change known calls to dunder attributes. -} = mapExpressions proc $ maybe' (Map.lookup str dunderFunctions) ex $ \dunder -> Call (Dot ex1 (Ident dunder pos) pos) [] pos {- Expand out literals into functions -} proc ex@(Int _ _ pos) = Call (Var (Ident "int" pos) pos) [ArgExpr ex pos] pos proc ex@(Strings _ pos) = Call (Var (Ident "str" pos) pos) [ArgExpr ex pos] pos proc ex = mapExpressions proc ex
jrahm/DuckTest
src/DuckTest/AST/Preprocess.hs
bsd-2-clause
1,593
0
14
487
486
255
231
27
6
module Kis ( KisRequest(..) , KisConfig(..) , KisClient , Kis(..) , KisException(..) , KisClock(..) , KisRead(..) , KisWrite(..) , NotificationHandler(..) , SqliteBackendType(..) , constClock , realTimeClock , runClient , runSingleClientSqlite , runKis , withSqliteKis , withSqliteKisWithNotifs , module Kis.Model ) where import Kis.Kis import Kis.Model import Kis.Notifications import Kis.Time import Kis.SqliteBackend import Control.Concurrent.Async import Control.Monad.RWS import qualified Data.Text as T runKis :: [KisClient IO a] -> [NotificationHandler] -> T.Text -> IO () runKis clients notifHandlers dbFile = withSqliteKisWithNotifs poolbackend kisConfig notifHandlers $ \kis -> do allClients <- forM clients $ \client -> async (runClient kis client) mapM_ wait allClients where poolbackend = PoolBackendType dbFile 10 kisConfig = KisConfig realTimeClock
lslah/kis-proto
src/Kis.hs
bsd-3-clause
983
0
14
228
265
157
108
34
1
-- Copyright (c) 2016-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. {-# LANGUAGE GADTs #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE OverloadedStrings #-} module Duckling.AmountOfMoney.EN.TT.Rules ( rules ) where import Data.HashMap.Strict (HashMap) import Data.String import Data.Text (Text) import Prelude import Duckling.AmountOfMoney.Helpers import Duckling.AmountOfMoney.Types (Currency(..)) import Duckling.Numeral.Helpers (isPositive) import Duckling.Regex.Types import Duckling.Types import qualified Data.HashMap.Strict as HashMap import qualified Data.Text as Text import qualified Duckling.AmountOfMoney.Helpers as Helpers import qualified Duckling.Numeral.Types as TNumeral ruleAGrand :: Rule ruleAGrand = Rule { name = "a grand" , pattern = [ regex "a grand" ] , prod = \_ -> Just . Token AmountOfMoney . withValue 1000 $ currencyOnly TTD } ruleGrand :: Rule ruleGrand = Rule { name = "<amount> grand" , pattern = [ Predicate isPositive , regex "grand" ] , prod = \case (Token Numeral TNumeral.NumeralData{TNumeral.value = v}:_) -> Just . Token AmountOfMoney . withValue (1000 * v) $ currencyOnly TTD _ -> Nothing } ruleDollarCoin :: Rule ruleDollarCoin = Rule { name = "dollar coin" , pattern = [ regex "(nickel|dime|quarter)s?" ] , prod = \tokens -> case tokens of (Token RegexMatch (GroupMatch (match:_)):_) -> do c <- HashMap.lookup (Text.toLower match) Helpers.dollarCoins Just . Token AmountOfMoney . withValue c $ currencyOnly TTD _ -> Nothing } rules :: [Rule] rules = [ ruleAGrand , ruleGrand , ruleDollarCoin ]
facebookincubator/duckling
Duckling/AmountOfMoney/EN/TT/Rules.hs
bsd-3-clause
1,819
0
17
390
452
264
188
51
2
-- | -- Module: Control.Wire.Event -- Copyright: (c) 2013 Ertugrul Soeylemez -- License: BSD3 -- Maintainer: Ertugrul Soeylemez <es@ertes.de> module Control.Wire.Event ( -- * Events Event, -- * Time-based at, never, now, periodic, periodicList, -- * Signal analysis became, noLonger, edge, -- * Modifiers (<&), (&>), dropE, dropWhileE, filterE, merge, mergeL, mergeR, notYet, once, takeE, takeWhileE, -- * Scans accumE, accum1E, iterateE, -- ** Special scans maximumE, minimumE, productE, sumE ) where import Control.Applicative import Control.Arrow import Control.Monad.Fix import Control.Wire.Core import Control.Wire.Session import Control.Wire.Unsafe.Event import Data.Fixed -- | Merge events with the leftmost event taking precedence. Equivalent -- to using the monoid interface with 'First'. Infixl 5. -- -- * Depends: now on both. -- -- * Inhibits: when any of the two wires inhibit. (<&) :: (Monad m) => Wire s e m a (Event b) -> Wire s e m a (Event b) -> Wire s e m a (Event b) (<&) = liftA2 (merge const) infixl 5 <& -- | Merge events with the rightmost event taking precedence. -- Equivalent to using the monoid interface with 'Last'. Infixl 5. -- -- * Depends: now on both. -- -- * Inhibits: when any of the two wires inhibit. (&>) :: (Monad m) => Wire s e m a (Event b) -> Wire s e m a (Event b) -> Wire s e m a (Event b) (&>) = liftA2 (merge (const id)) infixl 5 &> -- | Left scan for events. Each time an event occurs, apply the given -- function. -- -- * Depends: now. accumE :: (b -> a -> b) -- ^ Fold function -> b -- ^ Initial value. -> Wire s e m (Event a) (Event b) accumE f = loop' where loop' x' = mkSFN $ event (NoEvent, loop' x') (\y -> let x = f x' y in (Event x, loop' x)) -- | Left scan for events with no initial value. Each time an event -- occurs, apply the given function. The first event is produced -- unchanged. -- -- * Depends: now. accum1E :: (a -> a -> a) -- ^ Fold function -> Wire s e m (Event a) (Event a) accum1E f = initial where initial = mkSFN $ event (NoEvent, initial) (Event &&& accumE f) -- | At the given point in time. -- -- * Depends: now when occurring. at :: (HasTime t s) => t -- ^ Time of occurrence. -> Wire s e m a (Event a) at t' = mkSF $ \ds x -> let t = t' - dtime ds in if t <= 0 then (Event x, never) else (NoEvent, at t) -- | Occurs each time the predicate becomes true for the input signal, -- for example each time a given threshold is reached. -- -- * Depends: now. became :: (a -> Bool) -> Wire s e m a (Event a) became p = off where off = mkSFN $ \x -> if p x then (Event x, on) else (NoEvent, off) on = mkSFN $ \x -> (NoEvent, if p x then on else off) -- | Forget the first given number of occurrences. -- -- * Depends: now. dropE :: Int -> Wire s e m (Event a) (Event a) dropE n | n <= 0 = mkId dropE n = fix $ \again -> mkSFN $ \mev -> (NoEvent, if occurred mev then dropE (pred n) else again) -- | Forget all initial occurrences until the given predicate becomes -- false. -- -- * Depends: now. dropWhileE :: (a -> Bool) -> Wire s e m (Event a) (Event a) dropWhileE p = fix $ \again -> mkSFN $ \mev -> case mev of Event x | not (p x) -> (mev, mkId) _ -> (NoEvent, again) -- | Forget all occurrences for which the given predicate is false. -- -- * Depends: now. filterE :: (a -> Bool) -> Wire s e m (Event a) (Event a) filterE p = mkSF_ $ \mev -> case mev of Event x | p x -> mev _ -> NoEvent -- | On each occurrence, apply the function the event carries. -- -- * Depends: now. iterateE :: a -> Wire s e m (Event (a -> a)) (Event a) iterateE = accumE (\x f -> f x) -- | Maximum of all events. -- -- * Depends: now. maximumE :: (Ord a) => Wire s e m (Event a) (Event a) maximumE = accum1E max -- | Minimum of all events. -- -- * Depends: now. minimumE :: (Ord a) => Wire s e m (Event a) (Event a) minimumE = accum1E min -- | Left-biased event merge. mergeL :: Event a -> Event a -> Event a mergeL = merge const -- | Right-biased event merge. mergeR :: Event a -> Event a -> Event a mergeR = merge (const id) -- | Never occurs. never :: Wire s e m a (Event b) never = mkConst (Right NoEvent) -- | Occurs each time the predicate becomes false for the input signal, -- for example each time a given threshold is no longer exceeded. -- -- * Depends: now. noLonger :: (a -> Bool) -> Wire s e m a (Event a) noLonger p = off where off = mkSFN $ \x -> if p x then (NoEvent, off) else (Event x, on) on = mkSFN $ \x -> (NoEvent, if p x then off else on) -- | Events occur first when the predicate is false then when it is -- true, and then this pattern repeats. -- -- * Depends: now. edge :: (a -> Bool) -> Wire s e m a (Event a) edge p = off where off = mkSFN $ \x -> if p x then (Event x, on) else (NoEvent, off) on = mkSFN $ \x -> if p x then (NoEvent, on) else (Event x, off) -- | Forget the first occurrence. -- -- * Depends: now. notYet :: Wire s e m (Event a) (Event a) notYet = mkSFN $ event (NoEvent, notYet) (const (NoEvent, mkId)) -- | Occurs once immediately. -- -- * Depends: now when occurring. now :: Wire s e m a (Event a) now = mkSFN $ \x -> (Event x, never) -- | Forget all occurrences except the first. -- -- * Depends: now when occurring. once :: Wire s e m (Event a) (Event a) once = mkSFN $ \mev -> (mev, if occurred mev then never else once) -- | Periodic occurrence with the given time period. First occurrence -- is now. -- -- * Depends: now when occurring. periodic :: (HasTime t s) => t -> Wire s e m a (Event a) periodic int | int <= 0 = error "periodic: Non-positive interval" periodic int = mkSFN $ \x -> (Event x, loop' int) where loop' 0 = loop' int loop' t' = mkSF $ \ds x -> let t = t' - dtime ds in if t <= 0 then (Event x, loop' (mod' t int)) else (NoEvent, loop' t) -- | Periodic occurrence with the given time period. First occurrence -- is now. The event values are picked one by one from the given list. -- When the list is exhausted, the event does not occur again. periodicList :: (HasTime t s) => t -> [b] -> Wire s e m a (Event b) periodicList int _ | int <= 0 = error "periodic: Non-positive interval" periodicList _ [] = never periodicList int (x:xs) = mkSFN $ \_ -> (Event x, loop' int xs) where loop' _ [] = never loop' 0 xs' = loop' int xs' loop' t' xs0@(x':xs') = mkSF $ \ds _ -> let t = t' - dtime ds in if t <= 0 then (Event x', loop' (mod' t int) xs') else (NoEvent, loop' t xs0) -- | Product of all events. -- -- * Depends: now. productE :: (Num a) => Wire s e m (Event a) (Event a) productE = accumE (*) 1 -- | Sum of all events. -- -- * Depends: now. sumE :: (Num a) => Wire s e m (Event a) (Event a) sumE = accumE (+) 0 -- | Forget all but the first given number of occurrences. -- -- * Depends: now. takeE :: Int -> Wire s e m (Event a) (Event a) takeE n | n <= 0 = never takeE n = fix $ \again -> mkSFN $ \mev -> (mev, if occurred mev then takeE (pred n) else again) -- | Forget all but the initial occurrences for which the given -- predicate is true. -- -- * Depends: now. takeWhileE :: (a -> Bool) -> Wire s e m (Event a) (Event a) takeWhileE p = fix $ \again -> mkSFN $ \mev -> case mev of Event x | not (p x) -> (NoEvent, never) _ -> (mev, again)
Teaspot-Studio/netwire
Control/Wire/Event.hs
bsd-3-clause
7,886
0
17
2,306
2,538
1,385
1,153
159
4
{-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE Rank2Types #-} ----------------------------------------------------------------------------- -- | -- Copyright : Andrew Martin -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Andrew Martin <andrew.thaddeus@gmail.com> -- Stability : experimental -- Portability : non-portable -- -- There are two vector types provided by this module: 'Vector' and -- 'MVector'. They must be parameterized over a type that unifies -- with 'Rec Identity rs'. An example would be: -- -- > foo :: Vector (Rec Identity '[Int,Char,Bool]) -- -- This vector stores records that have an 'Int', a 'Char', and a 'Bool'. ----------------------------------------------------------------------------- module Data.Vector.Vinyl.Default.Empty.Monomorphic ( Vector, MVector -- * Accessors -- ** Length information , length, null -- ** Indexing , (!), (!?), head, last , unsafeIndex, unsafeHead, unsafeLast -- ** Monadic indexing , indexM, headM, lastM , unsafeIndexM, unsafeHeadM, unsafeLastM -- ** Extracting subvectors (slicing) , slice, init, tail, take, drop, splitAt , unsafeSlice, unsafeInit, unsafeTail, unsafeTake, unsafeDrop -- * Construction -- ** Initialisation , empty, singleton, replicate, generate, iterateN -- ** Monadic initialisation , replicateM, generateM, create -- ** Unfolding , unfoldr, unfoldrN , constructN, constructrN -- -- ** Enumeration -- , enumFromN, enumFromStepN, enumFromTo, enumFromThenTo -- ** Concatenation , cons, snoc, (++), concat -- ** Restricting memory usage , force -- * Modifying vectors -- ** Bulk updates , (//) , unsafeUpd -- , update_, unsafeUpdate_ -- ** Accumulations , accum, unsafeAccum -- , accumulate_, unsafeAccumulate_ -- ** Permutations , reverse -- , backpermute, unsafeBackpermute -- ** Safe destructive updates , modify -- * Elementwise operations -- ** Mapping , map, imap, concatMap -- ** Monadic mapping , mapM, mapM_, forM, forM_ -- ** Zipping - Omitted due to me being lazy -- , zipWith, zipWith3, zipWith4, zipWith5, zipWith6 -- , izipWith, izipWith3, izipWith4, izipWith5, izipWith6 -- ** Monadic zipping , zipWithM, zipWithM_ -- * Working with predicates -- ** Filtering , filter, ifilter, filterM , takeWhile, dropWhile -- ** Partitioning , partition, unstablePartition, span, break -- ** Searching , elem, notElem, find, findIndex , elemIndex -- , findIndices, elemIndices -- * Folding , foldl, foldl1, foldl', foldl1', foldr, foldr1, foldr', foldr1' , ifoldl, ifoldl', ifoldr, ifoldr' -- ** Specialised folds , all, any -- , sum, product , maximum, maximumBy, minimum, minimumBy , minIndex, minIndexBy, maxIndex, maxIndexBy -- ** Monadic folds , foldM, foldM', fold1M, fold1M' , foldM_, foldM'_, fold1M_, fold1M'_ -- * Prefix sums (scans) , prescanl, prescanl' , postscanl, postscanl' , scanl, scanl', scanl1, scanl1' , prescanr, prescanr' , postscanr, postscanr' , scanr, scanr', scanr1, scanr1' -- ** Lists , toList, fromList, fromListN -- ** Other vector types , G.convert -- ** Mutable vectors , freeze, thaw, copy, unsafeFreeze, unsafeThaw, unsafeCopy ) where import Control.Monad.Primitive import Control.Monad.ST import Data.Vector.Vinyl.Default.Empty.Monomorphic.Internal import Data.Vinyl.Core import Data.Vinyl.Functor (Identity(..)) import qualified Data.Vector.Generic as G import Prelude hiding ( length, null, replicate, (++), concat, head, last, init, tail, take, drop, splitAt, reverse, map, concatMap, zipWith, zipWith3, zip, zip3, unzip, unzip3, filter, takeWhile, dropWhile, span, break, elem, notElem, foldl, foldl1, foldr, foldr1, all, any, sum, product, minimum, maximum, scanl, scanl1, scanr, scanr1, enumFromTo, enumFromThenTo, mapM, mapM_ ) -- Length -- ------ -- | /O(1)/ Yield the length of the vector. length :: Vector (Rec Identity rs) -> Int length (V i _) = i {-# INLINE length #-} -- | /O(1)/ Test whether a vector if empty null :: Vector (Rec Identity rs) -> Bool null (V i _) = i == 0 {-# INLINE null #-} -- Indexing -- -------- -- | O(1) Indexing (!) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Int -> Rec Identity rs (!) = (G.!) {-# INLINE (!) #-} -- | O(1) Safe indexing (!?) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Int -> Maybe (Rec Identity rs) (!?) = (G.!?) {-# INLINE (!?) #-} -- | /O(1)/ First element head :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs head = G.head {-# INLINE head #-} -- | /O(1)/ Last element last :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs last = G.last {-# INLINE last #-} -- | /O(1)/ Unsafe indexing without bounds checking unsafeIndex :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Int -> Rec Identity rs {-# INLINE unsafeIndex #-} unsafeIndex = G.unsafeIndex -- | /O(1)/ First element without checking if the vector is empty unsafeHead :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE unsafeHead #-} unsafeHead = G.unsafeHead -- | /O(1)/ Last element without checking if the vector is empty unsafeLast :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE unsafeLast #-} unsafeLast = G.unsafeLast -- Monadic indexing -- ---------------- -- | /O(1)/ Indexing in a monad. -- -- The monad allows operations to be strict in the vector when necessary. -- Suppose vector copying is implemented like this: -- -- > copy mv v = ... write mv i (v ! i) ... -- -- For lazy vectors, @v ! i@ would not be evaluated which means that @mv@ -- would unnecessarily retain a reference to @v@ in each element written. -- -- With 'indexM', copying can be implemented like this instead: -- -- > copy mv v = ... do -- > x <- indexM v i -- > write mv i x -- -- Here, no references to @v@ are retained because indexing (but /not/ the -- elements) is evaluated eagerly. -- indexM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> Int -> m (Rec Identity rs) indexM = G.indexM {-# INLINE indexM #-} -- | /O(1)/ First element of a vector in a monad. See 'indexM' for an -- explanation of why this is useful. headM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) headM = G.headM {-# INLINE headM #-} -- | /O(1)/ Last element of a vector in a monad. See 'indexM' for an -- explanation of why this is useful. lastM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) lastM = G.lastM {-# INLINE lastM #-} -- | /O(1)/ Indexing in a monad without bounds checks. See 'indexM' for an -- explanation of why this is useful. unsafeIndexM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> Int -> m (Rec Identity rs) unsafeIndexM = G.unsafeIndexM {-# INLINE unsafeIndexM #-} -- | /O(1)/ First element in a monad without checking for empty vectors. -- See 'indexM' for an explanation of why this is useful. unsafeHeadM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) unsafeHeadM = G.unsafeHeadM {-# INLINE unsafeHeadM #-} -- | /O(1)/ Last element in a monad without checking for empty vectors. -- See 'indexM' for an explanation of why this is useful. unsafeLastM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (Rec Identity rs) unsafeLastM = G.unsafeLastM {-# INLINE unsafeLastM #-} -- Extracting subvectors (slicing) -- ------------------------------- -- | /O(1)/ Yield a slice of the vector without copying it. The vector must -- contain at least @i+n@ elements. slice :: G.Vector Vector (Rec Identity rs) => Int -- ^ @i@ starting index -> Int -- ^ @n@ length -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) slice = G.slice {-# INLINE slice #-} -- | /O(1)/ Yield all but the last element without copying. The vector may not -- be empty. init :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) init = G.init {-# INLINE init #-} -- | /O(1)/ Yield all but the first element without copying. The vector may not -- be empty. tail :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) tail = G.tail {-# INLINE tail #-} -- | /O(1)/ Yield at the first @n@ elements without copying. The vector may -- contain less than @n@ elements in which case it is returned unchanged. take :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) take = G.take {-# INLINE take #-} -- | /O(1)/ Yield all but the first @n@ elements without copying. The vector may -- contain less than @n@ elements in which case an empty vector is returned. drop :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) drop = G.drop {-# INLINE drop #-} -- | /O(1)/ Yield the first @n@ elements paired with the remainder without copying. -- -- Note that @'splitAt' n v@ is equivalent to @('take' n v, 'drop' n v)@ -- but slightly more efficient. splitAt :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) splitAt = G.splitAt {-# INLINE splitAt #-} -- | /O(1)/ Yield a slice of the vector without copying. The vector must -- contain at least @i+n@ elements but this is not checked. unsafeSlice :: G.Vector Vector (Rec Identity rs) => Int -- ^ @i@ starting index -> Int -- ^ @n@ length -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeSlice = G.unsafeSlice {-# INLINE unsafeSlice #-} -- | /O(1)/ Yield all but the last element without copying. The vector may not -- be empty but this is not checked. unsafeInit :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeInit = G.unsafeInit {-# INLINE unsafeInit #-} -- | /O(1)/ Yield all but the first element without copying. The vector may not -- be empty but this is not checked. unsafeTail :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeTail = G.unsafeTail {-# INLINE unsafeTail #-} -- | /O(1)/ Yield the first @n@ elements without copying. The vector must -- contain at least @n@ elements but this is not checked. unsafeTake :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeTake = G.unsafeTake {-# INLINE unsafeTake #-} -- | /O(1)/ Yield all but the first @n@ elements without copying. The vector -- must contain at least @n@ elements but this is not checked. unsafeDrop :: G.Vector Vector (Rec Identity rs) => Int -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) unsafeDrop = G.unsafeDrop {-# INLINE unsafeDrop #-} -- Initialisation -- -------------- -- | /O(1)/ Empty vector empty :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) empty = G.empty {-# INLINE empty #-} -- | /O(1)/ Vector with exactly one element singleton :: G.Vector Vector (Rec Identity rs) => Rec Identity rs -> Vector (Rec Identity rs) singleton = G.singleton {-# INLINE singleton #-} -- | /O(n)/ Vector of the given length with the same value in each position replicate :: G.Vector Vector (Rec Identity rs) => Int -> Rec Identity rs -> Vector (Rec Identity rs) replicate = G.replicate {-# INLINE replicate #-} -- | /O(n)/ Construct a vector of the given length by applying the function to -- each index generate :: G.Vector Vector (Rec Identity rs) => Int -> (Int -> Rec Identity rs) -> Vector (Rec Identity rs) generate = G.generate {-# INLINE generate #-} -- | /O(n)/ Apply function n times to value. Zeroth element is original value. iterateN :: G.Vector Vector (Rec Identity rs) => Int -> (Rec Identity rs -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity rs) iterateN = G.iterateN {-# INLINE iterateN #-} -- Unfolding -- --------- -- | /O(n)/ Construct a vector by repeatedly applying the generator function -- to a seed. The generator function yields 'Just' the next element and the -- new seed or 'Nothing' if there are no more elements. -- -- > unfoldr (\n -> if n == 0 then Nothing else Just (n,n-1)) 10 -- > = <10,9,8,7,6,5,4,3,2,1> unfoldr :: G.Vector Vector (Rec Identity rs) => (c -> Maybe (Rec Identity rs, c)) -> c -> Vector (Rec Identity rs) unfoldr = G.unfoldr {-# INLINE unfoldr #-} -- | /O(n)/ Construct a vector with at most @n@ by repeatedly applying the -- generator function to the a seed. The generator function yields 'Just' the -- next element and the new seed or 'Nothing' if there are no more elements. -- -- > unfoldrN 3 (\n -> Just (n,n-1)) 10 = <10,9,8> unfoldrN :: G.Vector Vector (Rec Identity rs) => Int -> (c -> Maybe (Rec Identity rs, c)) -> c -> Vector (Rec Identity rs) unfoldrN = G.unfoldrN {-# INLINE unfoldrN #-} -- | /O(n)/ Construct a vector with @n@ elements by repeatedly applying the -- generator function to the already constructed part of the vector. -- -- > constructN 3 f = let a = f <> ; b = f <a> ; c = f <a,b> in f <a,b,c> -- constructN :: G.Vector Vector (Rec Identity rs) => Int -> (Vector (Rec Identity rs) -> Rec Identity rs) -> Vector (Rec Identity rs) constructN = G.constructN {-# INLINE constructN #-} -- | /O(n)/ Construct a vector with @n@ elements from right to left by -- repeatedly applying the generator function to the already constructed part -- of the vector. -- -- > constructrN 3 f = let a = f <> ; b = f<a> ; c = f <b,a> in f <c,b,a> -- constructrN :: G.Vector Vector (Rec Identity rs) => Int -> (Vector (Rec Identity rs) -> Rec Identity rs) -> Vector (Rec Identity rs) constructrN = G.constructrN {-# INLINE constructrN #-} -- Concatenation -- ------------- -- | /O(n)/ Prepend an element cons :: G.Vector Vector (Rec Identity rs) => Rec Identity rs -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE cons #-} cons = G.cons -- | /O(n)/ Append an element snoc :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity rs) {-# INLINE snoc #-} snoc = G.snoc infixr 5 ++ -- | /O(m+n)/ Concatenate two vectors (++) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE (++) #-} (++) = (G.++) -- | /O(n)/ Concatenate all vectors in the list concat :: G.Vector Vector (Rec Identity rs) => [Vector (Rec Identity rs)] -> Vector (Rec Identity rs) {-# INLINE concat #-} concat = G.concat -- Monadic initialisation -- ---------------------- -- | /O(n)/ Execute the monadic action the given number of times and store the -- results in a vector. replicateM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Int -> m (Rec Identity rs) -> m (Vector (Rec Identity rs)) replicateM = G.replicateM {-# INLINE replicateM #-} -- | /O(n)/ Construct a vector of the given length by applying the monadic -- action to each index generateM :: (Monad m, G.Vector Vector (Rec Identity rs)) => Int -> (Int -> m (Rec Identity rs)) -> m (Vector (Rec Identity rs)) generateM = G.generateM {-# INLINE generateM #-} -- | Execute the monadic action and freeze the resulting vector. -- -- @ -- create (do { v \<- new 2; write v 0 \'a\'; write v 1 \'b\'; return v }) = \<'a','b'\> -- @ create :: G.Vector Vector (Rec Identity rs) => (forall s. ST s (G.Mutable Vector s (Rec Identity rs))) -> Vector (Rec Identity rs) -- NOTE: eta-expanded due to http://hackage.haskell.org/trac/ghc/ticket/4120 create p = G.create p {-# INLINE create #-} -- Restricting memory usage -- ------------------------ -- | /O(n)/ Yield the argument but force it not to retain any extra memory, -- possibly by copying it. -- -- This is especially useful when dealing with slices. For example: -- -- > force (slice 0 2 <huge vector>) -- -- Here, the slice retains a reference to the huge vector. Forcing it creates -- a copy of just the elements that belong to the slice and allows the huge -- vector to be garbage collected. force :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) force = G.force {-# INLINE force #-} -- Bulk updates -- ------------ -- | /O(m+n)/ For each pair @(i,a)@ from the list, replace the vector -- element at position @i@ by @a@. -- -- > <5,9,2,7> // [(2,1),(0,3),(2,8)] = <3,9,8,7> -- (//) :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -- ^ initial vector (of length @m@) -> [(Int, Rec Identity rs)] -- ^ list of index/value pairs (of length @n@) -> Vector (Rec Identity rs) (//) = (G.//) {-# INLINE (//) #-} -- | Same as ('//') but without bounds checking. unsafeUpd :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> [(Int, Rec Identity rs)] -> Vector (Rec Identity rs) unsafeUpd = G.unsafeUpd {-# INLINE unsafeUpd #-} -- Accumulations -- ------------- -- | /O(m+n)/ For each pair @(i,c)@ from the list, replace the vector element -- @a@ at position @i@ by @f a c@. -- -- > accum (+) <5,9,2> [(2,4),(1,6),(0,3),(1,7)] = <5+3, 9+6+7, 2+4> accum :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> c -> Rec Identity rs) -- ^ accumulating function @f@ -> Vector (Rec Identity rs) -- ^ initial vector (of length @m@) -> [(Int,c)] -- ^ list of index/value pairs (of length @n@) -> Vector (Rec Identity rs) accum = G.accum {-# INLINE accum #-} -- | Same as 'accum' but without bounds checking. unsafeAccum :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> c -> Rec Identity rs) -> Vector (Rec Identity rs) -> [(Int,c)] -> Vector (Rec Identity rs) unsafeAccum = G.unsafeAccum {-# INLINE unsafeAccum #-} -- Permutations -- ------------ -- | /O(n)/ Reverse a vector reverse :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE reverse #-} reverse = G.reverse -- Safe destructive updates -- ------------------------ -- | Apply a destructive operation to a vector. The operation will be -- performed in place if it is safe to do so and will modify a copy of the -- vector otherwise. -- -- @ -- modify (\\v -> write v 0 \'x\') ('replicate' 3 \'a\') = \<\'x\',\'a\',\'a\'\> -- @ modify :: (G.Vector Vector (Rec Identity rs)) => (forall s. G.Mutable Vector s (Rec Identity rs) -> ST s ()) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE modify #-} modify p = G.modify p -- Mapping -- ------- -- | /O(n)/ Map a function over a vector map :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) map = G.map {-# INLINE map #-} -- | /O(n)/ Apply a function to every element of a vector and its index imap :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Int -> Rec Identity rs -> Rec Identity ss) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) imap = G.imap {-# INLINE imap #-} -- | Map a function over a vector and concatenate the results. concatMap :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Vector (Rec Identity ss)) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) concatMap = G.concatMap {-# INLINE concatMap #-} -- Monadic mapping -- --------------- -- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a -- vector of results mapM :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> m (Rec Identity ss)) -> Vector (Rec Identity rs) -> m (Vector (Rec Identity ss)) mapM = G.mapM {-# INLINE mapM #-} -- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the -- results mapM_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> m b) -> Vector (Rec Identity rs) -> m () mapM_ = G.mapM_ {-# INLINE mapM_ #-} -- | /O(n)/ Apply the monadic action to all elements of the vector, yielding a -- vector of results. Equvalent to @flip 'mapM'@. forM :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => Vector (Rec Identity rs) -> (Rec Identity rs -> m (Rec Identity ss)) -> m (Vector (Rec Identity ss)) forM = G.forM {-# INLINE forM #-} -- | /O(n)/ Apply the monadic action to all elements of a vector and ignore the -- results. Equivalent to @flip 'mapM_'@. forM_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> (Rec Identity rs -> m b) -> m () forM_ = G.forM_ {-# INLINE forM_ #-} -- Zipping -- ------- -- -- | /O(min(m,n))/ Zip two vectors with the given function. -- zipWith :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- ) => ((a,a') -> (b,b') -> (c,c')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -- zipWith = G.zipWith -- {-# INLINE zipWith #-} -- -- -- | Zip three vectors with the given function. -- -- zipWith3 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -- zipWith3 = G.zipWith3 -- {-# INLINE zipWith3 #-} -- -- zipWith4 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -- zipWith4 = G.zipWith4 -- {-# INLINE zipWith4 #-} -- -- zipWith5 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -- zipWith5 = G.zipWith5 -- {-# INLINE zipWith5 #-} -- -- zipWith6 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- , G.Vector u g, G.Vector v g' -- ) => ((a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f') -> (g,g')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -> Vector u v (g,g') -- zipWith6 = G.zipWith6 -- {-# INLINE zipWith6 #-} -- -- -- | /O(min(m,n))/ Zip two vectors with a function that also takes the -- -- elements' indices. -- izipWith :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- ) => (Int -> (a,a') -> (b,b') -> (c,c')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -- izipWith = G.izipWith -- {-# INLINE izipWith #-} -- -- -- | Zip three vectors and their indices with the given function. -- izipWith3 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -- izipWith3 = G.izipWith3 -- {-# INLINE izipWith3 #-} -- -- izipWith4 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -- izipWith4 = G.izipWith4 -- {-# INLINE izipWith4 #-} -- -- izipWith5 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -- izipWith5 = G.izipWith5 -- {-# INLINE izipWith5 #-} -- -- izipWith6 :: ( G.Vector u a, G.Vector v a' -- , G.Vector u b, G.Vector v b' -- , G.Vector u c, G.Vector v c' -- , G.Vector u d, G.Vector v d' -- , G.Vector u e, G.Vector v e' -- , G.Vector u f, G.Vector v f' -- , G.Vector u g, G.Vector v g' -- ) => (Int -> (a,a') -> (b,b') -> (c,c') -> (d, d') -> (e,e') -> (f,f') -> (g,g')) -- -> Vector u v (a,a') -> Vector u v (b,b') -> Vector u v (c,c') -> Vector u v (d,d') -> Vector u v (e,e') -> Vector u v (f,f') -> Vector u v (g,g') -- izipWith6 = G.izipWith6 -- {-# INLINE izipWith6 #-} -- Monadic zipping -- --------------- -- | /O(min(m,n))/ Zip the two vectors with the monadic action and yield a -- vector of results zipWithM :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss), G.Vector Vector (Rec Identity ts)) => (Rec Identity rs -> Rec Identity ss -> m (Rec Identity ts)) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) -> m (Vector (Rec Identity ts)) zipWithM = G.zipWithM {-# INLINE zipWithM #-} -- | /O(min(m,n))/ Zip the two vectors with the monadic action and ignore the -- results zipWithM_ :: (Monad m, G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> m e) -> Vector (Rec Identity rs) -> Vector (Rec Identity ss)-> m () zipWithM_ = G.zipWithM_ {-# INLINE zipWithM_ #-} -- Filtering -- --------- -- | /O(n)/ Drop elements that do not satisfy the predicate filter :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) filter = G.filter {-# INLINE filter #-} -- | /O(n)/ Drop elements that do not satisfy the predicate which is applied to -- values and their indices ifilter :: G.Vector Vector (Rec Identity rs) => (Int -> Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) ifilter = G.ifilter {-# INLINE ifilter #-} -- | /O(n)/ Drop elements that do not satisfy the monadic predicate filterM :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> m Bool) -> Vector (Rec Identity rs) -> m (Vector (Rec Identity rs)) filterM = G.filterM {-# INLINE filterM #-} -- | /O(n)/ Yield the longest prefix of elements satisfying the predicate -- without copying. takeWhile :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) takeWhile = G.takeWhile {-# INLINE takeWhile #-} -- | /O(n)/ Drop the longest prefix of elements that satisfy the predicate -- without copying. dropWhile :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) dropWhile = G.dropWhile {-# INLINE dropWhile #-} -- Parititioning -- ------------- -- | /O(n)/ Split the vector in two parts, the first one containing those -- elements that satisfy the predicate and the second one those that don't. The -- relative order of the elements is preserved at the cost of a sometimes -- reduced performance compared to 'unstablePartition'. partition :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE partition #-} partition = G.partition -- | /O(n)/ Split the vector in two parts, the first one containing those -- elements that satisfy the predicate and the second one those that don't. -- The order of the elements is not preserved but the operation is often -- faster than 'partition'. unstablePartition :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE unstablePartition #-} unstablePartition = G.unstablePartition -- | /O(n)/ Split the vector into the longest prefix of elements that satisfy -- the predicate and the rest without copying. span :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE span #-} span = G.span -- | /O(n)/ Split the vector into the longest prefix of elements that do not -- satisfy the predicate and the rest without copying. break :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> (Vector (Rec Identity rs), Vector (Rec Identity rs)) {-# INLINE break #-} break = G.break -- Searching -- --------- infix 4 `elem` -- | /O(n)/ Check if the vector contains an element elem :: (G.Vector Vector (Rec Identity rs), Eq (Rec Identity rs)) => Rec Identity rs -> Vector (Rec Identity rs) -> Bool elem = G.elem {-# INLINE elem #-} infix 4 `notElem` -- | /O(n)/ Check if the vector does not contain an element (inverse of 'elem') notElem :: (G.Vector Vector (Rec Identity rs), Eq (Rec Identity rs)) => Rec Identity rs -> Vector (Rec Identity rs) -> Bool notElem = G.notElem {-# INLINE notElem #-} -- | /O(n)/ Yield 'Just' the first element matching the predicate or 'Nothing' -- if no such element exists. find :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Maybe (Rec Identity rs) find = G.find {-# INLINE find #-} -- | /O(n)/ Yield 'Just' the index of the first element matching the predicate -- or 'Nothing' if no such element exists. findIndex :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Maybe Int findIndex = G.findIndex {-# INLINE findIndex #-} {- -- | /O(n)/ Yield the indices of elements satisfying the predicate in ascending -- order. findIndices :: ((a, b) -> Bool) -> Vector (Rec Identity rs) -> Vector u v Int findIndices = G.findIndices {-# INLINE findIndices #-} -} -- | /O(n)/ Yield 'Just' the index of the first occurence of the given element or -- 'Nothing' if the vector does not contain the element. This is a specialised -- version of 'findIndex'. elemIndex :: (G.Vector Vector (Rec Identity rs), Eq (Rec Identity rs)) => Rec Identity rs -> Vector (Rec Identity rs) -> Maybe Int elemIndex = G.elemIndex {-# INLINE elemIndex #-} {- -- | /O(n)/ Yield the indices of all occurences of the given element in -- ascending order. This is a specialised version of 'findIndices'. elemIndices :: (a, b) -> Vector (Rec Identity rs) -> Vector Int elemIndices = G.elemIndices {-# INLINE elemIndices #-} -} -- Folding -- ------- -- | /O(n)/ Left fold foldl :: G.Vector Vector (Rec Identity rs) => (r -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r foldl = G.foldl {-# INLINE foldl #-} -- | /O(n)/ Left fold on non-empty vectors foldl1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldl1 = G.foldl1 {-# INLINE foldl1 #-} -- | /O(n)/ Left fold with strict accumulator foldl' :: G.Vector Vector (Rec Identity rs) => (r -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r foldl' = G.foldl' {-# INLINE foldl' #-} -- | /O(n)/ Left fold on non-empty vectors with strict accumulator foldl1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldl1' = G.foldl1' {-# INLINE foldl1' #-} -- | /O(n)/ Right fold foldr :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r foldr = G.foldr {-# INLINE foldr #-} -- | /O(n)/ Right fold on non-empty vectors foldr1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldr1 = G.foldr1 {-# INLINE foldr1 #-} -- | /O(n)/ Right fold with a strict accumulator foldr' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r foldr' = G.foldr' {-# INLINE foldr' #-} -- | /O(n)/ Right fold on non-empty vectors with strict accumulator foldr1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Rec Identity rs foldr1' = G.foldr1' {-# INLINE foldr1' #-} -- | /O(n)/ Left fold (function applied to each element and its index) ifoldl :: G.Vector Vector (Rec Identity rs) => (r -> Int -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r ifoldl = G.ifoldl {-# INLINE ifoldl #-} -- | /O(n)/ Left fold with strict accumulator (function applied to each element -- and its index) ifoldl' :: G.Vector Vector (Rec Identity rs) => (r -> Int -> Rec Identity rs -> r) -> r -> Vector (Rec Identity rs) -> r ifoldl' = G.ifoldl' {-# INLINE ifoldl' #-} -- | /O(n)/ Right fold (function applied to each element and its index) ifoldr :: G.Vector Vector (Rec Identity rs) => (Int -> Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r ifoldr = G.ifoldr {-# INLINE ifoldr #-} -- | /O(n)/ Right fold with strict accumulator (function applied to each -- element and its index) ifoldr' :: G.Vector Vector (Rec Identity rs) => (Int -> Rec Identity rs -> r -> r) -> r -> Vector (Rec Identity rs) -> r ifoldr' = G.ifoldr' {-# INLINE ifoldr' #-} -- Specialised folds -- ----------------- -- | /O(n)/ Check if all elements satisfy the predicate. all :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Bool {-# INLINE all #-} all = G.all -- | /O(n)/ Check if any element satisfies the predicate. any :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Bool) -> Vector (Rec Identity rs) -> Bool {-# INLINE any #-} any = G.any {- -- | /O(n)/ Compute the sum of the elements sum :: Vector (Rec Identity rs) -> (a, b) {-# INLINE sum #-} sum = G.sum -- | /O(n)/ Compute the product of the elements product :: Vector (Rec Identity rs) -> (a, b) {-# INLINE product #-} product = G.product -} -- | /O(n)/ Yield the maximum element of the vector. The vector may not be -- empty. maximum :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE maximum #-} maximum = G.maximum -- | /O(n)/ Yield the maximum element of the vector according to the given -- comparison function. The vector may not be empty. maximumBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE maximumBy #-} maximumBy = G.maximumBy -- | /O(n)/ Yield the minimum element of the vector. The vector may not be -- empty. minimum :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE minimum #-} minimum = G.minimum -- | /O(n)/ Yield the minimum element of the vector according to the given -- comparison function. The vector may not be empty. minimumBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Rec Identity rs {-# INLINE minimumBy #-} minimumBy = G.minimumBy -- | /O(n)/ Yield the index of the maximum element of the vector. The vector -- may not be empty. maxIndex :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Int {-# INLINE maxIndex #-} maxIndex = G.maxIndex -- | /O(n)/ Yield the index of the maximum element of the vector according to -- the given comparison function. The vector may not be empty. maxIndexBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Int {-# INLINE maxIndexBy #-} maxIndexBy = G.maxIndexBy -- | /O(n)/ Yield the index of the minimum element of the vector. The vector -- may not be empty. minIndex :: (G.Vector Vector (Rec Identity rs), Ord (Rec Identity rs)) => Vector (Rec Identity rs) -> Int {-# INLINE minIndex #-} minIndex = G.minIndex -- | /O(n)/ Yield the index of the minimum element of the vector according to -- the given comparison function. The vector may not be empty. minIndexBy :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Ordering) -> Vector (Rec Identity rs) -> Int {-# INLINE minIndexBy #-} minIndexBy = G.minIndexBy -- Monadic folds -- ------------- -- | /O(n)/ Monadic fold foldM :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m r foldM = G.foldM {-# INLINE foldM #-} -- | /O(n)/ Monadic fold over non-empty vectors fold1M :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m (Rec Identity rs) {-# INLINE fold1M #-} fold1M = G.fold1M -- | /O(n)/ Monadic fold with strict accumulator foldM' :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m r {-# INLINE foldM' #-} foldM' = G.foldM' -- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator fold1M' :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m (Rec Identity rs) {-# INLINE fold1M' #-} fold1M' = G.fold1M' -- | /O(n)/ Monadic fold that discards the result foldM_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m () {-# INLINE foldM_ #-} foldM_ = G.foldM_ -- | /O(n)/ Monadic fold over non-empty vectors that discards the result fold1M_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m () {-# INLINE fold1M_ #-} fold1M_ = G.fold1M_ -- | /O(n)/ Monadic fold with strict accumulator that discards the result foldM'_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (r -> Rec Identity rs -> m r) -> r -> Vector (Rec Identity rs) -> m () {-# INLINE foldM'_ #-} foldM'_ = G.foldM'_ -- | /O(n)/ Monadic fold over non-empty vectors with strict accumulator -- that discards the result fold1M'_ :: (Monad m, G.Vector Vector (Rec Identity rs)) => (Rec Identity rs -> Rec Identity rs -> m (Rec Identity rs)) -> Vector (Rec Identity rs) -> m () {-# INLINE fold1M'_ #-} fold1M'_ = G.fold1M'_ -- Prefix sums (scans) -- ------------------- -- | /O(n)/ Prescan -- -- @ -- prescanl f z = 'init' . 'scanl' f z -- @ -- -- Example: @prescanl (+) 0 \<1,2,3,4\> = \<0,1,3,6\>@ -- prescanl :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) prescanl = G.prescanl {-# INLINE prescanl #-} -- | /O(n)/ Prescan with strict accumulator prescanl' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) prescanl' = G.prescanl' {-# INLINE prescanl' #-} -- | /O(n)/ Scan -- -- @ -- postscanl f z = 'tail' . 'scanl' f z -- @ -- -- Example: @postscanl (+) 0 \<1,2,3,4\> = \<1,3,6,10\>@ -- postscanl :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) postscanl = G.postscanl {-# INLINE postscanl #-} -- | /O(n)/ Scan with strict accumulator postscanl' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) postscanl' = G.postscanl' {-# INLINE postscanl' #-} -- | /O(n)/ Haskell-style scan -- -- > scanl f z <x1,...,xn> = <y1,...,y(n+1)> -- > where y1 = z -- > yi = f y(i-1) x(i-1) -- -- Example: @scanl (+) 0 \<1,2,3,4\> = \<0,1,3,6,10\>@ -- scanl :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) scanl = G.scanl {-# INLINE scanl #-} -- | /O(n)/ Haskell-style scan with strict accumulator scanl' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity rs) -> Rec Identity rs -> Vector (Rec Identity ss) -> Vector (Rec Identity rs) scanl' = G.scanl' {-# INLINE scanl' #-} -- | /O(n)/ Scan over a non-empty vector -- -- > scanl f <x1,...,xn> = <y1,...,yn> -- > where y1 = x1 -- > yi = f y(i-1) xi -- scanl1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) scanl1 = G.scanl1 {-# INLINE scanl1 #-} -- | /O(n)/ Scan over a non-empty vector with a strict accumulator scanl1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) scanl1' = G.scanl1' {-# INLINE scanl1' #-} -- | /O(n)/ Right-to-left prescan -- -- @ -- prescanr f z = 'reverse' . 'prescanl' (flip f) z . 'reverse' -- @ -- prescanr :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) {-# INLINE prescanr #-} prescanr = G.prescanr -- | /O(n)/ Right-to-left prescan with strict accumulator prescanr' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) prescanr' = G.prescanr' {-# INLINE prescanr' #-} -- | /O(n)/ Right-to-left scan postscanr :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) postscanr = G.postscanr {-# INLINE postscanr #-} -- | /O(n)/ Right-to-left scan with strict accumulator postscanr' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) postscanr' = G.postscanr' {-# INLINE postscanr' #-} -- | /O(n)/ Right-to-left Haskell-style scan scanr :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) scanr = G.scanr {-# INLINE scanr #-} -- | /O(n)/ Right-to-left Haskell-style scan with strict accumulator scanr' :: (G.Vector Vector (Rec Identity rs), G.Vector Vector (Rec Identity ss)) => (Rec Identity rs -> Rec Identity ss -> Rec Identity ss) -> Rec Identity ss -> Vector (Rec Identity rs) -> Vector (Rec Identity ss) scanr' = G.scanr' {-# INLINE scanr' #-} -- | /O(n)/ Right-to-left scan over a non-empty vector scanr1 :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE scanr1 #-} scanr1 = G.scanr1 -- | /O(n)/ Right-to-left scan over a non-empty vector with a strict -- accumulator scanr1' :: G.Vector Vector (Rec Identity rs) => (Rec Identity rs -> Rec Identity rs -> Rec Identity rs) -> Vector (Rec Identity rs) -> Vector (Rec Identity rs) {-# INLINE scanr1' #-} scanr1' = G.scanr1' -- | /O(n)/ Convert a vector to a list toList :: G.Vector Vector (Rec Identity rs) => Vector (Rec Identity rs) -> [Rec Identity rs] toList = G.toList {-# INLINE toList #-} -- | /O(n)/ Convert a list to a vector fromList :: G.Vector Vector (Rec Identity rs) => [Rec Identity rs] -> Vector (Rec Identity rs) fromList = G.fromList {-# INLINE fromList #-} -- | /O(n)/ Convert the first @n@ elements of a list to a vector -- -- @ -- fromListN n xs = 'fromList' ('take' n xs) -- @ fromListN :: G.Vector Vector (Rec Identity rs) => Int -> [Rec Identity rs] -> Vector (Rec Identity rs) fromListN = G.fromListN {-# INLINE fromListN #-} -- Conversions - Mutable vectors -- ----------------------------- -- | /O(1)/ Unsafe convert a mutable vector to an immutable one without -- copying. The mutable vector may not be used after this operation. unsafeFreeze :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> m (Vector (Rec Identity rs)) unsafeFreeze = G.unsafeFreeze {-# INLINE unsafeFreeze #-} -- | /O(1)/ Unsafely convert an immutable vector to a mutable one without -- copying. The immutable vector may not be used after this operation. unsafeThaw :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (G.Mutable Vector (PrimState m) (Rec Identity rs)) unsafeThaw = G.unsafeThaw {-# INLINE unsafeThaw #-} -- | /O(n)/ Yield a mutable copy of the immutable vector. thaw :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => Vector (Rec Identity rs) -> m (G.Mutable Vector (PrimState m) (Rec Identity rs)) thaw = G.thaw {-# INLINE thaw #-} -- | /O(n)/ Yield an immutable copy of the mutable vector. freeze :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> m (Vector (Rec Identity rs)) freeze = G.freeze {-# INLINE freeze #-} -- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must -- have the same length. This is not checked. unsafeCopy :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> Vector (Rec Identity rs) -> m () unsafeCopy = G.unsafeCopy {-# INLINE unsafeCopy #-} -- | /O(n)/ Copy an immutable vector into a mutable one. The two vectors must -- have the same length. copy :: (PrimMonad m, G.Vector Vector (Rec Identity rs)) => G.Mutable Vector (PrimState m) (Rec Identity rs) -> Vector (Rec Identity rs) -> m () copy = G.copy {-# INLINE copy #-}
andrewthad/vinyl-vectors
src/Data/Vector/Vinyl/Default/Empty/Monomorphic.hs
bsd-3-clause
48,286
0
13
10,516
11,257
6,037
5,220
-1
-1
{-# LANGUAGE BangPatterns #-} module Main where import Control.Arrow as A import GalFld.GalFld import GalFld.More.SpecialPolys {-import System.Random-} import Data.List import Debug.Trace import Data.Maybe import GalFld.Core.Polynomials.FFTTuple {-import GalFld.Core.Polynomials.Conway-} {----------------------------------------------------------------------------------} {--- Beispiele-} e2f2Mipo = pList [1::F2,1,1] -- xยฒ+x+1 e2f2 = FFElem (pList [0,1::F2]) e2f2Mipo e40f2Mipo = pList [1::F2,1,0,1,0,1,0,0,1,0,0,0,1,1,0,1,1,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1] e40f2 = FFElem (pList [0,1::F2]) e40f2Mipo e10f3Mipo = pList [2::F3,1,0,0,2,2,2,0,0,0,1] e10f3 = FFElem (pTupUnsave [(1,1::F3)]) e10f3Mipo {- F16=E2(E2) - als Grad 2 Erweiterung von E2 durch MPol xยฒ+x+e2f2 - Mit einer Nullstelle: e2e2f2 -} e2e2f2Mipo = pList [e2f2,one,one] -- xยฒ+x+e2f2 e2e2f2 = FFElem (pList [0,one]) e2e2f2Mipo --e2e2f2 = FFElem (pList [0,e2f2]) e2e2f2Mipo {- F16=E4 - als Grad 4 Erweiterung con F2 durch MPol xโด+xยฒ+1 - Mit einer Nullstelle: e4f2 -} e4f2Mipo = pList [1::F2,1::F2,0,0,1::F2] -- xโด+xยฒ+1 e4f2 = FFElem (pList [0,1::F2]) e4f2Mipo {- - Beispiel in F3[x]: - f = Xยนยน+2xโน+2xโธ+xโถ+xโต+2xยณ+2xยฒ+1 - = (x+1)(xยฒ+1)ยณ(x+2)โด -} {-f=pList [1::F3,0,2,2,0,1,1,0,2,2,0,1]-} {-f = pTupUnsave [(11,1),(8,2::F3),(6,1),(5,1),(3,2),(2,2),(0,1)]-} {-f' = poly LE [1::F3,0,2,2,0,1,1,0,2,2,0,1] -} f = pTupUnsave [(11::Int,1),(8,2),(6,1),(5,1),(3,2),(2,2),(0,1)] a = pTupUnsave [(6,3::F5),(5,2),(4,1),(3,1),(1,2),(0,3)] b = pTupUnsave [(6,2::F5),(5,1),(4,3),(2,4)] c = pTupUnsave [(4,1::F5)] testPoly1 = pList $ listFFElem e40f2Mipo [ pList [0::F2,0,1,1] , 1 , pList [1::F2,1,1] , pList [0::F2,1] , pList [1::F2,1,0,1] ] testPoly2 = pList $ listFFElem e4f2Mipo [ pList [0::F2,0,1,1] , 1 , pList [1::F2,1,0,1] ] testPoly3 = pList $ listFFElem e4f2Mipo [ pList [0::F2,0,1,1] , 1 , 1 , pList [1::F2,1,0,1] ] testPoly = testPoly1^2 * testPoly2 * testPoly3 testPolyF5 = pList $ listFFElem (pList [2::F5,4,1]) [ pList [0::F5,0,1,1] , 1 , pList [1::F5,1,1] , pList [0::F5,1] , pList [1::F5,1,0,1] ] testPolyE10F3 = pList $ listFFElem e10f3Mipo [ pList [0::F3,0,1,1] , 1 , pList [1::F3,1,1] , pList [0::F3,1] , pList [1::F3,1,0,1] ] multMyPoly mulFunk f g = mulFunk f g {-multMyPoly' f 1 = f-} {-multMyPoly' f n = multPoly f $ multMyPoly' f (n-1)-} {-m = fromListsM [ [0::F5, 1, 0, 1, 0 ]-} {-, [0, -2, 0, 0, 0 ]-} {-, [0, 0, 0, 0, 0 ]-} {-, [0, 0, 0, -2, 0 ]-} {-, [0, 1, 0, 1, 0 ]]-} genBigM n = replicate n $ take n $ cycle $ elems (1::F101) m = fromListsM $ genBigM 100 {-m' = M.fromLists $ genBigM 100-} problem1d e deg = do print $ "Berechne monischen irred Polynome /=0 von Grad " ++ show deg print $ length $ findIrreds $ getAllMonicPs (elems e) [deg] prob1d e deg = map (\x -> map (\(i,f) -> berlekamp f) x) $ findTrivialsSff $ getAllMonicPs (elems e) [deg] l = take 100 $ getAllMonicPs (elems (1::F3)) [100] heavyBench mul f 0 = f heavyBench mul f n = mul f g where g = heavyBench mul f (n-1) main :: IO () {-main = print $ map fst $ sffAndBerlekamp testPoly-} {-main = print $ berlekampBasis testPoly-} {-main = print $ multMyPoly f 400-} {-main = print $ multMyPoly' f' 400-} {-main = print $ multMyPoly m' 10000-} {-main = print $ echelonM m-} {-main = print $ luDecomp' m'-} {-main = print $ map (\n -> (length $ prob1d (1::F2) n)) [1..10]-} {-main = print $ prob1d (1::F2) 9-} {-main = problem1d (1::F2) 13-} {-main = print $ berlekamp fFail-} {-main = print $ length $ filter (\x -> x) $ map (\f -> rabin f) $ getAllMonicPs (elems (1::F3)) [8]-} {-main = print $ map (\f -> hasNs f (elems (1::F3))) $ getAllMonicPs (elems (1::F3)) [2]-} {-main = mapM_ print $ map appBerlekamp $ map appSff $ findTrivialsNs $ getAllMonicPs (elems (1::F3)) [2]-} {-main = print $ length $ filter (\x -> x) $ map (rabin . toPMS) $ getAllMonicPs (elems (1::F3)) [8]-} {-main = print $ length $ findIrreds $ getAllMonicPs (elems (1::F3)) [9]-} {-main = mapM_ print $ map sffAndBerlekamp $ getAllMonicPs (elems (1::F3)) [3]-} {-main = print $ length $ findIrredsRabin $ getAllMonicPs (elems (1::F3)) [9]-} {-main = print $ snd $ (divPInv (pTupUnsave [(3^11,1),(1,-1)]) f)-} {-main = print $ foldr1 (+) $ map (snd) $ p2Tup $ heavyBench testPoly1 200-} {-main = print $ foldr1 (+) $ map (snd) $ heavyBench (p2Tup testPoly1) 200-} {-main = do-} {-print $ divP (pTup [(3^20,1::F3), (0,-1)]) (pTup [(40,1::F3), (1,1),(0,2)])-} {-main = print $ multPMKaratsuba (p2Tup (testPolyF5^1000)) (p2Tup (testPolyF5^1000))-} {-main = print $ foldr1 (+) $ map snd $ p2Tup $ heavyBench (multPK) testPolyF5 300-} {-main = print $ modMonom (5^21) a-} {-main = print $ m-} {-where m = factorP $ ggTP (piPoly $ pTupUnsave [(5,1::F3),(0,-1)]) (cyclotomicPoly (3^5-1) (1::F3))-} main = do let list = getAllP (elems (1::F5)) 8 putStrLn $ (\(f,g,a,b) -> "f="++show f++"\ng="++show g++"\ndivP f g = "++show a++"\ndivPInv="++show b) $ head $ filter (\(_,_,a,b) -> a /= b) $ map (\(x,y) -> (x,y,divP x y, divPInv x y)) $ zip list $ reverse list
maximilianhuber/softwareProjekt
profiling/AlgProfiling.hs
bsd-3-clause
5,861
0
22
1,630
1,569
934
635
66
1
module Internal.X86.Default where import Foreign import Foreign.C.Types import Data.List (dropWhileEnd) import Hapstone.Internal.Util import Hapstone.Internal.X86 import Test.QuickCheck import Test.QuickCheck.Instances -- generators for our datatypes instance Arbitrary X86Reg where arbitrary = elements [minBound..maxBound] instance Arbitrary X86OpType where arbitrary = elements [minBound..maxBound] instance Arbitrary X86AvxBcast where arbitrary = elements [minBound..maxBound] instance Arbitrary X86SseCc where arbitrary = elements [minBound..maxBound] instance Arbitrary X86AvxCc where arbitrary = elements [minBound..maxBound] instance Arbitrary X86AvxRm where arbitrary = elements [minBound..maxBound] instance Arbitrary X86Prefix where arbitrary = elements [minBound..maxBound] instance Arbitrary X86OpMemStruct where arbitrary = X86OpMemStruct <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary CsX86Op where arbitrary = CsX86Op <$> oneof [ Reg <$> arbitrary , Imm <$> arbitrary -- , Fp <$> arbitrary , Mem <$> arbitrary , pure Undefined ] <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary instance Arbitrary CsX86 where arbitrary = CsX86 <$> tuple <*> list <*> arbitrary <*> arbitrary <*> arbitrary <*> nZ <*> nZ <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary <*> (take 8 <$> arbitrary) where tuple = (,,,) <$> nZ <*> nZ <*> nZ <*> nZ nZ :: (Arbitrary a, Eq a, Num a) => Gen (Maybe a) nZ = fromZero <$> arbitrary list = (dropWhileEnd (==0) . take 4) <$> arbitrary instance Arbitrary X86Insn where arbitrary = elements [minBound..maxBound] instance Arbitrary X86InsnGroup where arbitrary = elements [minBound..maxBound]
ibabushkin/hapstone
test/Internal/X86/Default.hs
bsd-3-clause
1,915
0
20
419
517
278
239
45
0
{-# language CPP #-} {-# language MultiParamTypeClasses #-} #if __GLASGOW_HASKELL__ >= 800 {-# options_ghc -Wno-redundant-constraints #-} #endif module OpenCV.Internal.ImgProc.MiscImgTransform.ColorCodes where import "base" Data.Int ( Int32 ) import "base" Data.Proxy ( Proxy(..) ) import "base" Data.Word import "base" GHC.TypeLits import "this" OpenCV.Internal.ImgProc.MiscImgTransform import "this" OpenCV.TypeLevel -------------------------------------------------------------------------------- {- | Valid color conversions described by the following graph: <<doc/color_conversions.png>> -} class ColorConversion (fromColor :: ColorCode) (toColor :: ColorCode) where colorConversionCode :: Proxy fromColor -> Proxy toColor -> Int32 -- | Names of color encodings data ColorCode = BayerBG -- ^ ('bayerBG') Bayer pattern with BG in the second row, second and third column | BayerGB -- ^ ('bayerGB') Bayer pattern with GB in the second row, second and third column | BayerGR -- ^ ('bayerGR') Bayer pattern with GR in the second row, second and third column | BayerRG -- ^ ('bayerRG') Bayer pattern with RG in the second row, second and third column | BGR -- ^ ('bgr') 24 bit RGB color space with channels: (B8:G8:R8) | BGR555 -- ^ ('bgr555') 15 bit RGB color space | BGR565 -- ^ ('bgr565') 16 bit RGB color space | BGRA -- ^ ('bgra') 32 bit RGBA color space with channels: (B8:G8:R8:A8) | BGRA_I420 -- ^ ('bgra_I420') | BGRA_IYUV -- ^ ('bgra_IYUV') | BGRA_NV12 -- ^ ('bgra_NV12') | BGRA_NV21 -- ^ ('bgra_NV21') | BGRA_UYNV -- ^ ('bgra_UYNV') | BGRA_UYVY -- ^ ('bgra_UYVY') | BGRA_Y422 -- ^ ('bgra_Y422') | BGRA_YUNV -- ^ ('bgra_YUNV') | BGRA_YUY2 -- ^ ('bgra_YUY2') | BGRA_YUYV -- ^ ('bgra_YUYV') | BGRA_YV12 -- ^ ('bgra_YV12') | BGRA_YVYU -- ^ ('bgra_YVYU') | BGR_EA -- ^ ('bgr_EA') Edge-Aware | BGR_FULL -- ^ ('bgr_FULL') | BGR_I420 -- ^ ('bgr_I420') | BGR_IYUV -- ^ ('bgr_IYUV') | BGR_NV12 -- ^ ('bgr_NV12') | BGR_NV21 -- ^ ('bgr_NV21') | BGR_UYNV -- ^ ('bgr_UYNV') | BGR_UYVY -- ^ ('bgr_UYVY') | BGR_VNG -- ^ ('bgr_VNG') | BGR_Y422 -- ^ ('bgr_Y422') | BGR_YUNV -- ^ ('bgr_YUNV') | BGR_YUY2 -- ^ ('bgr_YUY2') | BGR_YUYV -- ^ ('bgr_YUYV') | BGR_YV12 -- ^ ('bgr_YV12') | BGR_YVYU -- ^ ('bgr_YVYU') | GRAY -- ^ ('gray') 8 bit single channel color space | GRAY_420 -- ^ ('gray_420') | GRAY_I420 -- ^ ('gray_I420') | GRAY_IYUV -- ^ ('gray_IYUV') | GRAY_NV12 -- ^ ('gray_NV12') | GRAY_NV21 -- ^ ('gray_NV21') | GRAY_UYNV -- ^ ('gray_UYNV') | GRAY_UYVY -- ^ ('gray_UYVY') | GRAY_Y422 -- ^ ('gray_Y422') | GRAY_YUNV -- ^ ('gray_YUNV') | GRAY_YUY2 -- ^ ('gray_YUY2') | GRAY_YUYV -- ^ ('gray_YUYV') | GRAY_YV12 -- ^ ('gray_YV12') | GRAY_YVYU -- ^ ('gray_YVYU') | HLS -- ^ ('hls') | HLS_FULL -- ^ ('hls_FULL') | HSV -- ^ ('hsv') | HSV_FULL -- ^ ('hsv_FULL') | Lab -- ^ ('lab') | LBGR -- ^ ('lbgr') | LRGB -- ^ ('lrgb') | Luv -- ^ ('luv') | MRGBA -- ^ ('mrgba') | RGB -- ^ ('rgb') 24 bit RGB color space with channels: (R8:G8:B8) | RGBA -- ^ ('rgba') | RGBA_I420 -- ^ ('rgba_I420') | RGBA_IYUV -- ^ ('rgba_IYUV') | RGBA_NV12 -- ^ ('rgba_NV12') | RGBA_NV21 -- ^ ('rgba_NV21') | RGBA_UYNV -- ^ ('rgba_UYNV') | RGBA_UYVY -- ^ ('rgba_UYVY') | RGBA_Y422 -- ^ ('rgba_Y422') | RGBA_YUNV -- ^ ('rgba_YUNV') | RGBA_YUY2 -- ^ ('rgba_YUY2') | RGBA_YUYV -- ^ ('rgba_YUYV') | RGBA_YV12 -- ^ ('rgba_YV12') | RGBA_YVYU -- ^ ('rgba_YVYU') | RGB_EA -- ^ ('rgb_EA') Edge-Aware | RGB_FULL -- ^ ('rgb_FULL') | RGB_I420 -- ^ ('rgb_I420') | RGB_IYUV -- ^ ('rgb_IYUV') | RGB_NV12 -- ^ ('rgb_NV12') | RGB_NV21 -- ^ ('rgb_NV21') | RGB_UYNV -- ^ ('rgb_UYNV') | RGB_UYVY -- ^ ('rgb_UYVY') | RGB_VNG -- ^ ('rgb_VNG') | RGB_Y422 -- ^ ('rgb_Y422') | RGB_YUNV -- ^ ('rgb_YUNV') | RGB_YUY2 -- ^ ('rgb_YUY2') | RGB_YUYV -- ^ ('rgb_YUYV') | RGB_YV12 -- ^ ('rgb_YV12') | RGB_YVYU -- ^ ('rgb_YVYU') | XYZ -- ^ ('xyz') | YCrCb -- ^ ('yCrCb') | YUV -- ^ ('yuv') | YUV420p -- ^ ('yuv420p') | YUV420sp -- ^ ('yuv420sp') | YUV_I420 -- ^ ('yuv_I420') | YUV_IYUV -- ^ ('yuv_IYUV') | YUV_YV12 -- ^ ('yuv_YV12') -------------------------------------------------------------------------------- bayerBG :: Proxy 'BayerBG ; bayerBG = Proxy bayerGB :: Proxy 'BayerGB ; bayerGB = Proxy bayerGR :: Proxy 'BayerGR ; bayerGR = Proxy bayerRG :: Proxy 'BayerRG ; bayerRG = Proxy bgr :: Proxy 'BGR ; bgr = Proxy bgr555 :: Proxy 'BGR555 ; bgr555 = Proxy bgr565 :: Proxy 'BGR565 ; bgr565 = Proxy bgra :: Proxy 'BGRA ; bgra = Proxy bgra_I420 :: Proxy 'BGRA_I420; bgra_I420 = Proxy bgra_IYUV :: Proxy 'BGRA_IYUV; bgra_IYUV = Proxy bgra_NV12 :: Proxy 'BGRA_NV12; bgra_NV12 = Proxy bgra_NV21 :: Proxy 'BGRA_NV21; bgra_NV21 = Proxy bgra_UYNV :: Proxy 'BGRA_UYNV; bgra_UYNV = Proxy bgra_UYVY :: Proxy 'BGRA_UYVY; bgra_UYVY = Proxy bgra_Y422 :: Proxy 'BGRA_Y422; bgra_Y422 = Proxy bgra_YUNV :: Proxy 'BGRA_YUNV; bgra_YUNV = Proxy bgra_YUY2 :: Proxy 'BGRA_YUY2; bgra_YUY2 = Proxy bgra_YUYV :: Proxy 'BGRA_YUYV; bgra_YUYV = Proxy bgra_YV12 :: Proxy 'BGRA_YV12; bgra_YV12 = Proxy bgra_YVYU :: Proxy 'BGRA_YVYU; bgra_YVYU = Proxy bgr_EA :: Proxy 'BGR_EA ; bgr_EA = Proxy bgr_FULL :: Proxy 'BGR_FULL ; bgr_FULL = Proxy bgr_I420 :: Proxy 'BGR_I420 ; bgr_I420 = Proxy bgr_IYUV :: Proxy 'BGR_IYUV ; bgr_IYUV = Proxy bgr_NV12 :: Proxy 'BGR_NV12 ; bgr_NV12 = Proxy bgr_NV21 :: Proxy 'BGR_NV21 ; bgr_NV21 = Proxy bgr_UYNV :: Proxy 'BGR_UYNV ; bgr_UYNV = Proxy bgr_UYVY :: Proxy 'BGR_UYVY ; bgr_UYVY = Proxy bgr_VNG :: Proxy 'BGR_VNG ; bgr_VNG = Proxy bgr_Y422 :: Proxy 'BGR_Y422 ; bgr_Y422 = Proxy bgr_YUNV :: Proxy 'BGR_YUNV ; bgr_YUNV = Proxy bgr_YUY2 :: Proxy 'BGR_YUY2 ; bgr_YUY2 = Proxy bgr_YUYV :: Proxy 'BGR_YUYV ; bgr_YUYV = Proxy bgr_YV12 :: Proxy 'BGR_YV12 ; bgr_YV12 = Proxy bgr_YVYU :: Proxy 'BGR_YVYU ; bgr_YVYU = Proxy gray :: Proxy 'GRAY ; gray = Proxy gray_420 :: Proxy 'GRAY_420 ; gray_420 = Proxy gray_I420 :: Proxy 'GRAY_I420; gray_I420 = Proxy gray_IYUV :: Proxy 'GRAY_IYUV; gray_IYUV = Proxy gray_NV12 :: Proxy 'GRAY_NV12; gray_NV12 = Proxy gray_NV21 :: Proxy 'GRAY_NV21; gray_NV21 = Proxy gray_UYNV :: Proxy 'GRAY_UYNV; gray_UYNV = Proxy gray_UYVY :: Proxy 'GRAY_UYVY; gray_UYVY = Proxy gray_Y422 :: Proxy 'GRAY_Y422; gray_Y422 = Proxy gray_YUNV :: Proxy 'GRAY_YUNV; gray_YUNV = Proxy gray_YUY2 :: Proxy 'GRAY_YUY2; gray_YUY2 = Proxy gray_YUYV :: Proxy 'GRAY_YUYV; gray_YUYV = Proxy gray_YV12 :: Proxy 'GRAY_YV12; gray_YV12 = Proxy gray_YVYU :: Proxy 'GRAY_YVYU; gray_YVYU = Proxy hls :: Proxy 'HLS ; hls = Proxy hls_FULL :: Proxy 'HLS_FULL ; hls_FULL = Proxy hsv :: Proxy 'HSV ; hsv = Proxy hsv_FULL :: Proxy 'HSV_FULL ; hsv_FULL = Proxy lab :: Proxy 'Lab ; lab = Proxy lbgr :: Proxy 'LBGR ; lbgr = Proxy lrgb :: Proxy 'LRGB ; lrgb = Proxy luv :: Proxy 'Luv ; luv = Proxy mrgba :: Proxy 'MRGBA ; mrgba = Proxy rgb :: Proxy 'RGB ; rgb = Proxy rgba :: Proxy 'RGBA ; rgba = Proxy rgba_I420 :: Proxy 'RGBA_I420; rgba_I420 = Proxy rgba_IYUV :: Proxy 'RGBA_IYUV; rgba_IYUV = Proxy rgba_NV12 :: Proxy 'RGBA_NV12; rgba_NV12 = Proxy rgba_NV21 :: Proxy 'RGBA_NV21; rgba_NV21 = Proxy rgba_UYNV :: Proxy 'RGBA_UYNV; rgba_UYNV = Proxy rgba_UYVY :: Proxy 'RGBA_UYVY; rgba_UYVY = Proxy rgba_Y422 :: Proxy 'RGBA_Y422; rgba_Y422 = Proxy rgba_YUNV :: Proxy 'RGBA_YUNV; rgba_YUNV = Proxy rgba_YUY2 :: Proxy 'RGBA_YUY2; rgba_YUY2 = Proxy rgba_YUYV :: Proxy 'RGBA_YUYV; rgba_YUYV = Proxy rgba_YV12 :: Proxy 'RGBA_YV12; rgba_YV12 = Proxy rgba_YVYU :: Proxy 'RGBA_YVYU; rgba_YVYU = Proxy rgb_EA :: Proxy 'RGB_EA ; rgb_EA = Proxy rgb_FULL :: Proxy 'RGB_FULL ; rgb_FULL = Proxy rgb_I420 :: Proxy 'RGB_I420 ; rgb_I420 = Proxy rgb_IYUV :: Proxy 'RGB_IYUV ; rgb_IYUV = Proxy rgb_NV12 :: Proxy 'RGB_NV12 ; rgb_NV12 = Proxy rgb_NV21 :: Proxy 'RGB_NV21 ; rgb_NV21 = Proxy rgb_UYNV :: Proxy 'RGB_UYNV ; rgb_UYNV = Proxy rgb_UYVY :: Proxy 'RGB_UYVY ; rgb_UYVY = Proxy rgb_VNG :: Proxy 'RGB_VNG ; rgb_VNG = Proxy rgb_Y422 :: Proxy 'RGB_Y422 ; rgb_Y422 = Proxy rgb_YUNV :: Proxy 'RGB_YUNV ; rgb_YUNV = Proxy rgb_YUY2 :: Proxy 'RGB_YUY2 ; rgb_YUY2 = Proxy rgb_YUYV :: Proxy 'RGB_YUYV ; rgb_YUYV = Proxy rgb_YV12 :: Proxy 'RGB_YV12 ; rgb_YV12 = Proxy rgb_YVYU :: Proxy 'RGB_YVYU ; rgb_YVYU = Proxy xyz :: Proxy 'XYZ ; xyz = Proxy yCrCb :: Proxy 'YCrCb ; yCrCb = Proxy yuv :: Proxy 'YUV ; yuv = Proxy yuv420p :: Proxy 'YUV420p ; yuv420p = Proxy yuv420sp :: Proxy 'YUV420sp ; yuv420sp = Proxy yuv_I420 :: Proxy 'YUV_I420 ; yuv_I420 = Proxy yuv_IYUV :: Proxy 'YUV_IYUV ; yuv_IYUV = Proxy yuv_YV12 :: Proxy 'YUV_YV12 ; yuv_YV12 = Proxy -------------------------------------------------------------------------------- instance ColorConversion 'BGR 'BGRA where colorConversionCode _ _ = c'COLOR_BGR2BGRA instance ColorConversion 'RGB 'RGBA where colorConversionCode _ _ = c'COLOR_RGB2RGBA instance ColorConversion 'BGRA 'BGR where colorConversionCode _ _ = c'COLOR_BGRA2BGR instance ColorConversion 'RGBA 'RGB where colorConversionCode _ _ = c'COLOR_RGBA2RGB instance ColorConversion 'BGR 'RGBA where colorConversionCode _ _ = c'COLOR_BGR2RGBA instance ColorConversion 'RGB 'BGRA where colorConversionCode _ _ = c'COLOR_RGB2BGRA instance ColorConversion 'RGBA 'BGR where colorConversionCode _ _ = c'COLOR_RGBA2BGR instance ColorConversion 'BGRA 'RGB where colorConversionCode _ _ = c'COLOR_BGRA2RGB instance ColorConversion 'BGR 'RGB where colorConversionCode _ _ = c'COLOR_BGR2RGB instance ColorConversion 'RGB 'BGR where colorConversionCode _ _ = c'COLOR_RGB2BGR instance ColorConversion 'BGRA 'RGBA where colorConversionCode _ _ = c'COLOR_BGRA2RGBA instance ColorConversion 'RGBA 'BGRA where colorConversionCode _ _ = c'COLOR_RGBA2BGRA instance ColorConversion 'BGR 'GRAY where colorConversionCode _ _ = c'COLOR_BGR2GRAY instance ColorConversion 'RGB 'GRAY where colorConversionCode _ _ = c'COLOR_RGB2GRAY instance ColorConversion 'GRAY 'BGR where colorConversionCode _ _ = c'COLOR_GRAY2BGR instance ColorConversion 'GRAY 'RGB where colorConversionCode _ _ = c'COLOR_GRAY2RGB instance ColorConversion 'GRAY 'BGRA where colorConversionCode _ _ = c'COLOR_GRAY2BGRA instance ColorConversion 'GRAY 'RGBA where colorConversionCode _ _ = c'COLOR_GRAY2RGBA instance ColorConversion 'BGRA 'GRAY where colorConversionCode _ _ = c'COLOR_BGRA2GRAY instance ColorConversion 'RGBA 'GRAY where colorConversionCode _ _ = c'COLOR_RGBA2GRAY instance ColorConversion 'BGR 'BGR565 where colorConversionCode _ _ = c'COLOR_BGR2BGR565 instance ColorConversion 'RGB 'BGR565 where colorConversionCode _ _ = c'COLOR_RGB2BGR565 instance ColorConversion 'BGR565 'BGR where colorConversionCode _ _ = c'COLOR_BGR5652BGR instance ColorConversion 'BGR565 'RGB where colorConversionCode _ _ = c'COLOR_BGR5652RGB instance ColorConversion 'BGRA 'BGR565 where colorConversionCode _ _ = c'COLOR_BGRA2BGR565 instance ColorConversion 'RGBA 'BGR565 where colorConversionCode _ _ = c'COLOR_RGBA2BGR565 instance ColorConversion 'BGR565 'BGRA where colorConversionCode _ _ = c'COLOR_BGR5652BGRA instance ColorConversion 'BGR565 'RGBA where colorConversionCode _ _ = c'COLOR_BGR5652RGBA instance ColorConversion 'GRAY 'BGR565 where colorConversionCode _ _ = c'COLOR_GRAY2BGR565 instance ColorConversion 'BGR565 'GRAY where colorConversionCode _ _ = c'COLOR_BGR5652GRAY instance ColorConversion 'BGR 'BGR555 where colorConversionCode _ _ = c'COLOR_BGR2BGR555 instance ColorConversion 'RGB 'BGR555 where colorConversionCode _ _ = c'COLOR_RGB2BGR555 instance ColorConversion 'BGR555 'BGR where colorConversionCode _ _ = c'COLOR_BGR5552BGR instance ColorConversion 'BGR555 'RGB where colorConversionCode _ _ = c'COLOR_BGR5552RGB instance ColorConversion 'BGRA 'BGR555 where colorConversionCode _ _ = c'COLOR_BGRA2BGR555 instance ColorConversion 'RGBA 'BGR555 where colorConversionCode _ _ = c'COLOR_RGBA2BGR555 instance ColorConversion 'BGR555 'BGRA where colorConversionCode _ _ = c'COLOR_BGR5552BGRA instance ColorConversion 'BGR555 'RGBA where colorConversionCode _ _ = c'COLOR_BGR5552RGBA instance ColorConversion 'GRAY 'BGR555 where colorConversionCode _ _ = c'COLOR_GRAY2BGR555 instance ColorConversion 'BGR555 'GRAY where colorConversionCode _ _ = c'COLOR_BGR5552GRAY instance ColorConversion 'BGR 'XYZ where colorConversionCode _ _ = c'COLOR_BGR2XYZ instance ColorConversion 'RGB 'XYZ where colorConversionCode _ _ = c'COLOR_RGB2XYZ instance ColorConversion 'XYZ 'BGR where colorConversionCode _ _ = c'COLOR_XYZ2BGR instance ColorConversion 'XYZ 'RGB where colorConversionCode _ _ = c'COLOR_XYZ2RGB instance ColorConversion 'BGR 'YCrCb where colorConversionCode _ _ = c'COLOR_BGR2YCrCb instance ColorConversion 'RGB 'YCrCb where colorConversionCode _ _ = c'COLOR_RGB2YCrCb instance ColorConversion 'YCrCb 'BGR where colorConversionCode _ _ = c'COLOR_YCrCb2BGR instance ColorConversion 'YCrCb 'RGB where colorConversionCode _ _ = c'COLOR_YCrCb2RGB instance ColorConversion 'BGR 'HSV where colorConversionCode _ _ = c'COLOR_BGR2HSV instance ColorConversion 'RGB 'HSV where colorConversionCode _ _ = c'COLOR_RGB2HSV instance ColorConversion 'BGR 'Lab where colorConversionCode _ _ = c'COLOR_BGR2Lab instance ColorConversion 'RGB 'Lab where colorConversionCode _ _ = c'COLOR_RGB2Lab instance ColorConversion 'BGR 'Luv where colorConversionCode _ _ = c'COLOR_BGR2Luv instance ColorConversion 'RGB 'Luv where colorConversionCode _ _ = c'COLOR_RGB2Luv instance ColorConversion 'BGR 'HLS where colorConversionCode _ _ = c'COLOR_BGR2HLS instance ColorConversion 'RGB 'HLS where colorConversionCode _ _ = c'COLOR_RGB2HLS instance ColorConversion 'HSV 'BGR where colorConversionCode _ _ = c'COLOR_HSV2BGR instance ColorConversion 'HSV 'RGB where colorConversionCode _ _ = c'COLOR_HSV2RGB instance ColorConversion 'Lab 'BGR where colorConversionCode _ _ = c'COLOR_Lab2BGR instance ColorConversion 'Lab 'RGB where colorConversionCode _ _ = c'COLOR_Lab2RGB instance ColorConversion 'Luv 'BGR where colorConversionCode _ _ = c'COLOR_Luv2BGR instance ColorConversion 'Luv 'RGB where colorConversionCode _ _ = c'COLOR_Luv2RGB instance ColorConversion 'HLS 'BGR where colorConversionCode _ _ = c'COLOR_HLS2BGR instance ColorConversion 'HLS 'RGB where colorConversionCode _ _ = c'COLOR_HLS2RGB instance ColorConversion 'BGR 'HSV_FULL where colorConversionCode _ _ = c'COLOR_BGR2HSV_FULL instance ColorConversion 'RGB 'HSV_FULL where colorConversionCode _ _ = c'COLOR_RGB2HSV_FULL instance ColorConversion 'BGR 'HLS_FULL where colorConversionCode _ _ = c'COLOR_BGR2HLS_FULL instance ColorConversion 'RGB 'HLS_FULL where colorConversionCode _ _ = c'COLOR_RGB2HLS_FULL instance ColorConversion 'HSV 'BGR_FULL where colorConversionCode _ _ = c'COLOR_HSV2BGR_FULL instance ColorConversion 'HSV 'RGB_FULL where colorConversionCode _ _ = c'COLOR_HSV2RGB_FULL instance ColorConversion 'HLS 'BGR_FULL where colorConversionCode _ _ = c'COLOR_HLS2BGR_FULL instance ColorConversion 'HLS 'RGB_FULL where colorConversionCode _ _ = c'COLOR_HLS2RGB_FULL instance ColorConversion 'LBGR 'Lab where colorConversionCode _ _ = c'COLOR_LBGR2Lab instance ColorConversion 'LRGB 'Lab where colorConversionCode _ _ = c'COLOR_LRGB2Lab instance ColorConversion 'LBGR 'Luv where colorConversionCode _ _ = c'COLOR_LBGR2Luv instance ColorConversion 'LRGB 'Luv where colorConversionCode _ _ = c'COLOR_LRGB2Luv instance ColorConversion 'Lab 'LBGR where colorConversionCode _ _ = c'COLOR_Lab2LBGR instance ColorConversion 'Lab 'LRGB where colorConversionCode _ _ = c'COLOR_Lab2LRGB instance ColorConversion 'Luv 'LBGR where colorConversionCode _ _ = c'COLOR_Luv2LBGR instance ColorConversion 'Luv 'LRGB where colorConversionCode _ _ = c'COLOR_Luv2LRGB instance ColorConversion 'BGR 'YUV where colorConversionCode _ _ = c'COLOR_BGR2YUV instance ColorConversion 'RGB 'YUV where colorConversionCode _ _ = c'COLOR_RGB2YUV instance ColorConversion 'YUV 'BGR where colorConversionCode _ _ = c'COLOR_YUV2BGR instance ColorConversion 'YUV 'RGB where colorConversionCode _ _ = c'COLOR_YUV2RGB instance ColorConversion 'YUV 'RGB_NV12 where colorConversionCode _ _ = c'COLOR_YUV2RGB_NV12 instance ColorConversion 'YUV 'BGR_NV12 where colorConversionCode _ _ = c'COLOR_YUV2BGR_NV12 instance ColorConversion 'YUV 'RGB_NV21 where colorConversionCode _ _ = c'COLOR_YUV2RGB_NV21 instance ColorConversion 'YUV 'BGR_NV21 where colorConversionCode _ _ = c'COLOR_YUV2BGR_NV21 instance ColorConversion 'YUV420sp 'RGB where colorConversionCode _ _ = c'COLOR_YUV420sp2RGB instance ColorConversion 'YUV420sp 'BGR where colorConversionCode _ _ = c'COLOR_YUV420sp2BGR instance ColorConversion 'YUV 'RGBA_NV12 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_NV12 instance ColorConversion 'YUV 'BGRA_NV12 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_NV12 instance ColorConversion 'YUV 'RGBA_NV21 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_NV21 instance ColorConversion 'YUV 'BGRA_NV21 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_NV21 instance ColorConversion 'YUV420sp 'RGBA where colorConversionCode _ _ = c'COLOR_YUV420sp2RGBA instance ColorConversion 'YUV420sp 'BGRA where colorConversionCode _ _ = c'COLOR_YUV420sp2BGRA instance ColorConversion 'YUV 'RGB_YV12 where colorConversionCode _ _ = c'COLOR_YUV2RGB_YV12 instance ColorConversion 'YUV 'BGR_YV12 where colorConversionCode _ _ = c'COLOR_YUV2BGR_YV12 instance ColorConversion 'YUV 'RGB_IYUV where colorConversionCode _ _ = c'COLOR_YUV2RGB_IYUV instance ColorConversion 'YUV 'BGR_IYUV where colorConversionCode _ _ = c'COLOR_YUV2BGR_IYUV instance ColorConversion 'YUV 'RGB_I420 where colorConversionCode _ _ = c'COLOR_YUV2RGB_I420 instance ColorConversion 'YUV 'BGR_I420 where colorConversionCode _ _ = c'COLOR_YUV2BGR_I420 instance ColorConversion 'YUV420p 'RGB where colorConversionCode _ _ = c'COLOR_YUV420p2RGB instance ColorConversion 'YUV420p 'BGR where colorConversionCode _ _ = c'COLOR_YUV420p2BGR instance ColorConversion 'YUV 'RGBA_YV12 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YV12 instance ColorConversion 'YUV 'BGRA_YV12 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YV12 instance ColorConversion 'YUV 'RGBA_IYUV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_IYUV instance ColorConversion 'YUV 'BGRA_IYUV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_IYUV instance ColorConversion 'YUV 'RGBA_I420 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_I420 instance ColorConversion 'YUV 'BGRA_I420 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_I420 instance ColorConversion 'YUV420p 'RGBA where colorConversionCode _ _ = c'COLOR_YUV420p2RGBA instance ColorConversion 'YUV420p 'BGRA where colorConversionCode _ _ = c'COLOR_YUV420p2BGRA instance ColorConversion 'YUV 'GRAY_420 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_420 instance ColorConversion 'YUV 'GRAY_NV21 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_NV21 instance ColorConversion 'YUV 'GRAY_NV12 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_NV12 instance ColorConversion 'YUV 'GRAY_YV12 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YV12 instance ColorConversion 'YUV 'GRAY_IYUV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_IYUV instance ColorConversion 'YUV 'GRAY_I420 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_I420 instance ColorConversion 'YUV420sp 'GRAY where colorConversionCode _ _ = c'COLOR_YUV420sp2GRAY instance ColorConversion 'YUV420p 'GRAY where colorConversionCode _ _ = c'COLOR_YUV420p2GRAY instance ColorConversion 'YUV 'RGB_UYVY where colorConversionCode _ _ = c'COLOR_YUV2RGB_UYVY instance ColorConversion 'YUV 'BGR_UYVY where colorConversionCode _ _ = c'COLOR_YUV2BGR_UYVY instance ColorConversion 'YUV 'RGB_Y422 where colorConversionCode _ _ = c'COLOR_YUV2RGB_Y422 instance ColorConversion 'YUV 'BGR_Y422 where colorConversionCode _ _ = c'COLOR_YUV2BGR_Y422 instance ColorConversion 'YUV 'RGB_UYNV where colorConversionCode _ _ = c'COLOR_YUV2RGB_UYNV instance ColorConversion 'YUV 'BGR_UYNV where colorConversionCode _ _ = c'COLOR_YUV2BGR_UYNV instance ColorConversion 'YUV 'RGBA_UYVY where colorConversionCode _ _ = c'COLOR_YUV2RGBA_UYVY instance ColorConversion 'YUV 'BGRA_UYVY where colorConversionCode _ _ = c'COLOR_YUV2BGRA_UYVY instance ColorConversion 'YUV 'RGBA_Y422 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_Y422 instance ColorConversion 'YUV 'BGRA_Y422 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_Y422 instance ColorConversion 'YUV 'RGBA_UYNV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_UYNV instance ColorConversion 'YUV 'BGRA_UYNV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_UYNV instance ColorConversion 'YUV 'RGB_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUY2 instance ColorConversion 'YUV 'BGR_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUY2 instance ColorConversion 'YUV 'RGB_YVYU where colorConversionCode _ _ = c'COLOR_YUV2RGB_YVYU instance ColorConversion 'YUV 'BGR_YVYU where colorConversionCode _ _ = c'COLOR_YUV2BGR_YVYU instance ColorConversion 'YUV 'RGB_YUYV where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUYV instance ColorConversion 'YUV 'BGR_YUYV where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUYV instance ColorConversion 'YUV 'RGB_YUNV where colorConversionCode _ _ = c'COLOR_YUV2RGB_YUNV instance ColorConversion 'YUV 'BGR_YUNV where colorConversionCode _ _ = c'COLOR_YUV2BGR_YUNV instance ColorConversion 'YUV 'RGBA_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUY2 instance ColorConversion 'YUV 'BGRA_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUY2 instance ColorConversion 'YUV 'RGBA_YVYU where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YVYU instance ColorConversion 'YUV 'BGRA_YVYU where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YVYU instance ColorConversion 'YUV 'RGBA_YUYV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUYV instance ColorConversion 'YUV 'BGRA_YUYV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUYV instance ColorConversion 'YUV 'RGBA_YUNV where colorConversionCode _ _ = c'COLOR_YUV2RGBA_YUNV instance ColorConversion 'YUV 'BGRA_YUNV where colorConversionCode _ _ = c'COLOR_YUV2BGRA_YUNV instance ColorConversion 'YUV 'GRAY_UYVY where colorConversionCode _ _ = c'COLOR_YUV2GRAY_UYVY instance ColorConversion 'YUV 'GRAY_YUY2 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUY2 instance ColorConversion 'YUV 'GRAY_Y422 where colorConversionCode _ _ = c'COLOR_YUV2GRAY_Y422 instance ColorConversion 'YUV 'GRAY_UYNV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_UYNV instance ColorConversion 'YUV 'GRAY_YVYU where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YVYU instance ColorConversion 'YUV 'GRAY_YUYV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUYV instance ColorConversion 'YUV 'GRAY_YUNV where colorConversionCode _ _ = c'COLOR_YUV2GRAY_YUNV instance ColorConversion 'RGBA 'MRGBA where colorConversionCode _ _ = c'COLOR_RGBA2mRGBA instance ColorConversion 'MRGBA 'RGBA where colorConversionCode _ _ = c'COLOR_mRGBA2RGBA instance ColorConversion 'RGB 'YUV_I420 where colorConversionCode _ _ = c'COLOR_RGB2YUV_I420 instance ColorConversion 'BGR 'YUV_I420 where colorConversionCode _ _ = c'COLOR_BGR2YUV_I420 instance ColorConversion 'RGB 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_RGB2YUV_IYUV instance ColorConversion 'BGR 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_BGR2YUV_IYUV instance ColorConversion 'RGBA 'YUV_I420 where colorConversionCode _ _ = c'COLOR_RGBA2YUV_I420 instance ColorConversion 'BGRA 'YUV_I420 where colorConversionCode _ _ = c'COLOR_BGRA2YUV_I420 instance ColorConversion 'RGBA 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_RGBA2YUV_IYUV instance ColorConversion 'BGRA 'YUV_IYUV where colorConversionCode _ _ = c'COLOR_BGRA2YUV_IYUV instance ColorConversion 'RGB 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_RGB2YUV_YV12 instance ColorConversion 'BGR 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_BGR2YUV_YV12 instance ColorConversion 'RGBA 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_RGBA2YUV_YV12 instance ColorConversion 'BGRA 'YUV_YV12 where colorConversionCode _ _ = c'COLOR_BGRA2YUV_YV12 instance ColorConversion 'BayerBG 'BGR where colorConversionCode _ _ = c'COLOR_BayerBG2BGR instance ColorConversion 'BayerGB 'BGR where colorConversionCode _ _ = c'COLOR_BayerGB2BGR instance ColorConversion 'BayerRG 'BGR where colorConversionCode _ _ = c'COLOR_BayerRG2BGR instance ColorConversion 'BayerGR 'BGR where colorConversionCode _ _ = c'COLOR_BayerGR2BGR instance ColorConversion 'BayerBG 'RGB where colorConversionCode _ _ = c'COLOR_BayerBG2RGB instance ColorConversion 'BayerGB 'RGB where colorConversionCode _ _ = c'COLOR_BayerGB2RGB instance ColorConversion 'BayerRG 'RGB where colorConversionCode _ _ = c'COLOR_BayerRG2RGB instance ColorConversion 'BayerGR 'RGB where colorConversionCode _ _ = c'COLOR_BayerGR2RGB instance ColorConversion 'BayerBG 'GRAY where colorConversionCode _ _ = c'COLOR_BayerBG2GRAY instance ColorConversion 'BayerGB 'GRAY where colorConversionCode _ _ = c'COLOR_BayerGB2GRAY instance ColorConversion 'BayerRG 'GRAY where colorConversionCode _ _ = c'COLOR_BayerRG2GRAY instance ColorConversion 'BayerGR 'GRAY where colorConversionCode _ _ = c'COLOR_BayerGR2GRAY instance ColorConversion 'BayerBG 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerBG2BGR_VNG instance ColorConversion 'BayerGB 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerGB2BGR_VNG instance ColorConversion 'BayerRG 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerRG2BGR_VNG instance ColorConversion 'BayerGR 'BGR_VNG where colorConversionCode _ _ = c'COLOR_BayerGR2BGR_VNG instance ColorConversion 'BayerBG 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerBG2RGB_VNG instance ColorConversion 'BayerGB 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerGB2RGB_VNG instance ColorConversion 'BayerRG 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerRG2RGB_VNG instance ColorConversion 'BayerGR 'RGB_VNG where colorConversionCode _ _ = c'COLOR_BayerGR2RGB_VNG instance ColorConversion 'BayerBG 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerBG2BGR_EA instance ColorConversion 'BayerGB 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerGB2BGR_EA instance ColorConversion 'BayerRG 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerRG2BGR_EA instance ColorConversion 'BayerGR 'BGR_EA where colorConversionCode _ _ = c'COLOR_BayerGR2BGR_EA instance ColorConversion 'BayerBG 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerBG2RGB_EA instance ColorConversion 'BayerGB 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerGB2RGB_EA instance ColorConversion 'BayerRG 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerRG2RGB_EA instance ColorConversion 'BayerGR 'RGB_EA where colorConversionCode _ _ = c'COLOR_BayerGR2RGB_EA -- | Gives the number of channels associated with a particular color encoding type family ColorCodeChannels (cc :: ColorCode) :: Nat where ColorCodeChannels 'BayerBG = 1 ColorCodeChannels 'BayerGB = 1 ColorCodeChannels 'BayerGR = 1 ColorCodeChannels 'BayerRG = 1 ColorCodeChannels 'BGR = 3 ColorCodeChannels 'BGR555 = 2 ColorCodeChannels 'BGR565 = 2 ColorCodeChannels 'BGRA = 4 ColorCodeChannels 'BGRA_I420 = 4 ColorCodeChannels 'BGRA_IYUV = 4 ColorCodeChannels 'BGRA_NV12 = 4 ColorCodeChannels 'BGRA_NV21 = 4 ColorCodeChannels 'BGRA_UYNV = 4 ColorCodeChannels 'BGRA_UYVY = 4 ColorCodeChannels 'BGRA_Y422 = 4 ColorCodeChannels 'BGRA_YUNV = 4 ColorCodeChannels 'BGRA_YUY2 = 4 ColorCodeChannels 'BGRA_YUYV = 4 ColorCodeChannels 'BGRA_YV12 = 4 ColorCodeChannels 'BGRA_YVYU = 4 ColorCodeChannels 'BGR_EA = 3 ColorCodeChannels 'BGR_FULL = 3 ColorCodeChannels 'BGR_I420 = 3 ColorCodeChannels 'BGR_IYUV = 3 ColorCodeChannels 'BGR_NV12 = 3 ColorCodeChannels 'BGR_NV21 = 3 ColorCodeChannels 'BGR_UYNV = 3 ColorCodeChannels 'BGR_UYVY = 3 ColorCodeChannels 'BGR_VNG = 3 ColorCodeChannels 'BGR_Y422 = 3 ColorCodeChannels 'BGR_YUNV = 3 ColorCodeChannels 'BGR_YUY2 = 3 ColorCodeChannels 'BGR_YUYV = 3 ColorCodeChannels 'BGR_YV12 = 3 ColorCodeChannels 'BGR_YVYU = 3 ColorCodeChannels 'GRAY = 1 ColorCodeChannels 'GRAY_420 = 1 ColorCodeChannels 'GRAY_I420 = 1 ColorCodeChannels 'GRAY_IYUV = 1 ColorCodeChannels 'GRAY_NV12 = 1 ColorCodeChannels 'GRAY_NV21 = 1 ColorCodeChannels 'GRAY_UYNV = 1 ColorCodeChannels 'GRAY_UYVY = 1 ColorCodeChannels 'GRAY_Y422 = 1 ColorCodeChannels 'GRAY_YUNV = 1 ColorCodeChannels 'GRAY_YUY2 = 1 ColorCodeChannels 'GRAY_YUYV = 1 ColorCodeChannels 'GRAY_YV12 = 1 ColorCodeChannels 'GRAY_YVYU = 1 ColorCodeChannels 'HLS = 3 ColorCodeChannels 'HLS_FULL = 3 ColorCodeChannels 'HSV = 3 ColorCodeChannels 'HSV_FULL = 3 ColorCodeChannels 'Lab = 3 ColorCodeChannels 'LBGR = 3 ColorCodeChannels 'LRGB = 3 ColorCodeChannels 'Luv = 3 ColorCodeChannels 'MRGBA = 4 ColorCodeChannels 'RGB = 3 ColorCodeChannels 'RGBA = 4 ColorCodeChannels 'RGBA_I420 = 4 ColorCodeChannels 'RGBA_IYUV = 4 ColorCodeChannels 'RGBA_NV12 = 4 ColorCodeChannels 'RGBA_NV21 = 4 ColorCodeChannels 'RGBA_UYNV = 4 ColorCodeChannels 'RGBA_UYVY = 4 ColorCodeChannels 'RGBA_Y422 = 4 ColorCodeChannels 'RGBA_YUNV = 4 ColorCodeChannels 'RGBA_YUY2 = 4 ColorCodeChannels 'RGBA_YUYV = 4 ColorCodeChannels 'RGBA_YV12 = 4 ColorCodeChannels 'RGBA_YVYU = 4 ColorCodeChannels 'RGB_EA = 3 ColorCodeChannels 'RGB_FULL = 3 ColorCodeChannels 'RGB_I420 = 3 ColorCodeChannels 'RGB_IYUV = 3 ColorCodeChannels 'RGB_NV12 = 3 ColorCodeChannels 'RGB_NV21 = 3 ColorCodeChannels 'RGB_UYNV = 3 ColorCodeChannels 'RGB_UYVY = 3 ColorCodeChannels 'RGB_VNG = 3 ColorCodeChannels 'RGB_Y422 = 3 ColorCodeChannels 'RGB_YUNV = 3 ColorCodeChannels 'RGB_YUY2 = 3 ColorCodeChannels 'RGB_YUYV = 3 ColorCodeChannels 'RGB_YV12 = 3 ColorCodeChannels 'RGB_YVYU = 3 ColorCodeChannels 'XYZ = 3 ColorCodeChannels 'YCrCb = 3 ColorCodeChannels 'YUV = 3 ColorCodeChannels 'YUV420p = 3 ColorCodeChannels 'YUV420sp = 3 ColorCodeChannels 'YUV_I420 = 1 ColorCodeChannels 'YUV_IYUV = 1 ColorCodeChannels 'YUV_YV12 = 1 class ColorCodeMatchesChannels (code :: ColorCode) (channels :: DS Nat) instance ColorCodeMatchesChannels code 'D instance (ColorCodeChannels code ~ channels) => ColorCodeMatchesChannels code ('S channels) type family ColorCodeDepth (srcCode :: ColorCode) (dstCode :: ColorCode) (srcDepth :: DS *) :: DS * where ColorCodeDepth 'BGR 'BGRA ('S depth) = 'S depth ColorCodeDepth 'RGB 'BGRA ('S depth) = 'S depth ColorCodeDepth 'BGRA 'BGR ('S depth) = 'S depth ColorCodeDepth 'RGBA 'BGR ('S depth) = 'S depth ColorCodeDepth 'RGB 'BGR ('S depth) = 'S depth ColorCodeDepth 'BGRA 'RGBA ('S depth) = 'S depth ColorCodeDepth 'BGR 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'BGRA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'BGRA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR565 'RGBA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'RGBA ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'GRAY ('S depth) = 'S depth ColorCodeDepth 'BGRA 'GRAY ('S depth) = 'S depth ColorCodeDepth 'RGB 'GRAY ('S depth) = 'S depth ColorCodeDepth 'RGBA 'GRAY ('S depth) = 'S depth ColorCodeDepth 'BGR565 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BGR555 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'GRAY 'BGR ('S depth) = 'S depth ColorCodeDepth 'GRAY 'BGRA ('S depth) = 'S depth ColorCodeDepth 'GRAY 'BGR565 ('S Word8) = 'S Word8 ColorCodeDepth 'GRAY 'BGR555 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'YCrCb ('S depth) = 'S depth ColorCodeDepth 'BGR 'YUV ('S depth) = 'S depth ColorCodeDepth 'RGB 'YCrCb ('S depth) = 'S depth ColorCodeDepth 'RGB 'YUV ('S depth) = 'S depth ColorCodeDepth 'YCrCb 'BGR ('S depth) = 'S depth ColorCodeDepth 'YCrCb 'RGB ('S depth) = 'S depth ColorCodeDepth 'YUV 'BGR ('S depth) = 'S depth ColorCodeDepth 'YUV 'RGB ('S depth) = 'S depth ColorCodeDepth 'BGR 'XYZ ('S depth) = 'S depth ColorCodeDepth 'RGB 'XYZ ('S depth) = 'S depth ColorCodeDepth 'XYZ 'BGR ('S depth) = 'S depth ColorCodeDepth 'XYZ 'RGB ('S depth) = 'S depth ColorCodeDepth 'BGR 'HSV ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HSV ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HSV_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HSV_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HLS ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HLS ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HLS_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'HLS_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'HSV ('S Float) = 'S Float ColorCodeDepth 'RGB 'HSV ('S Float) = 'S Float ColorCodeDepth 'BGR 'HSV_FULL ('S Float) = 'S Float ColorCodeDepth 'RGB 'HSV_FULL ('S Float) = 'S Float ColorCodeDepth 'BGR 'HLS ('S Float) = 'S Float ColorCodeDepth 'RGB 'HLS ('S Float) = 'S Float ColorCodeDepth 'BGR 'HLS_FULL ('S Float) = 'S Float ColorCodeDepth 'RGB 'HLS_FULL ('S Float) = 'S Float ColorCodeDepth 'HSV 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'BGR_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'RGB_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'BGR_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HLS 'RGB_FULL ('S Word8) = 'S Word8 ColorCodeDepth 'HSV 'BGR ('S Float) = 'S Float ColorCodeDepth 'HSV 'RGB ('S Float) = 'S Float ColorCodeDepth 'HSV 'BGR_FULL ('S Float) = 'S Float ColorCodeDepth 'HSV 'RGB_FULL ('S Float) = 'S Float ColorCodeDepth 'HLS 'BGR ('S Float) = 'S Float ColorCodeDepth 'HLS 'RGB ('S Float) = 'S Float ColorCodeDepth 'HLS 'BGR_FULL ('S Float) = 'S Float ColorCodeDepth 'HLS 'RGB_FULL ('S Float) = 'S Float ColorCodeDepth 'BGR 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'LBGR 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'LRGB 'Lab ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'LBGR 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'LRGB 'Luv ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'Lab ('S Float) = 'S Float ColorCodeDepth 'RGB 'Lab ('S Float) = 'S Float ColorCodeDepth 'LBGR 'Lab ('S Float) = 'S Float ColorCodeDepth 'LRGB 'Lab ('S Float) = 'S Float ColorCodeDepth 'BGR 'Luv ('S Float) = 'S Float ColorCodeDepth 'RGB 'Luv ('S Float) = 'S Float ColorCodeDepth 'LBGR 'Luv ('S Float) = 'S Float ColorCodeDepth 'LRGB 'Luv ('S Float) = 'S Float ColorCodeDepth 'Lab 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'LBGR ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'LRGB ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'RGB ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'LBGR ('S Word8) = 'S Word8 ColorCodeDepth 'Luv 'LRGB ('S Word8) = 'S Word8 ColorCodeDepth 'Lab 'BGR ('S Float) = 'S Float ColorCodeDepth 'Lab 'RGB ('S Float) = 'S Float ColorCodeDepth 'Lab 'LBGR ('S Float) = 'S Float ColorCodeDepth 'Lab 'LRGB ('S Float) = 'S Float ColorCodeDepth 'Luv 'BGR ('S Float) = 'S Float ColorCodeDepth 'Luv 'RGB ('S Float) = 'S Float ColorCodeDepth 'Luv 'LBGR ('S Float) = 'S Float ColorCodeDepth 'Luv 'LRGB ('S Float) = 'S Float ColorCodeDepth 'BayerBG 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'GRAY ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'GRAY ('S Word16) = 'S Word16 ColorCodeDepth 'BayerBG 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'BGR ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'BGR ('S Word16) = 'S Word16 ColorCodeDepth 'BayerBG 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'BGR_VNG ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'BGR_VNG ('S Word16) = 'S Word16 ColorCodeDepth 'BayerBG 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerBG 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGB 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGB 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'BayerGR 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerGR 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'BayerRG 'BGR_EA ('S Word8) = 'S Word8 ColorCodeDepth 'BayerRG 'BGR_EA ('S Word16) = 'S Word16 ColorCodeDepth 'YUV 'BGR_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_NV21 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_NV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'GRAY_420 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'YUV_YV12 ('S Word8) = 'S Word8 ColorCodeDepth 'RGB 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'BGR 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'BGRA 'YUV_IYUV ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGB_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGR_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'RGBA_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'BGRA_YVYU ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'GRAY_UYVY ('S Word8) = 'S Word8 ColorCodeDepth 'YUV 'GRAY_YUY2 ('S Word8) = 'S Word8 ColorCodeDepth 'RGBA 'MRGBA ('S Word8) = 'S Word8 ColorCodeDepth 'MRGBA 'RGBA ('S Word8) = 'S Word8 ColorCodeDepth srcCode dstCode 'D = 'D
Cortlandd/haskell-opencv
src/OpenCV/Internal/ImgProc/MiscImgTransform/ColorCodes.hs
bsd-3-clause
43,738
0
9
10,008
13,079
6,665
6,414
-1
-1
import Control.Monad import Data.MessagePack {- main = do sb <- newSimpleBuffer pc <- newPacker sb pack pc [(1,2),(2,3),(3::Int,4::Int)] pack pc [4,5,6::Int] pack pc "hoge" bs <- simpleBufferData sb print bs up <- newUnpacker defaultInitialBufferSize unpackerFeed up bs let f = do res <- unpackerExecute up when (res==1) $ do obj <- unpackerData up print obj f f return () -} main = do bs <- packb [(1,2),(2,3),(3::Int,4::Int)] print bs dat <- unpackb bs print (dat :: Result [(Int, Int)])
tanakh/hsmsgpack
test/Test.hs
bsd-3-clause
587
0
11
176
100
55
45
7
1
{-| Copyright : (c) Dave Laing, 2017 License : BSD3 Maintainer : dave.laing.80@gmail.com Stability : experimental Portability : non-portable -} module Ast.Error.Common ( module X ) where import Ast.Error.Common.Kind as X import Ast.Error.Common.Type as X
dalaing/type-systems
src/Ast/Error/Common.hs
bsd-3-clause
271
0
4
51
32
24
8
4
0
{-# LANGUAGE GADTs #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE EmptyCase #-} module Language.BCoPL.TypeLevel.MetaTheory.CompareNat where import Language.BCoPL.TypeLevel.Peano import Language.BCoPL.TypeLevel.CompareNat -- | ๅฎš็† 2.11 (CompareNat1: 0 < 1+a) zeroLtSucc1 :: Nat' n -> LessThan1 Z (S n) zeroLtSucc1 n = case n of Z' -> LSucc1 Z' S' n' -> LTrans1 Z' n (S' n) (zeroLtSucc1 n') (LSucc1 n) -- | ๅฎš็† 2.11 (CompareNat2: 0 < 1+a) zeroLtSucc2 :: Nat' n -> LessThan2 Z (S n) zeroLtSucc2 = LZero2 -- | ๅฎš็† 2.11 (CompareNat3: 0 < 1+a) zeroLtSucc3 :: Nat' n -> LessThan3 Z (S n) zeroLtSucc3 n = case n of Z' -> LSucc3 Z' S' n' -> LSuccR3 Z' n (zeroLtSucc3 n') -- | ๅฎš็† 2.12 (CompareNat1: 1+a < 1+b => a < b) ltPred1 :: Nat' n1 -> Nat' n2 -> LessThan1 (S n1) (S n2) -> LessThan1 n1 n2 ltPred1 n1 n2 lt = case lt of LSucc1 _ -> LSucc1 n1 LTrans1 _ n3 _ lt1 lt2 -> LTrans1 n1 (S' n1) n2 (LSucc1 n1) (lemma1 (S' n1) n3 n2 lt1 lt2) lemma1 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan1 n1 n2 -> LessThan1 n2 (S n3) -> LessThan1 n1 n3 lemma1 n1 n2 n3 lt1 lt2 = case lt2 of LSucc1 _ -> lt1 LTrans1 _ n4 _ lt3 lt4 -> LTrans1 n1 n2 n3 lt1 (lemma1 n2 n4 n3 lt3 lt4) -- | ๅฎš็† 2.12 (CompareNat2: 1+a < 1+b => a < b) ltPred2 :: Nat' n1 -> Nat' n2 -> LessThan2 (S n1) (S n2) -> LessThan2 n1 n2 ltPred2 n1 n2 lt = case lt of LSuccSucc2 _ _ lt' -> lt' pat -> case pat of {} -- | ๅฎš็† 2.12 (CompareNat3: 1+a < 1+b => a < b) ltPred3 :: Nat' n1 -> Nat' n2 -> LessThan3 (S n1) (S n2) -> LessThan3 n1 n2 ltPred3 n1 n2 lt = case lt of LSucc3 _ -> LSucc3 n1 LSuccR3 n1' n2' lt' -> lemma3 n1 n1' n2 (LSucc3 n1) lt' lemma3 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan3 n1 n2 -> LessThan3 n2 n3 -> LessThan3 n1 n3 lemma3 n1 n2 n3 lt1 lt2 = case lt2 of LSucc3 _ -> LSuccR3 n1 n2 lt1 LSuccR3 _ n4 lt3 -> lemma3 n1 n4 n3 (lemma3 n1 n2 n4 lt1 lt3) (LSucc3 n4) -- ๅฎš็† 2.13 -- | ๅฎš็† 2.13 (CompareNat1: a < b, b < c => a < c) trans1 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan1 n1 n2 -> LessThan1 n2 n3 -> LessThan1 n1 n3 trans1 = LTrans1 -- | ๅฎš็† 2.13 (CompareNat2: a < b, b < c => a < c) trans2 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan2 n1 n2 -> LessThan2 n2 n3 -> LessThan2 n1 n3 trans2 n1 n2 n3 lt1 lt2 = case lt2 of LSuccSucc2 n4 n5 lt3 -> case lt1 of LZero2 _ -> LZero2 n5 LSuccSucc2 n6 _ lt4 -> LSuccSucc2 n6 n5 (trans2 n6 n4 n5 lt4 lt3) pat -> case pat of {} -- | ๅฎš็† 2.13 (CompareNat3: a < b, b < c => a < c) trans3 :: Nat' n1 -> Nat' n2 -> Nat' n3 -> LessThan3 n1 n2 -> LessThan3 n2 n3 -> LessThan3 n1 n3 trans3 = lemma3 -- | ๅฎš็† 2.14 eqv13 :: Nat' n1 -> Nat' n2 -> LessThan1 n1 n2 -> LessThan3 n1 n2 eqv13 n1 n2 lt1 = case lt1 of LSucc1 _ -> LSucc3 n1 LTrans1 _ n3 _ lt2 lt3 -> trans3 n1 n3 n2 (eqv13 n1 n3 lt2) (eqv13 n3 n2 lt3) eqv32 :: Nat' n1 -> Nat' n2 -> LessThan3 n1 n2 -> LessThan2 n1 n2 eqv32 n1 n2 lt1 = case lt1 of LSucc3 _ -> case n1 of Z' -> LZero2 n1 S' n1' -> LSuccSucc2 n1' n1 (eqv32 n1' n1 (LSucc3 n1')) LSuccR3 _ n3 lt2 -> trans2 n1 n3 n2 (eqv32 n1 n3 lt2) (eqv32 n3 n2 (LSucc3 n3)) eqv21 :: Nat' n1 -> Nat' n2 -> LessThan2 n1 n2 -> LessThan1 n1 n2 eqv21 n1 n2 lt1 = case lt1 of LZero2 n3 -> case n3 of Z' -> LSucc1 n3 S' n4 -> trans1 n1 n3 n2 (eqv21 n1 n3 (LZero2 n4)) (LSucc1 n3) LSuccSucc2 n5 n6 lt2 -> succSucc1 n5 n6 (eqv21 n5 n6 lt2) succSucc1 :: Nat' n1 -> Nat' n2 -> LessThan1 n1 n2 -> LessThan1 (S n1) (S n2) succSucc1 n1 n2 lt = case lt of LSucc1 _ -> LSucc1 n2 LTrans1 _ n3 _ lt' lt'' -> LTrans1 (S' n1) (S' n3) (S' n2) (succSucc1 n1 n3 lt') (succSucc1 n3 n2 lt'')
nobsun/hs-bcopl
src/Language/BCoPL/TypeLevel/MetaTheory/CompareNat.hs
bsd-3-clause
3,794
0
15
1,041
1,587
762
825
77
3
module Web.Plurk.Types ( Return (..) , Message (..) , User (..) , Privacy (..) , Gender (..) , Relationship (..) , Qualifier (..) , ReadStat (..) , MsgType (..) , CommentStat (..) , KarmaStat (..) , Profile (..) , jsToInt , jsToDouble , jsToStr , jsToBool , jsToEnum , jsToDateTime , jsToList , jsToMap , jsToIntMap , jsToErrorMsg , jsToUser , jsToMessage , jsToKarmaStat , jsToProfile ) where import Data.IntMap (IntMap) import qualified Data.IntMap as IM import Data.Map (Map) import qualified Data.Map as M import Data.Maybe import Data.Ratio import Data.Time import Data.Time.Clock.POSIX import System.Locale import Text.JSON data Return a = PData a | PSucc | PError String data Message = Message { msg_plurk_id :: Int , msg_qualifier :: Qualifier , msg_is_unread :: ReadStat , msg_plurk_type :: MsgType , msg_user_id :: Int , msg_owner_id :: Int , msg_posted :: UTCTime , msg_no_comments :: CommentStat , msg_content :: String , msg_content_raw :: String , msg_response_count :: Int , msg_responses_seen :: Int , msg_limited_to :: [Int] } deriving Show data User = User { user_id :: Int , user_nick_name :: String , user_display_name :: String , user_has_profile_image :: Bool , user_avatar :: Int , user_location :: String , user_date_of_birth :: Day , user_full_name :: String , user_gender :: Gender , user_page_title :: String , user_karma :: Double , user_recruited :: Int , user_relationship :: Relationship } deriving Show data KarmaStat = KarmaStat { karma_stat_karma_trend :: [(UTCTime, Double)] , karma_stat_karma_fall_reason :: String , karma_stat_current_karma :: Double , karma_stat_karma_graph :: String } deriving Show data Profile = Profile { profile_friends_count :: Int , profile_fans_count :: Int , profile_unread_count :: Int , profile_alerts_count :: Int , profile_are_friends :: Bool , profile_is_fan :: Bool , profile_is_following :: Bool , profile_has_read_permission :: Bool , profile_user_info :: User , profile_privacy :: Privacy , profile_plurks_users :: IntMap User , profile_plurks :: [Message] } deriving Show data Privacy = World | OnlyFriends | OnlyMe instance Show Privacy where show World = "world" show OnlyFriends = "only_friends" show OnlyMe = "only_me" instance Read Privacy where readsPrec 0 "world" = [(World, "")] readsPrec 0 "only_friends" = [(OnlyFriends, "")] readsPrec 0 "only_me" = [(OnlyMe, "")] readsPrec _ _ = [(World, "")] data Gender = Female | Male | Other deriving Enum instance Show Gender where show Female = "female" show Male = "male" show Other = "other" data Relationship = NotSaying | Single | Married | Divorced | Engaged | InRelationship | Complicated | Widowed | OpenRelationship instance Show Relationship where show NotSaying = "not_saying" show Single = "single" show Married = "married" show Divorced = "divorced" show Engaged = "engaged" show InRelationship = "in_relationship" show Complicated = "complicated" show Widowed = "widowed" show OpenRelationship = "open_relationship" instance Read Relationship where readsPrec 0 "not_saying" = [(NotSaying, "")] readsPrec 0 "single" = [(Single, "")] readsPrec 0 "married" = [(Married, "")] readsPrec 0 "divorced" = [(Divorced, "")] readsPrec 0 "engaged" = [(Engaged, "")] readsPrec 0 "in_relationship" = [(InRelationship, "")] readsPrec 0 "complicated" = [(Complicated, "")] readsPrec 0 "widowed" = [(Widowed, "")] readsPrec 0 "open_relationship" = [(OpenRelationship, "")] readsPrec _ _ = [(NotSaying, "")] data Qualifier = Loves | Likes | Shares | Gives | Hates | Wants | Has | Will | Asks | Wishes | Was | Feels | Thinks | Says | Is | Colon | Freestyle | Hopes | Needs | Wonders instance Show Qualifier where show Loves = "loves" show Likes = "likes" show Shares = "shares" show Gives = "gives" show Hates = "hates" show Wants = "wants" show Has = "has" show Will = "will" show Asks = "asks" show Wishes = "wishes" show Was = "was" show Feels = "feels" show Thinks = "thinks" show Says = "says" show Is = "is" show Colon = ":" show Freestyle = "freestyle" show Hopes = "hopes" show Needs = "needs" show Wonders = "wonders" instance Read Qualifier where readsPrec 0 "loves" = [(Loves, "")] readsPrec 0 "likes" = [(Likes, "")] readsPrec 0 "shares" = [(Shares, "")] readsPrec 0 "gives" = [(Gives, "")] readsPrec 0 "hates" = [(Hates, "")] readsPrec 0 "wants" = [(Wants, "")] readsPrec 0 "has" = [(Has, "")] readsPrec 0 "will" = [(Will, "")] readsPrec 0 "asks" = [(Asks, "")] readsPrec 0 "wishes" = [(Wishes, "")] readsPrec 0 "was" = [(Was, "")] readsPrec 0 "feels" = [(Feels, "")] readsPrec 0 "thinks" = [(Thinks, "")] readsPrec 0 "says" = [(Says, "")] readsPrec 0 "is" = [(Is, "")] readsPrec 0 ":" = [(Colon, "")] readsPrec 0 "freestyle" = [(Freestyle, "")] readsPrec 0 "hopes" = [(Hopes, "")] readsPrec 0 "needs" = [(Needs, "")] readsPrec 0 "wonders" = [(Wonders, "")] readsPrec _ _ = [(Colon, "")] data ReadStat = Read | UnRead | Muted deriving (Enum, Show) data MsgType = Public | Private | PubLogged | PrivLogged deriving (Enum, Show) data CommentStat = EnResp | DisResp | OnlyFriendResp deriving (Enum, Show) jsToDouble :: JSValue -> Double jsToDouble JSNull = 0 jsToDouble (JSRational _ n) = fromRational n jsToDouble v = error $ "jsToDouble: " ++ show v jsToInt :: JSValue -> Int jsToInt JSNull = 0 jsToInt (JSRational _ n) = fromInteger $ numerator n jsToInt v = error $ "jsToInt: " ++ show v jsToStr :: JSValue -> String jsToStr JSNull = "" jsToStr (JSString s) = fromJSString s jsToStr v = error $ "jsToStr: " ++ show v jsToBool :: JSValue -> Bool jsToBool JSNull = False jsToBool (JSBool b) = b jsToBool v = error $ "jsToBool: " ++ show v jsToList :: JSValue -> [JSValue] jsToList JSNull = [] jsToList (JSArray a) = a jsToList v = error $ "jsToList: " ++ show v jsToMap :: JSValue -> Map String JSValue jsToMap JSNull = M.empty jsToMap (JSObject o) = M.fromList $ fromJSObject o jsToMap v = error $ "jsToMap: " ++ show v jsToIntMap :: JSValue -> IntMap JSValue jsToIntMap JSNull = IM.empty jsToIntMap (JSObject o) = IM.fromList $ map (\(k, v) -> (read k, v)) $ fromJSObject o jsToIntMap v = error $ "jsToIntMap: " ++ show v jsToEnum :: Enum a => JSValue -> a jsToEnum = toEnum . jsToInt jsToDateTime :: ParseTime a => JSValue -> Maybe a jsToDateTime = parseTime defaultTimeLocale fmt . jsToStr where fmt = "%a, %d %b %Y %H:%M:%S %Z" jsToErrorMsg :: JSValue -> String jsToErrorMsg = jsToStr . M.findWithDefault JSNull "error_text" . jsToMap getMapVal :: String -> Map String JSValue -> JSValue getMapVal = M.findWithDefault JSNull nullMsg = Message { msg_plurk_id = 0 , msg_qualifier = Colon , msg_is_unread = Read , msg_plurk_type = Public , msg_user_id = 0 , msg_owner_id = 0 , msg_posted = UTCTime (ModifiedJulianDay 0) (secondsToDiffTime 0) , msg_no_comments = EnResp , msg_content = "" , msg_content_raw = "" , msg_response_count = 0 , msg_responses_seen = 0 , msg_limited_to = [] } jsToMessage :: JSValue -> Message jsToMessage obj = msg where msg = nullMsg { msg_plurk_id = jsToInt $ val "plurk_id" , msg_qualifier = read $ jsToStr $ val "qualifier" , msg_is_unread = jsToEnum $ val "is_unread" , msg_plurk_type = jsToEnum $ val "plurk_type" , msg_user_id = jsToInt $ val "user_id" , msg_owner_id = jsToInt $ val "owner_id" , msg_posted = maybeTime $ jsToDateTime $ val "posted" , msg_no_comments = jsToEnum $ val "no_comments" , msg_content = jsToStr $ val "content" , msg_content_raw = jsToStr $ val "content_raw" , msg_response_count = jsToInt $ val "response_count" , msg_responses_seen = jsToInt $ val "responses_seen" , msg_limited_to = toList $ jsToStr $ val "limited_to" } val n = getMapVal n m m = jsToMap obj maybeTime = maybe (msg_posted nullMsg) id toList = go [] where go ls [] = ls go ls (_:ss) = let (uid, rest) = span (/= '|') ss in go (read uid : ls) (tail rest) nullUser = User { user_id = 0 , user_nick_name = "" , user_display_name = "" , user_has_profile_image = False , user_avatar = 0 , user_location = "" , user_date_of_birth = ModifiedJulianDay 0 , user_full_name = "" , user_gender = Female , user_page_title = "" , user_karma = 0 , user_recruited = 0 , user_relationship = NotSaying } jsToUser :: JSValue -> User jsToUser (JSObject o) = user where user = nullUser { user_id = jsToInt $ val "id" , user_nick_name = jsToStr $ val "nick_name" , user_display_name = jsToStr $ val "display_name" , user_has_profile_image = toEnum $ jsToInt $ val "has_profile_image" , user_avatar = jsToInt $ val "avatar" , user_gender = jsToEnum $ val "gender" , user_location = jsToStr $ val "location" , user_date_of_birth = maybeDay $ jsToDateTime $ val "date_of_birth" , user_full_name = jsToStr $ val "full_name" , user_page_title = jsToStr $ val "page_title" , user_karma = jsToDouble $ val "karma" , user_recruited = jsToInt $ val "recruited" , user_relationship = read $ jsToStr $ val "relationship" } val n = getMapVal n m m = M.fromList $ fromJSObject o maybeDay = maybe (user_date_of_birth nullUser) id jsToUser v = error $ "jsToUser: " ++ show v nullKarmaStat = KarmaStat { karma_stat_karma_trend = [] , karma_stat_karma_fall_reason = "" , karma_stat_current_karma = 0 , karma_stat_karma_graph = "" } jsToKarmaStat (JSObject o) = stat where stat = nullKarmaStat { karma_stat_karma_trend = toStats $ val "karma_trend" , karma_stat_karma_fall_reason = jsToStr $ val "karma_fall_reason" , karma_stat_current_karma = jsToDouble $ val "current_karma" , karma_stat_karma_graph = jsToStr $ val "karma_graph" } toStats = map (strToStat . span (/= '-') . jsToStr) . jsToList strToStat (t, k) = (intToTime t, read $ tail k) intToTime = posixSecondsToUTCTime . fromInteger . read val n = getMapVal n m m = M.fromList $ fromJSObject o jsToKarmaStat v = error $ "jsToKarmaStat: " ++ show v nullProfile = Profile { profile_friends_count = 0 , profile_fans_count = 0 , profile_unread_count = 0 , profile_alerts_count = 0 , profile_are_friends = False , profile_is_fan = False , profile_is_following = False , profile_has_read_permission = False , profile_user_info = nullUser , profile_privacy = World , profile_plurks_users = IM.empty , profile_plurks = [] } jsToProfile own obj = if own then owner else public where owner = common { profile_unread_count = jsToInt $ val "unread_count" , profile_alerts_count = jsToInt $ val "alerts_count" , profile_plurks_users = IM.map jsToUser $ jsToIntMap $ val "plurks_users" } public = common { profile_are_friends = jsToBool $ val "are_friends" , profile_is_fan = jsToBool $ val "is_fan" , profile_is_following = jsToBool $ val "is_following" , profile_has_read_permission = jsToBool $ val "has_read_permission" } common = nullProfile { profile_friends_count = jsToInt $ val "friends_count" , profile_fans_count = jsToInt $ val "fans_count" , profile_user_info = jsToUser $ val "user_info" , profile_privacy = read $ jsToStr $ val "privacy" , profile_plurks = map jsToMessage $ jsToList $ val "plurks" } val n = getMapVal n m m = jsToMap obj
crabtw/hsplurk
Web/Plurk/Types.hs
bsd-3-clause
15,627
0
14
6,558
3,641
2,052
1,589
360
2