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 DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
module Distribution.Types.BuildInfo (
BuildInfo(..),
emptyBuildInfo,
allLanguages,
allExtensions,
usedExtensions,
hcOptions,
hcProfOptions,
hcSharedOptions,
) where
import Prelude ()
import Distribution.Compat.Prelude
import Distribution.Types.ModuleRenaming
import Distribution.Package
import Distribution.ModuleName
import Distribution.Compiler
import Language.Haskell.Extension
import qualified Data.Map as Map
-- Consider refactoring into executable and library versions.
data BuildInfo = BuildInfo {
buildable :: Bool, -- ^ component is buildable here
buildTools :: [Dependency], -- ^ tools needed to build this bit
cppOptions :: [String], -- ^ options for pre-processing Haskell code
ccOptions :: [String], -- ^ options for C compiler
ldOptions :: [String], -- ^ options for linker
pkgconfigDepends :: [Dependency], -- ^ pkg-config packages that are used
frameworks :: [String], -- ^support frameworks for Mac OS X
extraFrameworkDirs:: [String], -- ^ extra locations to find frameworks.
cSources :: [FilePath],
jsSources :: [FilePath],
hsSourceDirs :: [FilePath], -- ^ where to look for the Haskell module hierarchy
otherModules :: [ModuleName], -- ^ non-exposed or non-main modules
autogenModules :: [ModuleName], -- ^ not present on sdist, Paths_* or user-generated with a custom Setup.hs
defaultLanguage :: Maybe Language,-- ^ language used when not explicitly specified
otherLanguages :: [Language], -- ^ other languages used within the package
defaultExtensions :: [Extension], -- ^ language extensions used by all modules
otherExtensions :: [Extension], -- ^ other language extensions used within the package
oldExtensions :: [Extension], -- ^ the old extensions field, treated same as 'defaultExtensions'
extraLibs :: [String], -- ^ what libraries to link with when compiling a program that uses your package
extraGHCiLibs :: [String], -- ^ if present, overrides extraLibs when package is loaded with GHCi.
extraLibDirs :: [String],
includeDirs :: [FilePath], -- ^directories to find .h files
includes :: [FilePath], -- ^ The .h files to be found in includeDirs
installIncludes :: [FilePath], -- ^ .h files to install with the package
options :: [(CompilerFlavor,[String])],
profOptions :: [(CompilerFlavor,[String])],
sharedOptions :: [(CompilerFlavor,[String])],
customFieldsBI :: [(String,String)], -- ^Custom fields starting
-- with x-, stored in a
-- simple assoc-list.
targetBuildDepends :: [Dependency], -- ^ Dependencies specific to a library or executable target
targetBuildRenaming :: Map PackageName ModuleRenaming
}
deriving (Generic, Show, Read, Eq, Typeable, Data)
instance Binary BuildInfo
instance Monoid BuildInfo where
mempty = BuildInfo {
buildable = True,
buildTools = [],
cppOptions = [],
ccOptions = [],
ldOptions = [],
pkgconfigDepends = [],
frameworks = [],
extraFrameworkDirs = [],
cSources = [],
jsSources = [],
hsSourceDirs = [],
otherModules = [],
autogenModules = [],
defaultLanguage = Nothing,
otherLanguages = [],
defaultExtensions = [],
otherExtensions = [],
oldExtensions = [],
extraLibs = [],
extraGHCiLibs = [],
extraLibDirs = [],
includeDirs = [],
includes = [],
installIncludes = [],
options = [],
profOptions = [],
sharedOptions = [],
customFieldsBI = [],
targetBuildDepends = [],
targetBuildRenaming = Map.empty
}
mappend = (<>)
instance Semigroup BuildInfo where
a <> b = BuildInfo {
buildable = buildable a && buildable b,
buildTools = combine buildTools,
cppOptions = combine cppOptions,
ccOptions = combine ccOptions,
ldOptions = combine ldOptions,
pkgconfigDepends = combine pkgconfigDepends,
frameworks = combineNub frameworks,
extraFrameworkDirs = combineNub extraFrameworkDirs,
cSources = combineNub cSources,
jsSources = combineNub jsSources,
hsSourceDirs = combineNub hsSourceDirs,
otherModules = combineNub otherModules,
autogenModules = combineNub autogenModules,
defaultLanguage = combineMby defaultLanguage,
otherLanguages = combineNub otherLanguages,
defaultExtensions = combineNub defaultExtensions,
otherExtensions = combineNub otherExtensions,
oldExtensions = combineNub oldExtensions,
extraLibs = combine extraLibs,
extraGHCiLibs = combine extraGHCiLibs,
extraLibDirs = combineNub extraLibDirs,
includeDirs = combineNub includeDirs,
includes = combineNub includes,
installIncludes = combineNub installIncludes,
options = combine options,
profOptions = combine profOptions,
sharedOptions = combine sharedOptions,
customFieldsBI = combine customFieldsBI,
targetBuildDepends = combineNub targetBuildDepends,
targetBuildRenaming = combineMap targetBuildRenaming
}
where
combine field = field a `mappend` field b
combineNub field = nub (combine field)
combineMby field = field b `mplus` field a
combineMap field = Map.unionWith mappend (field a) (field b)
emptyBuildInfo :: BuildInfo
emptyBuildInfo = mempty
-- | The 'Language's used by this component
--
allLanguages :: BuildInfo -> [Language]
allLanguages bi = maybeToList (defaultLanguage bi)
++ otherLanguages bi
-- | The 'Extension's that are used somewhere by this component
--
allExtensions :: BuildInfo -> [Extension]
allExtensions bi = usedExtensions bi
++ otherExtensions bi
-- | The 'Extensions' that are used by all modules in this component
--
usedExtensions :: BuildInfo -> [Extension]
usedExtensions bi = oldExtensions bi
++ defaultExtensions bi
-- |Select options for a particular Haskell compiler.
hcOptions :: CompilerFlavor -> BuildInfo -> [String]
hcOptions = lookupHcOptions options
hcProfOptions :: CompilerFlavor -> BuildInfo -> [String]
hcProfOptions = lookupHcOptions profOptions
hcSharedOptions :: CompilerFlavor -> BuildInfo -> [String]
hcSharedOptions = lookupHcOptions sharedOptions
lookupHcOptions :: (BuildInfo -> [(CompilerFlavor,[String])])
-> CompilerFlavor -> BuildInfo -> [String]
lookupHcOptions f hc bi = [ opt | (hc',opts) <- f bi
, hc' == hc
, opt <- opts ]
| sopvop/cabal | Cabal/Distribution/Types/BuildInfo.hs | bsd-3-clause | 7,270 | 0 | 11 | 2,167 | 1,374 | 821 | 553 | 143 | 1 |
-- |
-- Module : Language.C.Syntax
-- Copyright : (c) 2006-2011 Harvard University
-- (c) 2011-2013 Geoffrey Mainland
-- (c) 2013 Manuel M T Chakravarty
-- : (c) 2013-2015 Drexel University
-- License : BSD-style
-- Maintainer : mainland@cs.drexel.edu
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE FlexibleInstances #-}
module Language.C.Syntax where
import Data.Data (Data(..))
import Data.Loc
import Data.Typeable (Typeable)
data Extensions = Antiquotation
| C99
| C11
| Gcc
| Blocks
| ObjC
| CUDA
| OpenCL
deriving (Eq, Ord, Enum, Show)
data Id = Id String !SrcLoc
| AntiId String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data StringLit = StringLit [String] String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
type Linkage = StringLit
data Storage = Tauto !SrcLoc
| Tregister !SrcLoc
| Tstatic !SrcLoc
| Textern (Maybe Linkage) !SrcLoc
| Ttypedef !SrcLoc
-- Clang blocks
| T__block !SrcLoc
-- Objective-C
| TObjC__weak !SrcLoc
| TObjC__strong !SrcLoc
| TObjC__unsafe_unretained !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data TypeQual = Tconst !SrcLoc
| Tvolatile !SrcLoc
| AntiTypeQual String !SrcLoc
| AntiTypeQuals String !SrcLoc
-- C99
| Tinline !SrcLoc
| Trestrict !SrcLoc
-- GCC
| TAttr Attr
-- CUDA
| TCUDAdevice !SrcLoc
| TCUDAglobal !SrcLoc
| TCUDAhost !SrcLoc
| TCUDAconstant !SrcLoc
| TCUDAshared !SrcLoc
| TCUDArestrict !SrcLoc
| TCUDAnoinline !SrcLoc
-- OpenCL
| TCLprivate !SrcLoc
| TCLlocal !SrcLoc
| TCLglobal !SrcLoc
| TCLconstant !SrcLoc
| TCLreadonly !SrcLoc
| TCLwriteonly !SrcLoc
| TCLkernel !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Sign = Tsigned !SrcLoc
| Tunsigned !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data TypeSpec = Tvoid !SrcLoc
| Tchar (Maybe Sign) !SrcLoc
| Tshort (Maybe Sign) !SrcLoc
| Tint (Maybe Sign) !SrcLoc
| Tlong (Maybe Sign) !SrcLoc
| Tlong_long (Maybe Sign) !SrcLoc
| Tfloat !SrcLoc
| Tdouble !SrcLoc
| Tlong_double !SrcLoc
| Tstruct (Maybe Id) (Maybe [FieldGroup]) [Attr] !SrcLoc
| Tunion (Maybe Id) (Maybe [FieldGroup]) [Attr] !SrcLoc
| Tenum (Maybe Id) [CEnum] [Attr] !SrcLoc
| Tnamed Id -- A typedef name
[Id] -- Objective-C protocol references
!SrcLoc
-- C99
| T_Bool !SrcLoc
| Tfloat_Complex !SrcLoc
| Tdouble_Complex !SrcLoc
| Tlong_double_Complex !SrcLoc
| Tfloat_Imaginary !SrcLoc
| Tdouble_Imaginary !SrcLoc
| Tlong_double_Imaginary !SrcLoc
-- Gcc
| TtypeofExp Exp !SrcLoc
| TtypeofType Type !SrcLoc
| Tva_list !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data DeclSpec = DeclSpec [Storage] [TypeQual] TypeSpec !SrcLoc
| AntiDeclSpec String !SrcLoc
| AntiTypeDeclSpec [Storage] [TypeQual] String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
-- | There are two types of declarators in C, regular declarators and abstract
-- declarators. The former is for declaring variables, function parameters,
-- typedefs, etc. and the latter for abstract types---@typedef int
-- ({*}foo)(void)@ vs. @\tt int ({*})(void)@. The difference between the two is
-- just whether or not an identifier is attached to the declarator. We therefore
-- only define one 'Decl' type and use it for both cases.
data ArraySize = ArraySize Bool Exp !SrcLoc
| VariableArraySize !SrcLoc
| NoArraySize !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Decl = DeclRoot !SrcLoc
| Ptr [TypeQual] Decl !SrcLoc
| Array [TypeQual] ArraySize Decl !SrcLoc
| Proto Decl Params !SrcLoc
| OldProto Decl [Id] !SrcLoc
| AntiTypeDecl String !SrcLoc
-- Clang blocks
| BlockPtr [TypeQual] Decl !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Type = Type DeclSpec Decl !SrcLoc
| AntiType String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Designator = IndexDesignator Exp !SrcLoc
| MemberDesignator Id !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Designation = Designation [Designator] !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Initializer = ExpInitializer Exp !SrcLoc
| CompoundInitializer [(Maybe Designation, Initializer)] !SrcLoc
| AntiInit String !SrcLoc
| AntiInits String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
type AsmLabel = StringLit
data Init = Init Id Decl (Maybe AsmLabel) (Maybe Initializer) [Attr] !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Typedef = Typedef Id Decl [Attr] !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data InitGroup = InitGroup DeclSpec [Attr] [Init] !SrcLoc
| TypedefGroup DeclSpec [Attr] [Typedef] !SrcLoc
| AntiDecl String !SrcLoc
| AntiDecls String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Field = Field (Maybe Id) (Maybe Decl) (Maybe Exp) !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data FieldGroup = FieldGroup DeclSpec [Field] !SrcLoc
| AntiSdecl String !SrcLoc
| AntiSdecls String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data CEnum = CEnum Id (Maybe Exp) !SrcLoc
| AntiEnum String !SrcLoc
| AntiEnums String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Attr = Attr Id [Exp] !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Param = Param (Maybe Id) DeclSpec Decl !SrcLoc
| AntiParam String !SrcLoc
| AntiParams String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Params = Params [Param] Bool !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Func = Func DeclSpec Id Decl Params [BlockItem] !SrcLoc
| OldFunc DeclSpec Id Decl [Id] (Maybe [InitGroup]) [BlockItem] !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Definition = FuncDef Func !SrcLoc
| DecDef InitGroup !SrcLoc
| EscDef String !SrcLoc
| AntiFunc String !SrcLoc
| AntiEsc String !SrcLoc
| AntiEdecl String !SrcLoc
| AntiEdecls String !SrcLoc
-- Objective-C
| ObjCClassDec [Id] !SrcLoc
| ObjCClassIface Id (Maybe Id) [Id] [ObjCIvarDecl] [ObjCIfaceDecl] [Attr] !SrcLoc
| ObjCCatIface Id (Maybe Id) [Id] [ObjCIvarDecl] [ObjCIfaceDecl] !SrcLoc
| ObjCProtDec [Id] !SrcLoc
| ObjCProtDef Id [Id] [ObjCIfaceDecl] !SrcLoc
| ObjCClassImpl Id (Maybe Id) [ObjCIvarDecl] [Definition] !SrcLoc
| ObjCCatImpl Id Id [Definition] !SrcLoc
| ObjCSynDef [(Id, Maybe Id)] !SrcLoc
| ObjCDynDef [Id] !SrcLoc
| ObjCMethDef ObjCMethodProto [BlockItem] !SrcLoc
| ObjCCompAlias Id Id !SrcLoc
| AntiObjCMeth String !SrcLoc
| AntiObjCMeths String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Stm = Label Id [Attr] Stm !SrcLoc
| Case Exp Stm !SrcLoc
| Default Stm !SrcLoc
| Exp (Maybe Exp) !SrcLoc
| Block [BlockItem] !SrcLoc
| If Exp Stm (Maybe Stm) !SrcLoc
| Switch Exp Stm !SrcLoc
| While Exp Stm !SrcLoc
| DoWhile Stm Exp !SrcLoc
| For (Either InitGroup (Maybe Exp)) (Maybe Exp) (Maybe Exp) Stm !SrcLoc
| Goto Id !SrcLoc
| Continue !SrcLoc
| Break !SrcLoc
| Return (Maybe Exp) !SrcLoc
| Pragma String !SrcLoc
| Comment String Stm !SrcLoc
| AntiPragma String !SrcLoc
| AntiComment String Stm !SrcLoc
| AntiStm String !SrcLoc
| AntiStms String !SrcLoc
-- GCC
| Asm Bool -- @True@ if volatile, @False@ otherwise
[Attr] -- Attributes
AsmTemplate -- Assembly template
[AsmOut] -- Output operands
[AsmIn] -- Input operands
[AsmClobber] -- Clobbered registers
!SrcLoc
| AsmGoto Bool -- @True@ if volatile, @False@ otherwise
[Attr] -- Attributes
AsmTemplate -- Assembly template
[AsmIn] -- Input operands
[AsmClobber] -- Clobbered registers
[Id] -- Labels
!SrcLoc
-- Objective-C
| ObjCTry [BlockItem] [ObjCCatch] (Maybe [BlockItem]) !SrcLoc
-- ^Invariant: There is either at least one 'ObjCCatch' or the finally block is present.
| ObjCThrow (Maybe Exp) !SrcLoc
| ObjCSynchronized Exp [BlockItem] !SrcLoc
| ObjCAutoreleasepool [BlockItem] !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data BlockItem = BlockDecl InitGroup
| BlockStm Stm
| AntiBlockItem String !SrcLoc
| AntiBlockItems String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Signed = Signed
| Unsigned
deriving (Eq, Ord, Show, Data, Typeable)
-- | The 'String' parameter to 'Const' data constructors is the raw string
-- representation of the constant as it was parsed.
data Const = IntConst String Signed Integer !SrcLoc
| LongIntConst String Signed Integer !SrcLoc
| LongLongIntConst String Signed Integer !SrcLoc
| FloatConst String Rational !SrcLoc
| DoubleConst String Rational !SrcLoc
| LongDoubleConst String Rational !SrcLoc
| CharConst String Char !SrcLoc
| StringConst [String] String !SrcLoc
| AntiConst String !SrcLoc
| AntiInt String !SrcLoc
| AntiUInt String !SrcLoc
| AntiLInt String !SrcLoc
| AntiULInt String !SrcLoc
| AntiLLInt String !SrcLoc
| AntiULLInt String !SrcLoc
| AntiFloat String !SrcLoc
| AntiDouble String !SrcLoc
| AntiLongDouble String !SrcLoc
| AntiChar String !SrcLoc
| AntiString String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data Exp = Var Id !SrcLoc
| Const Const !SrcLoc
| BinOp BinOp Exp Exp !SrcLoc
| Assign Exp AssignOp Exp !SrcLoc
| PreInc Exp !SrcLoc
| PostInc Exp !SrcLoc
| PreDec Exp !SrcLoc
| PostDec Exp !SrcLoc
| UnOp UnOp Exp !SrcLoc
| SizeofExp Exp !SrcLoc
| SizeofType Type !SrcLoc
| Cast Type Exp !SrcLoc
| Cond Exp Exp Exp !SrcLoc
| Member Exp Id !SrcLoc
| PtrMember Exp Id !SrcLoc
| Index Exp Exp !SrcLoc
| FnCall Exp [Exp] !SrcLoc
| CudaCall Exp ExeConfig [Exp] !SrcLoc
| Seq Exp Exp !SrcLoc
| CompoundLit Type [(Maybe Designation, Initializer)] !SrcLoc
| StmExpr [BlockItem] !SrcLoc
| AntiExp String !SrcLoc
| AntiArgs String !SrcLoc
-- GCC
| BuiltinVaArg Exp Type !SrcLoc
-- Clang blocks
| BlockLit BlockType [Attr] [BlockItem] !SrcLoc
-- Objective-C
| ObjCMsg ObjCRecv [ObjCArg] [Exp] !SrcLoc
-- ^Invariant: First argument must at least have either a selector or an expression;
-- all other arguments must have an expression.
| ObjCLitConst (Maybe UnOp)
Const -- Anything except 'StringConst'
!SrcLoc
| ObjCLitString [Const] -- Must all be 'StringConst'
!SrcLoc
| ObjCLitBool Bool !SrcLoc
| ObjCLitArray [Exp] !SrcLoc
| ObjCLitDict [ObjCDictElem] !SrcLoc
| ObjCLitBoxed Exp !SrcLoc
| ObjCEncode Type !SrcLoc
| ObjCProtocol Id !SrcLoc
| ObjCSelector String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data BinOp = Add
| Sub
| Mul
| Div
| Mod
| Eq
| Ne
| Lt
| Gt
| Le
| Ge
| Land
| Lor
| And
| Or
| Xor
| Lsh
| Rsh
deriving (Eq, Ord, Show, Data, Typeable)
data AssignOp = JustAssign
| AddAssign
| SubAssign
| MulAssign
| DivAssign
| ModAssign
| LshAssign
| RshAssign
| AndAssign
| XorAssign
| OrAssign
deriving (Eq, Ord, Show, Data, Typeable)
data UnOp = AddrOf
| Deref
| Positive
| Negate
| Not
| Lnot
deriving (Eq, Ord, Show, Data, Typeable)
{------------------------------------------------------------------------------
-
- GCC extensions
-
------------------------------------------------------------------------------}
type AsmTemplate = StringLit
data AsmOut = AsmOut (Maybe Id) String Id
deriving (Eq, Ord, Show, Data, Typeable)
data AsmIn = AsmIn (Maybe Id) String Exp
deriving (Eq, Ord, Show, Data, Typeable)
type AsmClobber = String
{------------------------------------------------------------------------------
-
- Clang blocks
-
------------------------------------------------------------------------------}
data BlockType = BlockVoid !SrcLoc
| BlockParam [Param] !SrcLoc
| BlockType Type !SrcLoc
-- NB: Type may be something other than 'Proto', in which case clang defaults to
-- regard the type as the return type and assume the arguments to be 'void'.
deriving (Eq, Ord, Show, Data, Typeable)
{------------------------------------------------------------------------------
-
- Objective-C
-
------------------------------------------------------------------------------}
data ObjCIvarDecl = ObjCIvarVisi ObjCVisibilitySpec !SrcLoc
| ObjCIvarDecl FieldGroup !SrcLoc
-- -=chak FIXME: needs ANTI forms
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCVisibilitySpec = ObjCPrivate !SrcLoc
| ObjCPublic !SrcLoc
| ObjCProtected !SrcLoc
| ObjCPackage !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCIfaceDecl = ObjCIfaceProp [ObjCPropAttr] FieldGroup !SrcLoc
| ObjCIfaceReq ObjCMethodReq !SrcLoc
| ObjCIfaceMeth ObjCMethodProto !SrcLoc
| ObjCIfaceDecl InitGroup !SrcLoc
| AntiObjCProp String !SrcLoc
| AntiObjCProps String !SrcLoc
| AntiObjCIfaceDecl String !SrcLoc
| AntiObjCIfaceDecls String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCPropAttr = ObjCGetter Id !SrcLoc
| ObjCSetter Id !SrcLoc
| ObjCReadonly !SrcLoc
| ObjCReadwrite !SrcLoc
| ObjCAssign !SrcLoc
| ObjCRetain !SrcLoc
| ObjCCopy !SrcLoc
| ObjCNonatomic !SrcLoc
| ObjCAtomic !SrcLoc
| ObjCStrong !SrcLoc
| ObjCWeak !SrcLoc
| ObjCUnsafeUnretained !SrcLoc
| AntiObjCAttr String !SrcLoc
| AntiObjCAttrs String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCMethodReq = ObjCRequired !SrcLoc
| ObjCOptional !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCParam = ObjCParam (Maybe Id) (Maybe Type) [Attr] (Maybe Id) !SrcLoc
| AntiObjCParam String !SrcLoc
| AntiObjCParams String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCMethodProto = ObjCMethodProto Bool (Maybe Type) [Attr] [ObjCParam] Bool [Attr] !SrcLoc
-- ^Invariant: First parameter must at least either have a selector or
-- an identifier; all other parameters must have an identifier.
| AntiObjCMethodProto String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCCatch = ObjCCatch (Maybe Param) [BlockItem] !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCDictElem = ObjCDictElem Exp Exp !SrcLoc
| AntiObjCDictElems String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCRecv = ObjCRecvSuper !SrcLoc
| ObjCRecvExp Exp !SrcLoc
| AntiObjCRecv String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
data ObjCArg = ObjCArg (Maybe Id) (Maybe Exp) !SrcLoc
| AntiObjCArg String !SrcLoc
| AntiObjCArgs String !SrcLoc
deriving (Eq, Ord, Show, Data, Typeable)
{------------------------------------------------------------------------------
-
- CUDA
-
------------------------------------------------------------------------------}
data ExeConfig = ExeConfig
{ exeGridDim :: Exp
, exeBlockDim :: Exp
, exeSharedSize :: Maybe Exp
, exeStream :: Maybe Exp
, exeLoc :: !SrcLoc
}
deriving (Eq, Ord, Show, Data, Typeable)
{------------------------------------------------------------------------------
-
- Instances
-
------------------------------------------------------------------------------}
instance Located Id where
locOf (Id _ loc) = locOf loc
locOf (AntiId _ loc) = locOf loc
instance Located StringLit where
locOf (StringLit _ _ loc) = locOf loc
instance Located Storage where
locOf (Tauto loc) = locOf loc
locOf (Tregister loc) = locOf loc
locOf (Tstatic loc) = locOf loc
locOf (Textern _ loc) = locOf loc
locOf (Ttypedef loc) = locOf loc
locOf (T__block loc) = locOf loc
locOf (TObjC__weak loc) = locOf loc
locOf (TObjC__strong loc) = locOf loc
locOf (TObjC__unsafe_unretained loc) = locOf loc
instance Located TypeQual where
locOf (Tconst loc) = locOf loc
locOf (Tvolatile loc) = locOf loc
locOf (AntiTypeQual _ loc) = locOf loc
locOf (AntiTypeQuals _ loc) = locOf loc
locOf (Tinline loc) = locOf loc
locOf (Trestrict loc) = locOf loc
locOf (TAttr attr) = locOf attr
locOf (TCUDAdevice loc) = locOf loc
locOf (TCUDAglobal loc) = locOf loc
locOf (TCUDAhost loc) = locOf loc
locOf (TCUDAconstant loc) = locOf loc
locOf (TCUDAshared loc) = locOf loc
locOf (TCUDArestrict loc) = locOf loc
locOf (TCUDAnoinline loc) = locOf loc
locOf (TCLprivate loc) = locOf loc
locOf (TCLlocal loc) = locOf loc
locOf (TCLglobal loc) = locOf loc
locOf (TCLconstant loc) = locOf loc
locOf (TCLreadonly loc) = locOf loc
locOf (TCLwriteonly loc) = locOf loc
locOf (TCLkernel loc) = locOf loc
instance Located Sign where
locOf (Tsigned loc) = locOf loc
locOf (Tunsigned loc) = locOf loc
instance Located TypeSpec where
locOf (Tvoid loc) = locOf loc
locOf (Tchar _ loc) = locOf loc
locOf (Tshort _ loc) = locOf loc
locOf (Tint _ loc) = locOf loc
locOf (Tlong _ loc) = locOf loc
locOf (Tlong_long _ loc) = locOf loc
locOf (Tfloat loc) = locOf loc
locOf (Tdouble loc) = locOf loc
locOf (Tlong_double loc) = locOf loc
locOf (Tstruct _ _ _ loc) = locOf loc
locOf (Tunion _ _ _ loc) = locOf loc
locOf (Tenum _ _ _ loc) = locOf loc
locOf (Tnamed _ _ loc) = locOf loc
locOf (TtypeofExp _ loc) = locOf loc
locOf (TtypeofType _ loc) = locOf loc
locOf (T_Bool loc) = locOf loc
locOf (Tfloat_Complex loc) = locOf loc
locOf (Tdouble_Complex loc) = locOf loc
locOf (Tlong_double_Complex loc) = locOf loc
locOf (Tfloat_Imaginary loc) = locOf loc
locOf (Tdouble_Imaginary loc) = locOf loc
locOf (Tlong_double_Imaginary loc) = locOf loc
locOf (Tva_list loc) = locOf loc
instance Located DeclSpec where
locOf (DeclSpec _ _ _ loc) = locOf loc
locOf (AntiDeclSpec _ loc) = locOf loc
locOf (AntiTypeDeclSpec _ _ _ loc) = locOf loc
instance Located ArraySize where
locOf (ArraySize _ _ loc) = locOf loc
locOf (VariableArraySize loc) = locOf loc
locOf (NoArraySize loc) = locOf loc
instance Located Decl where
locOf (DeclRoot loc) = locOf loc
locOf (Ptr _ _ loc) = locOf loc
locOf (BlockPtr _ _ loc) = locOf loc
locOf (Array _ _ _ loc) = locOf loc
locOf (Proto _ _ loc) = locOf loc
locOf (OldProto _ _ loc) = locOf loc
locOf (AntiTypeDecl _ loc) = locOf loc
instance Located Type where
locOf (Type _ _ loc) = locOf loc
locOf (AntiType _ loc) = locOf loc
instance Located Designator where
locOf (IndexDesignator _ loc) = locOf loc
locOf (MemberDesignator _ loc) = locOf loc
instance Located Designation where
locOf (Designation _ loc) = locOf loc
instance Located Initializer where
locOf (ExpInitializer _ loc) = locOf loc
locOf (CompoundInitializer _ loc) = locOf loc
locOf (AntiInit _ loc) = locOf loc
locOf (AntiInits _ loc) = locOf loc
instance Located Init where
locOf (Init _ _ _ _ _ loc) = locOf loc
instance Located Typedef where
locOf (Typedef _ _ _ loc) = locOf loc
instance Located InitGroup where
locOf (InitGroup _ _ _ loc) = locOf loc
locOf (TypedefGroup _ _ _ loc) = locOf loc
locOf (AntiDecl _ loc) = locOf loc
locOf (AntiDecls _ loc) = locOf loc
instance Located Field where
locOf (Field _ _ _ loc) = locOf loc
instance Located FieldGroup where
locOf (FieldGroup _ _ loc) = locOf loc
locOf (AntiSdecl _ loc) = locOf loc
locOf (AntiSdecls _ loc) = locOf loc
instance Located CEnum where
locOf (CEnum _ _ loc) = locOf loc
locOf (AntiEnum _ loc) = locOf loc
locOf (AntiEnums _ loc) = locOf loc
instance Located Attr where
locOf (Attr _ _ loc) = locOf loc
instance Located Param where
locOf (Param _ _ _ loc) = locOf loc
locOf (AntiParam _ loc) = locOf loc
locOf (AntiParams _ loc) = locOf loc
instance Located Params where
locOf (Params _ _ loc) = locOf loc
instance Located Func where
locOf (Func _ _ _ _ _ loc) = locOf loc
locOf (OldFunc _ _ _ _ _ _ loc) = locOf loc
instance Located Definition where
locOf (FuncDef _ loc) = locOf loc
locOf (DecDef _ loc) = locOf loc
locOf (EscDef _ loc) = locOf loc
locOf (ObjCClassDec _ loc) = locOf loc
locOf (ObjCClassIface _ _ _ _ _ _ loc) = locOf loc
locOf (ObjCCatIface _ _ _ _ _ loc) = locOf loc
locOf (ObjCProtDec _ loc) = locOf loc
locOf (ObjCProtDef _ _ _ loc) = locOf loc
locOf (ObjCClassImpl _ _ _ _ loc) = locOf loc
locOf (ObjCCatImpl _ _ _ loc) = locOf loc
locOf (ObjCSynDef _ loc) = locOf loc
locOf (ObjCDynDef _ loc) = locOf loc
locOf (ObjCMethDef _ _ loc) = locOf loc
locOf (ObjCCompAlias _ _ loc) = locOf loc
locOf (AntiFunc _ loc) = locOf loc
locOf (AntiEsc _ loc) = locOf loc
locOf (AntiEdecl _ loc) = locOf loc
locOf (AntiEdecls _ loc) = locOf loc
locOf (AntiObjCMeth _ loc) = locOf loc
locOf (AntiObjCMeths _ loc) = locOf loc
instance Located Stm where
locOf (Label _ _ _ loc) = locOf loc
locOf (Case _ _ loc) = locOf loc
locOf (Default _ loc) = locOf loc
locOf (Exp _ loc) = locOf loc
locOf (Block _ loc) = locOf loc
locOf (If _ _ _ loc) = locOf loc
locOf (Switch _ _ loc) = locOf loc
locOf (While _ _ loc) = locOf loc
locOf (DoWhile _ _ loc) = locOf loc
locOf (For _ _ _ _ loc) = locOf loc
locOf (Goto _ loc) = locOf loc
locOf (Continue loc) = locOf loc
locOf (Break loc) = locOf loc
locOf (Return _ loc) = locOf loc
locOf (Pragma _ loc) = locOf loc
locOf (Comment _ _ loc) = locOf loc
locOf (Asm _ _ _ _ _ _ loc) = locOf loc
locOf (AsmGoto _ _ _ _ _ _ loc) = locOf loc
locOf (ObjCTry _ _ _ loc) = locOf loc
locOf (ObjCThrow _ loc) = locOf loc
locOf (ObjCSynchronized _ _ loc) = locOf loc
locOf (ObjCAutoreleasepool _ loc) = locOf loc
locOf (AntiPragma _ loc) = locOf loc
locOf (AntiComment _ _ loc) = locOf loc
locOf (AntiStm _ loc) = locOf loc
locOf (AntiStms _ loc) = locOf loc
instance Located BlockItem where
locOf (BlockDecl decl) = locOf decl
locOf (BlockStm stm) = locOf stm
locOf (AntiBlockItem _ loc) = locOf loc
locOf (AntiBlockItems _ loc) = locOf loc
instance Located Const where
locOf (IntConst _ _ _ loc) = locOf loc
locOf (LongIntConst _ _ _ loc) = locOf loc
locOf (LongLongIntConst _ _ _ loc) = locOf loc
locOf (FloatConst _ _ loc) = locOf loc
locOf (DoubleConst _ _ loc) = locOf loc
locOf (LongDoubleConst _ _ loc) = locOf loc
locOf (CharConst _ _ loc) = locOf loc
locOf (StringConst _ _ loc) = locOf loc
locOf (AntiConst _ loc) = locOf loc
locOf (AntiInt _ loc) = locOf loc
locOf (AntiUInt _ loc) = locOf loc
locOf (AntiLInt _ loc) = locOf loc
locOf (AntiULInt _ loc) = locOf loc
locOf (AntiLLInt _ loc) = locOf loc
locOf (AntiULLInt _ loc) = locOf loc
locOf (AntiFloat _ loc) = locOf loc
locOf (AntiDouble _ loc) = locOf loc
locOf (AntiLongDouble _ loc) = locOf loc
locOf (AntiChar _ loc) = locOf loc
locOf (AntiString _ loc) = locOf loc
instance Located Exp where
locOf (Var _ loc) = locOf loc
locOf (Const _ loc) = locOf loc
locOf (BinOp _ _ _ loc) = locOf loc
locOf (Assign _ _ _ loc) = locOf loc
locOf (PreInc _ loc) = locOf loc
locOf (PostInc _ loc) = locOf loc
locOf (PreDec _ loc) = locOf loc
locOf (PostDec _ loc) = locOf loc
locOf (UnOp _ _ loc) = locOf loc
locOf (SizeofExp _ loc) = locOf loc
locOf (SizeofType _ loc) = locOf loc
locOf (Cast _ _ loc) = locOf loc
locOf (Cond _ _ _ loc) = locOf loc
locOf (Member _ _ loc) = locOf loc
locOf (PtrMember _ _ loc) = locOf loc
locOf (Index _ _ loc) = locOf loc
locOf (FnCall _ _ loc) = locOf loc
locOf (CudaCall _ _ _ loc) = locOf loc
locOf (Seq _ _ loc) = locOf loc
locOf (CompoundLit _ _ loc) = locOf loc
locOf (StmExpr _ loc) = locOf loc
locOf (BuiltinVaArg _ _ loc) = locOf loc
locOf (BlockLit _ _ _ loc) = locOf loc
locOf (ObjCMsg _ _ _ loc) = locOf loc
locOf (ObjCLitConst _ _ loc) = locOf loc
locOf (ObjCLitString _ loc) = locOf loc
locOf (ObjCLitBool _ loc) = locOf loc
locOf (ObjCLitArray _ loc) = locOf loc
locOf (ObjCLitDict _ loc) = locOf loc
locOf (ObjCLitBoxed _ loc) = locOf loc
locOf (ObjCEncode _ loc) = locOf loc
locOf (ObjCProtocol _ loc) = locOf loc
locOf (ObjCSelector _ loc) = locOf loc
locOf (AntiExp _ loc) = locOf loc
locOf (AntiArgs _ loc) = locOf loc
instance Located BlockType where
locOf (BlockVoid loc) = locOf loc
locOf (BlockParam _ loc) = locOf loc
locOf (BlockType _ loc) = locOf loc
instance Located ExeConfig where
locOf conf = locOf (exeLoc conf)
instance Located ObjCIvarDecl where
locOf (ObjCIvarVisi _ loc) = locOf loc
locOf (ObjCIvarDecl _ loc) = locOf loc
instance Located ObjCVisibilitySpec where
locOf (ObjCPrivate loc) = locOf loc
locOf (ObjCPublic loc) = locOf loc
locOf (ObjCProtected loc) = locOf loc
locOf (ObjCPackage loc) = locOf loc
instance Located ObjCIfaceDecl where
locOf (ObjCIfaceProp _ _ loc) = locOf loc
locOf (ObjCIfaceReq _ loc) = locOf loc
locOf (ObjCIfaceMeth _ loc) = locOf loc
locOf (ObjCIfaceDecl _ loc) = locOf loc
locOf (AntiObjCIfaceDecl _ loc) = locOf loc
locOf (AntiObjCIfaceDecls _ loc) = locOf loc
locOf (AntiObjCProp _ loc) = locOf loc
locOf (AntiObjCProps _ loc) = locOf loc
instance Located ObjCPropAttr where
locOf (ObjCGetter _ loc) = locOf loc
locOf (ObjCSetter _ loc) = locOf loc
locOf (ObjCReadonly loc) = locOf loc
locOf (ObjCReadwrite loc) = locOf loc
locOf (ObjCAssign loc) = locOf loc
locOf (ObjCRetain loc) = locOf loc
locOf (ObjCCopy loc) = locOf loc
locOf (ObjCNonatomic loc) = locOf loc
locOf (ObjCAtomic loc) = locOf loc
locOf (ObjCStrong loc) = locOf loc
locOf (ObjCWeak loc) = locOf loc
locOf (ObjCUnsafeUnretained loc) = locOf loc
locOf (AntiObjCAttr _ loc) = locOf loc
locOf (AntiObjCAttrs _ loc) = locOf loc
instance Located ObjCMethodReq where
locOf (ObjCRequired loc) = locOf loc
locOf (ObjCOptional loc) = locOf loc
instance Located ObjCParam where
locOf (ObjCParam _ _ _ _ loc) = locOf loc
locOf (AntiObjCParam _ loc) = locOf loc
locOf (AntiObjCParams _ loc) = locOf loc
instance Located ObjCMethodProto where
locOf (ObjCMethodProto _ _ _ _ _ _ loc) = locOf loc
locOf (AntiObjCMethodProto _ loc) = locOf loc
instance Located ObjCCatch where
locOf (ObjCCatch _ _ loc) = locOf loc
instance Located ObjCRecv where
locOf (ObjCRecvSuper loc) = locOf loc
locOf (ObjCRecvExp _ loc) = locOf loc
locOf (AntiObjCRecv _ loc) = locOf loc
instance Located ObjCArg where
locOf (ObjCArg _ _ loc) = locOf loc
locOf (AntiObjCArg _ loc) = locOf loc
locOf (AntiObjCArgs _ loc) = locOf loc
instance Located ObjCDictElem where
locOf (ObjCDictElem _ _ loc) = locOf loc
locOf (AntiObjCDictElems _ loc) = locOf loc
{------------------------------------------------------------------------------
-
- Utilities
-
------------------------------------------------------------------------------}
funcProto :: Func -> InitGroup
funcProto f@(Func decl_spec ident decl params _ _) =
InitGroup decl_spec []
[Init ident (Proto decl params l) Nothing Nothing [] l] l
where
l = srclocOf f
funcProto f@(OldFunc decl_spec ident decl params _ _ _) =
InitGroup decl_spec []
[Init ident (OldProto decl params l) Nothing Nothing [] l] l
where
l = srclocOf f
isPtr :: Type -> Bool
isPtr (Type _ decl _) = go decl
where
go (DeclRoot _) = False
go (Ptr _ _ _) = True
go (BlockPtr _ _ _) = True
go (Array _ _ _ _) = True
go (Proto _ _ _) = False
go (OldProto _ _ _) = False
go (AntiTypeDecl _ _) = error "isPtr: encountered antiquoted type declaration"
isPtr (AntiType _ _) = error "isPtr: encountered antiquoted type"
ctypedef :: Id -> Decl -> [Attr] -> Typedef
ctypedef ident decl attrs =
Typedef ident decl attrs (ident `srcspan` decl `srcspan` attrs)
cdeclSpec :: [Storage] -> [TypeQual] -> TypeSpec -> DeclSpec
cdeclSpec storage quals spec =
DeclSpec storage quals spec (storage `srcspan` quals `srcspan` spec)
cinitGroup :: DeclSpec -> [Attr] -> [Init] -> InitGroup
cinitGroup dspec attrs inis =
InitGroup dspec attrs inis (dspec `srcspan` attrs `srcspan` inis)
ctypedefGroup :: DeclSpec -> [Attr] -> [Typedef] -> InitGroup
ctypedefGroup dspec attrs typedefs =
TypedefGroup dspec attrs typedefs (dspec `srcspan` attrs `srcspan` typedefs)
| mwu-tow/language-c-quote | Language/C/Syntax.hs | bsd-3-clause | 34,130 | 0 | 10 | 12,156 | 10,130 | 5,088 | 5,042 | 1,206 | 7 |
{-# LANGUAGE FlexibleContexts #-}
module Mental.Memoize where
import Protolude
import qualified Data.Map as Map
memoizeM :: (Ord a, MonadState (Map a b) m)
=> (a -> m b)
-> a
-> m b
memoizeM = memoizeM' identity const
memoizeM' :: (Ord a, MonadState s m)
=> (s -> Map a b)
-> (Map a b -> s -> s)
-> (a -> m b)
-> a
-> m b
memoizeM' getMemo setMemo f a = do
cached <- Map.lookup a <$> gets getMemo
case cached of
Just b -> pure b
Nothing -> do
b <- f a
modify (\s -> setMemo (Map.insert a b (getMemo s)) s)
pure b
| romac/mental | src/Mental/Memoize.hs | bsd-3-clause | 640 | 0 | 19 | 237 | 269 | 134 | 135 | 23 | 2 |
-- continuedfraction.hs
module Math.ContinuedFraction where
import Math.NumberTheoryFundamentals (intSqrt)
import Math.QQ
import Math.QuadraticField
-- initially we're only interested in continued fractions for quadratic irrationalities
-- we are looking to write
-- sqrt n = a0 + 1/a1+ 1/a2+ 1/a3+ ...
-- and b0/c0 = a0/1, b1/c1 = (a0a1+1)/a1, etc, ie bi/ci is the value of the truncated continued fraction
-- Our fundamental iteration is that if at stage i, we have
-- sqrt n - bi/ci = z = x + y sqrt n
-- Then we set
-- a_i+1 = floor z
-- the following involves integer arithmetic only, so is exact (no rounding errors)
floorQF (QF n (Q a b) (Q c d)) | a >= 0 && c >= 0 = (a * d + intSqrt (b*b * c*c * n)) `div` (b*d)
-- proof that this is correct.
-- let sqrt (b*b * c*c * n) = intSqrt (b*b * c*c * n) + epsilon, where epsilon < 1
-- then a/b + c/d sqrt n == (a * d + sqrt (b*b * c*c * n)) / (b*d)
-- == (a * d + intSqrt (b*b * c*c * n)) `div` (b*d)
-- + ( intSqrt (b*b * c*c * n) `mod` (b*d) + epsilon) / (b*d)
-- The first summand is an integer, so we just need to show that the second summand is < 1
-- Well, this is clear, since anything `mod` (b*d) <= b*d-1, and epsilon < 1, so their sum divided by b*d is < 1
-- !! However, note that it doesn't work if a or c is <0
nextConvergent n ( (bi_2,ci_2), (bi_1,ci_1), ai_1, xi_1) =
let
ai = floorQF (QF n 1 0 / xi_1)
xi = (QF n 1 0 / xi_1) - QF n (Q ai 1) 0
bi = ai * bi_1 + bi_2
ci = ai * ci_1 + ci_2
in ( (bi_1,ci_1), (bi,ci), ai, xi)
convergentsForSqrt n
| a0*a0 == n = error ("convergentsForSqrt: " ++ show n ++ " is perfect square")
| otherwise = map (\(_,bc,a,_) -> (a,bc)) (iterate (nextConvergent n) ( (1,0),(a0,1),a0,x0 ))
where
a0 = intSqrt n
x0 = QF n (Q (-a0) 1) 1
-- to start the iteration we set b_-1 == 1, c_-1 == 0
-- TEST CODE
toDoubleQF (QF n (Q a b) (Q c d)) = fromInteger a / fromInteger b + sqrt (fromInteger n) * fromInteger c / fromInteger d :: Double
floorQF' z = floor (toDoubleQF z)
-- the version below, which doesn't use quadratic fields directly, succumbs to rounding errors much sooner
nextConvergent' ( (bi_2,ci_2), (bi_1,ci_1), ai_1, xi_1) =
let
-- Q ai 1 = floorQF (1/xi_1)
ai = floor (1/xi_1)
xi = (1/xi_1) - fromInteger ai
bi = ai * bi_1 + bi_2
ci = ai * ci_1 + ci_2
in ( (bi_1,ci_1), (bi,ci), ai, xi)
convergentsForSqrt' n =
let
a0 = intSqrt n
-- x0 = QF n (-a0/1) 1
x0 = sqrt (fromInteger n) - (fromInteger a0)
in map (\(_,bc,a,_) -> (a,bc)) (iterate nextConvergent' ( (1,0),(a0,1),a0,x0 ))
-- ie b_-1 == 1, c_-1 == 0
| nfjinjing/bench-euler | src/Math/ContinuedFraction.hs | bsd-3-clause | 2,696 | 6 | 14 | 704 | 778 | 432 | 346 | 31 | 1 |
data X
= X {
foo :: Int,
bar :: String
} deriving (Eq, Ord Show)
f x = x
| itchyny/vim-haskell-indent | test/recordtype/eq_first.in.hs | mit | 73 | 3 | 6 | 20 | 38 | 20 | 18 | -1 | -1 |
module MCTS.Games.Confrontation where
data Side = Light
| Dark
deriving (Eq)
data Piece = Aragorn
| Boromir
| Frodo
| Gandalf
| Gimli
| Legolas
| Merry
| Pippin
| Sam
| Balrog
| BlackRider
| CaveTroll
| FlyingNazgul
| Orcs
| Saruman
| Shelob
| Warg
| WitchKing
deriving (Eq, Show)
lightPieces :: [Piece]
lightPieces = [ Aragorn
, Boromir
, Frodo
, Gandalf
, Gimli
, Legolas
, Merry
, Pippin
, Sam
]
darkPieces :: [Piece]
darkPieces = [ Balrog
, BlackRider
, CaveTroll
, FlyingNazgul
, Orcs
, Saruman
, Shelob
, Warg
, WitchKing
]
strength :: Piece -> Int
strength p = case p of
Aragorn -> 4
Boromir -> 0
Frodo -> 1
Gandalf -> 5
Gimli -> 3
Legolas -> 3
Merry -> 2
Pippin -> 1
Sam -> 2
Balrog -> 5
BlackRider -> 3
CaveTroll -> 9
FlyingNazgul -> 3
Orcs -> 2
Saruman -> 4
Shelob -> 5
Warg -> 2
WitchKing -> 5
side :: Piece -> Side
side p = if p `elem` lightPieces then Light else Dark
data LightCard = L1
| L2
| L3
| L4
| L5
| Cloak
| LMagic
| Noble
| LRetreat
instance Show LightCard where
show card = case card of
L1 -> "1"
L2 -> "2"
L3 -> "3"
L4 -> "4"
L5 -> "5"
Cloak -> "Elven Cloak"
LMagic -> "Magic"
Noble -> "Noble Sacrifice"
LRetreat -> "Retreat"
lightCards :: [LightCard]
lightCards = [L1, L2, L3, L4, L5, Cloak, LMagic, Noble, LRetreat]
data DarkCard = D1
| D2
| D3
| D4
| D5
| D6
| Eye
| DMagic
| DRetreat
instance Show DarkCard where
show card = case card of
D1 -> "1"
D2 -> "2"
D3 -> "3"
D4 -> "4"
D5 -> "5"
D6 -> "6"
Eye -> "Eye of Sauron"
DMagic -> "Magic"
DRetreat -> "Retreat"
darkCards :: [DarkCard]
darkCards = [D1, D2, D3, D4, D5, D6, Eye, DMagic, DRetreat]
| rudyardrichter/MCTS | src/MCTS/Games/Confrontation.hs | mit | 2,683 | 0 | 8 | 1,435 | 623 | 360 | 263 | 109 | 18 |
module CO4.Algorithms.TopologicalSort
(bindingGroups, adtGroups)
where
import Data.Graph (stronglyConnComp,flattenSCC)
import Data.List (nub)
import CO4.Language
import CO4.Names (untypedName)
import CO4.Algorithms.Free (free)
-- |Computes groups of mutually recursive value declarations that are returned in
-- topological order
bindingGroups :: [Binding] -> [[Binding]]
bindingGroups bindings =
let graph = map toNode bindings
toNode b@(Binding n e) = (b, untypedName n, map untypedName $ free e)
in
map (nub . flattenSCC) $ stronglyConnComp graph
-- |Computes groups of mutually recursive ADT declarations that are returned in
-- topological order
adtGroups :: [Adt] -> [[Adt]]
adtGroups adts =
let graph = map toNode adts
toNode adt@(Adt name _ conss) =
(adt, name, nub $ concatMap fromConstructor conss)
fromConstructor (CCon _ args) = concatMap fromType args
fromType (TVar _ ) = []
fromType (TCon c ts ) = c : (concatMap fromType ts)
in
map (nub . flattenSCC) $ stronglyConnComp graph
| apunktbau/co4 | src/CO4/Algorithms/TopologicalSort.hs | gpl-3.0 | 1,141 | 0 | 12 | 293 | 331 | 178 | 153 | 21 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{- |
Module : Neovim.RPC.EventHandler
Description : Event handling loop
Copyright : (c) Sebastian Witte
License : Apache-2.0
Maintainer : woozletoff@gmail.com
Stability : experimental
-}
module Neovim.RPC.EventHandler (
runEventHandler,
) where
import Neovim.Classes
import Neovim.Context
import qualified Neovim.Context.Internal as Internal
import Neovim.Plugin.IPC.Classes
import qualified Neovim.RPC.Classes as MsgpackRPC
import Neovim.RPC.Common
import Neovim.RPC.FunctionCall
import Control.Applicative
import Control.Concurrent.STM hiding (writeTQueue)
import Control.Monad.Reader
import Control.Monad.Trans.Resource
import Data.ByteString (ByteString)
import Conduit as C
import qualified Data.Map as Map
import Data.Serialize (encode)
import System.IO (Handle)
import System.Log.Logger
import Prelude
-- | This function will establish a connection to the given socket and write
-- msgpack-rpc requests to it.
runEventHandler :: Handle
-> Internal.Config RPCConfig
-> IO ()
runEventHandler writeableHandle env =
runEventHandlerContext env . runConduit $ do
eventHandlerSource
.| eventHandler
.| (sinkHandleFlush writeableHandle)
-- | Convenient monad transformer stack for the event handler
newtype EventHandler a =
EventHandler (ResourceT (ReaderT (Internal.Config RPCConfig) IO) a)
deriving ( Functor, Applicative, Monad, MonadIO
, MonadReader (Internal.Config RPCConfig))
runEventHandlerContext
:: Internal.Config RPCConfig -> EventHandler a -> IO a
runEventHandlerContext env (EventHandler a) =
runReaderT (runResourceT a) env
eventHandlerSource :: ConduitT () SomeMessage EventHandler ()
eventHandlerSource = asks Internal.eventQueue >>= \q ->
forever $ yield =<< readSomeMessage q
eventHandler :: ConduitM SomeMessage EncodedResponse EventHandler ()
eventHandler = await >>= \case
Nothing ->
return () -- i.e. close the conduit -- TODO signal shutdown globally
Just message -> do
handleMessage (fromMessage message, fromMessage message)
eventHandler
type EncodedResponse = C.Flush ByteString
yield' :: (MonadIO io) => MsgpackRPC.Message -> ConduitM i EncodedResponse io ()
yield' o = do
liftIO . debugM "EventHandler" $ "Sending: " ++ show o
yield . Chunk . encode $ toObject o
yield Flush
handleMessage :: (Maybe FunctionCall, Maybe MsgpackRPC.Message)
-> ConduitM i EncodedResponse EventHandler ()
handleMessage = \case
(Just (FunctionCall fn params reply time), _) -> do
cfg <- asks (Internal.customConfig)
messageId <- atomically' $ do
i <- readTVar (nextMessageId cfg)
modifyTVar' (nextMessageId cfg) succ
modifyTVar' (recipients cfg) $ Map.insert i (time, reply)
return i
yield' $ MsgpackRPC.Request (Request fn messageId params)
(_, Just r@MsgpackRPC.Response{}) ->
yield' r
(_, Just n@MsgpackRPC.Notification{}) ->
yield' n
_ ->
return () -- i.e. skip to next message
| saep/nvim-hs | library/Neovim/RPC/EventHandler.hs | apache-2.0 | 3,458 | 0 | 17 | 967 | 785 | 412 | 373 | -1 | -1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module HERMIT.Context
( -- * HERMIT Contexts
-- ** Path Synonyms
AbsolutePathH
, LocalPathH
-- ** The Standard Context
, HermitC
, topLevelHermitC
, toHermitC
-- ** Bindings
, HermitBindingSite(..)
, BindingDepth
, HermitBinding
, hbDepth
, hbSite
, hbPath
, hermitBindingSiteExpr
, hermitBindingSummary
, hermitBindingExpr
-- ** Adding bindings to contexts
, AddBindings(..)
, addBindingGroup
, addDefBinding
, addDefBindingsExcept
, addLambdaBinding
, addAltBindings
, addCaseBinderBinding
, addForallBinding
-- ** Reading bindings from the context
, BoundVars(..)
, boundIn
, findBoundVars
, ReadBindings(..)
, lookupHermitBinding
, lookupHermitBindingDepth
, lookupHermitBindingSite
, inScope
-- ** Accessing GHC rewrite rules from the context
, HasCoreRules(..)
-- ** Accessing temporary lemmas in scope
, LemmaContext(..)
-- ** An empty Context
, HasEmptyContext(..)
) where
import Prelude hiding (lookup)
import Control.Monad
import Data.Map hiding (map, foldr, filter)
import Language.KURE
import Language.KURE.ExtendableContext
import HERMIT.Core
import HERMIT.GHC hiding (empty)
import HERMIT.Lemma
------------------------------------------------------------------------
-- | The depth of a binding. Used, for example, to detect shadowing when inlining.
type BindingDepth = Int
-- | HERMIT\'s representation of variable bindings.
-- Bound expressions cannot be inlined without checking for shadowing issues (using the depth information).
data HermitBindingSite = LAM -- ^ A lambda-bound variable.
| NONREC CoreExpr -- ^ A non-recursive binding of an expression.
| REC CoreExpr -- ^ A recursive binding that does not depend on the current expression (i.e. we're not in the binding group of that binding).
| SELFREC -- ^ A recursive binding of a superexpression of the current node (i.e. we're in the RHS of that binding).
| MUTUALREC CoreExpr -- ^ A recursive binding that is mutually recursive with the binding under consideration (i.e. we're in another definition in the same recursive binding group.).
| CASEALT -- ^ A variable bound in a case alternative.
| CASEBINDER CoreExpr (AltCon,[Var]) -- ^ A case binder. We store both the scrutinised expression, and the case alternative 'AltCon' and variables.
| FORALL -- ^ A universally quantified type variable.
| TOPLEVEL CoreExpr -- ^ A special case. When we're focussed on ModGuts, we treat all top-level bindings as being in scope at depth 0.
data HermitBinding = HB { hbDepth :: BindingDepth
, hbSite :: HermitBindingSite
, hbPath :: AbsolutePathH
}
-- | Retrieve the expression in a 'HermitBindingSite', if there is one.
hermitBindingSiteExpr :: HermitBindingSite -> KureM CoreExpr
hermitBindingSiteExpr b = case b of
LAM -> fail "variable is lambda-bound, not bound to an expression."
NONREC e -> return e
REC e -> return e
MUTUALREC e -> return e
SELFREC -> fail "identifier recursively refers to the expression under consideration."
CASEALT -> fail "variable is bound in a case alternative, not bound to an expression."
CASEBINDER e _ -> return e
FORALL -> fail "variable is a universally quantified type variable."
TOPLEVEL e -> return e
hermitBindingSummary :: HermitBinding -> String
hermitBindingSummary b = show (hbDepth b) ++ "$" ++ case hbSite b of
LAM -> "LAM"
NONREC {} -> "NONREC"
REC {} -> "REC"
MUTUALREC {} -> "MUTUALREC"
SELFREC {} -> "SELFREC"
CASEALT -> "CASEALT"
CASEBINDER {} -> "CASEBINDER"
FORALL -> "FORALL"
TOPLEVEL {} -> "TOPLEVEL"
-- | Retrieve the expression in a 'HermitBinding', if there is one.
hermitBindingExpr :: HermitBinding -> KureM CoreExpr
hermitBindingExpr = hermitBindingSiteExpr . hbSite
------------------------------------------------------------------------
-- | A class of contexts that can have HERMIT bindings added to them.
class AddBindings c where
-- | Add a complete set of parrallel bindings to the context.
-- (Parallel bindings occur in recursive let bindings and case alternatives.)
-- This can also be used for solitary bindings (e.g. lambdas).
-- Bindings are added in parallel sets to help with shadowing issues.
addHermitBindings :: [(Var,HermitBindingSite,AbsolutePathH)] -> c -> c
-- | The bindings are just discarded.
instance AddBindings (SnocPath crumb) where
addHermitBindings :: [(Var,HermitBindingSite,AbsolutePathH)] -> SnocPath crumb -> SnocPath crumb
addHermitBindings _ = id
instance ReadPath c Crumb => ReadPath (ExtendContext c e) Crumb where
absPath = absPath . baseContext
-- | The bindings are added to the base context and the extra context.
instance (AddBindings c, AddBindings e) => AddBindings (ExtendContext c e) where
addHermitBindings :: [(Var,HermitBindingSite,AbsolutePathH)] -> ExtendContext c e -> ExtendContext c e
addHermitBindings bnds c = c
{ baseContext = addHermitBindings bnds (baseContext c)
, extraContext = addHermitBindings bnds (extraContext c)
}
-------------------------------------------
-- | Add all bindings in a binding group to a context.
addBindingGroup :: (AddBindings c, ReadPath c Crumb) => CoreBind -> c -> c
addBindingGroup (NonRec v e) c = addHermitBindings [(v,NONREC e,absPath c @@ Let_Bind)] c
addBindingGroup (Rec ies) c = addHermitBindings [ (i, REC e, absPath c @@ Let_Bind) | (i,e) <- ies ] c
-- | Add the binding for a recursive definition currently under examination.
-- Note that because the expression may later be modified, the context only records the identifier, not the expression.
addDefBinding :: (AddBindings c, ReadPath c Crumb) => Id -> c -> c
addDefBinding i c = addHermitBindings [(i,SELFREC,absPath c @@ Def_Id)] c
-- | Add a list of recursive bindings to the context, except the nth binding in the list.
-- The idea is to exclude the definition being descended into.
addDefBindingsExcept :: (AddBindings c, ReadPath c Crumb) => Int -> [(Id,CoreExpr)] -> c -> c
addDefBindingsExcept n ies c = addHermitBindings [ (i, MUTUALREC e, absPath c @@ Rec_Def m) | (m,(i,e)) <- zip [0..] ies, m /= n ] c
-- | Add the case binder for a specific case alternative.
addCaseBinderBinding :: (AddBindings c, ReadPath c Crumb) => (Id,CoreExpr,CoreAlt) -> c -> c
addCaseBinderBinding (i,e,(con,vs,_)) c = addHermitBindings [(i,CASEBINDER e (con,vs),absPath c @@ Case_Binder)] c
-- | Add a lambda bound variable to a context.
-- All that is known is the variable, which may shadow something.
-- If so, we don't worry about that here, it is instead checked during inlining.
addLambdaBinding :: (AddBindings c, ReadPath c Crumb) => Var -> c -> c
addLambdaBinding v c = addHermitBindings [(v,LAM,absPath c @@ Lam_Var)] c
-- | Add the variables bound by a 'DataCon' in a case.
-- They are all bound at the same depth.
addAltBindings :: (AddBindings c, ReadPath c Crumb) => [Var] -> c -> c
addAltBindings vs c = addHermitBindings [ (v, CASEALT, absPath c @@ Alt_Var i) | (v,i) <- zip vs [1..] ] c
-- | Add a universally quantified type variable to a context.
addForallBinding :: (AddBindings c, ReadPath c Crumb) => TyVar -> c -> c
addForallBinding v c = addHermitBindings [(v,FORALL,absPath c @@ ForAllTy_Var)] c
------------------------------------------------------------------------
-- | A class of contexts that stores the set of variables in scope that have been bound during the traversal.
class BoundVars c where
boundVars :: c -> VarSet
instance BoundVars VarSet where
boundVars :: VarSet -> VarSet
boundVars = id
-- | List all variables bound in the context that match the given predicate.
findBoundVars :: BoundVars c => (Var -> Bool) -> c -> VarSet
findBoundVars p = filterVarSet p . boundVars
-- | A class of contexts from which HERMIT bindings can be retrieved.
class BoundVars c => ReadBindings c where
hermitDepth :: c -> BindingDepth
hermitBindings :: c -> Map Var HermitBinding
-- | Determine if a variable is bound in a context.
boundIn :: ReadBindings c => Var -> c -> Bool
boundIn i c = i `member` hermitBindings c
-- | Determine whether a variable is in scope.
inScope :: BoundVars c => c -> Var -> Bool
inScope c v = not (isDeadBinder v || (isLocalVar v && (v `notElemVarSet` boundVars c)))
-- Used in Dictionary.Inline and Dictionary.Fold to check if variables are in scope.
-- | Lookup the binding for a variable in a context.
lookupHermitBinding :: (ReadBindings c, Monad m) => Var -> c -> m HermitBinding
lookupHermitBinding v = maybe (fail "binding not found in HERMIT context.") return . lookup v . hermitBindings
-- | Lookup the depth of a variable's binding in a context.
lookupHermitBindingDepth :: (ReadBindings c, Monad m) => Var -> c -> m BindingDepth
lookupHermitBindingDepth v = liftM hbDepth . lookupHermitBinding v
-- | Lookup the binding for a variable in a context, ensuring it was bound at the specified depth.
lookupHermitBindingSite :: (ReadBindings c, Monad m) => Var -> BindingDepth -> c -> m HermitBindingSite
lookupHermitBindingSite v depth c = do HB d bnd _ <- lookupHermitBinding v c
guardMsg (d == depth) "lookupHermitBinding succeeded, but depth does not match. The variable has probably been shadowed."
return bnd
------------------------------------------------------------------------
-- | A class of contexts that store GHC rewrite rules.
class HasCoreRules c where
hermitCoreRules :: c -> [CoreRule]
addHermitCoreRules :: [CoreRule] -> c -> c
instance HasCoreRules [CoreRule] where
hermitCoreRules :: [CoreRule] -> [CoreRule]
hermitCoreRules = id
addHermitCoreRules :: [CoreRule] -> [CoreRule] -> [CoreRule]
addHermitCoreRules = (++)
------------------------------------------------------------------------
-- | A class of contexts that provide an empty context.
class HasEmptyContext c where
setEmptyContext :: c -> c
------------------------------------------------------------------------
-- | A class of contexts that can store local Lemmas as we descend past implications.
class LemmaContext c where
addAntecedent :: LemmaName -> Lemma -> c -> c
getAntecedents :: c -> Lemmas
instance LemmaContext c => LemmaContext (ExtendContext c e) where
addAntecedent nm l ec = extendContext (extraContext ec)
(addAntecedent nm l $ baseContext ec)
getAntecedents = getAntecedents . baseContext
------------------------------------------------------------------------
type AbsolutePathH = AbsolutePath Crumb
type LocalPathH = LocalPath Crumb
-- | The HERMIT context, containing all bindings in scope and the current location in the AST.
-- The bindings here are lazy by choice, so that we can avoid the cost
-- of building the context if we never use it.
data HermitC = HermitC
{ hermitC_bindings :: Map Var HermitBinding -- ^ All (local to this module) bindings in scope.
, hermitC_depth :: BindingDepth -- ^ The depth of the most recent bindings.
, hermitC_path :: AbsolutePathH -- ^ The 'AbsolutePath' to the current node from the root.
, hermitC_specRules :: [CoreRule] -- ^ In-scope GHC RULES found in IdInfos.
, hermitC_lemmas :: Lemmas -- ^ Local lemmas as we pass implications in a proof.
}
-- | Build a HermitC out of any context that has the capabilities.
toHermitC :: (HasCoreRules c, LemmaContext c, ReadBindings c, ReadPath c Crumb) => c -> HermitC
toHermitC c =
HermitC { hermitC_bindings = hermitBindings c
, hermitC_depth = hermitDepth c
, hermitC_path = absPath c
, hermitC_specRules = hermitCoreRules c
, hermitC_lemmas = getAntecedents c
}
------------------------------------------------------------------------
-- | The |HermitC| empty context has an initial depth of 0, an empty path, and no bindings nor rules.
instance HasEmptyContext HermitC where
setEmptyContext :: HermitC -> HermitC
setEmptyContext c = c
{ hermitC_bindings = empty
, hermitC_depth = 0
, hermitC_path = mempty
, hermitC_specRules = []
, hermitC_lemmas = empty
}
-- | A special HERMIT context intended for use only when focussed on ModGuts.
-- All top-level bindings are considered to be in scope at depth 0.
topLevelHermitC :: ModGuts -> HermitC
topLevelHermitC mg = let ies = concatMap bindToVarExprs (mg_binds mg)
in HermitC
{ hermitC_bindings = fromList [ (i , HB 0 (TOPLEVEL e) mempty) | (i,e) <- ies ]
, hermitC_depth = 0
, hermitC_path = mempty
, hermitC_specRules = concatMap (idCoreRules . fst) ies
, hermitC_lemmas = empty
}
------------------------------------------------------------------------
-- | Retrieve the 'AbsolutePath' to the current node, from the HERMIT context.
instance ReadPath HermitC Crumb where
absPath :: HermitC -> AbsolutePath Crumb
absPath = hermitC_path
-- | Extend the 'AbsolutePath' stored in the HERMIT context.
instance ExtendPath HermitC Crumb where
(@@) :: HermitC -> Crumb -> HermitC
c @@ n = c { hermitC_path = hermitC_path c @@ n }
------------------------------------------------------------------------
instance AddBindings HermitC where
addHermitBindings :: [(Var,HermitBindingSite,AbsolutePathH)] -> HermitC -> HermitC
addHermitBindings vbs c =
let nextDepth = succ (hermitC_depth c)
vhbs = [ (v, HB nextDepth b p) | (v,b,p) <- vbs ]
in c { hermitC_bindings = fromList vhbs `union` hermitC_bindings c
, hermitC_depth = nextDepth
, hermitC_specRules = concat [ idCoreRules i | (i,_,_) <- vbs, isId i ] ++ hermitC_specRules c
}
------------------------------------------------------------------------
instance BoundVars HermitC where
boundVars :: HermitC -> VarSet
boundVars = mkVarSet . keys . hermitC_bindings
instance ReadBindings HermitC where
hermitDepth :: HermitC -> BindingDepth
hermitDepth = hermitC_depth
hermitBindings :: HermitC -> Map Var HermitBinding
hermitBindings = hermitC_bindings
------------------------------------------------------------------------
instance HasCoreRules HermitC where
hermitCoreRules :: HermitC -> [CoreRule]
hermitCoreRules = hermitC_specRules
addHermitCoreRules :: [CoreRule] -> HermitC -> HermitC
addHermitCoreRules rules c = c { hermitC_specRules = rules ++ hermitC_specRules c }
------------------------------------------------------------------------
instance LemmaContext HermitC where
addAntecedent :: LemmaName -> Lemma -> HermitC -> HermitC
addAntecedent nm l c = c { hermitC_lemmas = insert nm l (hermitC_lemmas c) }
getAntecedents :: HermitC -> Lemmas
getAntecedents = hermitC_lemmas
| conal/hermit | src/HERMIT/Context.hs | bsd-2-clause | 16,385 | 0 | 15 | 4,320 | 2,947 | 1,627 | 1,320 | 214 | 9 |
{-# LANGUAGE BangPatterns #-}
module Tests.ImportanceSampler where
import Data.Dynamic
import Language.Hakaru.Types
import Language.Hakaru.Lambda
import Language.Hakaru.Distribution
import Language.Hakaru.ImportanceSampler
-- import Test.QuickCheck.Monadic
import Tests.Models
-- Some test programs in our language
test_mixture :: IO ()
test_mixture = sample prog_mixture conds >>=
print . take 10 >>
putChar '\n' >>
empiricalMeasure 1000 prog_mixture conds >>=
print
where conds = [Just (toDyn (Lebesgue 2 :: Density Double))]
prog_dup :: Measure (Bool, Bool)
prog_dup = do
let c = unconditioned (bern 0.5)
x <- c
y <- c
return (x,y)
prog_dbn :: Measure Bool
prog_dbn = do
s0 <- unconditioned (bern 0.75)
s1 <- unconditioned (if s0 then bern 0.75 else bern 0.25)
_ <- conditioned (if s1 then bern 0.90 else bern 0.10)
s2 <- unconditioned (if s1 then bern 0.75 else bern 0.25)
_ <- conditioned (if s2 then bern 0.90 else bern 0.10)
return s2
test_dbn :: IO ()
test_dbn = sample prog_dbn conds >>=
print . take 10 >>
putChar '\n' >>
empiricalMeasure 1000 prog_dbn conds >>=
print
where conds = [Just (toDyn (Discrete True)),
Just (toDyn (Discrete True))]
prog_hmm :: Integer -> Measure Bool
prog_hmm n = do
s <- unconditioned (bern 0.75)
loop_hmm n s
loop_hmm :: Integer -> (Bool -> Measure Bool)
loop_hmm !numLoops s = do
_ <- conditioned (if s then bern 0.90 else bern 0.10)
u <- unconditioned (if s then bern 0.75 else bern 0.25)
if (numLoops > 1) then loop_hmm (numLoops - 1) u
else return s
test_hmm :: IO ()
test_hmm = sample (prog_hmm 2) conds >>=
print . take 10 >>
putChar '\n' >>
empiricalMeasure 1000 (prog_hmm 2) conds >>=
print
where conds = [Just (toDyn (Discrete True)),
Just (toDyn (Discrete True))]
prog_carRoadModel :: Measure (Double, Double)
prog_carRoadModel = do
speed <- unconditioned (uniform 5 15)
let z0 = lit 0
_ <- conditioned (normal z0 1)
z1 <- unconditioned (normal (z0 + speed) 1)
_ <- conditioned (normal z1 1)
z2 <- unconditioned (normal (z1 + speed) 1)
_ <- conditioned (normal z2 1)
z3 <- unconditioned (normal (z2 + speed) 1)
_ <- conditioned (normal z3 1)
z4 <- unconditioned (normal (z3 + speed) 1)
return (z4, z3)
test_carRoadModel :: IO ()
test_carRoadModel = sample prog_carRoadModel conds >>=
print . take 10 >>
putChar '\n' >>
empiricalMeasure 1000 prog_carRoadModel conds >>=
print
where conds = [Just (toDyn (Lebesgue 0 :: Density Double)),
Just (toDyn (Lebesgue 11 :: Density Double)),
Just (toDyn (Lebesgue 19 :: Density Double)),
Just (toDyn (Lebesgue 33 :: Density Double))]
prog_categorical :: Measure Bool
prog_categorical = do
rain <- unconditioned (categorical [(True, 0.2), (False, 0.8)])
sprinkler <- unconditioned (if rain
then bern 0.01 else bern 0.4)
_ <- conditioned (if rain
then (if sprinkler then bern 0.99 else bern 0.8)
else (if sprinkler then bern 0.90 else bern 0.1))
return rain
test_categorical :: IO ()
test_categorical = sample prog_categorical conds >>=
print . take 10 >>
putChar '\n' >>
empiricalMeasure 1000 prog_categorical conds >>=
print
where conds = [Just (toDyn (Discrete True))]
prog_multiple_conditions :: Measure Double
prog_multiple_conditions = do
b <- unconditioned (beta 1 1)
_ <- conditioned (bern b)
_ <- conditioned (bern b)
return b
| bitemyapp/hakaru | Tests/ImportanceSampler.hs | bsd-3-clause | 3,832 | 2 | 13 | 1,129 | 1,371 | 674 | 697 | 100 | 5 |
-- |
-- Module : Crypto.ECC.Edwards25519
-- License : BSD-style
-- Maintainer : Olivier Chéron <olivier.cheron@gmail.com>
-- Stability : experimental
-- Portability : unknown
--
-- Arithmetic primitives over curve edwards25519.
--
-- Twisted Edwards curves are a familly of elliptic curves allowing
-- complete addition formulas without any special case and no point at
-- infinity. Curve edwards25519 is based on prime 2^255 - 19 for
-- efficient implementation. Equation and parameters are given in
-- <https://tools.ietf.org/html/rfc7748 RFC 7748>.
--
-- This module provides types and primitive operations that are useful
-- to implement cryptographic schemes based on curve edwards25519:
--
-- - arithmetic functions for point addition, doubling, negation,
-- scalar multiplication with an arbitrary point, with the base point,
-- etc.
--
-- - arithmetic functions dealing with scalars modulo the prime order
-- L of the base point
--
-- All functions run in constant time unless noted otherwise.
--
-- Warnings:
--
-- 1. Curve edwards25519 has a cofactor h = 8 so the base point does
-- not generate the entire curve and points with order 2, 4, 8 exist.
-- When implementing cryptographic algorithms, special care must be
-- taken using one of the following methods:
--
-- - points must be checked for membership in the prime-order
-- subgroup
--
-- - or cofactor must be cleared by multiplying points by 8
--
-- Utility functions are provided to implement this. Testing
-- subgroup membership with 'pointHasPrimeOrder' is 50-time slower
-- than call 'pointMulByCofactor'.
--
-- 2. Scalar arithmetic is always reduced modulo L, allowing fixed
-- length and constant execution time, but this reduction is valid
-- only when points are in the prime-order subgroup.
--
-- 3. Because of modular reduction in this implementation it is not
-- possible to multiply points directly by scalars like 8.s or L.
-- This has to be decomposed into several steps.
--
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module Crypto.ECC.Edwards25519
( Scalar
, Point
-- * Scalars
, scalarGenerate
, scalarDecodeLong
, scalarEncode
-- * Points
, pointDecode
, pointEncode
, pointHasPrimeOrder
-- * Arithmetic functions
, toPoint
, scalarAdd
, scalarMul
, pointNegate
, pointAdd
, pointDouble
, pointMul
, pointMulByCofactor
, pointsMulVarTime
) where
import Data.Word
import Foreign.C.Types
import Foreign.Ptr
import Crypto.Error
import Crypto.Internal.ByteArray (Bytes, ScrubbedBytes, withByteArray)
import qualified Crypto.Internal.ByteArray as B
import Crypto.Internal.Compat
import Crypto.Internal.Imports
import Crypto.Random
scalarArraySize :: Int
scalarArraySize = 40 -- maximum [9 * 4 {- 32 bits -}, 5 * 8 {- 64 bits -}]
-- | A scalar modulo prime order of curve edwards25519.
newtype Scalar = Scalar ScrubbedBytes
deriving (Show,NFData)
instance Eq Scalar where
(Scalar s1) == (Scalar s2) = unsafeDoIO $
withByteArray s1 $ \ps1 ->
withByteArray s2 $ \ps2 ->
fmap (/= 0) (ed25519_scalar_eq ps1 ps2)
{-# NOINLINE (==) #-}
pointArraySize :: Int
pointArraySize = 160 -- maximum [4 * 10 * 4 {- 32 bits -}, 4 * 5 * 8 {- 64 bits -}]
-- | A point on curve edwards25519.
newtype Point = Point Bytes
deriving NFData
instance Show Point where
showsPrec d p =
let bs = pointEncode p :: Bytes
in showParen (d > 10) $ showString "Point "
. shows (B.convertToBase B.Base16 bs :: Bytes)
instance Eq Point where
(Point p1) == (Point p2) = unsafeDoIO $
withByteArray p1 $ \pp1 ->
withByteArray p2 $ \pp2 ->
fmap (/= 0) (ed25519_point_eq pp1 pp2)
{-# NOINLINE (==) #-}
-- | Generate a random scalar.
scalarGenerate :: MonadRandom randomly => randomly Scalar
scalarGenerate = throwCryptoError . scalarDecodeLong <$> generate
where
-- Scalar generation is based on a fixed number of bytes so that
-- there is no timing leak. But because of modular reduction
-- distribution is not uniform. We use many more bytes than
-- necessary so the probability bias is small. With 512 bits we
-- get 22% of scalars with a higher frequency, but the relative
-- probability difference is only 2^(-260).
generate :: MonadRandom randomly => randomly ScrubbedBytes
generate = getRandomBytes 64
-- | Serialize a scalar to binary, i.e. a 32-byte little-endian
-- number.
scalarEncode :: B.ByteArray bs => Scalar -> bs
scalarEncode (Scalar s) =
B.allocAndFreeze 32 $ \out ->
withByteArray s $ \ps -> ed25519_scalar_encode out ps
-- | Deserialize a little-endian number as a scalar. Input array can
-- have any length from 0 to 64 bytes.
--
-- Note: it is not advised to put secret information in the 3 lowest
-- bits of a scalar if this scalar may be multiplied to untrusted
-- points outside the prime-order subgroup.
scalarDecodeLong :: B.ByteArrayAccess bs => bs -> CryptoFailable Scalar
scalarDecodeLong bs
| B.length bs > 64 = CryptoFailed CryptoError_EcScalarOutOfBounds
| otherwise = unsafeDoIO $ withByteArray bs initialize
where
len = fromIntegral $ B.length bs
initialize inp = do
s <- B.alloc scalarArraySize $ \ps ->
ed25519_scalar_decode_long ps inp len
return $ CryptoPassed (Scalar s)
{-# NOINLINE scalarDecodeLong #-}
-- | Add two scalars.
scalarAdd :: Scalar -> Scalar -> Scalar
scalarAdd (Scalar a) (Scalar b) =
Scalar $ B.allocAndFreeze scalarArraySize $ \out ->
withByteArray a $ \pa ->
withByteArray b $ \pb ->
ed25519_scalar_add out pa pb
-- | Multiply two scalars.
scalarMul :: Scalar -> Scalar -> Scalar
scalarMul (Scalar a) (Scalar b) =
Scalar $ B.allocAndFreeze scalarArraySize $ \out ->
withByteArray a $ \pa ->
withByteArray b $ \pb ->
ed25519_scalar_mul out pa pb
-- | Multiplies a scalar with the curve base point.
toPoint :: Scalar -> Point
toPoint (Scalar scalar) =
Point $ B.allocAndFreeze pointArraySize $ \out ->
withByteArray scalar $ \pscalar ->
ed25519_point_base_scalarmul out pscalar
-- | Serialize a point to a 32-byte array.
--
-- Format is binary compatible with 'Crypto.PubKey.Ed25519.PublicKey'
-- from module "Crypto.PubKey.Ed25519".
pointEncode :: B.ByteArray bs => Point -> bs
pointEncode (Point p) =
B.allocAndFreeze 32 $ \out ->
withByteArray p $ \pp ->
ed25519_point_encode out pp
-- | Deserialize a 32-byte array as a point, ensuring the point is
-- valid on edwards25519.
--
-- /WARNING:/ variable time
pointDecode :: B.ByteArrayAccess bs => bs -> CryptoFailable Point
pointDecode bs
| B.length bs == 32 = unsafeDoIO $ withByteArray bs initialize
| otherwise = CryptoFailed CryptoError_PointSizeInvalid
where
initialize inp = do
(res, p) <- B.allocRet pointArraySize $ \pp ->
ed25519_point_decode_vartime pp inp
if res == 0 then return $ CryptoFailed CryptoError_PointCoordinatesInvalid
else return $ CryptoPassed (Point p)
{-# NOINLINE pointDecode #-}
-- | Test whether a point belongs to the prime-order subgroup
-- generated by the base point. Result is 'True' for the identity
-- point.
--
-- @
-- pointHasPrimeOrder p = 'pointNegate' p == 'pointMul' l_minus_one p
-- @
pointHasPrimeOrder :: Point -> Bool
pointHasPrimeOrder (Point p) = unsafeDoIO $
withByteArray p $ \pp ->
fmap (/= 0) (ed25519_point_has_prime_order pp)
{-# NOINLINE pointHasPrimeOrder #-}
-- | Negate a point.
pointNegate :: Point -> Point
pointNegate (Point a) =
Point $ B.allocAndFreeze pointArraySize $ \out ->
withByteArray a $ \pa ->
ed25519_point_negate out pa
-- | Add two points.
pointAdd :: Point -> Point -> Point
pointAdd (Point a) (Point b) =
Point $ B.allocAndFreeze pointArraySize $ \out ->
withByteArray a $ \pa ->
withByteArray b $ \pb ->
ed25519_point_add out pa pb
-- | Add a point to itself.
--
-- @
-- pointDouble p = 'pointAdd' p p
-- @
pointDouble :: Point -> Point
pointDouble (Point a) =
Point $ B.allocAndFreeze pointArraySize $ \out ->
withByteArray a $ \pa ->
ed25519_point_double out pa
-- | Multiply a point by h = 8.
--
-- @
-- pointMulByCofactor p = 'pointMul' scalar_8 p
-- @
pointMulByCofactor :: Point -> Point
pointMulByCofactor (Point a) =
Point $ B.allocAndFreeze pointArraySize $ \out ->
withByteArray a $ \pa ->
ed25519_point_mul_by_cofactor out pa
-- | Scalar multiplication over curve edwards25519.
--
-- Note: when the scalar had reduction modulo L and the input point
-- has a torsion component, the output point may not be in the
-- expected subgroup.
pointMul :: Scalar -> Point -> Point
pointMul (Scalar scalar) (Point base) =
Point $ B.allocAndFreeze pointArraySize $ \out ->
withByteArray scalar $ \pscalar ->
withByteArray base $ \pbase ->
ed25519_point_scalarmul out pbase pscalar
-- | Multiply the point @p@ with @s2@ and add a lifted to curve value @s1@.
--
-- @
-- pointsMulVarTime s1 s2 p = 'pointAdd' ('toPoint' s1) ('pointMul' s2 p)
-- @
--
-- /WARNING:/ variable time
pointsMulVarTime :: Scalar -> Scalar -> Point -> Point
pointsMulVarTime (Scalar s1) (Scalar s2) (Point p) =
Point $ B.allocAndFreeze pointArraySize $ \out ->
withByteArray s1 $ \ps1 ->
withByteArray s2 $ \ps2 ->
withByteArray p $ \pp ->
ed25519_base_double_scalarmul_vartime out ps1 pp ps2
foreign import ccall unsafe "cryptonite_ed25519_scalar_eq"
ed25519_scalar_eq :: Ptr Scalar
-> Ptr Scalar
-> IO CInt
foreign import ccall unsafe "cryptonite_ed25519_scalar_encode"
ed25519_scalar_encode :: Ptr Word8
-> Ptr Scalar
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_scalar_decode_long"
ed25519_scalar_decode_long :: Ptr Scalar
-> Ptr Word8
-> CSize
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_scalar_add"
ed25519_scalar_add :: Ptr Scalar -- sum
-> Ptr Scalar -- a
-> Ptr Scalar -- b
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_scalar_mul"
ed25519_scalar_mul :: Ptr Scalar -- out
-> Ptr Scalar -- a
-> Ptr Scalar -- b
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_point_encode"
ed25519_point_encode :: Ptr Word8
-> Ptr Point
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_point_decode_vartime"
ed25519_point_decode_vartime :: Ptr Point
-> Ptr Word8
-> IO CInt
foreign import ccall unsafe "cryptonite_ed25519_point_eq"
ed25519_point_eq :: Ptr Point
-> Ptr Point
-> IO CInt
foreign import ccall "cryptonite_ed25519_point_has_prime_order"
ed25519_point_has_prime_order :: Ptr Point
-> IO CInt
foreign import ccall unsafe "cryptonite_ed25519_point_negate"
ed25519_point_negate :: Ptr Point -- minus_a
-> Ptr Point -- a
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_point_add"
ed25519_point_add :: Ptr Point -- sum
-> Ptr Point -- a
-> Ptr Point -- b
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_point_double"
ed25519_point_double :: Ptr Point -- two_a
-> Ptr Point -- a
-> IO ()
foreign import ccall unsafe "cryptonite_ed25519_point_mul_by_cofactor"
ed25519_point_mul_by_cofactor :: Ptr Point -- eight_a
-> Ptr Point -- a
-> IO ()
foreign import ccall "cryptonite_ed25519_point_base_scalarmul"
ed25519_point_base_scalarmul :: Ptr Point -- scaled
-> Ptr Scalar -- scalar
-> IO ()
foreign import ccall "cryptonite_ed25519_point_scalarmul"
ed25519_point_scalarmul :: Ptr Point -- scaled
-> Ptr Point -- base
-> Ptr Scalar -- scalar
-> IO ()
foreign import ccall "cryptonite_ed25519_base_double_scalarmul_vartime"
ed25519_base_double_scalarmul_vartime :: Ptr Point -- combo
-> Ptr Scalar -- scalar1
-> Ptr Point -- base2
-> Ptr Scalar -- scalar2
-> IO ()
| vincenthz/cryptonite | Crypto/ECC/Edwards25519.hs | bsd-3-clause | 13,150 | 0 | 13 | 3,756 | 2,282 | 1,217 | 1,065 | 212 | 2 |
module RunSampler ( SamplerModel (..)
, SamplerOpts (..), samplerOpts
, runSampler
, createSweeps
) where
import Options.Applicative
import Data.Monoid ((<>))
import System.FilePath.Posix ((</>))
import System.Directory
import Control.Monad (when, forM_, void)
import qualified Control.Monad.Trans.State as S
import Control.Monad.IO.Class
import Data.Binary
import qualified Data.ByteString as BS
import Text.Printf
import Control.Concurrent
import Control.Concurrent.STM
import System.Random.MWC
import Data.Random
import Numeric.Log
import BayesStack.Gibbs.Concurrent
data SamplerOpts = SamplerOpts { burnin :: Int
, lag :: Int
, iterations :: Maybe Int
, updateBlock :: Int
, sweepsDir :: FilePath
, nCaps :: Int
, hyperEstOpts :: HyperEstOpts
}
samplerOpts = SamplerOpts
<$> option ( long "burnin"
<> short 'b'
<> metavar "N"
<> value 100
<> help "Number of sweeps to run before taking samples"
)
<*> option ( long "lag"
<> short 'l'
<> metavar "N"
<> value 10
<> help "Number of sweeps between diagnostic samples"
)
<*> option ( long "iterations"
<> short 'i'
<> metavar "N"
<> value Nothing
<> reader (pure . auto)
<> help "Number of sweeps to run for"
)
<*> option ( long "diff-batch"
<> short 'u'
<> metavar "N"
<> value 100
<> help "Number of update diffs to batch before updating global state"
)
<*> strOption ( long "sweeps"
<> short 'S'
<> metavar "DIR"
<> value "sweeps"
<> help "Directory in which to place model state output"
)
<*> option ( long "threads"
<> short 'N'
<> value 1
<> metavar "INT"
<> help "Number of worker threads to start"
)
<*> hyperEstOpts'
data HyperEstOpts = HyperEstOpts { hyperEst :: Bool
, hyperBurnin :: Int
, hyperLag :: Int
}
hyperEstOpts' = HyperEstOpts
<$> switch ( long "hyper"
<> short 'H'
<> help "Enable hyperparameter estimation"
)
<*> option ( long "hyper-burnin"
<> metavar "N"
<> value 10
<> help "Number of sweeps before starting hyperparameter estimations (must be multiple of --lag)"
)
<*> option ( long "hyper-lag"
<> metavar "L"
<> value 10
<> help "Number of sweeps between hyperparameter estimations (must be multiple of --lag)"
)
class Binary ms => SamplerModel ms where
modelLikelihood :: ms -> Log Double
estimateHypers :: ms -> ms
summarizeHypers :: ms -> String
processSweep :: SamplerModel ms => SamplerOpts -> TVar (Log Double) -> Int -> ms -> IO ()
processSweep opts lastMaxV sweepN m = do
let l = modelLikelihood m
putStr $ printf "Sweep %d: %f\n" sweepN (ln l)
appendFile (sweepsDir opts </> "likelihood.log")
$ printf "%d\t%f\n" sweepN (ln l)
when (sweepN >= burnin opts) $ do
newMax <- atomically $ do oldL <- readTVar lastMaxV
if l > oldL then writeTVar lastMaxV l >> return True
else return False
when (newMax && sweepN >= burnin opts) $
let fname = sweepsDir opts </> printf "%05d.state" sweepN
in encodeFile fname m
doEstimateHypers :: SamplerModel ms => SamplerOpts -> Int -> S.StateT ms IO ()
doEstimateHypers opts@(SamplerOpts {hyperEstOpts=HyperEstOpts True burnin lag}) iterN
| iterN >= burnin && iterN `mod` lag == 0 = do
liftIO $ putStrLn "Parameter estimation"
m <- S.get
S.modify estimateHypers
m' <- S.get
void $ liftIO $ forkIO
$ appendFile (sweepsDir opts </> "hyperparams.log")
$ printf "%5d\t%f\t%f\t%s\n"
iterN
(ln $ modelLikelihood m)
(ln $ modelLikelihood m')
(summarizeHypers m')
doEstimateHypers _ _ = return ()
withSystemRandomIO = withSystemRandom :: (GenIO -> IO a) -> IO a
samplerIter :: SamplerModel ms => SamplerOpts -> [WrappedUpdateUnit ms]
-> TMVar () -> TVar (Log Double)
-> Int -> S.StateT ms IO ()
samplerIter opts uus processSweepRunning lastMaxV lagN = do
let sweepN = lagN * lag opts
shuffledUus <- liftIO $ withSystemRandomIO $ \mwc->runRVar (shuffle uus) mwc
let uus' = concat $ replicate (lag opts) shuffledUus
m <- S.get
S.put =<< liftIO (gibbsUpdate (nCaps opts) (updateBlock opts) m uus')
when (sweepN == burnin opts) $ liftIO $ putStrLn "Burn-in complete"
S.get >>= \m->do liftIO $ atomically $ takeTMVar processSweepRunning
void $ liftIO $ forkIO $ do
processSweep opts lastMaxV sweepN m
liftIO $ atomically $ putTMVar processSweepRunning ()
doEstimateHypers opts sweepN
checkOpts :: SamplerOpts -> IO ()
checkOpts opts = do
let hyperOpts = hyperEstOpts opts
when (burnin opts `mod` lag opts /= 0)
$ error "--burnin must be multiple of --lag"
when (hyperEst hyperOpts && hyperBurnin hyperOpts `mod` lag opts /= 0)
$ error "--hyper-burnin must be multiple of --lag"
when (hyperEst hyperOpts && hyperLag hyperOpts `mod` lag opts /= 0)
$ error "--hyper-lag must be multiple of --lag"
runSampler :: SamplerModel ms => SamplerOpts -> ms -> [WrappedUpdateUnit ms] -> IO ()
runSampler opts m uus = do
checkOpts opts
setNumCapabilities (nCaps opts)
createDirectoryIfMissing False (sweepsDir opts)
putStrLn "Starting sampler..."
putStrLn $ "Initial likelihood = "++show (ln $ modelLikelihood m)
putStrLn $ "Burning in for "++show (burnin opts)++" samples"
let lagNs = maybe [0..] (\n->[0..n `div` lag opts]) $ iterations opts
lastMaxV <- atomically $ newTVar 0
processSweepRunning <- atomically $ newTMVar ()
void $ S.runStateT (forM_ lagNs (samplerIter opts uus processSweepRunning lastMaxV)) m
atomically $ takeTMVar processSweepRunning
createSweeps :: SamplerOpts -> IO ()
createSweeps (SamplerOpts {sweepsDir=sweepsDir}) = do
exists <- doesDirectoryExist sweepsDir
if exists
then error "Sweeps directory already exists"
else createDirectory sweepsDir
| beni55/bayes-stack | network-topic-models/RunSampler.hs | bsd-3-clause | 7,342 | 0 | 18 | 2,818 | 1,881 | 915 | 966 | 151 | 2 |
{-
Teak synthesiser for the Balsa language
Copyright (C) 2007-2010 The University of Manchester
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(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, see <http://www.gnu.org/licenses/>.
Andrew Bardsley <bardsley@cs.man.ac.uk> (and others, see AUTHORS)
School of Computer Science, The University of Manchester
Oxford Road, MANCHESTER, M13 9PL, UK
-}
module Options (
CommandLineOption (..),
CommandLineOptions (..),
parseOptions,
parseNameValuePairs,
showOptionUsage,
SubOption (..),
SubOptionUsage (..),
SubOptionUsages (..),
SubOptionError,
boolSubOption,
parseSubOptionsString,
subOptionsUsage,
addSubOption,
removeSubOption,
replaceSubOption,
findSubOption,
getSubOption,
findBoolSubOption,
appendSubOptionUsages
) where
import Data.List
import Data.Maybe
import Data.Char (isAlphaNum)
import Control.Monad
import Misc
data CommandLineOption state =
CommandLineOption {
optionLongName :: String,
optionShortName :: Char,
optionArgNames :: [String],
optionSummary :: String,
optionOperation :: state -> [String] -> IO state }
| CommandLineSeparator String
shortNameGiven :: CommandLineOption state -> Bool
shortNameGiven option = isAlphaNum $ optionShortName option
longNameGiven :: CommandLineOption state -> Bool
longNameGiven option = optionLongName option /= ""
data CommandLineOptions state = CommandLineOptions {
optionUsage :: String -> IO (),
optionOptions :: [CommandLineOption state] }
showOptionUsage :: String -> String -> CommandLineOptions state -> String
showOptionUsage indent1 _indent2 (CommandLineOptions _ options) = joinWith "\n" usage ++ "\n"
where
argsStrs = map optionPattern options
summaryStrs = map optionSummary' options
optionSummary' option@(CommandLineOption {}) = optionSummary option
optionSummary' _ = "\n" -- Treat as an `other' row. no -- between option and summary
optionPattern option@(CommandLineOption {})
| shortNameGiven option = "-" ++ [shortName] ++ args ++
if longNameGiven option then " (or --" ++ longName ++ ")" else ""
| longNameGiven option = "--" ++ longName ++ args
| otherwise = error "showOptionUsage: option with long or short name"
where
shortName = optionShortName option
longName = optionLongName option
args = concat $ map argStr $ optionArgNames option
argStr name = " <" ++ name ++ ">"
optionPattern (CommandLineSeparator section) = section
usage = columnFormat [argsStrs, summaryStrs] [indent1, " -- "] [indent1, " "]
parseOptions :: CommandLineOptions state -> state -> [String] -> IO (state, [String])
parseOptions options state args = body args
where
optionList = optionOptions options
body [] = return (state, [])
body ("--":args) = return (state, args)
body (name@('-':'-':longArg):args) = takeOption name args foundArg
where foundArg = find (matchLong longArg) optionList
body (name@['-', shortArg]:args) = takeOption name args foundArg
where foundArg = find (matchShort shortArg) optionList
body (name@('-':_:_):args) = takeOption name args Nothing
body args = return (state, args)
matchLong arg option@(CommandLineOption {}) = longNameGiven option && optionLongName option == arg
matchLong _ _ = False
matchShort arg option@(CommandLineOption {}) = shortNameGiven option && optionShortName option == arg
matchShort _ _ = False
takeOption name args Nothing = do
optionUsage options $ "unrecognised command line option `" ++ name ++ "'"
body args
takeOption name args (Just option)
| optionCount > argCount = do
optionUsage options $ "too few arguments for option `" ++ name ++ "', "
++ show optionCount ++ " needed, only " ++ show argCount ++ " given"
body []
| otherwise = do
state' <- optionOperation option state theseArgs
parseOptions options state' restArgs
where
argCount = length args
(theseArgs, restArgs) = splitAt optionCount args
optionCount = length $ optionArgNames option
parseNameValuePairs :: String -> Maybe [(String, Maybe String)]
parseNameValuePairs opts = mapM splitPair $ splitWith ":" opts
where
splitPair pair = checkPair $ splitWith "=" pair
where
checkPair [name, value] = return (name, Just value)
checkPair [name] = return (name, Nothing)
checkPair _ = fail ""
class SubOption subOption where
matchSubOption :: subOption -> subOption -> Bool
data SubOptionUsage subOption = SubOptionUsage {
subOptionIsBool :: Bool,
subOptionArgName :: String,
subOptionDescription :: String,
subOptionSampleValue :: String,
subOptionCanParseValue :: String -> Bool,
subOptionParseValue :: String -> ([subOption], [subOption]) } -- (add, remove)
data SubOptionUsages subOption = SubOptionUsages {
subOptionClassName :: String,
subOptionShowValue :: subOption -> String,
subOptionNoneValue :: Maybe [subOption],
subOptionDefaultValue :: Maybe [subOption],
subOptionUsages :: [(String, SubOptionUsage subOption)] }
boolSubOption :: String -> subOption -> SubOptionUsage subOption
boolSubOption desc opt = SubOptionUsage True "" desc "" (const True) (const ([opt], []))
addSubOption :: SubOption subOption => [subOption] -> subOption -> [subOption]
addSubOption opts opt = opt : removeSubOption opts opt
removeSubOption :: SubOption subOption => [subOption] -> subOption -> [subOption]
removeSubOption opts opt = filter (not . matchSubOption opt) opts
replaceSubOption :: SubOption subOption => [subOption] -> subOption -> [subOption]
replaceSubOption opts opt
| isJust i = replaceAt opts (fromJust i) opt
| otherwise = addSubOption opts opt
where i = findIndex (matchSubOption opt) opts
-- findSubOption : find a sub-option `matchSubOption'ing the given one (if any)
findSubOption :: SubOption subOption => [subOption] -> subOption -> Maybe subOption
findSubOption opts opt = find (matchSubOption opt) opts
-- getSubOption : like findSubOption but use the given option if none is found in the list
getSubOption :: SubOption subOption => [subOption] -> subOption -> subOption
getSubOption opts opt = fromMaybe opt $ find (matchSubOption opt) opts
findBoolSubOption :: SubOption subOption => [subOption] -> subOption -> Bool
findBoolSubOption opts opt = isJust $ findSubOption opts opt
type SubOptionError subOption = [subOption] -> String -> IO ()
parseSubOption :: (Monad m, SubOption subOption) => SubOptionUsages subOption ->
([subOption] -> String -> m ()) -> [subOption] -> (String, Maybe String) -> m [subOption]
parseSubOption usage _ _ ("none", Nothing)
| isJust $ subOptionNoneValue usage = return $ fromJust $ subOptionNoneValue usage
parseSubOption _ localError opts ("none", Just _) = do
localError opts "can't pass a value to `none' option"
return opts
parseSubOption usage _ _ ("default", Nothing)
| isJust $ subOptionDefaultValue usage = return $ fromJust $ subOptionDefaultValue usage
parseSubOption _ localError opts ("default", Just _) = do
localError opts "can't pass a value to `none' option"
return opts
parseSubOption _ localError opts ("no-none", _) = do
localError opts "can't use `no-' prefix with `none' option"
return opts
parseSubOption _ localError opts ("no-default", _) = do
localError opts "can't use `no-' prefix with `default' option"
return opts
parseSubOption usage localError opts (name, maybeValue)
| isNothing opt = do
localError opts $ "unrecognised " ++ className ++ " option `" ++ bareName ++ "'"
return opts
| not isBool && isNothing maybeValue = do
localError opts $ "must pass a value to option `" ++ bareName ++ "'"
return opts
| isBool && isJust maybeValue = do
localError opts $ "can't pass a value to boolean option `" ++ bareName ++ "'"
return opts
| not isBool && not (subOptionCanParseValue (fromJust opt) value) = do
localError opts $ "bad value `" ++ value ++ "' for " ++ className ++ " option `" ++ name ++ "'"
return opts
| no = return $ foldl' addSubOption (foldl' removeSubOption opts subOptionsToAdd) subOptionsToRemove
| otherwise = return $ foldl' addSubOption (foldl' removeSubOption opts subOptionsToRemove) subOptionsToAdd
where
value = fromMaybe "true" $ maybeValue
isBool = subOptionIsBool $ fromJust opt
className = subOptionClassName usage
opt = lookup bareName $ subOptionUsages usage
-- Just (_, _, _, _, testArg, f) = opt
(subOptionsToAdd, subOptionsToRemove) = subOptionParseValue (fromJust opt) value
bareName = if no then drop 3 name else name
no = isPrefixOf "no-" name
parseSubOptionsString :: (Monad m, SubOption subOption) => SubOptionUsages subOption ->
([subOption] -> String -> m ()) -> [subOption] -> String -> m [subOption]
parseSubOptionsString usage localError opts optString = do
let pairs = parseNameValuePairs optString
when (isNothing pairs) $ localError opts $ "bad " ++ subOptionClassName usage ++ " options"
foldM (parseSubOption usage localError) opts $ fromJust pairs
prettyPrintSubOptions :: SubOption subOption => SubOptionUsages subOption ->
String -> [subOption] -> IO ()
prettyPrintSubOptions usage prefix opts = mapM_ putStrLn $ columnFormat [optOns, optNames, optValues, optDescs]
[prefix,"",""," -- "] [prefix,"",""," "]
where
optionOnDef (name, optUsage) =
(on, name, value, subOptionDescription optUsage)
where
on = if allOptsFound then " " else "no-"
value
| allOptsFound && showValue = " = " ++ optValue
| otherwise = ""
(sampleAdded, sampleRemoved) = subOptionParseValue optUsage $ subOptionSampleValue optUsage
-- This option is on if all its added options are and none of its removed options
allOptsFound = all (isJust . findSubOption opts) sampleAdded &&
all (isNothing . findSubOption opts) sampleRemoved
(showValue, optValue) = case (sampleAdded, sampleRemoved) of
([sample], []) | not (subOptionIsBool optUsage) -> (True, subOptionShowValue usage $
fromMaybe sample $ findSubOption opts sample)
_ -> (False, "")
(optOns, optNames, optValues, optDescs) = unzip4 $ map optionOnDef $ subOptionUsages usage
subOptionsUsage :: SubOption subOption => SubOptionUsages subOption -> [subOption] -> String -> String -> IO ()
subOptionsUsage usage opts commandLineOption message = do
putStrLn $ " " ++ capitalise optionClass ++ " sub-options status and usage"
putStrLn ""
putStrLn $
" usage: " ++ commandLineOption ++ " (<option>:)*[<option>] where <option> ::= [no-]<name>[=<value>]"
putStrLn " `no-' prefix indicates that the option is off for the set of arguments given"
when (isJust $ subOptionNoneValue usage) $
putStrLn $ " `none' can be given as <name> to remove existing options"
when (isJust $ subOptionDefaultValue usage) $
putStrLn $ " `default' can be given as <name> to return options to defaults"
putStrLn ""
prettyPrintSubOptions usage " " opts
putStrLn ""
when (message /= "") $ putStrLn $ "*** " ++ message
where optionClass = subOptionClassName usage
appendSubOptionUsages :: SubOption subOption =>
SubOptionUsages subOption -> SubOptionUsages subOption -> SubOptionUsages subOption
appendSubOptionUsages l r = l { subOptionUsages = subOptionUsages l ++ subOptionUsages r }
| Mahdi89/eTeak | src/Options.hs | bsd-3-clause | 13,461 | 0 | 17 | 3,874 | 3,231 | 1,641 | 1,590 | 208 | 9 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeFamilies #-}
module TcRnExports (tcRnExports, exports_from_avail) where
import GhcPrelude
import HsSyn
import PrelNames
import RdrName
import TcRnMonad
import TcEnv
import TcType
import RnNames
import RnEnv
import RnUnbound ( reportUnboundName )
import ErrUtils
import Id
import IdInfo
import Module
import Name
import NameEnv
import NameSet
import Avail
import TyCon
import SrcLoc
import HscTypes
import Outputable
import ConLike
import DataCon
import PatSyn
import Maybes
import Util (capitalise)
import Control.Monad
import DynFlags
import RnHsDoc ( rnHsDoc )
import RdrHsSyn ( setRdrNameSpace )
import Data.Either ( partitionEithers )
{-
************************************************************************
* *
\subsection{Export list processing}
* *
************************************************************************
Processing the export list.
You might think that we should record things that appear in the export
list as ``occurrences'' (using @addOccurrenceName@), but you'd be
wrong. We do check (here) that they are in scope, but there is no
need to slurp in their actual declaration (which is what
@addOccurrenceName@ forces).
Indeed, doing so would big trouble when compiling @PrelBase@, because
it re-exports @GHC@, which includes @takeMVar#@, whose type includes
@ConcBase.StateAndSynchVar#@, and so on...
Note [Exports of data families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose you see (Trac #5306)
module M where
import X( F )
data instance F Int = FInt
What does M export? AvailTC F [FInt]
or AvailTC F [F,FInt]?
The former is strictly right because F isn't defined in this module.
But then you can never do an explicit import of M, thus
import M( F( FInt ) )
because F isn't exported by M. Nor can you import FInt alone from here
import M( FInt )
because we don't have syntax to support that. (It looks like an import of
the type FInt.)
At one point I implemented a compromise:
* When constructing exports with no export list, or with module M(
module M ), we add the parent to the exports as well.
* But not when you see module M( f ), even if f is a
class method with a parent.
* Nor when you see module M( module N ), with N /= M.
But the compromise seemed too much of a hack, so we backed it out.
You just have to use an explicit export list:
module M( F(..) ) where ...
-}
data ExportAccum -- The type of the accumulating parameter of
-- the main worker function in rnExports
= ExportAccum
[(LIE GhcRn, Avails)] -- Export items with names and
-- their exported stuff
-- Not nub'd!
ExportOccMap -- Tracks exported occurrence names
emptyExportAccum :: ExportAccum
emptyExportAccum = ExportAccum [] emptyOccEnv
type ExportOccMap = OccEnv (Name, IE GhcPs)
-- Tracks what a particular exported OccName
-- in an export list refers to, and which item
-- it came from. It's illegal to export two distinct things
-- that have the same occurrence name
tcRnExports :: Bool -- False => no 'module M(..) where' header at all
-> Maybe (Located [LIE GhcPs]) -- Nothing => no explicit export list
-> TcGblEnv
-> RnM TcGblEnv
-- Complains if two distinct exports have same OccName
-- Warns about identical exports.
-- Complains about exports items not in scope
tcRnExports explicit_mod exports
tcg_env@TcGblEnv { tcg_mod = this_mod,
tcg_rdr_env = rdr_env,
tcg_imports = imports,
tcg_src = hsc_src }
= unsetWOptM Opt_WarnWarningsDeprecations $
-- Do not report deprecations arising from the export
-- list, to avoid bleating about re-exporting a deprecated
-- thing (especially via 'module Foo' export item)
do {
-- If the module header is omitted altogether, then behave
-- as if the user had written "module Main(main) where..."
-- EXCEPT in interactive mode, when we behave as if he had
-- written "module Main where ..."
-- Reason: don't want to complain about 'main' not in scope
-- in interactive mode
; dflags <- getDynFlags
; let real_exports
| explicit_mod = exports
| ghcLink dflags == LinkInMemory = Nothing
| otherwise
= Just (noLoc [noLoc
(IEVar (noLoc (IEName $ noLoc main_RDR_Unqual)))])
-- ToDo: the 'noLoc' here is unhelpful if 'main'
-- turns out to be out of scope
; let do_it = exports_from_avail real_exports rdr_env imports this_mod
; (rn_exports, final_avails)
<- if hsc_src == HsigFile
then do (msgs, mb_r) <- tryTc do_it
case mb_r of
Just r -> return r
Nothing -> addMessages msgs >> failM
else checkNoErrs do_it
; let final_ns = availsToNameSetWithSelectors final_avails
; traceRn "rnExports: Exports:" (ppr final_avails)
; let new_tcg_env =
tcg_env { tcg_exports = final_avails,
tcg_rn_exports = case tcg_rn_exports tcg_env of
Nothing -> Nothing
Just _ -> rn_exports,
tcg_dus = tcg_dus tcg_env `plusDU`
usesOnly final_ns }
; failIfErrsM
; return new_tcg_env }
exports_from_avail :: Maybe (Located [LIE GhcPs])
-- Nothing => no explicit export list
-> GlobalRdrEnv
-> ImportAvails
-- Imported modules; this is used to test if a
-- 'module Foo' export is valid (it's not valid
-- if we didn't import Foo!)
-> Module
-> RnM (Maybe [(LIE GhcRn, Avails)], Avails)
-- (Nothing, _) <=> no explicit export list
-- if explicit export list is present it contains
-- each renamed export item together with its exported
-- names.
exports_from_avail Nothing rdr_env _imports _this_mod
-- The same as (module M) where M is the current module name,
-- so that's how we handle it, except we also export the data family
-- when a data instance is exported.
= do {
; warnMissingExportList <- woptM Opt_WarnMissingExportList
; warnIfFlag Opt_WarnMissingExportList
warnMissingExportList
(missingModuleExportWarn $ moduleName _this_mod)
; let avails =
map fix_faminst . gresToAvailInfo
. filter isLocalGRE . globalRdrEnvElts $ rdr_env
; return (Nothing, avails) }
where
-- #11164: when we define a data instance
-- but not data family, re-export the family
-- Even though we don't check whether this is actually a data family
-- only data families can locally define subordinate things (`ns` here)
-- without locally defining (and instead importing) the parent (`n`)
fix_faminst (AvailTC n ns flds) =
let new_ns =
case ns of
[] -> [n]
(p:_) -> if p == n then ns else n:ns
in AvailTC n new_ns flds
fix_faminst avail = avail
exports_from_avail (Just (L _ rdr_items)) rdr_env imports this_mod
= do ExportAccum ie_avails _
<- foldAndRecoverM do_litem emptyExportAccum rdr_items
let final_exports = nubAvails (concat (map snd ie_avails)) -- Combine families
return (Just ie_avails, final_exports)
where
do_litem :: ExportAccum -> LIE GhcPs -> RnM ExportAccum
do_litem acc lie = setSrcSpan (getLoc lie) (exports_from_item acc lie)
-- Maps a parent to its in-scope children
kids_env :: NameEnv [GlobalRdrElt]
kids_env = mkChildEnv (globalRdrEnvElts rdr_env)
imported_modules = [ imv_name imv
| xs <- moduleEnvElts $ imp_mods imports
, imv <- importedByUser xs ]
exports_from_item :: ExportAccum -> LIE GhcPs -> RnM ExportAccum
exports_from_item acc@(ExportAccum ie_avails occs)
(L loc (IEModuleContents (L lm mod)))
| let earlier_mods = [ mod
| ((L _ (IEModuleContents (L _ mod))), _) <- ie_avails ]
, mod `elem` earlier_mods -- Duplicate export of M
= do { warnIfFlag Opt_WarnDuplicateExports True
(dupModuleExport mod) ;
return acc }
| otherwise
= do { let { exportValid = (mod `elem` imported_modules)
|| (moduleName this_mod == mod)
; gre_prs = pickGREsModExp mod (globalRdrEnvElts rdr_env)
; new_exports = map (availFromGRE . fst) gre_prs
; names = map (gre_name . fst) gre_prs
; all_gres = foldr (\(gre1,gre2) gres -> gre1 : gre2 : gres) [] gre_prs
}
; checkErr exportValid (moduleNotImported mod)
; warnIfFlag Opt_WarnDodgyExports
(exportValid && null gre_prs)
(nullModuleExport mod)
; traceRn "efa" (ppr mod $$ ppr all_gres)
; addUsedGREs all_gres
; occs' <- check_occs (IEModuleContents (noLoc mod)) occs names
-- This check_occs not only finds conflicts
-- between this item and others, but also
-- internally within this item. That is, if
-- 'M.x' is in scope in several ways, we'll have
-- several members of mod_avails with the same
-- OccName.
; traceRn "export_mod"
(vcat [ ppr mod
, ppr new_exports ])
; return (ExportAccum (((L loc (IEModuleContents (L lm mod))), new_exports) : ie_avails)
occs') }
exports_from_item acc@(ExportAccum lie_avails occs) (L loc ie)
| isDoc ie
= do new_ie <- lookup_doc_ie ie
return (ExportAccum ((L loc new_ie, []) : lie_avails) occs)
| otherwise
= do (new_ie, avail) <-
setSrcSpan loc $ lookup_ie ie
if isUnboundName (ieName new_ie)
then return acc -- Avoid error cascade
else do
occs' <- check_occs ie occs (availNames avail)
return (ExportAccum ((L loc new_ie, [avail]) : lie_avails) occs')
-------------
lookup_ie :: IE GhcPs -> RnM (IE GhcRn, AvailInfo)
lookup_ie (IEVar (L l rdr))
= do (name, avail) <- lookupGreAvailRn $ ieWrappedName rdr
return (IEVar (L l (replaceWrappedName rdr name)), avail)
lookup_ie (IEThingAbs (L l rdr))
= do (name, avail) <- lookupGreAvailRn $ ieWrappedName rdr
return (IEThingAbs (L l (replaceWrappedName rdr name)), avail)
lookup_ie ie@(IEThingAll n')
= do
(n, avail, flds) <- lookup_ie_all ie n'
let name = unLoc n
return (IEThingAll (replaceLWrappedName n' (unLoc n))
, AvailTC name (name:avail) flds)
lookup_ie ie@(IEThingWith l wc sub_rdrs _)
= do
(lname, subs, avails, flds)
<- addExportErrCtxt ie $ lookup_ie_with l sub_rdrs
(_, all_avail, all_flds) <-
case wc of
NoIEWildcard -> return (lname, [], [])
IEWildcard _ -> lookup_ie_all ie l
let name = unLoc lname
return (IEThingWith (replaceLWrappedName l name) wc subs
(flds ++ (map noLoc all_flds)),
AvailTC name (name : avails ++ all_avail)
(map unLoc flds ++ all_flds))
lookup_ie _ = panic "lookup_ie" -- Other cases covered earlier
lookup_ie_with :: LIEWrappedName RdrName -> [LIEWrappedName RdrName]
-> RnM (Located Name, [LIEWrappedName Name], [Name],
[Located FieldLabel])
lookup_ie_with (L l rdr) sub_rdrs
= do name <- lookupGlobalOccRn $ ieWrappedName rdr
(non_flds, flds) <- lookupChildrenExport name sub_rdrs
if isUnboundName name
then return (L l name, [], [name], [])
else return (L l name, non_flds
, map (ieWrappedName . unLoc) non_flds
, flds)
lookup_ie_all :: IE GhcPs -> LIEWrappedName RdrName
-> RnM (Located Name, [Name], [FieldLabel])
lookup_ie_all ie (L l rdr) =
do name <- lookupGlobalOccRn $ ieWrappedName rdr
let gres = findChildren kids_env name
(non_flds, flds) = classifyGREs gres
addUsedKids (ieWrappedName rdr) gres
warnDodgyExports <- woptM Opt_WarnDodgyExports
when (null gres) $
if isTyConName name
then when warnDodgyExports $
addWarn (Reason Opt_WarnDodgyExports)
(dodgyExportWarn name)
else -- This occurs when you export T(..), but
-- only import T abstractly, or T is a synonym.
addErr (exportItemErr ie)
return (L l name, non_flds, flds)
-------------
lookup_doc_ie :: IE GhcPs -> RnM (IE GhcRn)
lookup_doc_ie (IEGroup lev doc) = do rn_doc <- rnHsDoc doc
return (IEGroup lev rn_doc)
lookup_doc_ie (IEDoc doc) = do rn_doc <- rnHsDoc doc
return (IEDoc rn_doc)
lookup_doc_ie (IEDocNamed str) = return (IEDocNamed str)
lookup_doc_ie _ = panic "lookup_doc_ie" -- Other cases covered earlier
-- In an export item M.T(A,B,C), we want to treat the uses of
-- A,B,C as if they were M.A, M.B, M.C
-- Happily pickGREs does just the right thing
addUsedKids :: RdrName -> [GlobalRdrElt] -> RnM ()
addUsedKids parent_rdr kid_gres = addUsedGREs (pickGREs parent_rdr kid_gres)
classifyGREs :: [GlobalRdrElt] -> ([Name], [FieldLabel])
classifyGREs = partitionEithers . map classifyGRE
classifyGRE :: GlobalRdrElt -> Either Name FieldLabel
classifyGRE gre = case gre_par gre of
FldParent _ Nothing -> Right (FieldLabel (occNameFS (nameOccName n)) False n)
FldParent _ (Just lbl) -> Right (FieldLabel lbl True n)
_ -> Left n
where
n = gre_name gre
isDoc :: IE GhcPs -> Bool
isDoc (IEDoc _) = True
isDoc (IEDocNamed _) = True
isDoc (IEGroup _ _) = True
isDoc _ = False
-- Renaming and typechecking of exports happens after everything else has
-- been typechecked.
-- Renaming exports lists is a minefield. Five different things can appear in
-- children export lists ( T(A, B, C) ).
-- 1. Record selectors
-- 2. Type constructors
-- 3. Data constructors
-- 4. Pattern Synonyms
-- 5. Pattern Synonym Selectors
--
-- However, things get put into weird name spaces.
-- 1. Some type constructors are parsed as variables (-.->) for example.
-- 2. All data constructors are parsed as type constructors
-- 3. When there is ambiguity, we default type constructors to data
-- constructors and require the explicit `type` keyword for type
-- constructors.
--
-- This function first establishes the possible namespaces that an
-- identifier might be in (`choosePossibleNameSpaces`).
--
-- Then for each namespace in turn, tries to find the correct identifier
-- there returning the first positive result or the first terminating
-- error.
--
lookupChildrenExport :: Name -> [LIEWrappedName RdrName]
-> RnM ([LIEWrappedName Name], [Located FieldLabel])
lookupChildrenExport spec_parent rdr_items =
do
xs <- mapAndReportM doOne rdr_items
return $ partitionEithers xs
where
-- Pick out the possible namespaces in order of priority
-- This is a consequence of how the parser parses all
-- data constructors as type constructors.
choosePossibleNamespaces :: NameSpace -> [NameSpace]
choosePossibleNamespaces ns
| ns == varName = [varName, tcName]
| ns == tcName = [dataName, tcName]
| otherwise = [ns]
-- Process an individual child
doOne :: LIEWrappedName RdrName
-> RnM (Either (LIEWrappedName Name) (Located FieldLabel))
doOne n = do
let bareName = (ieWrappedName . unLoc) n
lkup v = lookupSubBndrOcc_helper False True
spec_parent (setRdrNameSpace bareName v)
name <- combineChildLookupResult $ map lkup $
choosePossibleNamespaces (rdrNameSpace bareName)
traceRn "lookupChildrenExport" (ppr name)
-- Default to data constructors for slightly better error
-- messages
let unboundName :: RdrName
unboundName = if rdrNameSpace bareName == varName
then bareName
else setRdrNameSpace bareName dataName
case name of
NameNotFound -> do { ub <- reportUnboundName unboundName
; let l = getLoc n
; return (Left (L l (IEName (L l ub))))}
FoundFL fls -> return $ Right (L (getLoc n) fls)
FoundName par name -> do { checkPatSynParent spec_parent par name
; return $ Left (replaceLWrappedName n name) }
IncorrectParent p g td gs -> failWithDcErr p g td gs
-- Note: [Typing Pattern Synonym Exports]
-- It proved quite a challenge to precisely specify which pattern synonyms
-- should be allowed to be bundled with which type constructors.
-- In the end it was decided to be quite liberal in what we allow. Below is
-- how Simon described the implementation.
--
-- "Personally I think we should Keep It Simple. All this talk of
-- satisfiability makes me shiver. I suggest this: allow T( P ) in all
-- situations except where `P`'s type is ''visibly incompatible'' with
-- `T`.
--
-- What does "visibly incompatible" mean? `P` is visibly incompatible
-- with
-- `T` if
-- * `P`'s type is of form `... -> S t1 t2`
-- * `S` is a data/newtype constructor distinct from `T`
--
-- Nothing harmful happens if we allow `P` to be exported with
-- a type it can't possibly be useful for, but specifying a tighter
-- relationship is very awkward as you have discovered."
--
-- Note that this allows *any* pattern synonym to be bundled with any
-- datatype type constructor. For example, the following pattern `P` can be
-- bundled with any type.
--
-- ```
-- pattern P :: (A ~ f) => f
-- ```
--
-- So we provide basic type checking in order to help the user out, most
-- pattern synonyms are defined with definite type constructors, but don't
-- actually prevent a library author completely confusing their users if
-- they want to.
--
-- So, we check for exactly four things
-- 1. The name arises from a pattern synonym definition. (Either a pattern
-- synonym constructor or a pattern synonym selector)
-- 2. The pattern synonym is only bundled with a datatype or newtype.
-- 3. Check that the head of the result type constructor is an actual type
-- constructor and not a type variable. (See above example)
-- 4. Is so, check that this type constructor is the same as the parent
-- type constructor.
--
--
-- Note: [Types of TyCon]
--
-- This check appears to be overlly complicated, Richard asked why it
-- is not simply just `isAlgTyCon`. The answer for this is that
-- a classTyCon is also an `AlgTyCon` which we explicitly want to disallow.
-- (It is either a newtype or data depending on the number of methods)
--
-- | Given a resolved name in the children export list and a parent. Decide
-- whether we are allowed to export the child with the parent.
-- Invariant: gre_par == NoParent
-- See note [Typing Pattern Synonym Exports]
checkPatSynParent :: Name -- ^ Alleged parent type constructor
-- User wrote T( P, Q )
-> Parent -- The parent of P we discovered
-> Name -- ^ Either a
-- a) Pattern Synonym Constructor
-- b) A pattern synonym selector
-> TcM () -- Fails if wrong parent
checkPatSynParent _ (ParentIs {}) _
= return ()
checkPatSynParent _ (FldParent {}) _
= return ()
checkPatSynParent parent NoParent mpat_syn
| isUnboundName parent -- Avoid an error cascade
= return ()
| otherwise
= do { parent_ty_con <- tcLookupTyCon parent
; mpat_syn_thing <- tcLookupGlobal mpat_syn
-- 1. Check that the Id was actually from a thing associated with patsyns
; case mpat_syn_thing of
AnId i | isId i
, RecSelId { sel_tycon = RecSelPatSyn p } <- idDetails i
-> handle_pat_syn (selErr i) parent_ty_con p
AConLike (PatSynCon p) -> handle_pat_syn (psErr p) parent_ty_con p
_ -> failWithDcErr parent mpat_syn (ppr mpat_syn) [] }
where
psErr = exportErrCtxt "pattern synonym"
selErr = exportErrCtxt "pattern synonym record selector"
assocClassErr :: SDoc
assocClassErr = text "Pattern synonyms can be bundled only with datatypes."
handle_pat_syn :: SDoc
-> TyCon -- ^ Parent TyCon
-> PatSyn -- ^ Corresponding bundled PatSyn
-- and pretty printed origin
-> TcM ()
handle_pat_syn doc ty_con pat_syn
-- 2. See note [Types of TyCon]
| not $ isTyConWithSrcDataCons ty_con
= addErrCtxt doc $ failWithTc assocClassErr
-- 3. Is the head a type variable?
| Nothing <- mtycon
= return ()
-- 4. Ok. Check they are actually the same type constructor.
| Just p_ty_con <- mtycon, p_ty_con /= ty_con
= addErrCtxt doc $ failWithTc typeMismatchError
-- 5. We passed!
| otherwise
= return ()
where
expected_res_ty = mkTyConApp ty_con (mkTyVarTys (tyConTyVars ty_con))
(_, _, _, _, _, res_ty) = patSynSig pat_syn
mtycon = fst <$> tcSplitTyConApp_maybe res_ty
typeMismatchError :: SDoc
typeMismatchError =
text "Pattern synonyms can only be bundled with matching type constructors"
$$ text "Couldn't match expected type of"
<+> quotes (ppr expected_res_ty)
<+> text "with actual type of"
<+> quotes (ppr res_ty)
{-===========================================================================-}
check_occs :: IE GhcPs -> ExportOccMap -> [Name] -> RnM ExportOccMap
check_occs ie occs names -- 'names' are the entities specifed by 'ie'
= foldlM check occs names
where
check occs name
= case lookupOccEnv occs name_occ of
Nothing -> return (extendOccEnv occs name_occ (name, ie))
Just (name', ie')
| name == name' -- Duplicate export
-- But we don't want to warn if the same thing is exported
-- by two different module exports. See ticket #4478.
-> do { warnIfFlag Opt_WarnDuplicateExports
(not (dupExport_ok name ie ie'))
(dupExportWarn name_occ ie ie')
; return occs }
| otherwise -- Same occ name but different names: an error
-> do { global_env <- getGlobalRdrEnv ;
addErr (exportClashErr global_env name' name ie' ie) ;
return occs }
where
name_occ = nameOccName name
dupExport_ok :: Name -> IE GhcPs -> IE GhcPs -> Bool
-- The Name is exported by both IEs. Is that ok?
-- "No" iff the name is mentioned explicitly in both IEs
-- or one of the IEs mentions the name *alone*
-- "Yes" otherwise
--
-- Examples of "no": module M( f, f )
-- module M( fmap, Functor(..) )
-- module M( module Data.List, head )
--
-- Example of "yes"
-- module M( module A, module B ) where
-- import A( f )
-- import B( f )
--
-- Example of "yes" (Trac #2436)
-- module M( C(..), T(..) ) where
-- class C a where { data T a }
-- instance C Int where { data T Int = TInt }
--
-- Example of "yes" (Trac #2436)
-- module Foo ( T ) where
-- data family T a
-- module Bar ( T(..), module Foo ) where
-- import Foo
-- data instance T Int = TInt
dupExport_ok n ie1 ie2
= not ( single ie1 || single ie2
|| (explicit_in ie1 && explicit_in ie2) )
where
explicit_in (IEModuleContents _) = False -- module M
explicit_in (IEThingAll r)
= nameOccName n == rdrNameOcc (ieWrappedName $ unLoc r) -- T(..)
explicit_in _ = True
single IEVar {} = True
single IEThingAbs {} = True
single _ = False
dupModuleExport :: ModuleName -> SDoc
dupModuleExport mod
= hsep [text "Duplicate",
quotes (text "Module" <+> ppr mod),
text "in export list"]
moduleNotImported :: ModuleName -> SDoc
moduleNotImported mod
= hsep [text "The export item",
quotes (text "module" <+> ppr mod),
text "is not imported"]
nullModuleExport :: ModuleName -> SDoc
nullModuleExport mod
= hsep [text "The export item",
quotes (text "module" <+> ppr mod),
text "exports nothing"]
missingModuleExportWarn :: ModuleName -> SDoc
missingModuleExportWarn mod
= hsep [text "The export item",
quotes (text "module" <+> ppr mod),
text "is missing an export list"]
dodgyExportWarn :: Name -> SDoc
dodgyExportWarn item
= dodgyMsg (text "export") item (dodgyMsgInsert item :: IE GhcRn)
exportErrCtxt :: Outputable o => String -> o -> SDoc
exportErrCtxt herald exp =
text "In the" <+> text (herald ++ ":") <+> ppr exp
addExportErrCtxt :: (OutputableBndrId s) => IE s -> TcM a -> TcM a
addExportErrCtxt ie = addErrCtxt exportCtxt
where
exportCtxt = text "In the export:" <+> ppr ie
exportItemErr :: IE GhcPs -> SDoc
exportItemErr export_item
= sep [ text "The export item" <+> quotes (ppr export_item),
text "attempts to export constructors or class methods that are not visible here" ]
dupExportWarn :: OccName -> IE GhcPs -> IE GhcPs -> SDoc
dupExportWarn occ_name ie1 ie2
= hsep [quotes (ppr occ_name),
text "is exported by", quotes (ppr ie1),
text "and", quotes (ppr ie2)]
dcErrMsg :: Name -> String -> SDoc -> [SDoc] -> SDoc
dcErrMsg ty_con what_is thing parents =
text "The type constructor" <+> quotes (ppr ty_con)
<+> text "is not the parent of the" <+> text what_is
<+> quotes thing <> char '.'
$$ text (capitalise what_is)
<> text "s can only be exported with their parent type constructor."
$$ (case parents of
[] -> empty
[_] -> text "Parent:"
_ -> text "Parents:") <+> fsep (punctuate comma parents)
failWithDcErr :: Name -> Name -> SDoc -> [Name] -> TcM a
failWithDcErr parent thing thing_doc parents = do
ty_thing <- tcLookupGlobal thing
failWithTc $ dcErrMsg parent (tyThingCategory' ty_thing)
thing_doc (map ppr parents)
where
tyThingCategory' :: TyThing -> String
tyThingCategory' (AnId i)
| isRecordSelector i = "record selector"
tyThingCategory' i = tyThingCategory i
exportClashErr :: GlobalRdrEnv -> Name -> Name -> IE GhcPs -> IE GhcPs
-> MsgDoc
exportClashErr global_env name1 name2 ie1 ie2
= vcat [ text "Conflicting exports for" <+> quotes (ppr occ) <> colon
, ppr_export ie1' name1'
, ppr_export ie2' name2' ]
where
occ = nameOccName name1
ppr_export ie name = nest 3 (hang (quotes (ppr ie) <+> text "exports" <+>
quotes (ppr name))
2 (pprNameProvenance (get_gre name)))
-- get_gre finds a GRE for the Name, so that we can show its provenance
get_gre name
= fromMaybe (pprPanic "exportClashErr" (ppr name)) (lookupGRE_Name global_env name)
get_loc name = greSrcSpan (get_gre name)
(name1', ie1', name2', ie2') = if get_loc name1 < get_loc name2
then (name1, ie1, name2, ie2)
else (name2, ie2, name1, ie1)
| ezyang/ghc | compiler/typecheck/TcRnExports.hs | bsd-3-clause | 29,466 | 56 | 23 | 9,607 | 5,470 | 2,833 | 2,637 | 412 | 16 |
-----------------------------------------------------------------------------
-- |
-- License : BSD-3-Clause
-- Maintainer : Todd Mohney <toddmohney@gmail.com>
--
-- The deploy keys API, as described at
-- <https://developer.github.com/v3/repos/keys>
module GitHub.Endpoints.Repos.DeployKeys (
-- * Querying deploy keys
deployKeysForR,
deployKeyForR,
-- ** Create
createRepoDeployKeyR,
-- ** Delete
deleteRepoDeployKeyR,
) where
import GitHub.Data
import GitHub.Internal.Prelude
import Prelude ()
-- | Querying deploy keys.
-- See <https://developer.github.com/v3/repos/keys/#list-deploy-keys>
deployKeysForR :: Name Owner -> Name Repo -> FetchCount -> Request 'RA (Vector RepoDeployKey)
deployKeysForR user repo =
pagedQuery ["repos", toPathPart user, toPathPart repo, "keys"] []
-- | Querying a deploy key.
-- See <https://developer.github.com/v3/repos/keys/#get-a-deploy-key>
deployKeyForR :: Name Owner -> Name Repo -> Id RepoDeployKey -> Request 'RA RepoDeployKey
deployKeyForR user repo keyId =
query ["repos", toPathPart user, toPathPart repo, "keys", toPathPart keyId] []
-- | Create a deploy key.
-- See <https://developer.github.com/v3/repos/keys/#add-a-new-deploy-key>.
createRepoDeployKeyR :: Name Owner -> Name Repo -> NewRepoDeployKey -> Request 'RW RepoDeployKey
createRepoDeployKeyR user repo key =
command Post ["repos", toPathPart user, toPathPart repo, "keys"] (encode key)
-- | Delete a deploy key.
-- See <https://developer.github.com/v3/repos/keys/#remove-a-deploy-key>
deleteRepoDeployKeyR :: Name Owner -> Name Repo -> Id RepoDeployKey -> GenRequest 'MtUnit 'RW ()
deleteRepoDeployKeyR user repo keyId =
Command Delete ["repos", toPathPart user, toPathPart repo, "keys", toPathPart keyId] mempty
| jwiegley/github | src/GitHub/Endpoints/Repos/DeployKeys.hs | bsd-3-clause | 1,778 | 0 | 10 | 258 | 360 | 193 | 167 | -1 | -1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
-- | Functions for manipulating translation units.
--
-- To start analyzing a translation unit, call 'Index.withNew' to create a new index and
-- call 'withParsed' in the callback. Inside the callback for 'withParsed', you'll have
-- access to a 'FFI.TranslationUnit' value; you can call 'getCursor' to turn that into an
-- AST cursor which can be traversed using the functions in "Clang.Cursor".
--
-- This module is intended to be imported qualified.
module Clang.TranslationUnit
(
-- * Creating a translation unit
withParsed
, withLoaded
, withReparsing
, FFI.TranslationUnitFlags
, FFI.ReparseFlags
, ReparsingCallback
, ParseContinuation(..)
-- * Saving
, save
, FFI.SaveTranslationUnitFlags
-- AST traversal and metadata
, getCursor
, getDiagnosticSet
, getSpelling
) where
import Data.Traversable
import Control.Monad.IO.Class
import Data.Maybe (fromMaybe)
import qualified Data.Vector as DV
-- import System.FilePath ((</>))
import Clang.Internal.BitFlags
import Clang.Internal.Monad
import qualified Clang.Internal.FFI as FFI
-- import Paths_LibClang (getDataFileName)
-- | Creates a translation unit by parsing source code.
--
-- Note that not all command line arguments which are accepted by the \'clang\' frontend can
-- be used here. You should avoid passing \'-c\', \'-o\', \'-fpch-deps\', and the various
-- \'-M\' options. If you provide a 'FilePath' when calling 'withParsed', also be sure not
-- to provide the filename in the command line arguments as well.
withParsed :: ClangBase m
=> FFI.Index s' -- ^ The index into which the translation unit should be loaded.
-> Maybe FilePath -- ^ The file to load, or 'Nothing' if the file is specified in
-- the command line arguments.
-> [String] -- ^ The command line arguments libclang should use when compiling this
-- file. Most arguments which you'd use with the \'clang\' frontend
-- are accepted.
-> DV.Vector FFI.UnsavedFile -- ^ Unsaved files which may be needed to parse this
-- translation unit. This may include the source
-- file itself or any file it includes.
-> [FFI.TranslationUnitFlags] -- ^ Flags that affect the processing of this
-- translation unit.
-> (forall s. FFI.TranslationUnit s -> ClangT s m a) -- ^ A callback.
-> ClangT s' m (Maybe a) -- ^ The return value of the callback, or 'Nothing'
-- if the file couldn't be parsed.
withParsed idx mayPath args ufs flags f = do
-- liftIO $ FFI.setClangResourcesPath idx =<< clangResourcesPath
mayTU <- FFI.parseTranslationUnit idx mayPath args ufs (orFlags flags)
traverse go mayTU
where
go tu = clangScope $ f =<< fromOuterScope tu
-- | Creates a translation unit by loading a saved AST file.
--
-- Such an AST file can be created using 'save'.
withLoaded :: ClangBase m
=> FFI.Index s' -- ^ The index into which the translation unit should be loaded.
-> FilePath -- ^ The file to load.
-> (forall s. FFI.TranslationUnit s -> ClangT s m a) -- ^ A callback.
-> ClangT s' m a
withLoaded idx path f = do
-- liftIO $ FFI.setClangResourcesPath idx =<< clangResourcesPath
f =<< FFI.createTranslationUnit idx path
-- | Creates a translation unit by parsing source code.
--
-- This works like 'withParsed', except that the translation unit can be reparsed over and over
-- again by returning a 'Reparse' value from the callback. This is useful for interactive
-- analyses like code completion. Processing can be stopped by returning a 'ParseComplete' value.
withReparsing :: ClangBase m
=> FFI.Index s' -- ^ The index into which the translation unit should be loaded.
-> Maybe FilePath -- ^ The file to load, or 'Nothing' if the file is specified in
-- the command line arguments.
-> [String] -- ^ The command line arguments libclang should use when compiling
-- this file. Most arguments which you'd use with the \'clang\'
-- frontend are accepted.
-> DV.Vector FFI.UnsavedFile -- ^ Unsaved files which may be needed to parse this
-- translation unit. This may include the source
-- file itself or any file it includes.
-> [FFI.TranslationUnitFlags] -- ^ Flags that affect the processing of this
-- translation unit.
-> ReparsingCallback m r -- ^ A callback which uses the translation unit. May be
-- called many times depending on the return value.
-- See 'ParseContinuation' for more information.
-> ClangT s' m (Maybe r) -- ^ The return value of the callback, as passed to
-- 'ParseComplete', or 'Nothing' if the file could
-- not be parsed.
withReparsing idx mayPath args ufs flags f = do
-- liftIO $ FFI.setClangResourcesPath idx =<< clangResourcesPath
mayTU <- FFI.parseTranslationUnit idx mayPath args ufs (orFlags flags)
case mayTU of
Nothing -> return Nothing
Just tu -> iterReparse f tu
iterReparse :: ClangBase m
=> ReparsingCallback m r
-> FFI.TranslationUnit s'
-> ClangT s' m (Maybe r)
iterReparse f tu = do
cont <- clangScope $ f =<< fromOuterScope tu
case cont of
Reparse nextF ufs mayFlags ->
do res <- FFI.reparseTranslationUnit tu ufs (makeFlags mayFlags)
if res then iterReparse nextF tu
else return Nothing
ParseComplete finalVal -> return $ Just finalVal
where
makeFlags = orFlags . (fromMaybe [FFI.DefaultReparseFlags])
-- | A callback for use with 'withReparsing'.
type ReparsingCallback m r = forall s. FFI.TranslationUnit s
-> ClangT s m (ParseContinuation m r)
-- | A continuation returned by a 'ReparsingCallback'.
data ParseContinuation m r
-- | 'Reparse' signals that the translation unit should be reparsed. It contains a callback
-- which will be called with the updated translation unit after reparsing, a 'DV.Vector' of
-- unsaved files which may be needed to reparse, and a set of flags affecting reparsing. The
-- default reparsing flags can be requested by specifying 'Nothing'.
= Reparse (ReparsingCallback m r) (DV.Vector FFI.UnsavedFile) (Maybe [FFI.ReparseFlags])
-- | 'ParseComplete' signals that processing is finished. It contains a final result which
-- will be returned by 'withReparsing'.
| ParseComplete r
-- clangResourcesPath :: IO FilePath
-- clangResourcesPath =
-- getDataFileName $ "build" </> "out" </> "lib" </> "clang" </> "3.4"
-- | Saves a translation unit as an AST file with can be loaded later using 'withLoaded'.
save :: ClangBase m
=> FFI.TranslationUnit s' -- ^ The translation unit to save.
-> FilePath -- ^ The filename to save to.
-> Maybe [FFI.SaveTranslationUnitFlags] -- ^ Flags that affect saving, or 'Nothing' for
-- the default set of flags.
-> ClangT s m Bool
save t fname mayFlags = liftIO $ FFI.saveTranslationUnit t fname (orFlags flags)
where flags = fromMaybe [FFI.DefaultSaveTranslationUnitFlags] mayFlags
{-
-- | Reparses the provided translation unit using the same command line arguments
-- that were originally used to parse it. If the file has changed on disk, or if
-- the unsaved files have changed, those changes will become visible.
--
-- Note that 'reparse' invalidates all cursors and source locations that refer into
-- the reparsed translation unit. This makes it unsafe. However, 'reparse' can be
-- more efficient than calling 'withParsed' a second time.
reparse :: ClangBase m
=> FFI.TranslationUnit s' -- ^ The translation unit to reparse.
-> DV.Vector FFI.UnsavedFile -- ^ Unsaved files which may be needed to reparse
-- this translation unit.
-> Maybe [FFI.ReparseFlags] -- ^ Flags that affect reparsing, or 'Nothing' for the
-- default set of flags.
-> ClangT s m Bool
reparse t ufs mayFlags = FFI.reparseTranslationUnit t ufs (orFlags flags)
where flags = fromMaybe [FFI.DefaultReparseFlags] mayFlags
-}
-- | Retrieve the cursor associated with this translation unit. This cursor is the root of
-- this translation unit's AST; you can begin exploring the AST further using the functions
-- in "Clang.Cursor".
getCursor :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.Cursor s)
getCursor tu = liftIO $ FFI.getTranslationUnitCursor mkProxy tu
-- | Retrieve the complete set of diagnostics associated with the given translation unit.
getDiagnosticSet :: ClangBase m => FFI.TranslationUnit s'-> ClangT s m (FFI.DiagnosticSet s)
getDiagnosticSet = FFI.getDiagnosticSetFromTU
-- | Retrieve a textual representation of this translation unit.
getSpelling :: ClangBase m => FFI.TranslationUnit s' -> ClangT s m (FFI.ClangString s)
getSpelling = FFI.getTranslationUnitSpelling
| deech/LibClang | src/Clang/TranslationUnit.hs | bsd-3-clause | 9,598 | 0 | 16 | 2,614 | 1,089 | 592 | 497 | 87 | 3 |
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Module : Data.Array.Accelerate.CUDA.Array.Cache
-- Copyright : [2015..2015] Robert Clifton-Everest, Manuel M T Chakravarty,
-- Gabriele Keller
-- License : BSD3
--
-- Maintainer : Robert Clifton-Everest <robertce@cse.unsw.edu.au>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
module Data.Array.Accelerate.CUDA.Array.Cache (
-- Tables for host/device memory associations
MemoryTable, new, malloc, withRemote, free, insertUnmanaged, reclaim
) where
import Data.Functor
import Data.IntMap.Strict ( IntMap )
import Data.Proxy
import Data.Typeable ( Typeable )
import Control.Concurrent.MVar ( MVar, newMVar, withMVar, modifyMVar, readMVar )
import Control.Exception ( bracket_ )
import Control.Monad.IO.Class ( MonadIO, liftIO )
import Control.Monad.Trans.Reader
import Foreign.CUDA.Ptr ( DevicePtr )
import Prelude hiding ( lookup )
import qualified Foreign.CUDA.Driver as CUDA
import qualified Data.IntMap.Strict as IM
import Data.Array.Accelerate.Array.Data ( ArrayData )
import Data.Array.Accelerate.Array.Memory ( PrimElt )
import Data.Array.Accelerate.CUDA.Array.Table ( CRM, contextId )
import Data.Array.Accelerate.CUDA.Context ( Context, push, pop )
import Data.Array.Accelerate.CUDA.Execute.Event ( Event, EventTable, waypoint, query )
import Data.Array.Accelerate.CUDA.Execute.Stream ( Stream )
import Data.Array.Accelerate.Error
import qualified Data.Array.Accelerate.CUDA.Debug as D
import qualified Data.Array.Accelerate.Array.Memory.Cache as MC
-- We leverage the memory cache from the accelerate base package. However, we
-- actually need multiple caches. This is because every pointer has an
-- associated CUDA context. We could pair every DevicePtr with its context and
-- just have a single table, but the MemoryCache API in the base package assumes
-- that remote pointers can be re-used, something that would not be true for
-- pointers allocated under different contexts.
--
data MemoryTable = MemoryTable EventTable (MVar (IntMap (MC.MemoryCache DevicePtr (Maybe Event))))
instance MC.Task (Maybe Event) where
isDone Nothing = return True
isDone (Just e) = query e
-- Create a MemoryTable.
--
new :: EventTable -> IO MemoryTable
new et = trace "initialise CUDA memory table" $ MemoryTable et <$> newMVar IM.empty
-- Perform action on the device ptr that matches the given host-side array. Any
-- operations
--
withRemote :: PrimElt e a => Context -> MemoryTable -> ArrayData e -> (DevicePtr a -> IO b) -> Maybe Stream -> IO (Maybe b)
withRemote ctx (MemoryTable et ref) ad run ms = do
ct <- readMVar ref
case IM.lookup (contextId ctx) ct of
Nothing -> $internalError "withRemote" "context not found"
Just mc -> do
streaming ms $ MC.withRemote mc ad run'
where
run' p = do
c <- run p
case ms of
Nothing -> return (Nothing, c)
Just s -> do
e <- waypoint ctx et s
return (Just e, c)
-- Allocate a new device array to be associated with the given host-side array.
-- Has the same properties as `Data.Array.Accelerate.Array.Memory.Cache.malloc`
malloc :: forall a b. (Typeable a, PrimElt a b) => Context -> MemoryTable -> ArrayData a -> Bool -> Int -> IO Bool
malloc !ctx (MemoryTable _ !ref) !ad !frozen !n = do
mt <- modifyMVar ref $ \ct -> blocking $ do
case IM.lookup (contextId ctx) ct of
Nothing -> trace "malloc/context not found" $ insertContext ctx ct
Just mt -> return (ct, mt)
blocking $ MC.malloc mt ad frozen n
-- Explicitly free an array in the MemoryCache. Has the same properties as
-- `Data.Array.Accelerate.Array.Memory.Cache.free`
free :: PrimElt a b => Context -> MemoryTable -> ArrayData a -> IO ()
free !ctx (MemoryTable _ !ref) !arr = withMVar ref $ \ct ->
case IM.lookup (contextId ctx) ct of
Nothing -> message "free/context not found"
Just mt -> MC.free (Proxy :: Proxy CRM) mt arr
-- Record an association between a host-side array and a device memory area that was
-- not allocated by accelerate. The device memory will NOT be freed by the memory
-- manager.
--
insertUnmanaged :: (PrimElt a b) => Context -> MemoryTable -> ArrayData a -> DevicePtr b -> IO ()
insertUnmanaged !ctx (MemoryTable _ !ref) !arr !ptr = do
mt <- modifyMVar ref $ \ct -> blocking $ do
case IM.lookup (contextId ctx) ct of
Nothing -> trace "insertUnmanaged/context not found" $ insertContext ctx ct
Just mt -> return (ct, mt)
blocking $ MC.insertUnmanaged mt arr ptr
insertContext :: Context -> IntMap (MC.MemoryCache DevicePtr (Maybe Event)) -> CRM (IntMap (MC.MemoryCache DevicePtr (Maybe Event)), MC.MemoryCache DevicePtr (Maybe Event))
insertContext ctx ct = do
mt <- MC.new (\p -> bracket_ (push ctx) pop (CUDA.free p))
return (IM.insert (contextId ctx) mt ct, mt)
-- Removing entries
-- ----------------
-- Initiate garbage collection and finalise any arrays that have been marked as
-- unreachable.
--
reclaim :: MemoryTable -> IO ()
reclaim (MemoryTable _ ref) = withMVar ref (blocking . mapM_ MC.reclaim . IM.elems)
-- Miscellaneous
-- -------------
{-# INLINE blocking #-}
blocking :: CRM a -> IO a
blocking = flip runReaderT Nothing
{-# INLINE streaming #-}
streaming :: Maybe Stream -> CRM a -> IO a
streaming = flip runReaderT
-- Debug
-- -----
{-# INLINE trace #-}
trace :: MonadIO m => String -> m a -> m a
trace msg next = message msg >> next
{-# INLINE message #-}
message :: MonadIO m => String -> m ()
message msg = liftIO $ D.traceIO D.dump_gc ("gc: " ++ msg)
| flowbox-public/accelerate-cuda | Data/Array/Accelerate/CUDA/Array/Cache.hs | bsd-3-clause | 6,399 | 0 | 17 | 1,612 | 1,515 | 807 | 708 | 90 | 3 |
{-# LANGUAGE BangPatterns, MagicHash #-}
-- |
-- Module : Data.Text.Internal.Fusion
-- Copyright : (c) Tom Harper 2008-2009,
-- (c) Bryan O'Sullivan 2009-2010,
-- (c) Duncan Coutts 2009
--
-- License : BSD-style
-- Maintainer : bos@serpentine.com
-- Stability : experimental
-- Portability : GHC
--
-- /Warning/: this is an internal module, and does not have a stable
-- API or name. Functions in this module may not check or enforce
-- preconditions expected by public modules. Use at your own risk!
--
-- Text manipulation functions represented as fusible operations over
-- streams.
module Data.Text.Internal.Fusion
(
-- * Types
Stream(..)
, Step(..)
-- * Creation and elimination
, stream
, unstream
, reverseStream
, length
-- * Transformations
, reverse
-- * Construction
-- ** Scans
, reverseScanr
-- ** Accumulating maps
, mapAccumL
-- ** Generation and unfolding
, unfoldrN
-- * Indexing
, index
, findIndex
, countChar
) where
import Prelude (Bool(..), Char, Maybe(..), Monad(..), Int,
Num(..), Ord(..), ($), (&&),
fromIntegral, otherwise)
import Data.Bits ((.&.))
import Data.Text.Internal (Text(..))
import Data.Text.Internal.Private (runText)
import Data.Text.Internal.Unsafe.Char (ord, unsafeChr, unsafeWrite)
import Data.Text.Internal.Unsafe.Shift (shiftL, shiftR)
import qualified Data.Text.Array as A
import qualified Data.Text.Internal.Fusion.Common as S
import Data.Text.Internal.Fusion.Types
import Data.Text.Internal.Fusion.Size
import qualified Data.Text.Internal as I
import qualified Data.Text.Internal.Encoding.Utf16 as U16
default(Int)
-- | /O(n)/ Convert a 'Text' into a 'Stream Char'.
stream :: Text -> Stream Char
stream (Text arr off len) = Stream next off (betweenSize (len `shiftR` 1) len)
where
!end = off+len
next !i
| i >= end = Done
| n >= 0xD800 && n <= 0xDBFF = Yield (U16.chr2 n n2) (i + 2)
| otherwise = Yield (unsafeChr n) (i + 1)
where
n = A.unsafeIndex arr i
n2 = A.unsafeIndex arr (i + 1)
{-# INLINE [0] stream #-}
-- | /O(n)/ Convert a 'Text' into a 'Stream Char', but iterate
-- backwards.
reverseStream :: Text -> Stream Char
reverseStream (Text arr off len) = Stream next (off+len-1) (betweenSize (len `shiftR` 1) len)
where
{-# INLINE next #-}
next !i
| i < off = Done
| n >= 0xDC00 && n <= 0xDFFF = Yield (U16.chr2 n2 n) (i - 2)
| otherwise = Yield (unsafeChr n) (i - 1)
where
n = A.unsafeIndex arr i
n2 = A.unsafeIndex arr (i - 1)
{-# INLINE [0] reverseStream #-}
-- | /O(n)/ Convert a 'Stream Char' into a 'Text'.
unstream :: Stream Char -> Text
unstream (Stream next0 s0 len) = runText $ \done -> do
-- Before encoding each char we perform a buffer realloc check assuming
-- worst case encoding size of two 16-bit units for the char. Just add an
-- extra space to the buffer so that we do not end up reallocating even when
-- all the chars are encoded as single unit.
let mlen = upperBound 4 len + 1
arr0 <- A.new mlen
let outer !arr !maxi = encode
where
-- keep the common case loop as small as possible
encode !si !di =
case next0 si of
Done -> done arr di
Skip si' -> encode si' di
Yield c si'
-- simply check for the worst case
| maxi < di + 1 -> realloc si di
| otherwise -> do
n <- unsafeWrite arr di c
encode si' (di + n)
-- keep uncommon case separate from the common case code
{-# NOINLINE realloc #-}
realloc !si !di = do
let newlen = (maxi + 1) * 2
arr' <- A.new newlen
A.copyM arr' 0 arr 0 di
outer arr' (newlen - 1) si di
outer arr0 (mlen - 1) s0 0
{-# INLINE [0] unstream #-}
{-# RULES "STREAM stream/unstream fusion" forall s. stream (unstream s) = s #-}
-- ----------------------------------------------------------------------------
-- * Basic stream functions
length :: Stream Char -> Int
length = S.lengthI
{-# INLINE[0] length #-}
-- | /O(n)/ Reverse the characters of a string.
reverse :: Stream Char -> Text
reverse (Stream next s len0)
| isEmpty len0 = I.empty
| otherwise = I.text arr off' len'
where
len0' = upperBound 4 (larger len0 4)
(arr, (off', len')) = A.run2 (A.new len0' >>= loop s (len0'-1) len0')
loop !s0 !i !len marr =
case next s0 of
Done -> return (marr, (j, len-j))
where j = i + 1
Skip s1 -> loop s1 i len marr
Yield x s1 | i < least -> {-# SCC "reverse/resize" #-} do
let newLen = len `shiftL` 1
marr' <- A.new newLen
A.copyM marr' (newLen-len) marr 0 len
write s1 (len+i) newLen marr'
| otherwise -> write s1 i len marr
where n = ord x
least | n < 0x10000 = 0
| otherwise = 1
m = n - 0x10000
lo = fromIntegral $ (m `shiftR` 10) + 0xD800
hi = fromIntegral $ (m .&. 0x3FF) + 0xDC00
write t j l mar
| n < 0x10000 = do
A.unsafeWrite mar j (fromIntegral n)
loop t (j-1) l mar
| otherwise = do
A.unsafeWrite mar (j-1) lo
A.unsafeWrite mar j hi
loop t (j-2) l mar
{-# INLINE [0] reverse #-}
-- | /O(n)/ Perform the equivalent of 'scanr' over a list, only with
-- the input and result reversed.
reverseScanr :: (Char -> Char -> Char) -> Char -> Stream Char -> Stream Char
reverseScanr f z0 (Stream next0 s0 len) = Stream next (Scan1 z0 s0) (len+1) -- HINT maybe too low
where
{-# INLINE next #-}
next (Scan1 z s) = Yield z (Scan2 z s)
next (Scan2 z s) = case next0 s of
Yield x s' -> let !x' = f x z
in Yield x' (Scan2 x' s')
Skip s' -> Skip (Scan2 z s')
Done -> Done
{-# INLINE reverseScanr #-}
-- | /O(n)/ Like 'unfoldr', 'unfoldrN' builds a stream from a seed
-- value. However, the length of the result is limited by the
-- first argument to 'unfoldrN'. This function is more efficient than
-- 'unfoldr' when the length of the result is known.
unfoldrN :: Int -> (a -> Maybe (Char,a)) -> a -> Stream Char
unfoldrN n = S.unfoldrNI n
{-# INLINE [0] unfoldrN #-}
-------------------------------------------------------------------------------
-- ** Indexing streams
-- | /O(n)/ stream index (subscript) operator, starting from 0.
index :: Stream Char -> Int -> Char
index = S.indexI
{-# INLINE [0] index #-}
-- | The 'findIndex' function takes a predicate and a stream and
-- returns the index of the first element in the stream
-- satisfying the predicate.
findIndex :: (Char -> Bool) -> Stream Char -> Maybe Int
findIndex = S.findIndexI
{-# INLINE [0] findIndex #-}
-- | /O(n)/ The 'count' function returns the number of times the query
-- element appears in the given stream.
countChar :: Char -> Stream Char -> Int
countChar = S.countCharI
{-# INLINE [0] countChar #-}
-- | /O(n)/ Like a combination of 'map' and 'foldl''. Applies a
-- function to each element of a 'Text', passing an accumulating
-- parameter from left to right, and returns a final 'Text'.
mapAccumL :: (a -> Char -> (a,Char)) -> a -> Stream Char -> (a, Text)
mapAccumL f z0 (Stream next0 s0 len) = (nz, I.text na 0 nl)
where
(na,(nz,nl)) = A.run2 (A.new mlen >>= \arr -> outer arr mlen z0 s0 0)
where mlen = upperBound 4 len
outer arr top = loop
where
loop !z !s !i =
case next0 s of
Done -> return (arr, (z,i))
Skip s' -> loop z s' i
Yield x s'
| j >= top -> {-# SCC "mapAccumL/resize" #-} do
let top' = (top + 1) `shiftL` 1
arr' <- A.new top'
A.copyM arr' 0 arr 0 top
outer arr' top' z s i
| otherwise -> do d <- unsafeWrite arr i c
loop z' s' (i+d)
where (z',c) = f z x
j | ord c < 0x10000 = i
| otherwise = i + 1
{-# INLINE [0] mapAccumL #-}
| bgamari/text | src/Data/Text/Internal/Fusion.hs | bsd-2-clause | 8,823 | 0 | 22 | 3,030 | 2,263 | 1,191 | 1,072 | 152 | 4 |
{-# LANGUAGE CPP, ForeignFunctionInterface, GeneralizedNewtypeDeriving,
OverloadedStrings #-}
-- | Core types and operations for DOM manipulation.
module Haste.DOM.Core (
Elem (..), IsElem (..), Attribute, AttrName (..),
set, with, attribute, children,
click, focus, blur,
document, documentBody,
deleteChild, clearChildren,
setChildren, getChildren,
getLastChild, getFirstChild, getChildBefore,
insertChildBefore, appendChild,
-- Deprecated
removeChild, addChild, addChildBefore
) where
import Haste.Prim
import Control.Monad.IO.Class
import Haste.Foreign
import Data.String
#ifdef __HASTE__
foreign import ccall jsSet :: Elem -> JSString -> JSString -> IO ()
foreign import ccall jsSetAttr :: Elem -> JSString -> JSString -> IO ()
foreign import ccall jsSetStyle :: Elem -> JSString -> JSString -> IO ()
foreign import ccall jsAppendChild :: Elem -> Elem -> IO ()
foreign import ccall jsGetFirstChild :: Elem -> IO (Ptr (Maybe Elem))
foreign import ccall jsGetLastChild :: Elem -> IO (Ptr (Maybe Elem))
foreign import ccall jsGetChildren :: Elem -> IO (Ptr [Elem])
foreign import ccall jsSetChildren :: Elem -> Ptr [Elem] -> IO ()
foreign import ccall jsAddChildBefore :: Elem -> Elem -> Elem -> IO ()
foreign import ccall jsGetChildBefore :: Elem -> IO (Ptr (Maybe Elem))
foreign import ccall jsKillChild :: Elem -> Elem -> IO ()
foreign import ccall jsClearChildren :: Elem -> IO ()
#else
jsSet :: Elem -> JSString -> JSString -> IO ()
jsSet = error "Tried to use jsSet on server side!"
jsSetAttr :: Elem -> JSString -> JSString -> IO ()
jsSetAttr = error "Tried to use jsSetAttr on server side!"
jsSetStyle :: Elem -> JSString -> JSString -> IO ()
jsSetStyle = error "Tried to use jsSetStyle on server side!"
jsAppendChild :: Elem -> Elem -> IO ()
jsAppendChild = error "Tried to use jsAppendChild on server side!"
jsGetFirstChild :: Elem -> IO (Ptr (Maybe Elem))
jsGetFirstChild = error "Tried to use jsGetFirstChild on server side!"
jsGetLastChild :: Elem -> IO (Ptr (Maybe Elem))
jsGetLastChild = error "Tried to use jsGetLastChild on server side!"
jsGetChildren :: Elem -> IO (Ptr [Elem])
jsGetChildren = error "Tried to use jsGetChildren on server side!"
jsSetChildren :: Elem -> Ptr [Elem] -> IO ()
jsSetChildren = error "Tried to use jsSetChildren on server side!"
jsAddChildBefore :: Elem -> Elem -> Elem -> IO ()
jsAddChildBefore = error "Tried to use jsAddChildBefore on server side!"
jsGetChildBefore :: Elem -> IO (Ptr (Maybe Elem))
jsGetChildBefore = error "Tried to use jsGetChildBefore on server side!"
jsKillChild :: Elem -> Elem -> IO ()
jsKillChild = error "Tried to use jsKillChild on server side!"
jsClearChildren :: Elem -> IO ()
jsClearChildren = error "Tried to use jsClearChildren on server side!"
#endif
-- | A DOM node.
newtype Elem = Elem JSAny
deriving (ToAny, FromAny)
-- | The class of types backed by DOM elements.
class IsElem a where
-- | Get the element representing the object.
elemOf :: a -> Elem
-- | Attempt to create an object from an 'Elem'.
fromElem :: Elem -> IO (Maybe a)
fromElem = const $ return Nothing
instance IsElem Elem where
elemOf = id
fromElem = return . Just
-- | The name of an attribute. May be either a common property, an HTML
-- attribute or a style attribute.
data AttrName
= PropName !JSString
| StyleName !JSString
| AttrName !JSString
instance IsString AttrName where
fromString = PropName . fromString
-- | A key/value pair representing the value of an attribute.
-- May represent a property, an HTML attribute, a style attribute or a list
-- of child elements.
data Attribute
= Attribute !AttrName !JSString
| Children ![Elem]
-- | Construct an 'Attribute'.
attribute :: AttrName -> JSString -> Attribute
attribute = Attribute
-- | Set a number of 'Attribute's on an element.
set :: (IsElem e, MonadIO m) => e -> [Attribute] -> m ()
set e as =
liftIO $ mapM_ set' as
where
e' = elemOf e
set' (Attribute (PropName k) v) = jsSet e' k v
set' (Attribute (StyleName k) v) = jsSetStyle e' k v
set' (Attribute (AttrName k) v) = jsSetAttr e' k v
set' (Children cs) = mapM_ (flip jsAppendChild e') cs
-- | Attribute adding a list of child nodes to an element.
children :: [Elem] -> Attribute
children = Children
-- | Set a number of 'Attribute's on the element produced by an IO action.
-- Gives more convenient syntax when creating elements:
--
-- newElem "div" `with` [
-- style "border" =: "1px solid black",
-- ...
-- ]
--
with :: (IsElem e, MonadIO m) => m e -> [Attribute] -> m e
with m attrs = do
x <- m
set x attrs
return x
-- | Generate a click event on an element.
click :: (IsElem e, MonadIO m) => e -> m ()
click = liftIO . click' . elemOf
where
{-# NOINLINE click' #-}
click' :: Elem -> IO ()
click' = ffi "(function(e) {e.click();})"
-- | Generate a focus event on an element.
focus :: (IsElem e, MonadIO m) => e -> m ()
focus = liftIO . focus' . elemOf
where
{-# NOINLINE focus' #-}
focus' :: Elem -> IO ()
focus' = ffi "(function(e) {e.focus();})"
-- | Generate a blur event on an element.
blur :: (IsElem e, MonadIO m) => e -> m ()
blur = liftIO . blur' . elemOf
where
{-# NOINLINE blur' #-}
blur' :: Elem -> IO ()
blur' = ffi "(function(e) {e.blur();})"
-- | The DOM node corresponding to document.
document :: Elem
document = constant "document"
-- | The DOM node corresponding to document.body.
documentBody :: Elem
documentBody = constant "document.body"
-- | Append the first element as a child of the second element.
appendChild :: (IsElem parent, IsElem child, MonadIO m) => parent -> child -> m ()
appendChild parent child = liftIO $ jsAppendChild (elemOf child) (elemOf parent)
{-# DEPRECATED addChild "Use appendChild instead" #-}
-- | DEPRECATED: use 'appendChild' instead!
addChild :: (IsElem parent, IsElem child, MonadIO m) => child -> parent -> m ()
addChild = flip appendChild
-- | Insert an element into a container, before another element.
-- For instance:
-- @
-- insertChildBefore theContainer olderChild childToAdd
-- @
insertChildBefore :: (IsElem parent, IsElem before, IsElem child, MonadIO m)
=> parent -> before -> child -> m ()
insertChildBefore parent oldChild child =
liftIO $ jsAddChildBefore (elemOf child) (elemOf parent) (elemOf oldChild)
{-# DEPRECATED addChildBefore "Use insertChildBefore instead" #-}
-- | DEPRECATED: use 'insertChildBefore' instead!
addChildBefore :: (IsElem parent, IsElem child, MonadIO m)
=> child -> parent -> child -> m ()
addChildBefore child parent oldChild = insertChildBefore parent oldChild child
-- | Get the sibling before the given one, if any.
getChildBefore :: (IsElem e, MonadIO m) => e -> m (Maybe Elem)
getChildBefore e = liftIO $ fromPtr `fmap` jsGetChildBefore (elemOf e)
-- | Get the first of an element's children.
getFirstChild :: (IsElem e, MonadIO m) => e -> m (Maybe Elem)
getFirstChild e = liftIO $ fromPtr `fmap` jsGetFirstChild (elemOf e)
-- | Get the last of an element's children.
getLastChild :: (IsElem e, MonadIO m) => e -> m (Maybe Elem)
getLastChild e = liftIO $ fromPtr `fmap` jsGetLastChild (elemOf e)
-- | Get a list of all children belonging to a certain element.
getChildren :: (IsElem e, MonadIO m) => e -> m [Elem]
getChildren e = liftIO $ fromPtr `fmap` jsGetChildren (elemOf e)
-- | Clear the given element's list of children, and append all given children
-- to it.
setChildren :: (IsElem parent, IsElem child, MonadIO m)
=> parent
-> [child]
-> m ()
setChildren e ch = liftIO $ jsSetChildren (elemOf e) (toPtr $ map elemOf ch)
-- | Remove all children from the given element.
clearChildren :: (IsElem e, MonadIO m) => e -> m ()
clearChildren = liftIO . jsClearChildren . elemOf
-- | Remove the second element from the first's children.
deleteChild :: (IsElem parent, IsElem child, MonadIO m)
=> parent
-> child
-> m ()
deleteChild parent child = liftIO $ jsKillChild (elemOf child) (elemOf parent)
{-# DEPRECATED removeChild "Use deleteChild instead" #-}
-- | DEPRECATED: use 'deleteChild' instead!
removeChild :: (IsElem parent, IsElem child, MonadIO m)
=> child
-> parent
-> m ()
removeChild child parent = liftIO $ jsKillChild (elemOf child) (elemOf parent)
| akru/haste-compiler | libraries/haste-lib/src/Haste/DOM/Core.hs | bsd-3-clause | 8,425 | 0 | 11 | 1,742 | 1,910 | 1,021 | 889 | 145 | 4 |
-- | Parsing all context-free grammars using Earley's algorithm.
module Text.Earley
( -- * Context-free grammars
Prod, satisfy, (<?>), Grammar, rule
, -- * Derived operators
symbol, namedSymbol, word
, -- * Parsing
Report(..), Result(..), parser, allParses, fullParses
-- * Recognition
, report
)
where
import Text.Earley.Grammar
import Text.Earley.Derived
import Text.Earley.Parser
| bitemyapp/Earley | Text/Earley.hs | bsd-3-clause | 411 | 0 | 5 | 79 | 83 | 58 | 25 | 9 | 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="ru-RU">
<title>Active Scan Rules - Beta | 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>Индекс</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>Favorites</label>
<type>javax.help.FavoritesView</type>
</view>
</helpset> | thc202/zap-extensions | addOns/ascanrulesBeta/src/main/javahelp/org/zaproxy/zap/extension/ascanrulesBeta/resources/help_ru_RU/helpset_ru_RU.hs | apache-2.0 | 996 | 78 | 67 | 162 | 440 | 221 | 219 | -1 | -1 |
module Scope2 where
-- import qualified Control.Parallel.Strategies as T
import qualified Control.Parallel.Strategies as S
-- should fail, as there are two possible qualifiers...
f = let (n1, n22_2)
= S.runEval
(do n1' <- S.rpar n11
n22_2 <- S.rpar n22
return (n1', n22_2))
in n1 + n22_2
where
n11 = f
n22 = f
| RefactoringTools/HaRe | old/testing/evalAddEvalMon/Scope2_TokOut.hs | bsd-3-clause | 434 | 0 | 15 | 177 | 98 | 53 | 45 | 10 | 1 |
module Mod5 where
f1 0 l = take 42 l
f1 n l = take n l
f2 0 hi = drop 0 hi
f2 0 l = drop 0 l
f2 n l = drop n l
g = 42 | kmate/HaRe | old/testing/instantiate/Mod5_TokOut.hs | bsd-3-clause | 121 | 0 | 5 | 44 | 84 | 41 | 43 | 7 | 1 |
-- | This is the syntax for bkp files which are parsed in 'ghc --backpack'
-- mode. This syntax is used purely for testing purposes.
module BkpSyn (
-- * Backpack abstract syntax
HsUnitId(..),
LHsUnitId,
HsModuleSubst,
LHsModuleSubst,
HsModuleId(..),
LHsModuleId,
HsComponentId(..),
LHsUnit, HsUnit(..),
LHsUnitDecl, HsUnitDecl(..),
HsDeclType(..),
IncludeDecl(..),
LRenaming, Renaming(..),
) where
import GhcPrelude
import HsSyn
import SrcLoc
import Outputable
import Module
import PackageConfig
{-
************************************************************************
* *
User syntax
* *
************************************************************************
-}
data HsComponentId = HsComponentId {
hsPackageName :: PackageName,
hsComponentId :: ComponentId
}
instance Outputable HsComponentId where
ppr (HsComponentId _pn cid) = ppr cid -- todo debug with pn
data HsUnitId n = HsUnitId (Located n) [LHsModuleSubst n]
type LHsUnitId n = Located (HsUnitId n)
type HsModuleSubst n = (Located ModuleName, LHsModuleId n)
type LHsModuleSubst n = Located (HsModuleSubst n)
data HsModuleId n = HsModuleVar (Located ModuleName)
| HsModuleId (LHsUnitId n) (Located ModuleName)
type LHsModuleId n = Located (HsModuleId n)
-- | Top level @unit@ declaration in a Backpack file.
data HsUnit n = HsUnit {
hsunitName :: Located n,
hsunitBody :: [LHsUnitDecl n]
}
type LHsUnit n = Located (HsUnit n)
-- | A declaration in a package, e.g. a module or signature definition,
-- or an include.
data HsDeclType = ModuleD | SignatureD
data HsUnitDecl n
= DeclD HsDeclType (Located ModuleName) (Maybe (Located (HsModule GhcPs)))
| IncludeD (IncludeDecl n)
type LHsUnitDecl n = Located (HsUnitDecl n)
-- | An include of another unit
data IncludeDecl n = IncludeDecl {
idUnitId :: LHsUnitId n,
idModRenaming :: Maybe [ LRenaming ],
-- | Is this a @dependency signature@ include? If so,
-- we don't compile this include when we instantiate this
-- unit (as there should not be any modules brought into
-- scope.)
idSignatureInclude :: Bool
}
-- | Rename a module from one name to another. The identity renaming
-- means that the module should be brought into scope.
data Renaming = Renaming { renameFrom :: Located ModuleName
, renameTo :: Maybe (Located ModuleName) }
type LRenaming = Located Renaming
| ezyang/ghc | compiler/backpack/BkpSyn.hs | bsd-3-clause | 2,669 | 0 | 12 | 718 | 492 | 295 | 197 | 47 | 0 |
module List1 where
data Expr = Var String Int Int |
Add Expr Expr |
Mul Expr Expr
eval :: [Expr] -> [Int]
eval xs = [x | (Var var_1 x y) <- xs] | kmate/HaRe | old/testing/addField/List1_TokOut.hs | bsd-3-clause | 170 | 0 | 9 | 60 | 75 | 42 | 33 | 6 | 1 |
-- | Module with single foreign export
module MyForeignLib.Hello (sayHi) where
import MyForeignLib.SomeBindings
import MyForeignLib.AnotherVal
foreign export ccall sayHi :: IO ()
-- | Say hi!
sayHi :: IO ()
sayHi = putStrLn $
"Hi from a foreign library! Foo has value " ++ show valueOfFoo
++ " and anotherVal has value " ++ show anotherVal
| mydaum/cabal | cabal-testsuite/PackageTests/ForeignLibs/src/MyForeignLib/Hello.hs | bsd-3-clause | 350 | 0 | 8 | 66 | 75 | 41 | 34 | 8 | 1 |
{-# OPTIONS_GHC -fno-warn-redundant-constraints #-}
module ShouldCompile where
-- I bet this test is a mistake! From the layout it
-- looks as if 'test' takes three args, the latter two
-- of higher rank. But the parens around these args are
-- missing, so it parses as
-- test :: [a]
-- -> forall a. Ord a
-- => [b]
-- -> forall c. Num c
-- => [c]
-- -> [a]
--
-- But maybe that what was intended; I'm not sure
-- Anyway it should typecheck!
test :: [a] -- ^ doc1
-> forall b. (Ord b) => [b] {-^ doc2 -}
-> forall c. (Num c) => [c] -- ^ doc3
-> [a]
test xs ys zs = xs
| ghc-android/ghc | testsuite/tests/haddock/should_compile_noflag_haddock/haddockC027.hs | bsd-3-clause | 652 | 0 | 12 | 205 | 90 | 59 | 31 | -1 | -1 |
{-# LANGUAGE MultiWayIf #-}
module TcMultiWayIfFail where
x1 = if | True -> 1 :: Int
| False -> "2"
| otherwise -> [3 :: Int]
| wxwxwwxxx/ghc | testsuite/tests/typecheck/should_fail/TcMultiWayIfFail.hs | bsd-3-clause | 154 | 0 | 8 | 54 | 46 | 25 | 21 | 5 | 3 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE GADTs #-}
{-|
Module : SodaFunctions
Description : SODA Query Level Functions
Copyright : (c) Steven W
License : MIT
Maintainer : Steven W <StevenW.Info@gmail.com>
Stability : Unstable
The types for adding in SODA query level functions into a clause or other part of a SoQL query.
-}
module SodaFunctions
( SodaFunc (..)
, SodaAgg (..)
, Paren (Paren)
-- * SODA binary operators
-- $ops
, SodaOp
, ($==)
, ($&&)
, ($||)
, ($<)
, ($<=)
, ($>)
, ($>=)
, ($+)
, ($-)
, ($*)
, ($/)
, ($++)
) where
import Data.List
import Datatypes
-- Would some more dependent type features have made this simpler?
-- |The regular SODA, query level functions. Use the constructors of this type to add a function into a SODA query.
--
-- You can find all of the documentation about what they do inside of a SODA query at the <https://dev.socrata.com/docs/functions/ SODA documentation>
--
-- Unfortunately declaring all of the typeclasses is pretty verbose, and some constructors have a lot of parameters, so the type declerations of the constructors can get pretty long. Also, there should be some extra constraints on some of them such as only having geometric types as input, but the typeclasses just haven't been made yet.
data SodaFunc datatype where
Between :: (SodaExpr m, SodaExpr n, SodaExpr o, SodaOrd a) => m a -> n a -> o a -> SodaFunc Checkbox
-- This is unfortunately more constrained than it should be (I think). I'm pretty sure the case results can have different types.
Case :: (SodaType a) => [(Expr Checkbox, Expr a)] -> SodaFunc a
-- I think you can technically have values as the first parameter, but based on the response times in testing, I'm not sure it's intended. Possibly put in SodaAgg.
ConvexHull :: (SodaGeo geo) => Column geo -> SodaFunc MultiPolygon
DateTruncY :: (SodaExpr m) => m Timestamp -> SodaFunc Timestamp
DateTruncYM :: (SodaExpr m) => m Timestamp -> SodaFunc Timestamp
DateTruncYMD :: (SodaExpr m) => m Timestamp -> SodaFunc Timestamp
Distance :: (SodaExpr m, SodaExpr n) => m Point -> n Point -> SodaFunc SodaNum
-- Can't use in where?
Extent :: (SodaExpr m, SodaGeo geo) => m geo -> SodaFunc MultiPolygon
-- Input needs to be constrained. This is going to need to be fixed because the list has to all be the same type which is problematic. Maybe if I made all of the different expressions as one type instead? Or maybe I say that you can't put in columns and make a SodaFunc for values?
In :: (SodaExpr m, SodaType a) => m a -> [Expr a] -> SodaFunc Checkbox
Intersects :: (SodaExpr m, SodaExpr n, SodaGeo a, SodaGeo b) => m a -> n b -> SodaFunc Checkbox
IsNotNull :: (SodaExpr m, SodaType a) => m a -> SodaFunc Checkbox
IsNull :: (SodaExpr m, SodaType a) => m a -> SodaFunc Checkbox
Like :: (SodaExpr m, SodaExpr n) => m SodaText -> n SodaText -> SodaFunc Checkbox
Lower :: (SodaExpr m) => m SodaText -> SodaFunc SodaText
Not :: (SodaExpr m) => m Checkbox -> SodaFunc Checkbox
NotBetween :: (SodaExpr m, SodaExpr n, SodaExpr o, SodaType a) => m a -> n a -> o a -> SodaFunc Checkbox
NotIn :: (SodaExpr m, SodaType a, SodaType b) => m a -> [Expr b] -> SodaFunc Checkbox
NotLike :: (SodaExpr m, SodaExpr n) => m SodaText -> n SodaText -> SodaFunc Checkbox
NumPoints :: (SodaExpr m, SodaGeo geo) => m geo -> SodaFunc SodaNum
Simplify :: (SodaExpr m, SodaExpr n, SodaSimplifyGeo geoAlt) => m geoAlt -> n SodaNum -> SodaFunc geoAlt
SimplifyPreserveTopology :: (SodaExpr m, SodaExpr n, SodaSimplifyGeo geoAlt) => m geoAlt -> n SodaNum -> SodaFunc geoAlt
StartsWith :: (SodaExpr m, SodaExpr n) => m SodaText -> n SodaText -> SodaFunc Checkbox
-- First parameter might be Agg instead of Column
-- Is this really an aggregate or can you actually put any expression in the input?
StdDevPop :: (SodaType num) => Column num -> SodaFunc SodaNum
-- First parameter might be Agg instead of Column
StdDevSamp :: (SodaType num) => Column num -> SodaFunc SodaNum
Upper :: (SodaExpr m) => m SodaText -> SodaFunc SodaText
WithinBox :: (SodaExpr m, SodaExpr n, SodaExpr o, SodaExpr p, SodaExpr q, SodaGeo geo) => m geo -> n SodaNum -> o SodaNum -> p SodaNum -> q SodaNum -> SodaFunc Checkbox
WithinCircle :: (SodaExpr m, SodaExpr n, SodaExpr o, SodaExpr p, SodaGeo geo) => m geo -> n SodaNum -> o SodaNum -> p SodaNum -> SodaFunc Checkbox
WithinPolygon :: (SodaExpr m, SodaExpr n, SodaGeo geo) => m geo -> n MultiPolygon -> SodaFunc Checkbox
-- This needs to be fixed for certain types. It's not always the same as putting the toUrlParam of their parts in the right place.
instance SodaExpr SodaFunc where
toUrlParam (Between val first last) = (toUrlParam val) ++ " between " ++ (toUrlParam first) ++ " and " ++ (toUrlParam last)
toUrlParam (Case paths) = "case(" ++ (intercalate ", " (map (\(cond, result) -> (exprUrlParam cond) ++ ", " ++ (exprUrlParam result)) paths)) ++ ")"
toUrlParam (ConvexHull shape) = "convex_hull(" ++ toUrlParam shape ++ ")"
toUrlParam (DateTruncY time) = "date_trunc_y(" ++ (toUrlParam time) ++ ")"
toUrlParam (DateTruncYM time) = "date_trunc_ym(" ++ (toUrlParam time) ++ ")"
toUrlParam (DateTruncYMD time) = "date_trunc_ymd(" ++ (toUrlParam time) ++ ")"
toUrlParam (Distance pointA pointB) = "distance_in_meters(" ++ (toUrlParam pointA) ++ ", " ++ (toUrlParam pointB) ++ ")"
toUrlParam (Extent points) = "extent(" ++ (toUrlParam points) ++ ")"
toUrlParam (In element values) = (toUrlParam element) ++ " IN(" ++ (intercalate ", " (map exprUrlParam values)) ++ ")"
toUrlParam (Intersects shapeA shapeB) = "intersects(" ++ (toUrlParam shapeA) ++ ", " ++ (toUrlParam shapeB) ++ ")"
toUrlParam (IsNotNull a) = toUrlParam a ++ " IS NOT NULL"
toUrlParam (IsNull a) = toUrlParam a ++ " IS NULL"
toUrlParam (Like textA textB) = (toUrlParam textA) ++ " like " ++ (toUrlParam textB)
toUrlParam (Lower text) = "lower(" ++ (toUrlParam text) ++ ")"
toUrlParam (Not a) = "NOT " ++ toUrlParam a
toUrlParam (NotBetween val first last) = (toUrlParam val) ++ " not between " ++ (toUrlParam first) ++ " and " ++ (toUrlParam last)
toUrlParam (NotIn element values) = (toUrlParam element) ++ " not in(" ++ (intercalate ", " (map exprUrlParam values)) ++ ")"
toUrlParam (NotLike textA textB) = (toUrlParam textA) ++ " not like " ++ (toUrlParam textB)
toUrlParam (NumPoints points) = "num_points(" ++ (toUrlParam points) ++ ")"
toUrlParam (Simplify geometry tolerance) = "simplify(" ++ (toUrlParam geometry) ++ ", " ++ (toUrlParam tolerance) ++ ")"
toUrlParam (SimplifyPreserveTopology geometry tolerance) = "simplify_preserve_topology(" ++ (toUrlParam geometry) ++ ", " ++ (toUrlParam tolerance) ++ ")"
toUrlParam (StartsWith haystack needle) = "starts_with(" ++ (toUrlParam haystack) ++ ", " ++ (toUrlParam needle) ++ ")"
toUrlParam (StdDevPop nums) = "stddev_pop(" ++ (toUrlParam nums) ++ ")"
toUrlParam (StdDevSamp nums) = "stddev_samp(" ++ (toUrlParam nums) ++ ")"
toUrlParam (Upper text) = "upper(" ++ (toUrlParam text) ++ ")"
toUrlParam (WithinBox shape nwLat nwLong seLat seLong) = "within_box(" ++ (toUrlParam shape) ++ ", " ++ (toUrlParam nwLat) ++ ", " ++ (toUrlParam nwLong) ++ ", " ++ (toUrlParam seLat) ++ ", " ++ (toUrlParam seLong) ++ ")"
toUrlParam (WithinCircle point centerLat centerLong radius) = "within_circle(" ++ (toUrlParam point) ++ ", " ++ (toUrlParam centerLat) ++ ", " ++ (toUrlParam centerLong) ++ ", " ++ (toUrlParam radius) ++ ")"
toUrlParam (WithinPolygon point multipolygon) = "within_polygon(" ++ (toUrlParam point) ++ ", " ++ (toUrlParam multipolygon) ++ ")"
lower sodafunc = Left BadLower
-- |The SODA, query level functions which are aggregates. Seperating them out doesn't actually have any function, but it's good to know which ones are aggregates. It would be nice if there was some way to have $where clauses be able to assert at the type level that they don't have any aggregates, but I can't think of any way to do it.
data SodaAgg datatype where
Avg :: SodaNumeric a => Column a -> SodaAgg a
Count :: SodaType a => Column a -> SodaAgg SodaNum
Max :: SodaOrd a => Column a -> SodaAgg a
Min :: SodaOrd a => Column a -> SodaAgg a
Sum :: SodaNumeric a => Column a -> SodaAgg a -- I've put in an issue to see if this works with SodaOrd like the SODA documentation says it does, or whether it's actually SodaNumeric which it seems to do in actual queries.
instance SodaExpr SodaAgg where
toUrlParam (Avg col) = "avg(" ++ (toUrlParam col) ++ ")"
toUrlParam (Count rows) = "count(" ++ (toUrlParam rows) ++ ")"
toUrlParam (Max numbers) = "max(" ++ (toUrlParam numbers) ++ ")"
toUrlParam (Min numbers) = "min(" ++ (toUrlParam numbers) ++ ")"
toUrlParam (Sum nums) = "sum(" ++ (toUrlParam nums) ++ ")"
lower sodaagg = Left BadLower
-- |Sometimes you need to add parenthesis in a SODA query to assure the correct order of operations. This type allows that.
data Paren datatype where
Paren :: (SodaExpr m, SodaType a) => m a -> Paren a
instance SodaExpr Paren where
toUrlParam (Paren a) = "(" ++ toUrlParam a ++ ")"
lower a = Left BadLower
---
-- SODA Operators
-- $ops
--
-- The SODA operators (I forgot what I was going to put here).
-- Equals should actually have the same types on both sides except numeric types.
-- Need to figure out what to do about type ambiguities when there are different types.
-- |The operators provided by SODA. The constructors are hidden and the corresponding infix operators are used instead in order to look more like natural SoQL. This could be included with the SodaFunc type, but that would be a lot of constructors so it's broken out to make smaller and, hopefully, simpler types.
-- Just a side note, but it seems that you can make an equality comparison with numeric types and text that only has numeric characters. This library doesn't support that, and I don't see it supporting this functionality in the future because it makes equality not transitive "at the type level". I'm not sure that, that's the best way to describe it. However, I mean that comparing a text column "name" against '40000' is fine and a number field "salary" against '40000' is also fine, but the SODA level type checker rejects comparing "name" against "salary".
data SodaOp datatype where
Equals :: (SodaExpr m, SodaExpr n, SodaType a, SodaType b) => m a -> n b -> SodaOp Checkbox -- Don't export
NotEquals :: (SodaExpr m, SodaExpr n, SodaType a, SodaType b) => m a -> n b -> SodaOp Checkbox -- Don't export
And :: (SodaExpr m, SodaExpr n) => m Checkbox -> n Checkbox -> SodaOp Checkbox -- Don't export
Or :: (SodaExpr m, SodaExpr n) => m Checkbox -> n Checkbox -> SodaOp Checkbox -- Don't export
Less :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b-> SodaOp Checkbox
LessOrEquals :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b-> SodaOp Checkbox
Greater :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b-> SodaOp Checkbox
GreaterOrEquals :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b-> SodaOp Checkbox
Add :: (SodaExpr m, SodaExpr n, SodaNumeric numA, SodaNumeric numB) => m numA -> n numB -> SodaOp numB
-- Might have to add another similar operator with different characters for final type going the other way.
Subtract :: (SodaExpr m, SodaExpr n, SodaNumeric numA, SodaNumeric numB) => m numA -> n numB -> SodaOp numB
Multiply :: (SodaExpr m, SodaExpr n, SodaNumeric numA, SodaNumeric numB, SodaNumeric numC) => m numA -> n numB -> SodaOp numC
Divide :: (SodaExpr m, SodaExpr n, SodaNumeric numA, SodaNumeric numB, SodaNumeric numC) => m numA -> n numB -> SodaOp numC
Concatenate :: (SodaExpr m, SodaExpr n) => m SodaText -> n SodaText -> SodaOp SodaText
instance SodaExpr SodaOp where
toUrlParam (Equals a b) = toUrlParam a ++ " = " ++ toUrlParam b
toUrlParam (NotEquals a b) = toUrlParam a ++ " != " ++ toUrlParam b
toUrlParam (And a b) = toUrlParam a ++ " AND " ++ toUrlParam b
toUrlParam (Or a b) = toUrlParam a ++ " OR " ++ toUrlParam b
toUrlParam (Less a b) = toUrlParam a ++ " < " ++ toUrlParam b
toUrlParam (LessOrEquals a b) = toUrlParam a ++ " <= " ++ toUrlParam b
toUrlParam (Greater a b) = toUrlParam a ++ " > " ++ toUrlParam b
toUrlParam (GreaterOrEquals a b) = toUrlParam a ++ " >= " ++ toUrlParam b
toUrlParam (Add a b) = toUrlParam a ++ " + " ++ toUrlParam b
toUrlParam (Subtract a b) = toUrlParam a ++ " - " ++ toUrlParam b
toUrlParam (Multiply a b) = toUrlParam a ++ " * " ++ toUrlParam b
toUrlParam (Divide a b) = toUrlParam a ++ " / " ++ toUrlParam b
toUrlParam (Concatenate a b) = toUrlParam a ++ " || " ++ toUrlParam b
lower a = Left BadLower
-- Possibly have two equals signs for this and one for filters?
-- |The equals comparison operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>. The infix operator $= was already in use for simple filters so I used the double equals notation that many other languages use for the equality comparison. Currently it's a bit restrictive because you should be able to compare different numeric types together, which this doesn't allow. I'll come up with some sort of solution in the future.
infixr 4 $==
($==) :: (SodaExpr m, SodaExpr n, SodaType a) => m a -> n a -> SodaOp Checkbox
($==) = Equals
-- |The not equals comparison operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>. It's type is a bit restrictive like $==
infixr 4 $!=
($!=) :: (SodaExpr m, SodaExpr n, SodaType a) => m a -> n a -> SodaOp Checkbox
($!=) = Equals
-- |The \"AND\" boolean operator as mentioned in the <https://dev.socrata.com/docs/queries/where.html SODA documentation>. Since you can't use letters in Haskell operators I chose && as the operator since it's similar to the \"AND\" operator used in many other languages.
infixr 3 $&&
($&&) :: (SodaExpr m, SodaExpr n) => m Checkbox -> n Checkbox -> SodaOp Checkbox
($&&) = And
-- |The \"OR\" boolean operator as mentioned in the <https://dev.socrata.com/docs/queries/where.html SODA documentation>. Since you can't use letters in Haskell operators I chose || as the operator since it's similar to the \"OR\" operator used in many other languages.
infixr 2 $||
($||) :: (SodaExpr m, SodaExpr n) => m Checkbox -> n Checkbox -> SodaOp Checkbox
($||) = Or
-- |The less than comparison operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixr 4 $<
($<) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b -> SodaOp Checkbox
($<) = Less
-- |The less than or equals comparison operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixr 4 $<=
($<=) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b -> SodaOp Checkbox
($<=) = LessOrEquals
-- |The greater than comparison operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixr 4 $>
($>) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b -> SodaOp Checkbox
($>) = Greater
-- |The greater than or equals comparison operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixr 4 $>=
($>=) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b -> SodaOp Checkbox
($>=) = GreaterOrEquals
-- |The addition operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixl 6 $+
($+) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b -> SodaOp b
($+) = Add
-- |The subtraction operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixl 6 $-
($-) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b) => m a -> n b -> SodaOp b
($-) = Subtract
-- |The multiplication operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixl 7 $*
($*) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b, SodaNumeric c) => m a -> n b -> SodaOp c
($*) = Multiply
-- |The division operator as mentioned in the <https://dev.socrata.com/docs/datatypes/number.html SODA documentation>.
infixl 7 $/
($/) :: (SodaExpr m, SodaExpr n, SodaNumeric a, SodaNumeric b, SodaNumeric c) => m a -> n b -> SodaOp c
($/) = Divide
-- |The concatenation operator as mentioned in the <https://dev.socrata.com/docs/datatypes/text.html SODA documentation>. The \"||\" operator used in the actual SODA queries, I used for the OR operator, so I decided to make it similar to the Haskell concatenation operator.
infixr 5 $++
($++) :: (SodaExpr m, SodaExpr n) => m SodaText -> n SodaText -> SodaOp SodaText
($++) = Concatenate
| StevenWInfo/haskell-soda | src/SodaFunctions.hs | mit | 18,516 | 0 | 17 | 4,759 | 4,502 | 2,304 | 2,198 | 169 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
module Crypto.Hash.SHA256
(
SHA256
, SHA224
) where
import qualified Data.ByteString as B
import qualified Data.ByteString.Lazy as LBS
import qualified Data.ByteString.Lazy.Char8 as LC
import Data.ByteString (ByteString)
import Data.ByteString.Builder
import Control.Monad.ST
import Data.Int
import Data.Word
import Data.Bits
import Data.Monoid
import Data.Array.Unboxed
import Data.Array.Unsafe
import Data.Array.ST
import Data.List(foldl')
import Crypto.Hash.ADT
initHs :: [Word32]
initHs = [
0x6a09e667 , 0xbb67ae85 , 0x3c6ef372 , 0xa54ff53a
, 0x510e527f , 0x9b05688c , 0x1f83d9ab , 0x5be0cd19 ]
initKs :: [Word32]
initKs = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 ]
encodeInt64Helper :: Int64 -> [Word8]
encodeInt64Helper x_ = [w7, w6, w5, w4, w3, w2, w1, w0]
where x = x_ * 8
w7 = fromIntegral $ (x `shiftR` 56) .&. 0xff
w6 = fromIntegral $ (x `shiftR` 48) .&. 0xff
w5 = fromIntegral $ (x `shiftR` 40) .&. 0xff
w4 = fromIntegral $ (x `shiftR` 32) .&. 0xff
w3 = fromIntegral $ (x `shiftR` 24) .&. 0xff
w2 = fromIntegral $ (x `shiftR` 16) .&. 0xff
w1 = fromIntegral $ (x `shiftR` 8) .&. 0xff
w0 = fromIntegral $ (x `shiftR` 0) .&. 0xff
encodeInt64 :: Int64 -> ByteString
encodeInt64 = B.pack . encodeInt64Helper
sha256BlockSize = 64
lastChunk :: Int64 -> ByteString -> [ByteString]
lastChunk msglen s
| len < 56 = [s <> B.cons 0x80 (B.replicate (55 - len) 0x0) <> encodedLen]
| len < 120 = helper (s <> B.cons 0x80 (B.replicate (119 - len) 0x0) <> encodedLen)
where
len = B.length s
encodedLen = encodeInt64 msglen
helper bs = [s1, s2]
where (s1, s2) = B.splitAt 64 bs
data SHA256 = SHA256 {-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
deriving Eq
data SHA224 = SHA224 {-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
{-# UNPACK #-} !Word32
initHash :: SHA256
initHash = fromList initHs
where fromList (a:b:c:d:e:f:g:h:_) = SHA256 a b c d e f g h
initHash224 :: SHA256
initHash224 = fromList [0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4]
where fromList (a:b:c:d:e:f:g:h:_) = SHA256 a b c d e f g h
instance Show SHA256 where
show = LC.unpack . toLazyByteString . foldMap word32HexFixed . toList
where toList (SHA256 a b c d e f g h) = a:b:c:d:e:f:g:[h]
instance Show SHA224 where
show = LC.unpack . toLazyByteString . foldMap word32HexFixed . toList
where toList (SHA224 a b c d e f g h) = a:b:c:d:e:f:[g]
instance Eq SHA224 where
(SHA224 a1 b1 c1 d1 e1 f1 g1 _) == (SHA224 a2 b2 c2 d2 e2 f2 g2 _) =
a1 == a2 && b1 == b2 && c1 == c2 && d1 == d2
&& e1 == e2 && f1 == f2 && g1 == g2
{-# INLINABLE sha256BlockUpdate #-}
sha256BlockUpdate :: SHA256 -> Word32 -> SHA256
sha256BlockUpdate (SHA256 a b c d e f g h) w =
let
!s1 = (e `rotateR` 6) `xor` (e `rotateR` 11) `xor` (e `rotateR` 25)
!ch = (e .&. f) `xor` (complement e .&. g)
!temp1 = h + s1 + ch + w
!s0 = (a `rotateR` 2) `xor` (a `rotateR` 13) `xor` (a `rotateR` 22)
!maj = (a .&. b) `xor` (a .&. c) `xor` (b .&. c)
!temp2 = s0 + maj
in SHA256 (temp1 + temp2) a b c (d + temp1) e f g
{-# INLINE readW64 #-}
readW64 :: ByteString -> Word64
readW64 = B.foldl' acc 0 . B.take 8
where acc x c = x `shiftL` 8 + fromIntegral c
acc :: Word64 -> Word8 -> Word64
{-# INLINE acc #-}
prepareBlock :: ByteString -> UArray Int Word32
prepareBlock s = runST $ do
iou <- newArray (0, 63) 0 :: ST s (STUArray s Int Word32)
let
!w1 = readW64 s
!w2 = readW64 (B.drop 8 s)
!w3 = readW64 (B.drop 16 s)
!w4 = readW64 (B.drop 24 s)
!w5 = readW64 (B.drop 32 s)
!w6 = readW64 (B.drop 40 s)
!w7 = readW64 (B.drop 48 s)
!w8 = readW64 (B.drop 56 s)
write2 k x = writeArray iou (2*k) (fromIntegral (x `shiftR` 32)) >>
writeArray iou (1+2*k) (fromIntegral (x .&. 0xffffffff))
{-# INLINE write2 #-}
write2 0 w1
write2 1 w2
write2 2 w3
write2 3 w4
write2 4 w5
write2 5 w6
write2 6 w7
write2 7 w8
let go i = readArray iou (i-16) >>= \x1 ->
readArray iou (i-15) >>= \x2 ->
readArray iou (i- 7) >>= \x3 ->
readArray iou (i- 2) >>= \x4 ->
let !s0 = (x2 `rotateR` 7) `xor` (x2 `rotateR` 18) `xor` (x2 `shiftR` 3)
!s1 = (x4 `rotateR` 17) `xor` (x4 `rotateR` 19) `xor` (x4 `shiftR` 10)
in writeArray iou i (x1 + s0 + x3 + s1)
{-# INLINE go #-}
mapM_ go [16..63]
unsafeFreeze iou
{-# INLINE encodeChunk #-}
encodeChunk :: SHA256 -> ByteString -> SHA256
encodeChunk hv@(SHA256 a b c d e f g h) bs = SHA256 (a+a') (b+b') (c+c') (d+d') (e+e') (f+f') (g+g') (h+h')
where
SHA256 a' b' c' d' e' f' g' h' = foldl' sha256BlockUpdate hv (zipWith (+) (elems (prepareBlock bs)) initKs)
{-# NOINLINE sha256Hash #-}
sha256Hash :: LBS.ByteString -> SHA256
sha256Hash = sha256Final . LBS.foldlChunks sha256Update sha256Init
sha256Init :: Context SHA256
sha256Init = Context 0 0 B.empty initHash
{-# NOINLINE sha256Update #-}
sha256Update :: Context SHA256 -> ByteString -> Context SHA256
sha256Update ctx@(Context n k w hv) s
| B.null s = ctx
| sizeRead < sizeToRead = Context (n + fromIntegral sizeRead) (k + sizeRead) (w <> s1) hv
| sizeRead >= sizeToRead = sha256Update (Context (n + fromIntegral sizeToRead) 0 mempty (encodeChunk hv (w <> s1))) s'
where
!sizeToRead = sha256BlockSize - k
(!s1, !s') = B.splitAt sizeToRead s
!sizeRead = B.length s1
{-# NOINLINE sha256Final #-}
sha256Final :: Context SHA256 -> SHA256
sha256Final (Context n _ w hv) = foldl' encodeChunk hv (lastChunk n w)
fromSHA224 :: SHA224 -> SHA256
fromSHA256 :: SHA256 -> SHA224
fromSHA224 (SHA224 a b c d e f g h) = SHA256 a b c d e f g h
fromSHA256 (SHA256 a b c d e f g h) = SHA224 a b c d e f g h
sha224Init :: Context SHA224
sha224Init = fmap fromSHA256 (Context 0 0 B.empty initHash224)
sha224Update :: Context SHA224 -> ByteString -> Context SHA224
sha224Update = fmap (fmap fromSHA256) . sha256Update . fmap fromSHA224
sha224Final :: Context SHA224 -> SHA224
sha224Final = fromSHA256 . sha256Final . fmap fromSHA224
--{-# NOINLINE sha224Hash #-}
sha224Hash :: LBS.ByteString -> SHA224
sha224Hash = sha224Final . LBS.foldlChunks sha224Update sha224Init
instance HashAlgorithm SHA256 where
hashBlockSize = const 64
hashDigestSize = const 32
hashInit = sha256Init
hashUpdate = sha256Update
hashFinal = sha256Final
instance HashAlgorithm SHA224 where
hashBlockSize = const 64
hashDigestSize = const 28
hashInit = sha224Init
hashUpdate = sha224Update
hashFinal = sha224Final
| wangbj/hashing | src/Crypto/Hash/SHA256.hs | mit | 8,091 | 0 | 26 | 2,059 | 3,070 | 1,646 | 1,424 | 184 | 1 |
{-# LANGUAGE EmptyDataDecls, DeriveGeneric, OverloadedStrings, ScopedTypeVariables #-}
{-|
Module : Main
Description : The @minimalistic@ HAAP example
This module presents a minimalistic example of the usage of HAAP, consisting on testing an @HSpec@
specification, running several code analysis plugins, providing global feedback with the @ranking@ and
@tournament@ plugins, visualization of solutions with @CodeWorld@, all connected by a webpage
generated by @Hakyll@.
-}
module Main where
import HAAP
import Data.Default
import Data.Binary
import Data.Char
import Data.Monoid hiding ((<>))
import qualified Data.Map as Map
import Data.Unique
import Control.DeepSeq
import Control.Monad.IO.Class
import System.Random.Shuffle
import System.Process
import GHC.Generics (Generic(..))
example :: Project
example = Project
{ projectName = "example"
, projectPath = "."
, projectTmpPath = "tmp"
, projectGroups = []
, projectTasks = []
}
emptyExample_DB = Example_DB (HaapTourneyDB 1 [])
data Example_DB = Example_DB
{ exTourneyDB :: HaapTourneyDB ExPlayer }
deriving (Generic)
instance Binary Example_DB
lnsTourney :: DBLens (BinaryDB Example_DB) (HaapTourneyDB ExPlayer)
lnsTourney = DBLens
(BinaryDBQuery exTourneyDB)
(\st -> BinaryDBUpdate $ \db -> ((),db { exTourneyDB = st }) )
{-|
An HAAP script that runs tests with the @HSpec@ plugin, runs several code analysis plugins, generates
feedback with the @ranking@ and @tournament@ plugins, provides visualization with the @CodeWorld@ plugin
and uses the @Hakyll@ plugin to generate a webpage that connects all artifacts.
-}
main = do
let hakyllArgs = HakyllArgs defaultConfiguration True True True def
let dbArgs = BinaryDBArgs "db" emptyExample_DB def
-- load the @Hakyll@ and database @DB@ plugins
runHaap example $ useHakyll hakyllArgs $ useBinaryDB dbArgs $ do
useRank $ useTourney $ renderHaapTourney exTourney
data ExPlayer = ExPlayer (String,Bool)
deriving (Eq,Ord,Show,Generic)
instance Binary ExPlayer
instance NFData ExPlayer
instance Pretty ExPlayer where
pretty (ExPlayer x) = string (fst x)
instance TourneyPlayer ExPlayer where
isDefaultPlayer (ExPlayer (_,b)) = b
defaultPlayer = do
i <- newUnique
return $ ExPlayer ("random" ++ show (hashUnique i),True)
exTourney :: MonadIO m => HaapTourney t m (BinaryDB Example_DB) ExPlayer Link
exTourney = HaapTourney
{ tourneyMax = 10
, tourneyTitle = "Tourney"
, tourneyNotes = ""
, tourneyRounds = mkRounds
, tourneyPlayerTag = "Group"
, tourneyPlayers = grupos
, tourneyPath = "torneio"
, lensTourneyDB = lnsTourney
, tourneyMatch = match
, renderMatch = return
, deleteTourney = const $ return ()
}
where
grupos = Left $ map (ExPlayer . mapFst show) $ zip [1..] (replicate 4 False ++ replicate 10 True)
match tno rno mno players = do
return (zip players [1..],"link")
--mkRounds sz = [TourneyRound 16 4 1 1,TourneyRound 4 4 1 1,TourneyRound 1 1 1 1]
mkRounds _ = [TourneyRound 128 4 2 1,TourneyRound 64 4 1 1,TourneyRound 16 4 1 1,TourneyRound 4 4 1 1,TourneyRound 1 1 1 1]
| hpacheco/HAAP | examples/tourney/tourney.hs | mit | 3,203 | 0 | 14 | 657 | 750 | 408 | 342 | 63 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE OverloadedStrings #-}
module Text.Greek.Source.Perseus.TEI where
--import Text.Greek.Parse.Utility
import Text.Greek.Xml.Parse
--import Text.Parsec.Char
--import Text.Parsec.Combinator
import qualified Data.Text as Text
import qualified Data.XML.Types as Xml
teiNamespace :: Text.Text
teiNamespace = "http://www.tei-c.org/ns/1.0"
tei :: Text.Text -> Xml.Name
tei t = Xml.Name t (Just teiNamespace) Nothing
data Document = Document
{ documentHeader :: TeiHeader
, documentText :: Text
} deriving Show
documentParser :: EventParser Document
documentParser = elementA (tei "TEI") $ \_ -> Document
<$> teiHeaderParser
<*> textParser
data TeiHeader = TeiHeader
{
} deriving Show
teiHeaderParser :: EventParser TeiHeader
teiHeaderParser = do
_ <- elementOpen (tei "teiHeader")
return TeiHeader
data Text = Text
{
} deriving Show
textParser :: EventParser Text
textParser = do
_ <- elementOpen (tei "text")
return Text
| scott-fleischman/greek-grammar | haskell/greek-grammar/src/Text/Greek/Source/Perseus/TEI.hs | mit | 1,023 | 2 | 10 | 164 | 246 | 139 | 107 | 31 | 1 |
module Tests.Application where
import Test.Tasty
import MoneyStacks.Application as App
import GHC.IO.Handle
import System.IO
import System.Directory
import System.Environment (withArgs)
-- |return as String what is printed to StdOut
catchOutput :: IO () -> IO String
catchOutput f = do
tmpd <- getTemporaryDirectory
(tmpf, tmph) <- openTempFile tmpd "haskell_stdout"
stdout_dup <- hDuplicate stdout
hDuplicateTo tmph stdout
hClose tmph
f
hDuplicateTo stdout_dup stdout
str <- readFile tmpf
removeFile tmpf
return str
-- |Run an application with given argument string and return the stdout output as string
runWithArgs :: String -> IO () -> IO String
runWithArgs argstr f = catchOutput $ withArgs (words argstr) f
applicationTests = testGroup "MoneyStacks.Application" [appTests]
-- TODO
appTests = testGroup "Application tests (checking CLI output)" []
| apirogov/MoneyStacks | tests/Tests/Application.hs | mit | 880 | 0 | 8 | 145 | 225 | 111 | 114 | 23 | 1 |
-- | The module that contains all of the type definitions in the library.
-- They're contained in one place so that recursive module imports may be
-- avoided when only because of type definitions.
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
module WhatIsThisGame.Data where
--------------------
-- Global Imports --
import Graphics.Rendering.OpenGL hiding ( Shader
, Color
)
import qualified Data.Map.Strict as Map
import Graphics.UI.GLFW as GLFW
import Graphics.Rendering.FTGL
import Data.Vinyl.Universe
import Graphics.GLUtil
import Linear.Matrix
import Control.Lens
import Data.Monoid
import Data.Vinyl
import Linear.V4
import Linear.V2
----------
-- Code --
-- | The data structure for window configuration.
data WindowConfig = WindowConfig { _cfgWidth :: Int
, _cfgHeight :: Int
, _cfgFullscreen :: Bool
, _cfgJumpKey :: Key
, _cfgShootKey :: Key
, _cfgSlowKey :: Key
, _cfgFastKey :: Key
}
-- | Showing the @'WindowConfig'@ as a @'String'@.
instance Show WindowConfig where
show wc = mconcat [ "width=", show $ _cfgWidth wc, "\n"
, "height=", show $ _cfgHeight wc, "\n"
, "fullscreen=", show $ _cfgFullscreen wc, "\n"
, "jumpkey=", show $ fromEnum $ _cfgJumpKey wc, "\n"
, "shootkey=", show $ fromEnum $ _cfgShootKey wc, "\n"
, "slowkey=", show $ fromEnum $ _cfgSlowKey wc, "\n"
, "fastkey=", show $ fromEnum $ _cfgFastKey wc, "\n"
]
$(makeLenses ''WindowConfig)
-- | The default @'WindowConfig'@.
defaultWindowConfig :: WindowConfig
defaultWindowConfig = WindowConfig { _cfgWidth = 640
, _cfgHeight = 480
, _cfgFullscreen = False
, _cfgJumpKey = CharKey ' '
, _cfgShootKey = CharKey 'E'
, _cfgSlowKey = CharKey 'A'
, _cfgFastKey = CharKey 'D'
}
-- | The matrix of the camera.
type CamMatrix = PlainFieldRec '["cam" ::: M33 GLfloat]
-- | A vertex coordinate to pass to GLSL.
type VertexCoord = "vertexCoord" ::: V2 GLfloat
-- | A texture coordinate to pass to GLSL.
type TextureCoord = "textureCoord" ::: V2 GLfloat
-- | A color to pass to GLSL.
type GLSLColor = "color" ::: V4 GLfloat
-- | An instance of the @'VertexCoord'@.
vertexCoord :: SField VertexCoord
vertexCoord = SField
-- | An instance of the @'TextureCoord'@.
textureCoord :: SField TextureCoord
textureCoord = SField
-- | An instance for the @'GLSLColor'@.
glslColor :: SField GLSLColor
glslColor = SField
-- | A synonym for a color represented by 4 @'Float'@s.
newtype Color = Color (V4 Float)
-- | An instance of the @'Color'@ datatype.
white, black, red, green, blue :: Color
white = Color $ V4 1 1 1 1
black = Color $ V4 0 0 0 1
red = Color $ V4 1 0 0 1
green = Color $ V4 0 1 0 1
blue = Color $ V4 0 0 1 1
-- | A type to be used when calculating collision.
data CollisionRectangle = CollisionRectangle { _crPos :: V2 Float
, _crSize :: V2 Float
}
-- | This instance defines that a type can be converted to a
-- @'CollisionRectangle'@, and can therefore be used to calculate collision.
class Collidable a where
toCollisionRectangle :: a -> CollisionRectangle
-- | A data structure to represent a sprite.
newtype Sprite = Sprite TextureObject
-- | A data structure to represent an animation. In other words, a list of
-- @'Sprite'@s.
newtype Animation = Animation [String]
-- | A data structure to represent a shader.
newtype Shader = Shader ShaderProgram
-- | An abstract representation of a request to load an asset.
data AssetLoad = SpriteLoad FilePath
| ShaderLoad FilePath
| FontLoad FilePath
| AssetLoads [AssetLoad]
-- | Allowing @'AssetLoad'@s to be joined together into one nebulous
-- @'AssetLoad'@ containing all of the loads.
instance Monoid AssetLoad where
mempty = AssetLoads []
mappend (AssetLoads l1) (AssetLoads l2) = AssetLoads $ l1 ++ l2
mappend (AssetLoads l1) assetLoad = AssetLoads $ assetLoad : l1
mappend assetLoad (AssetLoads l1) = AssetLoads $ assetLoad : l1
mappend assetLoad1 assetLoad2 = AssetLoads [assetLoad1, assetLoad2]
-- | An API for accessing assets.
data Assets = Assets { getSprites :: Map.Map FilePath Sprite
, getShaders :: Map.Map FilePath Shader
, getFonts :: Map.Map FilePath Font
}
-- | Allowing different @'Assets'@ to be joined. Primarily for easier loading
-- of assets.
instance Monoid Assets where
mempty = Assets { getSprites = mempty
, getShaders = mempty
, getFonts = mempty
}
mappend a1 a2 =
Assets { getSprites = getSprites a1 `mappend` getSprites a2
, getShaders = getShaders a1 `mappend` getShaders a2
, getFonts = getFonts a1 `mappend` getFonts a2
}
-- | A datatype representing a @'Sprite'@ render.
data SpriteRender = SpriteRender Sprite (V2 Float) (V2 Float)
-- | A datatype representing multiple @'Sprite'@ renders - grouped by if they
-- share the same @'Sprite'@.
newtype SpriteBatch = SpriteBatch [SpriteRender]
-- | A datatype representing a @'Font'@ render.
data TextRender = TextRender Font String (V2 Float) Int
-- | A datatype to represent a bunch of renders.
data Render = RenderSprite SpriteRender
| RenderSprites SpriteBatch
| RenderText TextRender
-- | A type to represent multiple @'Render'@ calls in succession.
type Renders = [Render]
-- | A synonym for map's access function.
(!) :: Ord a => Map.Map a b -> a -> b
(!) = (Map.!)
-- | Specifying that a type can be rendered.
class Renderable a where
render :: Assets -> a -> Renders
-- | The definition of the information necessary for an entity.
data Entity = Entity { getName :: String
, getPosition :: V2 Float
, getSize :: V2 Float
, getHealth :: Float
, shouldShoot :: Bool
}
-- | Rendering an entity.
instance Renderable Entity where
render assets e =
[ RenderSprite $ SpriteRender (getSprites assets ! getName e)
(getPosition e)
(getSize e)
]
-- | Allowing an @'Entity'@ to check collision.
instance Collidable Entity where
toCollisionRectangle entity =
CollisionRectangle { _crPos = getPosition entity
, _crSize = getSize entity
}
-- | A type to represent the defaults for a type of bullet.
data BulletType = PlayerBullet
| EnemyBullet
-- | The bullet type.
data Bullet = Bullet { getBulletType :: BulletType
, getBulletPosition :: V2 Float
, getBulletSize :: V2 Float
, getBulletDamage :: V2 Float
, getBulletSpeed :: V2 Float
}
-- | Rendering a bullet.
instance Renderable Bullet where
render assets b =
[ RenderSprite $ SpriteRender (getSprites assets ! getSpriteName b)
(getBulletPosition b)
(getBulletSize b)
]
where getSpriteName :: Bullet -> String
getSpriteName bt =
case getBulletType bt of
PlayerBullet -> "res/bullet.png"
EnemyBullet -> "res/bullet.png"
-- | Allowing a @'Bullet'@ to check collision.
instance Collidable Bullet where
toCollisionRectangle bullet =
CollisionRectangle { _crPos = getBulletPosition bullet
, _crSize = getBulletSize bullet
}
-- | The default move speed of the player.
playerMoveSpeed :: Float
playerMoveSpeed = 20
-- | The default height of the ground.
groundHeight :: Float
groundHeight = 10
-- | Checking if an @'Entity'@ is dead.
isDead :: Entity -> Bool
isDead e = getHealth e <= 0
-- | Checking if an @'Entity'@ is on the ground.
onGround :: Entity -> Bool
onGround e = (getPosition e ^. _y) <= groundHeight
-- | An alternative type to be used instead of the @'EntityUpdate'@ type. It
-- works by creating one through an @'Entity'@ controller and then applying
-- it to an @'Entity'@ to create the next @'Entity'@ for the frame.
type EntityTransform = (Entity -> Maybe Entity)
-- | Specifying the @'World'@ type.
data World = World { worldGetPlayer :: Entity
, worldGetBackgrounds :: [Entity]
, worldGetAsteroids :: [Entity]
, worldGetEnemies :: [Entity]
, worldGetBullets :: [Bullet]
, worldGetScore :: Int
, worldGetLives :: Int
}
| crockeo/whatisthisgame | src/WhatIsThisGame/Data.hs | mit | 9,542 | 0 | 11 | 3,211 | 1,628 | 933 | 695 | 149 | 1 |
module Network.IRC.Client.Encode
( packWithEncoding
, unpackWithEncoding
, fromStrict' ) where
import Data.Text.Encoding
import qualified Data.Text as T
import qualified Data.ByteString as P (ByteString) -- type name only
import qualified Data.ByteString as S
import qualified Data.ByteString.Char8 as B
import qualified Data.ByteString.Lazy.Char8 as BL
import qualified Data.ByteString.Lazy.Internal as BLI
import Prelude
-- | Convert String to ByteString(Strict) with Encoding.
packWithEncoding :: String -> B.ByteString
packWithEncoding = encodeUtf8 . T.pack
-- | Convert ByteString to String with Encoding
unpackWithEncoding :: B.ByteString -> String
unpackWithEncoding = T.unpack . decodeUtf8
-- |/O(1)/ Convert a strict 'ByteString' into a lazy 'ByteString'.
--
-- sadly hack...
--
-- Because of bytestring 0.9.x version, nothing provides Lazy \<-\> Strict conversion function.
--
-- written referring to bytestring-0.10.x
fromStrict' :: P.ByteString -> BL.ByteString
fromStrict' bs | S.null bs = BLI.Empty
| otherwise = BLI.Chunk bs BLI.Empty
| cosmo0920/hs-IRC | Network/IRC/Client/Encode.hs | mit | 1,137 | 0 | 9 | 224 | 192 | 121 | 71 | 19 | 1 |
module Ch4prob where
-- 4.8.1 --
halve :: [a] -> ([a], [a])
halve x = splitAt dee x
where
dee = (length x) `div` 2
-- 4.8.2.a --
safetail1 xs = if null xs then [] else tail xs
-- 4.8.2.b --
safetail2 xs | null xs = []
| otherwise = tail xs
-- 4.8.2.c --
-- safetail3 as pattern matching
safetail3 :: [a] -> [a]
safetail3 [] = []
safetail3 (_:xs) = xs
-- note that the type signature borrowed from last which I first used was too restrictive because it prevented the [] set from being an acceptable value.
-- solution had to do with x in the second def changed to [x]
-- what if we just wanted the value and not the value in cased in a list.
-- 4.8.3 --
disjunk False False = False
disjunk False True = True
disjunk True False = True
disjunk True True = True
-- 4.8.4 --
disJunk False False = False
disJunk _ _ = True
-- 4.8.5 --
d3sjunk True b = b
d3sjunk False _ = False
-- note that b should be either a True or False
-- 4.8.6
-- using an earlier example as a guide
dada4 = \x -> \y -> x + y
dada6 = \x -> \y -> \z -> x * y * z
| HaskellForCats/HaskellForCats | MenaBeginning/Ch004/ch4Probs2.hs | mit | 1,241 | 0 | 9 | 436 | 298 | 164 | 134 | 20 | 2 |
-- | SPDX-License-Identifier: MIT
--
-- Implements the /HMAC-Based One-Time Password Algorithm/ (HOTP) as
-- defined in [RFC 4226](https://tools.ietf.org/html/rfc4226)
-- and the /Time-Based One-Time Password Algorithm/ (TOTP) as defined
-- in [RFC 6238](https://tools.ietf.org/html/rfc6238).
--
-- Many operations in this module take or return a 'Word32' OTP value
-- (whose most significant bit is always 0) which is truncated modulo
-- @10^digits@ according to the 'Word8' /digits/
-- parameter. Consequently, passing a value above 10 won't produce
-- more than 10 digits and will effectively return the raw
-- non-truncated 31-bit OTP value.
--
-- @since 0.1.0.0
module Data.OTP
( -- * HOTP
hotp
, hotpCheck
-- * TOTP
, totp
, totpCheck
-- * Auxiliary
, totpCounter
, counterRange
, totpCounterRange
, HashAlgorithm(..)
, Secret
) where
import Data.Bits
import qualified Data.ByteString as BS
import Data.Time
import Data.Time.Clock.POSIX
import Data.Word
import HashImpl
{- | Compute /HMAC-Based One-Time Password/ using secret key and counter value.
>>> hotp SHA1 "1234" 100 6
317569
>>> hotp SHA512 "1234" 100 6
134131
>>> hotp SHA512 "1234" 100 8
55134131
-}
hotp
:: HashAlgorithm -- ^ Hashing algorithm
-> Secret -- ^ Shared secret
-> Word64 -- ^ Counter value
-> Word8 -- ^ Number of base10 digits in HOTP value
-> Word32 -- ^ HOTP value
hotp alg key cnt digits
| digits >= 10 = snum
| otherwise = snum `rem` (10 ^ digits)
where
-- C
msg = bsFromW64 cnt
-- Snum = StToNum(Sbits)
-- Sbits = DT(HS)
-- HS = HMAC(K,C)
snum = trunc $ hmac alg key msg
-- DT(HS)
trunc :: BS.ByteString -> Word32
trunc b = case bsToW32 rb of
Left e -> error e
Right res -> res .&. (0x80000000 - 1) -- reset highest bit
where
offset = BS.last b .&. 15 -- take low 4 bits of last byte
rb = BS.take 4 $ BS.drop (fromIntegral offset) b -- resulting 4 byte value
-- StToNum(Sbits)
bsToW32 :: BS.ByteString -> Either String Word32
bsToW32 bs = case BS.unpack bs of
[ b0, b1, b2, b3 ] -> Right $! (((((fI b0 `shiftL` 8) .|. fI b1) `shiftL` 8) .|. fI b2) `shiftL` 8) .|. fI b3
_ -> Left "bsToW32: the impossible happened"
where
fI = fromIntegral
bsFromW64 :: Word64 -> BS.ByteString
bsFromW64 w = BS.pack [ b j | j <- [ 7, 6 .. 0 ] ]
where
b j = fromIntegral (w `shiftR` (j*8))
{- | Check presented password against a valid range.
>>> hotp SHA1 "1234" 10 6
50897
>>> hotpCheck SHA1 "1234" (0,0) 10 6 50897
True
>>> hotpCheck SHA1 "1234" (0,0) 9 6 50897
False
>>> hotpCheck SHA1 "1234" (0,1) 9 6 50897
True
>>> hotpCheck SHA1 "1234" (1,0) 11 6 50897
True
>>> hotpCheck SHA1 "1234" (2,2) 8 6 50897
True
>>> hotpCheck SHA1 "1234" (2,2) 7 6 50897
False
>>> hotpCheck SHA1 "1234" (2,2) 12 6 50897
True
>>> hotpCheck SHA1 "1234" (2,2) 13 6 50897
False
-}
hotpCheck
:: HashAlgorithm -- ^ Hash algorithm to use
-> Secret -- ^ Shared secret
-> (Word8, Word8) -- ^ Valid counter range, before and after ideal
-> Word64 -- ^ Ideal (expected) counter value
-> Word8 -- ^ Number of base10 digits in a password
-> Word32 -- ^ Password (i.e. HOTP value) entered by user
-> Bool -- ^ True if password is valid
hotpCheck alg secr rng cnt len pass =
let counters = counterRange rng cnt
passwds = map (\c -> hotp alg secr c len) counters
in any (pass ==) passwds
{- | Compute a /Time-Based One-Time Password/ using secret key and time.
>>> totp SHA1 "1234" (read "2010-10-10 00:01:00 UTC") 30 6
388892
>>> totp SHA1 "1234" (read "2010-10-10 00:01:00 UTC") 30 8
43388892
>>> totp SHA1 "1234" (read "2010-10-10 00:01:15 UTC") 30 8
43388892
>>> totp SHA1 "1234" (read "2010-10-10 00:01:31 UTC") 30 8
39110359
-}
totp
:: HashAlgorithm -- ^ Hash algorithm to use
-> Secret -- ^ Shared secret
-> UTCTime -- ^ Time of TOTP
-> Word64 -- ^ Time range in seconds
-> Word8 -- ^ Number of base10 digits in TOTP value
-> Word32 -- ^ TOTP value
totp alg secr time period len =
hotp alg secr (totpCounter time period) len
{- | Check presented password against time periods.
>>> totp SHA1 "1234" (read "2010-10-10 00:00:00 UTC") 30 6
778374
>>> totpCheck SHA1 "1234" (0, 0) (read "2010-10-10 00:00:00 UTC") 30 6 778374
True
>>> totpCheck SHA1 "1234" (0, 0) (read "2010-10-10 00:00:30 UTC") 30 6 778374
False
>>> totpCheck SHA1 "1234" (1, 0) (read "2010-10-10 00:00:30 UTC") 30 6 778374
True
>>> totpCheck SHA1 "1234" (1, 0) (read "2010-10-10 00:01:00 UTC") 30 6 778374
False
>>> totpCheck SHA1 "1234" (2, 0) (read "2010-10-10 00:01:00 UTC") 30 6 778374
True
-}
totpCheck
:: HashAlgorithm -- ^ Hash algorithm to use
-> Secret -- ^ Shared secret
-> (Word8, Word8) -- ^ Valid counter range, before and after ideal
-> UTCTime -- ^ Time of TOTP
-> Word64 -- ^ Time range in seconds
-> Word8 -- ^ Number of base10 digits in a password
-> Word32 -- ^ Password given by user
-> Bool -- ^ True if password is valid
totpCheck alg secr rng time period len pass =
let counters = totpCounterRange rng time period
passwds = map (\c -> hotp alg secr c len) counters
in any (pass ==) passwds
{- | Calculate HOTP counter using time. Starting time (T0
according to RFC6238) is 0 (begining of UNIX epoch)
>>> totpCounter (read "2010-10-10 00:00:00 UTC") 30
42888960
>>> totpCounter (read "2010-10-10 00:00:30 UTC") 30
42888961
>>> totpCounter (read "2010-10-10 00:01:00 UTC") 30
42888962
-}
totpCounter
:: UTCTime -- ^ Time of totp
-> Word64 -- ^ Time range in seconds
-> Word64 -- ^ Resulting counter
totpCounter time period =
let timePOSIX = floor $ utcTimeToPOSIXSeconds time
in timePOSIX `div` period
{- | Make a sequence of acceptable counters, protected from
arithmetic overflow.
>>> counterRange (0, 0) 9000
[9000]
>>> counterRange (1, 0) 9000
[8999,9000]
>>> length $ counterRange (5000, 0) 9000
501
>>> length $ counterRange (5000, 5000) 9000
1000
>>> counterRange (2, 2) maxBound
[18446744073709551613,18446744073709551614,18446744073709551615]
>>> counterRange (2, 2) minBound
[0,1,2]
>>> counterRange (2, 2) (maxBound `div` 2)
[9223372036854775805,9223372036854775806,9223372036854775807,9223372036854775808,9223372036854775809]
>>> counterRange (5, 5) 9000
[8995,8996,8997,8998,8999,9000,9001,9002,9003,9004,9005]
RFC recommends avoiding excessively large values for counter ranges.
-}
counterRange
:: (Word8, Word8) -- ^ Number of counters before and after ideal
-> Word64 -- ^ Ideal counter value
-> [Word64]
counterRange (tolow, tohigh) ideal = [l..h]
where
l' = ideal - fromIntegral tolow
l | l' <= ideal = l'
| otherwise = 0
h' = ideal + fromIntegral tohigh
h | ideal <= h' = h'
| otherwise = maxBound
{- | Make a sequence of acceptable periods.
>>> totpCounterRange (0, 0) (read "2010-10-10 00:01:00 UTC") 30
[42888962]
>>> totpCounterRange (2, 0) (read "2010-10-10 00:01:00 UTC") 30
[42888960,42888961,42888962]
>>> totpCounterRange (0, 2) (read "2010-10-10 00:01:00 UTC") 30
[42888962,42888963,42888964]
>>> totpCounterRange (2, 2) (read "2010-10-10 00:01:00 UTC") 30
[42888960,42888961,42888962,42888963,42888964]
-}
totpCounterRange :: (Word8, Word8)
-> UTCTime
-> Word64
-> [Word64]
totpCounterRange rng time period =
counterRange rng $ totpCounter time period
| matshch/OTP | src/Data/OTP.hs | mit | 7,909 | 0 | 22 | 2,085 | 1,025 | 570 | 455 | 100 | 3 |
-- | Compiling the payoff language to Futhark
module Examples.PayoffToFuthark where
import Data.List
import ContractTranslation
import Contract
import Data.Text.Template
import qualified Data.ByteString.Lazy as S
import qualified Data.Text as T
import qualified Data.Text.Lazy as E
internalFuncName = "payoffInternal"
funcName = "payoffFun"
-- | Two lists: labels of observables and names of template variables.
-- | These lists used to translate labels and names to indices.
data Params = Params {obsP :: [String], templateP :: [String]}
deriving (Show)
fromBinOp op = case op of
ILAdd -> "+"
ILSub -> "-"
ILMult -> "*"
ILDiv -> "/"
ILAnd -> "&&"
ILOr -> "||"
ILLess -> "<"
ILLessN -> "<"
ILLeq -> "<="
ILEqual -> "=="
fromUnOp op = case op of
ILNot -> "!"
ILNeg -> "-"
fromTexpr params e = case e of
Tnum n -> show n
Tvar s -> inParens ("tenv[" ++ show (paramIndex s (templateP params)) ++ "]")
fromILTexpr params e = case e of
ILTplus e1 e2 -> fromILTexpr params e1 ++ " + " ++ fromILTexpr params e2
ILTexpr e -> fromTexpr params e
fromILTexprZ params e = case e of
ILTplusZ e1 e2 -> fromILTexprZ params e1 ++ " + " ++ fromILTexprZ params e2
ILTexprZ e -> fromILTexpr params e
ILTnumZ n -> show n
-- we shadow t0 variable with new bindings and this allows us to just keep the same name for updated counted everywhere
loopif cond e1 e2 t =
let templ = template $
T.pack
"let t0 = (loop t0 = t0 while (!(${cond}))&&(t0 < ${t}) do t0+1) in \n if ${cond} then (${e1}) else (${e2})" in
let ctx = [("cond", cond), ("e1",e1), ("e2", e2), ("t",t)] in
substTempl (context $ Data.List.map (\(a1,a2) -> (T.pack a1, T.pack a2)) ctx) templ
-- | Pretty-printing Futhark code.
-- | Assumptions:
-- | the external environment is an array which is indexed with discrete time, i.e. if contact horizon is [n] then the environment should contain n values for an observable;
-- | there are only two parties in a payoff exression and payoff(p1,p2) is always traslated as positive discounted value disc[t+t0].
fromPayoff params e =
case e of
ILIf e' e1 e2 -> inParens ("if " ++ inParens (fromPayoff params e') ++
"then " ++ inParens (fromPayoff params e1) ++
"else " ++ inParens (fromPayoff params e2))
ILFloat v -> show v ++ "f32"
ILNat n -> show n
ILBool b -> show b
ILtexpr e -> inParens (fromILTexpr params e) ++ " + t0"
ILNow -> "t_now"
ILModel (LabR (Stock l)) t ->
-- we simplify the lookup procedure to just indexing in the environment
inParens ("ext[" ++ (fromILTexprZ params t ++ "+ t0") ++ "," ++ show (paramIndex l (obsP params)) ++ "]")
ILUnExpr op e -> inParens (fromUnOp op ++ fromPayoff params e)
ILBinExpr op e1 e2 -> inParens (inParens (fromPayoff params e1) ++ spaced (fromBinOp op) ++ inParens (fromPayoff params e2))
ILLoopIf e e1 e2 t -> loopif (fromPayoff params e)
(fromPayoff params e1)
(fromPayoff params e2)
(fromTexpr params t)
-- this is also a simplifying assumption:
ILPayoff t p1' p2' -> "disc" ++ inSqBr (fromILTexpr params t ++ "+ t0")
-- inParens (ifThenElse (show p1' ++ "== p1 && " ++ show p2' ++ "== p2") "1"
-- (ifThenElse (show p1' ++ "== p2 && " ++ show p2' ++ "== p1") "-1" "0"))
-- | Two index translation functions
data IndexTrans = IndT {obsT :: Int -> Int, payoffT :: Int -> Int}
empty_tenv = (\_ -> error "Empty template env")
-- | Translation of time scale to indices.
-- | Ideally, this should be done in Coq with corresponding proofs.
-- | Reindex actually does a bit more: it evaluates template expression in the empty template environment.
-- | For that reason it works only for template-closed expressions.
reindex :: IndexTrans -> ILExpr -> ILExpr
reindex indT e =
case e of
ILIf e' e1 e2 -> ILIf (reindex indT e') (reindex indT e1) (reindex indT e2)
ILFloat v -> ILFloat v
ILNat n -> ILNat n
ILBool b -> ILBool b
ILtexpr e -> let n = iLTexprSem e empty_tenv in ILtexpr (ILTexpr (Tnum ((obsT indT) n)))
ILNow -> ILNow
ILModel (LabR (Stock l)) t -> let n = iLTexprSemZ t empty_tenv in
ILModel (LabR (Stock l)) (ILTnumZ ((obsT indT) n))
ILUnExpr op e -> ILUnExpr op (reindex indT e)
ILBinExpr op e1 e2 -> ILBinExpr op (reindex indT e1) (reindex indT e2)
ILLoopIf e e1 e2 t -> ILLoopIf (reindex indT e) (reindex indT e1)
(reindex indT e2) t
ILPayoff t p1 p2 -> let n = iLTexprSem t empty_tenv in
ILPayoff (ILTexpr (Tnum ((payoffT indT) n))) p1 p2
reindexTexpr :: (Int -> Int) -> TExpr -> TExpr
reindexTexpr rf e = case e of
Tnum n -> Tnum (rf n)
Tvar s -> Tvar s
reindexILTexpr rf e = case e of
ILTplus e1 e2 -> ILTplus (reindexILTexpr rf e1) (reindexILTexpr rf e2)
ILTexpr e -> ILTexpr (reindexTexpr rf e)
reindexILTexprZ rf e = case e of
ILTplusZ e1 e2 -> ILTplusZ (reindexILTexprZ rf e1) (reindexILTexprZ rf e2)
ILTexprZ e -> ILTexprZ (reindexILTexpr rf e)
ILTnumZ n -> ILTnumZ (rf n)
-- some helpers for pretty-printing
inParens s = "(" ++ s ++ ")"
inCurlBr s = "{" ++ s ++ "}"
inSqBr s = "[" ++ s ++ "]"
newLn s = "\n" ++ s
inBlock = newLn . inCurlBr . newLn
commaSeparated = intercalate ", "
surroundBy c s = c ++ s ++ c
spaced = surroundBy " "
ifThenElse cond e1 e2 = "if " ++ spaced (inParens cond) ++ "then" ++ spaced e1 ++ "else" ++ spaced e2
dec name params ty body = "let " ++ name ++ inParens params ++ ": " ++ ty ++ " = " ++ body
fcall f args = f ++ inParens (intercalate ", " args)
lambda v e = "(\\" ++ v ++ "->" ++ e ++ ")"
header = ""
payoffInternalDec params e =
dec internalFuncName "ext : [][]f32, tenv : []i32, disc : []f32, t0 : i32, t_now : i32" "f32" (fromPayoff params e)
payoffDec = dec funcName "ext : [][]f32, tenv : []i32, disc : []f32, t_now : i32" "f32"
(fcall internalFuncName ["ext", "tenv", "disc", "0", "t_now"])
ppFutharkCode params e = payoffInternalDec params e ++ newLn payoffDec
-- | Create 'Context' from association list (taken from "template" package examples)
context :: [(T.Text, T.Text)] -> Context
context assocs x = maybe err id . lookup x $ assocs
where err = error $ "Could not find key: " ++ T.unpack x
substTempl :: Context -> Template -> String
substTempl ctx tmpl = E.unpack $ render tmpl ctx
-- | Translate template variables according to the order they appear
-- | in the given list of variable names
paramIndex :: String -> [String] -> Int
paramIndex p = maybe err id . findIndex (\x -> x == p)
where err = error $ "Could not find parameter: " ++ p
wrapInModule modName code = substTempl (context ctx) modTempl
where
ctx = Data.List.map (\(a1,a2) -> (T.pack a1, T.pack a2))
[("code", code),
("modName", modName),
("fcall", fcall funcName ["ext", "[]", "disc", "0"])]
modTempl = template $ T.pack "module $modName = { $code \n\n let payoff disc _ ext = $fcall }"
compileAndWrite path params exp =
let path' = if null path then "./" else path in
do
let out = header ++ ppFutharkCode params exp
writeFile (path ++ "PayoffFunction.fut") out
| annenkov/contracts | Coq/Extraction/contracts-haskell/src/Examples/PayoffToFuthark.hs | mit | 7,701 | 0 | 18 | 2,213 | 2,297 | 1,154 | 1,143 | 128 | 11 |
module FunctorsAndMonoids where
import Data.Char
import Data.List
import Data.Monoid
import Control.Applicative
import qualified Data.Foldable as F
fmapIO = do line <- fmap (intersperse '-' . reverse . map toUpper) getLine
putStrLn line
-- Works with partial application for '+' function which essentialy has a singnature of 'Num a => a -> a -> a'
magic = pure (+) <*> Just 3 <*> Just 5
-- With partial application this works!
magic3 = pure (sum3) <*> Just 10 <*> Just 100 <*> Just 1000
fmapNormal = fmap (+3) [1, 2, 3]
fmapInfix = (+3) <$> [1, 2, 3]
sum3 :: Int -> Int -> Int -> Int
sum3 a b c = a + b + c
-- the next two functions show where applicative functors works really cool
-- the catch is that both lines looks almost the same, but the second line works with 'Maybe'. Which can in fact be any other 'Functor'
concatNormal = (++) "johntra" "volta"
concatInMaybe = (++) <$> Just "johntra" <*> Just "volta"
-- IO is also an applicative functor
glueTwoLines = (++) <$> getLine <*> getLine
zipListExample = getZipList $ max <$> ZipList [1,2,3,4,5,3] <*> ZipList [5,3,1,2]
-- Magic start happening here
-- sequenceA :: (Applicative f) => [f a] -> f [a]
-- sequenceA = foldr (liftA2 (:)) (pure [])
useSequence = sequenceA [Just 3, Just 2, Just 1]
-- Ordering is a Monoid!
-- If one string is lesser/greater then the other -> returns LT/GT
-- If strings are equal by length -> compare lexicographicaly... using monoid concan with length compare!
lengthCompare :: String -> String -> Ordering
lengthCompare x y = (length x `compare` length y) `mappend`
(x `compare` y)
where vowels = length . filter (`elem` "aeiou")
-- Maybe are monoids denifed as 'instance Monoid a => Monoid (Maybe a) where', but there are also 2 useful typeclasses
maybeWithFirst = getFirst $ First (Nothing) `mappend` First (Just 5) `mappend` First (Just 3) -- result is Just 5
maybeWithLast = getLast $ Last (Nothing) `mappend` Last (Just 5) `mappend` Last (Just 3) -- result is Just 3
data Tree a = Empty | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
instance F.Foldable Tree where
foldMap f Empty = mempty
foldMap f (Node x l r) = F.foldMap f l `mappend`
f x `mappend`
F.foldMap f r
testTree = Node 5
(Node 3
(Node 1 Empty Empty)
(Node 6 Empty Empty)
)
(Node 9
(Node 8 Empty Empty)
(Node 10 Empty Empty)
)
-- this maps values of a tree to Any Monoid and then calculate this monoid's value which considering the implementation of Any should be true if any
-- of values is True
checkAnyIsThree = getAny $ F.foldMap (\x -> Any $ x == 3) testTree
-- First maps each element into an array and then calculate array's monoid which is - concatenate all elements!
turnToArray tree = F.foldMap (\x -> [x]) tree
| aquatir/remember_java_api | code-sample-haskell/hello_world/func_magic/functors_and_monoids.hs | mit | 3,006 | 0 | 12 | 808 | 760 | 417 | 343 | 40 | 1 |
factorial :: Integer -> Integer
factorial n
| n==0 =1
| n>0 =n* factorial (n-1)
| otherwise =error " undefined negative error "
main=print(factorial 200)
| manuchandel/Academics | Principles-Of-Programming-Languages/factorial.hs | mit | 158 | 0 | 9 | 29 | 81 | 38 | 43 | 6 | 1 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-missing-fields #-}
-- | A Shakespearean module for TypeScript, introducing type-safe,
-- compile-time variable and url interpolation. It is exactly the same as
-- "Text.Julius", except that the template is first compiled to Javascript with
-- the system tool @tsc@.
--
-- To use this module, @tsc@ must be installed on your system.
--
-- If you interpolate variables,
-- the template is first wrapped with a function containing javascript variables representing shakespeare variables,
-- then compiled with @tsc@,
-- and then the value of the variables are applied to the function.
-- This means that in production the template can be compiled
-- once at compile time and there will be no dependency in your production
-- system on @tsc@.
--
-- Your code:
--
-- > var b = 1
-- > console.log(#{a} + b)
--
-- Final Result:
--
-- > ;(function(shakespeare_var_a){
-- > var b = 1;
-- > console.log(shakespeare_var_a + b);
-- > })(#{a});
--
--
-- Important Warnings! This integration is not ideal.
--
-- Due to the function wrapper, all type declarations must be in separate .d.ts files.
-- However, if you don't interpolate variables, no function wrapper will be
-- created, and you can make type declarations in the same file.
--
-- This does not work cross-platform!
--
-- Unfortunately tsc does not support stdin and stdout.
-- So a hack of writing to temporary files using the mktemp
-- command is used. This works on my version of Linux, but not for windows
-- unless perhaps you install a mktemp utility, which I have not tested.
-- Please vote up this bug: <http://typescript.codeplex.com/workitem/600>
--
-- Making this work on Windows would not be very difficult, it will just require a new
-- package with a dependency on a package like temporary.
--
-- Further reading:
--
-- 1. Shakespearean templates: <https://www.yesodweb.com/book/shakespearean-templates>
--
-- 2. TypeScript: <https://www.typescriptlang.org/>
module Text.TypeScript
( -- * Functions
-- ** Template-Reading Functions
-- | These QuasiQuoter and Template Haskell methods return values of
-- type @'JavascriptUrl' url@. See the Yesod book for details.
tsc
, tscJSX
, typeScriptFile
, typeScriptJSXFile
, typeScriptFileReload
, typeScriptJSXFileReload
#ifdef TEST_EXPORT
, typeScriptSettings
, typeScriptJSXSettings
#endif
) where
import Language.Haskell.TH.Quote (QuasiQuoter (..))
import Language.Haskell.TH.Syntax
import Text.Shakespeare
import Text.Julius
-- | The TypeScript language compiles down to Javascript.
-- We do this compilation once at compile time to avoid needing to do it during the request.
-- We call this a preConversion because other shakespeare modules like Lucius use Haskell to compile during the request instead rather than a system call.
typeScriptSettings :: Q ShakespeareSettings
typeScriptSettings = do
jsettings <- javascriptSettings
return $ jsettings { varChar = '#'
, preConversion = Just PreConvert {
preConvert = ReadProcess "sh" ["-c", "TMP_IN=$(mktemp XXXXXXXXXX.ts); TMP_OUT=$(mktemp XXXXXXXXXX.js); cat /dev/stdin > ${TMP_IN} && tsc --out ${TMP_OUT} ${TMP_IN} && cat ${TMP_OUT}; rm ${TMP_IN} && rm ${TMP_OUT}"]
, preEscapeIgnoreBalanced = "'\""
, preEscapeIgnoreLine = "//"
, wrapInsertion = Just WrapInsertion {
wrapInsertionIndent = Nothing
, wrapInsertionStartBegin = ";(function("
, wrapInsertionSeparator = ", "
, wrapInsertionStartClose = "){"
, wrapInsertionEnd = "})"
, wrapInsertionAddParens = False
}
}
}
-- | Identical to 'typeScriptSettings' but uses jsx when compiling TypeScript
typeScriptJSXSettings :: Q ShakespeareSettings
typeScriptJSXSettings = do
tsSettings <- typeScriptSettings
let rp = ReadProcess "sh" ["-c", "TMP_IN=$(mktemp XXXXXXXXXX.tsx); TMP_OUT=$(mktemp XXXXXXXXXX.js); cat /dev/stdin > ${TMP_IN} && tsc --module amd --jsx react --out ${TMP_OUT} ${TMP_IN} && cat ${TMP_OUT}; rm ${TMP_IN} && rm ${TMP_OUT}"]
return $ tsSettings {
preConversion = fmap (\pc -> pc { preConvert = rp }) (preConversion tsSettings)
}
-- | Read inline, quasiquoted TypeScript
tsc :: QuasiQuoter
tsc = QuasiQuoter { quoteExp = \s -> do
rs <- typeScriptSettings
quoteExp (shakespeare rs) s
}
-- | Read inline, quasiquoted TypeScript with jsx
tscJSX :: QuasiQuoter
tscJSX = QuasiQuoter { quoteExp = \s -> do
rs <- typeScriptJSXSettings
quoteExp (shakespeare rs) s
}
-- | Read in a TypeScript template file. This function reads the file once, at
-- compile time.
typeScriptFile :: FilePath -> Q Exp
typeScriptFile fp = do
rs <- typeScriptSettings
shakespeareFile rs fp
-- | Read in a TypeScript template file with jsx. This function reads the file
-- once, at compile time.
typeScriptJSXFile :: FilePath -> Q Exp
typeScriptJSXFile fp = do
rs <- typeScriptJSXSettings
shakespeareFile rs fp
-- | Read in a TypeScript template file. This impure function uses
-- unsafePerformIO to re-read the file on every call, allowing for rapid
-- iteration.
typeScriptFileReload :: FilePath -> Q Exp
typeScriptFileReload fp = do
rs <- typeScriptSettings
shakespeareFileReload rs fp
-- | Read in a TypeScript with jsx template file. This impure function uses
-- unsafePerformIO to re-read the file on every call, allowing for rapid
-- iteration.
typeScriptJSXFileReload :: FilePath -> Q Exp
typeScriptJSXFileReload fp = do
rs <- typeScriptJSXSettings
shakespeareFileReload rs fp
| yesodweb/shakespeare | Text/TypeScript.hs | mit | 5,640 | 1 | 16 | 1,048 | 541 | 332 | 209 | 61 | 1 |
{-|
Handler for a single image, showing the image, title, description, tags, and allows
the uploader to modify everything.
-}
module Handler.Image where
import Text.Julius (rawJS)
import Yesod.Auth
import Database.Esqueleto
import Control.Arrow
import Import hiding ((==.), delete, (=.), update)
import Handler.Tags
modifyForm :: Image -> [(String,String)] -> Html -> MForm Handler (FormResult (Text, Maybe Textarea, [(String,String)]), Widget)
modifyForm image tags html = do
(rtitle, vtitle) <- mreq textField "" (Just $ imageTitle image)
(rdescription, vdescription) <- mopt textareaField "" (Just $ imageDescription image)
(rtags, vtags) <- mreq tagsField "" (Just tags)
return ((,,) <$> rtitle <*> rdescription <*> rtags, do
master <- handlerToWidget getYesod
viewClass <- newIdent
editClass <- newIdent
editButtonClass <- newIdent
-- Deals with hiding and showing when going into or out of edit mode
toWidget [julius|
$(".#{rawJS editClass}").addClass("hidden");
editMode = false;
$(".#{rawJS editButtonClass}").on("click", function(){
if (editMode) {
editMode = false;
$(".#{rawJS editClass}").addClass("hidden");
$(".#{rawJS viewClass}").removeClass("hidden");
} else {
editMode = true;
$(".#{rawJS editClass}").removeClass("hidden");
$(".#{rawJS viewClass}").addClass("hidden");
}
});
$(".#{rawJS editClass}>*").addClass("form-control");
|]
[whamlet|
#{html}
<div .container>
<h1 .#{viewClass}>#{imageTitle image}
<div .#{editClass} .form-group>
^{fvInput vtitle}
<img src=#{relativeToAbsolute master $ imageFilename image} .img-thumbnail .img-responsive>
$maybe description <- imageDescription image
<p .#{viewClass}>#{description}
<div .#{editClass} .form-group>
^{fvInput vdescription}
<h2>Tags
<p .#{viewClass}>
#{tagsToText tags}
<div .#{editClass} .form-group>
^{fvInput vtags}
<p> Uploaded on #{show $ imageUploadTime image}
<button type=button .btn .btn-default .#{editButtonClass} .#{viewClass}>
Edit
<button .#{editClass} type=submit .btn .btn-primary>Submit
<button .#{editClass} .#{editButtonClass} type=button .btn .btn-danger>Cancel
|])
-- | Shows the image, its title, description, tags, upload date, and allows the
-- uploader to modify the image info and tags.
getImageR :: ImageId -> Handler Html
getImageR imageId = do
mImage <- runDB $ get imageId
case mImage of
Nothing -> defaultLayout $ [whamlet|
<p>This image doesn't exist!
|]
Just image -> do
tags <- runDB $
select $
from $ \(imgTagLink `InnerJoin` tag `InnerJoin` cat) -> do
on (cat ^. TagCategoryId ==. tag ^. TagTagCategory)
on (tag ^. TagId ==. imgTagLink ^. ImageTagLinkTagId)
where_ (imgTagLink ^. ImageTagLinkImageId ==. val imageId)
return (cat,tag)
let tagsStrings =
map
(\(Entity _ cat, Entity _ tag) ->
(unpack $ tagCategoryName cat, unpack $ tagName tag))
tags
((_,modifyWidget),enctype) <- runFormPost $ modifyForm image tagsStrings
defaultLayout [whamlet|
<form method=post enctype=#{enctype} #image-modificcation-form>
^{modifyWidget}
|]
postImageR :: ImageId -> Handler Html
postImageR imageId = do
mImage <- runDB $ get imageId
case mImage of
Nothing -> redirect $ ImageR imageId
Just image -> do
tags <- fmap (map (unpack . tagCategoryName . entityVal ***
unpack . tagName . entityVal))
$ runDB
$ select
$ from $ \(imgTagLink `InnerJoin` tag `InnerJoin` cat) -> do
on (tag ^. TagTagCategory ==. cat ^. TagCategoryId)
on (imgTagLink ^. ImageTagLinkTagId ==. tag ^. TagId)
where_ (imgTagLink ^. ImageTagLinkImageId ==. val imageId)
return (cat, tag)
((result,_),_) <- runFormPost $ modifyForm image tags
case result of
FormSuccess (title, description, listOfTags) -> do
muser <- maybeAuth
case muser of
Nothing -> do
setMessage "You must be logged in to upload images."
redirect $ AuthR LoginR
Just (Entity _ _) -> do
-- if successful and logged in, modify image and tags adequately
runDB $ do
update $ \img -> do
set img [ImageTitle =. val title
,ImageDescription =. val description]
where_ (img ^. ImageId ==. val imageId)
-- simply delete all tags associated to the image then runs
-- the tag writing procedure again
delete $ from $ \imgTagLink -> do
where_ (imgTagLink ^. ImageTagLinkImageId ==. val imageId)
writeTags imageId listOfTags
setMessage "Image successfully modified"
redirect $ ImageR imageId
_ -> do
setMessage "Image modification failed for unknown reasons."
redirect $ ImageR imageId | alexisVallet/aci-webapp | Handler/Image.hs | gpl-2.0 | 5,364 | 0 | 33 | 1,640 | 1,041 | 528 | 513 | -1 | -1 |
{-# LANGUAGE RankNTypes #-}
-- Copyright (C) 2002-2003 David Roundy
--
-- 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, 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; see the file COPYING. If not, write to
-- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-- Boston, MA 02110-1301, USA.
{-# LANGUAGE CPP #-}
module Darcs.UI.Commands.Move ( move, mv ) where
import Prelude hiding ( (^) )
import Control.Applicative ( (<$>) )
import Control.Monad ( when, unless, forM_, forM )
import Data.Maybe ( fromMaybe )
import Darcs.Util.SignalHandler ( withSignalsBlocked )
import Darcs.UI.Commands
( DarcsCommand(..), withStdOpts, nodefaults, commandAlias, amInHashedRepository )
import Darcs.UI.Flags ( DarcsFlag(Quiet)
, doAllowCaseOnly, doAllowWindowsReserved, useCache, dryRun, umask
, maybeFixSubPaths, fixSubPaths )
import Darcs.UI.Options ( DarcsOption, (^), odesc, ocheck, onormalise, defaultFlags )
import qualified Darcs.UI.Options.All as O
import Darcs.Repository.Diff ( treeDiff )
import Darcs.Repository.Flags ( UpdateWorking (..), DiffAlgorithm(..) )
import Darcs.Repository.Prefs ( filetypeFunction )
import System.FilePath.Posix ( (</>), takeFileName )
import System.Directory ( renameDirectory )
import Darcs.Repository.State ( readRecordedAndPending, readRecorded, updateIndex )
import Darcs.Repository
( Repository
, withRepoLock
, RepoJob(..)
, addPendingDiffToPending
, listFiles
)
import Darcs.Patch.Witnesses.Ordered ( FL(..), (+>+) )
import Darcs.Patch.Witnesses.Sealed ( emptyGap, freeGap, joinGap, FreeLeft )
import Darcs.Util.Global ( debugMessage )
import qualified Darcs.Patch
import Darcs.Patch ( RepoPatch, PrimPatch )
import Darcs.Patch.Apply( ApplyState )
import Data.List ( nub, sort )
import qualified System.FilePath.Windows as WindowsFilePath
import Darcs.UI.Commands.Util.Tree ( treeHas, treeHasDir, treeHasAnycase, treeHasFile )
import Storage.Hashed.Tree( Tree, modifyTree )
import Storage.Hashed.Plain( readPlainTree )
import Darcs.Util.Path
( floatPath
, fp2fn
, fn2fp
, superName
, SubPath()
, toFilePath
, AbsolutePath
)
import Darcs.Util.Workaround ( renameFile )
moveDescription :: String
moveDescription = "Move or rename files."
moveHelp :: String
moveHelp =
"Darcs cannot reliably distinguish between a file being deleted and a\n" ++
"new one added, and a file being moved. Therefore Darcs always assumes\n" ++
"the former, and provides the `darcs mv` command to let Darcs know when\n" ++
"you want the latter. This command will also move the file in the\n" ++
"working tree (unlike `darcs remove`), unless it has already been moved.\n" ++
"\n" ++
-- Note that this paragraph is very similar to one in ./Add.lhs.
"Darcs will not rename a file if another file in the same folder has\n" ++
"the same name, except for case. The `--case-ok` option overrides this\n" ++
"behaviour. Windows and OS X usually use filesystems that do not allow\n" ++
"files a folder to have the same name except for case (for example,\n" ++
"`ReadMe` and `README`). If `--case-ok` is used, the repository might be\n" ++
"unusable on those systems!\n"
moveBasicOpts :: DarcsOption a (Bool -> Bool -> Maybe String -> a)
moveBasicOpts = O.allowProblematicFilenames ^ O.workingRepoDir
moveAdvancedOpts :: DarcsOption a (O.UMask -> a)
moveAdvancedOpts = O.umask
moveOpts :: DarcsOption a
(Bool
-> Bool
-> Maybe String
-> Maybe O.StdCmdAction
-> Bool
-> Bool
-> O.Verbosity
-> Bool
-> O.UMask
-> O.UseCache
-> Maybe String
-> Bool
-> Maybe String
-> Bool
-> a)
moveOpts = moveBasicOpts `withStdOpts` moveAdvancedOpts
move :: DarcsCommand [DarcsFlag]
move = DarcsCommand
{ commandProgramName = "darcs"
, commandName = "move"
, commandHelp = moveHelp
, commandDescription = moveDescription
, commandExtraArgs = -1
, commandExtraArgHelp = ["<SOURCE> ... <DESTINATION>"]
, commandCommand = moveCmd
, commandPrereq = amInHashedRepository
, commandGetArgPossibilities = listFiles False
, commandArgdefaults = nodefaults
, commandAdvancedOptions = odesc moveAdvancedOpts
, commandBasicOptions = odesc moveBasicOpts
, commandDefaults = defaultFlags moveOpts
, commandCheckOptions = ocheck moveOpts
, commandParseOptions = onormalise moveOpts
}
moveCmd :: (AbsolutePath, AbsolutePath) -> [DarcsFlag] -> [String] -> IO ()
moveCmd fps opts args
| length args < 2 =
fail "The `darcs move' command requires at least two arguments."
| length args == 2 = do
xs <- maybeFixSubPaths fps args
case xs of
[Just from, Just to]
| from == to -> fail "Cannot rename a file or directory onto itself!"
| toFilePath from == "" -> fail "Cannot move the root of the repository"
| otherwise -> moveFile opts from to
_ -> fail "Both source and destination must be valid."
| otherwise = let (froms, to) = (init args, last args) in do
x <- head <$> maybeFixSubPaths fps [to]
case x of
Nothing -> fail "Invalid destination directory."
Just to' -> do
xs <- nub . sort <$> fixSubPaths fps froms
if to' `elem` xs
then fail "Cannot rename a file or directory onto itself!"
else case xs of
[] -> fail "Nothing to move."
froms' -> moveFilesToDir opts froms' to'
data FileKind = Dir | File
deriving (Show, Eq)
data FileStatus =
Nonexistant
| Unadded FileKind
| Shadow FileKind -- ^ known to darcs, but absent in working copy
| Known FileKind
deriving Show
fileStatus :: Tree IO -- ^ tree of the working directory
-> Tree IO -- ^ tree of recorded and pending changes
-> Tree IO -- ^ tree of recorded changes
-> FilePath
-> IO FileStatus
fileStatus work cur recorded fp = do
existsInCur <- treeHas cur fp
existsInRec <- treeHas recorded fp
existsInWork <- treeHas work fp
case (existsInRec, existsInCur, existsInWork) of
(_, True, True) -> do
isDirCur <- treeHasDir cur fp
isDirWork <- treeHasDir work fp
unless (isDirCur == isDirWork) . fail $ "don't know what to do with " ++ fp
return . Known $ if isDirCur then Dir else File
(_, False, True) -> do
isDir <- treeHasDir work fp
if isDir
then return $ Unadded Dir
else return $ Unadded File
(False, False, False) -> return Nonexistant
(_, _, False) -> do
isDir <- treeHasDir cur fp
if isDir
then return $ Shadow Dir
else return $ Shadow File
-- | Takes two filenames (as 'Subpath'), and tries to move the first
-- into/onto the second. Needs to guess what that means: renaming or moving
-- into a directory, and whether it is a post-hoc move.
moveFile :: [DarcsFlag] -> SubPath -> SubPath -> IO ()
moveFile opts old new = withRepoAndState opts $ \(repo, work, cur, recorded) -> do
let old_fp = toFilePath old
new_fp = toFilePath new
new_fs <- fileStatus work cur recorded new_fp
old_fs <- fileStatus work cur recorded old_fp
let doSimpleMove = simpleMove repo opts cur work old_fp new_fp
case (old_fs, new_fs) of
(Nonexistant, _) -> fail $ old_fp ++ " does not exist."
(Unadded k, _) -> fail $ show k ++ " " ++ old_fp ++ " is unadded."
(Known _, Nonexistant) -> doSimpleMove
(Known _, Shadow _) -> doSimpleMove
(_, Nonexistant) -> fail $ old_fp ++ " is not in the repository."
(Known _, Known Dir) -> moveToDir repo opts cur work [old_fp] new_fp
(Known _, Unadded Dir) -> fail $
new_fp ++ " is not known to darcs; please add it to the repository."
(Known _, _) -> fail $ new_fp ++ " already exists."
(Shadow k, Unadded k') | k == k' -> doSimpleMove
(Shadow File, Known Dir) -> moveToDir repo opts cur work [old_fp] new_fp
(Shadow Dir, Known Dir) -> doSimpleMove
(Shadow File, Known File) -> doSimpleMove
(Shadow k, _) -> fail $
"cannot move " ++ show k ++ " " ++ old_fp ++ " into " ++ new_fp
++ " : " ++ "did you already move it elsewhere?"
moveFilesToDir :: [DarcsFlag] -> [SubPath] -> SubPath -> IO ()
moveFilesToDir opts froms to = withRepoAndState opts $ \(repo, work, cur, _) ->
moveToDir repo opts cur work (map toFilePath froms) $ toFilePath to
withRepoAndState :: [DarcsFlag]
-> (forall p wR wU .
(ApplyState p ~ Tree, RepoPatch p) =>
(Repository p wR wU wR, Tree IO, Tree IO, Tree IO)
-> IO ())
-> IO ()
withRepoAndState opts f =
withRepoLock dr uc YesUpdateWorking um $ RepoJob $ \repo -> do
work <- readPlainTree "."
cur <- readRecordedAndPending repo
recorded <- readRecorded repo
f (repo, work, cur, recorded)
where
dr = dryRun opts
uc = useCache opts
um = umask opts
simpleMove :: (RepoPatch p, ApplyState p ~ Tree) => Repository p wR wU wT
-> [DarcsFlag] -> Tree IO -> Tree IO -> FilePath -> FilePath
-> IO ()
simpleMove repository opts cur work old_fp new_fp = do
doMoves repository opts cur work [(old_fp, new_fp)]
unless (Quiet `elem` opts) $
putStrLn $ unwords ["Moved:", old_fp, "to:", new_fp]
moveToDir :: (RepoPatch p, ApplyState p ~ Tree) => Repository p wR wU wT
-> [DarcsFlag] -> Tree IO -> Tree IO -> [FilePath] -> FilePath
-> IO ()
moveToDir repository opts cur work moved finaldir = do
let movetargets = map ((finaldir </>) . takeFileName) moved
moves = zip moved movetargets
doMoves repository opts cur work moves
unless (Quiet `elem` opts) $
putStrLn $ unwords $ ["Moved:"] ++ moved ++ ["to:", finaldir]
doMoves :: (RepoPatch p, ApplyState p ~ Tree) => Repository p wR wU wT
-> [DarcsFlag] -> Tree IO -> Tree IO
-> [(FilePath, FilePath)] -> IO ()
doMoves repository opts cur work moves = do
patches <- forM moves $ \(old, new) -> do
prePatch <- generatePreMovePatches opts cur work (old,new)
return (prePatch, old, new)
withSignalsBlocked $ do
forM_ patches $ \(prePatch, old, new) -> do
let -- Add any pre patches before the move patch
pendingDiff = joinGap (+>+)
(fromMaybe (emptyGap NilFL) prePatch)
(freeGap $ Darcs.Patch.move old new :>: NilFL)
addPendingDiffToPending repository YesUpdateWorking pendingDiff
moveFileOrDir work old new
updateIndex repository
-- Take the recorded/ working trees and the old and intended new filenames;
-- check if the new path is safe on windows. We potentially need to create
-- extra patches that are required to keep the repository consistent, in order
-- to allow the move patch to be applied.
generatePreMovePatches :: PrimPatch prim => [DarcsFlag] -> Tree IO -> Tree IO
-> (FilePath, FilePath)
-> IO (Maybe (FreeLeft (FL prim)))
generatePreMovePatches opts cur work (old,new) = do
-- Only allow Windows-invalid paths if we've been told to do so
unless newIsOkWindowsPath $ fail newNotOkWindowsPathMsg
-- Check if the first directory above the new path is in the repo (this
-- is the new path if itself is a directory), handling the case where
-- a user moves a file into a directory not known by darcs.
let dirPath = fn2fp $ superName $ fp2fn new
haveNewParent <- treeHasDir cur dirPath
unless haveNewParent $
fail $ "The target directory " ++ dirPath
++ " isn't known in the repository, did you forget to add it?"
newInRecorded <- hasNew cur
newInWorking <- hasNew work
oldInWorking <- treeHas work old
if oldInWorking -- We need to move the object
then do
-- We can't move if the target already exists in working
when newInWorking $ fail $ alreadyExists "working directory"
if newInRecorded
then Just <$> deleteNewFromRepoPatches
else return Nothing
else do
unless (Quiet `elem` opts) $
putStrLn "Detected post-hoc move."
-- Post-hoc move - user has moved/deleted the file in working, so
-- we can hopefully make a move patch to make the repository
-- consistent.
-- If we don't have the old or new in working, we're stuck
unless newInWorking $
fail $ "Cannot determine post-hoc move target, "
++ "no file/dir named:\n" ++ new
Just <$> if newInRecorded
then deleteNewFromRepoPatches
else return $ emptyGap NilFL
where
newIsOkWindowsPath =
doAllowWindowsReserved opts || WindowsFilePath.isValid new
newNotOkWindowsPathMsg =
"The filename " ++ new ++ " is not valid under Windows.\n"
++ "Use --reserved-ok to allow such filenames."
-- If we're moving to a file/dir that was recorded, but has been deleted,
-- we need to add patches to pending that remove the original.
deleteNewFromRepoPatches = do
unless (Quiet `elem` opts) $
putStrLn $ "Existing recorded contents of " ++ new
++ " will be overwritten."
ftf <- filetypeFunction
let curNoNew = modifyTree cur (floatPath new) Nothing
-- Return patches to remove new, so that the move patch
-- can move onto new
treeDiff MyersDiff ftf cur curNoNew
-- Check if the passed tree has the new filepath. The old path is removed
-- from the tree before checking if the new path is present.
hasNew s = treeHas_case (modifyTree s (floatPath old) Nothing) new
treeHas_case = if doAllowCaseOnly opts then treeHas else treeHasAnycase
alreadyExists inWhat =
if doAllowCaseOnly opts
then "A file or dir named "++new++" already exists in "
++ inWhat ++ "."
else "A file or dir named "++new++" (or perhaps differing "
++ "only in case)\nalready exists in "++ inWhat ++ ".\n"
++ "Use --case-ok to allow files differing only in case."
moveFileOrDir :: Tree IO -> FilePath -> FilePath -> IO ()
moveFileOrDir work old new = do
has_file <- treeHasFile work old
has_dir <- treeHasDir work old
when has_file $ do debugMessage $ unwords ["renameFile",old,new]
renameFile old new
when has_dir $ do debugMessage $ unwords ["renameDirectory",old,new]
renameDirectory old new
mv :: DarcsCommand [DarcsFlag]
mv = commandAlias "mv" Nothing move
| DavidAlphaFox/darcs | src/Darcs/UI/Commands/Move.hs | gpl-2.0 | 15,292 | 0 | 22 | 4,014 | 3,612 | 1,908 | 1,704 | 291 | 13 |
module Playlist where
import Control.Monad.Trans.State
import Data.List
import System.FilePath as F
type Song = F.FilePath
data Ext = M3u | Pls | Wpl | Xspf | Other deriving Eq
--A playlist is basically its location and a list of its songs
data Playlist = Pl {getPath :: F.FilePath,
getSongs :: [Song]} deriving (Eq, Show)
emptyP :: Playlist -> Bool
emptyP pl = null $ getSongs pl
--Current playlist will be the state
type PlState = StateT Playlist IO
addS :: Song -> PlState ()
addS s = do pl <- get
let songs = getSongs pl
put $ pl {getSongs = songs ++ [s]}
rmS :: Song -> PlState ()
rmS s = do pl <- get
let songs = getSongs pl
put $ pl {getSongs = filter (/=s) songs}
getExt :: F.FilePath -> Ext
getExt fp = case filter (/= ' ') (F.takeExtension fp) of
".m3u" -> M3u
".m3u8" -> M3u
".pls" -> Pls
".wpl" -> Wpl
".xspf" -> Xspf
_ -> Other
| fcostantini/PlEb | src/Playlist.hs | gpl-3.0 | 1,009 | 0 | 11 | 332 | 331 | 179 | 152 | 27 | 6 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{- | This module contains definitions for asynchronous actions that can be
performed by worker threads outside the scope of the HTTP request/response
cycle.
It uses the database as a queue, which isn't ideal but should be fine for
our low volume of messages. It uses the @immortal-queue@ package to expose
a queue consumer with a pool of worker threads.
-}
module Workers
( taskQueueConfig
, Task(..)
, AvalaraTask(..)
, enqueueTask
) where
import Control.Concurrent (threadDelay)
import Control.Concurrent.Async (wait)
import Control.Concurrent.STM (TVar, atomically, readTVar, writeTVar)
import Control.Exception.Safe (Exception(..), throwM)
import Control.Immortal.Queue (ImmortalQueue(..))
import Control.Monad (when)
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader (runReaderT, asks, lift)
import Control.Monad.Trans.Control (MonadBaseControl)
import Data.Aeson (ToJSON(toJSON), FromJSON, Result(..), fromJSON)
import Data.Foldable (asum)
import Data.Maybe (listToMaybe)
import Data.Monoid ((<>))
import Data.Scientific (Scientific)
import Data.Time
( UTCTime, TimeZone, Day, LocalTime(..), getCurrentTime, getCurrentTimeZone
, addUTCTime, utcToLocalTime, localTimeToUTC, fromGregorian, toGregorian
, midnight, addDays
)
import Database.Persist.Sql
( (=.), (==.), (<=.), (<.), (<-.), Entity(..), SelectOpt(..), ToBackendKey
, SqlBackend, SqlPersistT, runSqlPool, selectList, selectFirst, delete
, insert_, fromSqlKey, deleteWhere, deleteCascadeWhere, update, get
)
import GHC.Generics (Generic)
import Numeric.Natural (Natural)
import Avalara
( RefundTransactionRequest(..), VoidTransactionRequest(..), VoidReason(..)
, CommitTransactionRequest(..)
)
import Cache (Caches(..), SalesReports(..), SalesData(..))
import Config (Config(..), AvalaraStatus(AvalaraTesting), timedLogStr)
import Emails (EmailType, getEmailData)
import Images (makeImageConfig, scaleExistingImage, optimizeImage)
import Models
import Models.PersistJSON (JSONValue(..))
import Models.Fields (AvalaraTransactionCode(..), Cents(..))
import Routes.AvalaraUtils (createAvalaraTransaction)
import Server (avalaraRequest)
import qualified Avalara
import qualified Data.Text as T
import qualified Database.Esqueleto as E
import qualified Emails
-- | The possible tasks our async worker queue can process.
data Task
= OptimizeImage
FilePath
-- ^ FilePath
FilePath
-- ^ Destination Directory
| SendEmail EmailType
| CleanDatabase
| Avalara AvalaraTask
| UpdateSalesCache OrderId
-- ^ Record a new Order in the SalesReports Cache
| AddSalesReportDay
-- ^ Add today to the SalesReports Cache if it does not exist
| RemoveSoldOutProducts OrderId
-- ^ Remove any products in the Order from Carts if they are now sold
-- out.
deriving (Show, Generic, Eq)
instance FromJSON Task
instance ToJSON Task
data AvalaraTask
= RefundTransaction AvalaraTransactionCode Avalara.RefundType (Maybe Scientific)
-- ^ Refund the Transction with given RefundType and an optional
-- Percentage.
| CreateTransaction OrderId
-- ^ Create a Transaction for the Order, marking the Tax as included in
-- the order total.
| CommitTransaction Avalara.Transaction
-- ^ Commit an existing transaction.
| VoidTransaction Avalara.Transaction
-- ^ Void/delete a Transaction that was made but whose payment
-- processing failed.
deriving (Show, Generic, Eq)
instance FromJSON AvalaraTask
instance ToJSON AvalaraTask
data AvalaraError
= RequestFailed (Avalara.WithError Avalara.Transaction)
| TransactionCreationFailed
| NoTransactionCode
| OrderNotFound
deriving (Show)
instance Exception AvalaraError
-- | Enqueue a Task to be run asynchronously. An optional run time can be
-- passed, otherwise it will execute immediately.
enqueueTask :: MonadIO m => Maybe UTCTime -> Task -> SqlPersistT m ()
enqueueTask runAt task = do
time <- liftIO getCurrentTime
insert_ Job
{ jobAction = JSONValue $ toJSON task
, jobQueuedAt = time
, jobRunAt = runAt
, jobRetries = 0
}
-- | Process a queue of Jobs by querying the database and sending any due
-- jobs to worker threads.
taskQueueConfig :: Natural -> Config -> ImmortalQueue (Entity Job)
taskQueueConfig threadCount cfg@Config { getPool, getServerLogger, getCaches } =
ImmortalQueue
{ qThreadCount = threadCount
, qPollWorkerTime = 1000
, qPop = getNextItem
, qPush = runSql . insert_ . entityVal
, qHandler = performTask
, qFailure = handleError
}
where
runSql :: MonadBaseControl IO m => SqlPersistT m a -> m a
runSql = flip runSqlPool getPool
-- Grab the next item from Job table, preferring the jobs that have
-- passed their scheduled run time. When a job is found, remove it from
-- the database. If there are no jobs, wait 5 seconds before trying
-- again.
getNextItem :: IO (Entity Job)
getNextItem = do
currentTime <- getCurrentTime
maybeJob <- runSql $
(asum <$> sequence
[ selectFirst [JobRunAt <=. Just currentTime]
[Asc JobRunAt]
, selectFirst [JobRunAt ==. Nothing]
[Asc JobQueuedAt]
]) >>=
maybe (return Nothing)
(\e -> delete (entityKey e) >> return (Just e))
case maybeJob of
Nothing ->
threadDelay (5 * 1000000) >> getNextItem
Just a ->
return a
-- When an error occurs, log a message & re-add the job to the database.
handleError :: Exception e => Entity Job -> e -> IO ()
handleError (Entity _ job) e = case fromJSON (fromJSONValue $ jobAction job) of
Error err -> do
requeueJob job 3600
logMsg $
"Cannot Decode Worker Job: " <> T.pack err
Success action -> do
when (jobRetries job <= 5) $
requeueJob job 150
logMsg $
"Worker Job Failed: " <> describeTask action
<> " - " <> T.pack (displayException e)
-- Re add a job to the databse in the given amount of seconds.
requeueJob :: Job -> Integer -> IO ()
requeueJob job postponeSeconds = do
currentTime <- getCurrentTime
let reRunAt = addUTCTime (fromInteger postponeSeconds) currentTime
runSql $ insert_ job
{ jobRetries = jobRetries job + 1
, jobRunAt = Just reRunAt
}
-- Log a message to the server log.
logMsg :: T.Text -> IO ()
logMsg =
getServerLogger . timedLogStr
-- Describe the task for a log message.
describeTask :: Task -> T.Text
describeTask = \case
OptimizeImage filePath _ ->
"Optimize " <> T.pack filePath
SendEmail emailType -> case emailType of
Emails.AccountCreated cId ->
"Customer #" <> showSqlKey cId <> " Created Account Email"
Emails.PasswordReset cId _ ->
"Customer #" <> showSqlKey cId <> " Requested Password Reset Email"
Emails.PasswordResetSuccess cId ->
"Customer #" <> showSqlKey cId <> " Password Reset Succeeded Email"
Emails.OrderPlaced oId ->
"Order #" <> showSqlKey oId <> " Placed Email"
CleanDatabase ->
"Clean Database"
Avalara (RefundTransaction code type_ amount) ->
"Refund Avalara Transaction ("
<> T.pack (show code) <> "; " <> T.pack (show type_) <> "; "
<> T.pack (show amount) <> ")"
Avalara (CreateTransaction orderId) ->
"Create Avalara Transaction for Order #" <> showSqlKey orderId
Avalara (CommitTransaction trans) ->
"Commit Avalara Transaction " <> T.pack (show $ Avalara.tCode trans)
Avalara (VoidTransaction trans) ->
"Void Avalara Transaction " <> T.pack (show $ Avalara.tCode trans)
UpdateSalesCache orderId ->
"Update Sales Reports Cache with Order #" <> showSqlKey orderId
AddSalesReportDay ->
"Add Sales Report Day"
RemoveSoldOutProducts orderId ->
"Remove Sold Out Products in Order #" <> showSqlKey orderId <> " From Carts"
showSqlKey :: (ToBackendKey SqlBackend a) => Key a -> T.Text
showSqlKey =
T.pack . show . fromSqlKey
-- Perform the action specified by the job, throwing an error if we
-- cannot decode the Task.
performTask :: Entity Job -> IO ()
performTask (Entity _ job) =
case fromJSON (fromJSONValue $ jobAction job) of
Error decodingError ->
error decodingError
Success (OptimizeImage filePath destinationDirectory) -> do
imgCfg <- makeImageConfig
optimizeImage imgCfg filePath
scaleExistingImage imgCfg filePath destinationDirectory
Success (SendEmail emailType) ->
runSql (getEmailData emailType) >>= \case
Left err ->
error $ T.unpack err
Right emailData ->
Emails.sendWithRetries cfg emailData >>= wait
Success CleanDatabase ->
runSql cleanDatabase
Success (Avalara task) ->
performAvalaraTask task
Success (UpdateSalesCache orderId) ->
runSql $ updateSalesCache getCaches orderId
Success AddSalesReportDay ->
runSql $ addNewReportDate getCaches
Success (RemoveSoldOutProducts orderId) ->
runSql $ removeSoldOutVariants orderId
-- Perform an Avalara-specific action.
performAvalaraTask :: AvalaraTask -> IO ()
performAvalaraTask = \case
RefundTransaction code refundType refundPercent -> do
date <- getCurrentTime
let request =
RefundTransactionRequest
{ rtrTransctionCode = Nothing
, rtrDate = date
, rtrType = refundType
, rtrPercentage = refundPercent
, rtrLines = []
, rtrReferenceCode = Nothing
}
(AvalaraTransactionCode companyCode transctionCode) = code
runReaderT (avalaraRequest $ Avalara.refundTransaction companyCode transctionCode request) cfg >>= \case
Avalara.SuccessfulResponse _ ->
return ()
e ->
throwM $ RequestFailed e
CreateTransaction orderId -> flip runReaderT cfg $ do
result <- fmap listToMaybe . runSql $ E.select $ E.from
$ \(o `E.InnerJoin` sa `E.LeftOuterJoin` ba `E.InnerJoin` c) -> do
E.on $ c E.^. CustomerId E.==. o E.^. OrderCustomerId
E.on $ o E.^. OrderBillingAddressId E.==. ba E.?. AddressId
E.on $ o E.^. OrderShippingAddressId E.==. sa E.^. AddressId
E.where_ $ o E.^. OrderId E.==. E.val orderId
return (o, sa, ba, c)
case result of
Nothing ->
throwM OrderNotFound
Just (o, sa, ba, c) -> runSql $
createAvalaraTransaction o sa ba c True >>= \case
Nothing ->
throwM TransactionCreationFailed
Just transaction -> do
when (getAvalaraStatus cfg == AvalaraTesting) $
enqueueTask Nothing . Avalara
$ VoidTransaction transaction
companyCode <- lift $ asks getAvalaraCompanyCode
update orderId
[ OrderAvalaraTransactionCode =.
AvalaraTransactionCode companyCode
<$> Avalara.tCode transaction
]
CommitTransaction transaction -> do
let companyCode = getAvalaraCompanyCode cfg
transactionCode <- case Avalara.tCode transaction of
Nothing ->
throwM NoTransactionCode
Just tCode ->
return tCode
let request = Avalara.commitTransaction companyCode transactionCode
$ CommitTransactionRequest { ctsrCommit = True }
runReaderT (avalaraRequest request) cfg >>= \case
Avalara.SuccessfulResponse _ ->
return ()
e ->
throwM $ RequestFailed e
VoidTransaction transaction -> do
let companyCode = getAvalaraCompanyCode cfg
transactionCode <- case Avalara.tCode transaction of
Nothing ->
throwM NoTransactionCode
Just tCode ->
return tCode
let request =
Avalara.voidTransaction companyCode transactionCode
$ VoidTransactionRequest { vtrCode = DocDeleted }
runReaderT (avalaraRequest request) cfg >>= \case
Avalara.SuccessfulResponse _ ->
return ()
e ->
throwM $ RequestFailed e
-- | Remove Expired Carts & PasswordResets, Deactivate Expired Coupons.
cleanDatabase :: SqlPersistT IO ()
cleanDatabase = do
currentTime <- lift getCurrentTime
deleteWhere [PasswordResetExpirationTime <. currentTime]
deleteCascadeWhere [CartExpirationTime <. Just currentTime]
deactivateCoupons currentTime
enqueueTask (Just $ addUTCTime 3600 currentTime) CleanDatabase
where
-- De-activate coupons whose expiration date has passed and coupons
-- that have reached their maximum number of uses.
deactivateCoupons :: UTCTime -> SqlPersistT IO ()
deactivateCoupons currentTime =
E.update $ \c -> do
E.set c [ CouponIsActive E.=. E.val False ]
let orderCount = E.sub_select $ E.from $ \o -> do
E.where_ $ o E.^. OrderCouponId E.==. E.just (c E.^. CouponId)
return E.countRows
E.where_ $
(orderCount E.>=. c E.^. CouponTotalUses E.&&. c E.^. CouponTotalUses E.!=. E.val 0)
E.||. E.val currentTime E.>. c E.^. CouponExpirationDate
-- | Remove Cart Items for sold-out variants from the order.
removeSoldOutVariants :: OrderId -> SqlPersistT IO ()
removeSoldOutVariants orderId = do
soldOut <- E.select $ E.from $ \(op `E.InnerJoin` pv) -> do
E.on $ pv E.^. ProductVariantId E.==. op E.^. OrderProductProductVariantId
E.where_ $ pv E.^. ProductVariantQuantity E.<=. E.val 0
E.&&. op E.^. OrderProductOrderId E.==. E.val orderId
return pv
deleteWhere [CartItemProductVariantId <-. map entityKey soldOut]
-- | Add the given Order's total to the Daily & Monthly sales caches.
--
-- Adds a new SalesData if there is no SalesData for the Order's time
-- period.
updateSalesCache :: TVar Caches -> OrderId -> SqlPersistT IO ()
updateSalesCache cacheTVar orderId = do
mOrderDate <- fmap orderCreatedAt <$> get orderId
orderTotal <- getOrderTotal
<$> (map entityVal <$> selectList [OrderLineItemOrderId ==. orderId] [])
<*> (map entityVal <$> selectList [OrderProductOrderId ==. orderId] [])
zone <- liftIO getCurrentTimeZone
case mOrderDate of
Nothing ->
error "Could not fetch Order & date."
Just orderDate ->
lift . atomically $ do
cache <- readTVar cacheTVar
writeTVar cacheTVar $ cache
{ getSalesReportCache =
updateSalesReports (getSalesReportCache cache) zone orderDate
(updateReport orderTotal orderDate)
}
where
updateReport :: Cents -> UTCTime -> [SalesData] -> SalesData -> [SalesData]
updateReport total date sales newReport =
case sales of
[] ->
[ newReport { sdTotal = total } ]
[sale] ->
if sdDay newReport == sdDay sale then
[ sale { sdTotal = total + sdTotal sale } ]
else
[ sale, newReport { sdTotal = total + sdTotal sale } ]
sale : nextSale : rest ->
if date >= sdDay sale && date < sdDay nextSale then
sale { sdTotal = total + sdTotal sale } : rest
else
sale : updateReport total date (nextSale : rest) newReport
-- | Add a new SalesData entry for today to the SalesReports cache.
--
-- Does nothing if the entries already exist.
addNewReportDate :: TVar Caches -> SqlPersistT IO ()
addNewReportDate cacheTVar = do
today <- liftIO getCurrentTime
zone <- liftIO getCurrentTimeZone
lift . atomically $ do
cache <- readTVar cacheTVar
writeTVar cacheTVar $ cache
{ getSalesReportCache =
updateSalesReports (getSalesReportCache cache) zone today updateReport
}
enqueueTask (Just $ tomorrow zone today) AddSalesReportDay
where
tomorrow :: TimeZone -> UTCTime -> UTCTime
tomorrow zone today =
let day = localDay $ utcToLocalTime zone today
in
toTime zone $ addDays 1 day
updateReport :: [SalesData] -> SalesData -> [SalesData]
updateReport sales newReport =
if sdDay newReport `notElem` map sdDay sales then
drop 1 sales ++ [newReport]
else
sales
-- | Update the Monthly & Daily sales reports using a generic updater
-- function. The function is passed the reports and a Zero-total SalesData
-- corresponding to the passed UTCTime.
--
-- The length of the daily report will be limited to 31 items and the
-- monthly limited to 12 items.
updateSalesReports
:: SalesReports -> TimeZone -> UTCTime -> ([SalesData] -> SalesData -> [SalesData]) -> SalesReports
updateSalesReports reports zone reportDate reportUpdater =
reports
{ srDailySales =
limitLength 31 $ reportUpdater (srDailySales reports) dailyReport
, srMonthlySales =
limitLength 12 $ reportUpdater (srMonthlySales reports) monthlyReport
}
where
limitLength :: Int -> [a] -> [a]
limitLength maxLength items =
if length items > maxLength then
drop (length items - maxLength) items
else
items
-- Build a Daily SalesData item for the given date, starting at
-- midnight of the day, local time.
dailyReport :: SalesData
dailyReport =
let day = localDay $ utcToLocalTime zone reportDate
in
SalesData
{ sdDay = toTime zone day
, sdTotal = 0
}
-- Build a Monthly SalesData item for the given date, starting at the
-- first of the month, local time.
monthlyReport :: SalesData
monthlyReport =
let day = localDay $ utcToLocalTime zone reportDate
startOfMonth =
(\(y, m, _) -> fromGregorian y m 1) $ toGregorian day
in
SalesData
{ sdDay = toTime zone startOfMonth
, sdTotal = 0
}
-- Convert a Day to a UTCTime representing midnight in the local timezone.
toTime :: TimeZone -> Day -> UTCTime
toTime zone day =
localTimeToUTC zone $ LocalTime day midnight
| Southern-Exposure-Seed-Exchange/southernexposure.com | server/src/Workers.hs | gpl-3.0 | 19,987 | 0 | 28 | 6,314 | 4,358 | 2,261 | 2,097 | 372 | 33 |
module Game.Setup(setupGame) where
import Data.IORef
import qualified Linear as L
import Model.Camera
import Model.ClearColor
import Model.Entity
import Model.GameState
import Model.InputState
import Model.Light
import Model.Object
import Model.Types
import Model.World
setupGame :: IO InitialState
setupGame = do
w <- world
return (w, unloadedObjects, unloadedEntities)
world :: IO World
world = do
isIO <- newIORef inputState
return (gameState, isIO)
inputState :: InputState
inputState =
InputState { isKeyboardInput = []
, isMouseInput = MouseInput 0 0
}
gameState :: GameState
gameState =
GameState { gsCamera = camera
, gsObjects = [] -- to be loaded
, gsLights = lights
, gsClearColor = clearColor
, gsAmbiance = 0.1
, gsShaderPrograms = undefined -- overwritten later...
}
where camera = Camera (L.V3 0 0 0) 0 0 (pi/2)
lights = map snd lamps
clearColor = defaultClearColor
unloadedObjects :: UnloadedObjects
unloadedObjects =
map fst lamps ++
boxes
unloadedEntities :: UnloadedEntities
unloadedEntities =
[ EntityUnloaded { euUniqueName = "box2"
, euRelativePos = L.V3 0 0 0
, euRelativeRot = L.V3 0 0 0
, euScale = L.V3 1 1 1
, euAmbOverride = Nothing
, euGeometryName = "box2"
, euMaterialName = "placeholder"
}
, EntityUnloaded { euUniqueName = "hexagon_white"
, euRelativePos = L.V3 0 0 0
, euRelativeRot = L.V3 0 0 0
, euScale = L.V3 1 1 1
, euAmbOverride = Nothing
, euGeometryName = "hexagon"
, euMaterialName = "white"
}
, EntityUnloaded { euUniqueName = "hexagon_gray"
, euRelativePos = L.V3 0 0 0
, euRelativeRot = L.V3 0 0 0
, euScale = L.V3 1 1 1
, euAmbOverride = Nothing
, euGeometryName = "hexagon"
, euMaterialName = "gray"
}
, EntityUnloaded { euUniqueName = "light_box"
, euRelativePos = L.V3 0 0 0
, euRelativeRot = L.V3 0 0 0
, euScale = L.V3 1 1 1
, euAmbOverride = Just 1 -- fullbright
, euGeometryName = "box2"
, euMaterialName = "white"
}
]
lamps :: [(ObjectUnloaded, PointLight)]
lamps = [ createLamp (L.V3 (-1) 3 (-1)) (L.V3 0 0 0) (L.V3 0.01 0.01 0.01) "light_box" (L.V3 0.8 0.8 0.8)
, createLamp (L.V3 2 4 4) (L.V3 0 0 0) (L.V3 0.01 0.01 0.01) "light_box" (L.V3 0.8 0.8 0.8)
]
createLamp :: Translation -> Rotation -> Scale -> String -> ColorRGB -> (ObjectUnloaded, PointLight)
createLamp pos rot scale entName clr =
( ObjectUnloaded pos rot scale [entName],
PointLight pos 0 clr Nothing
)
boxes :: [ObjectUnloaded]
boxes = [ createBox (L.V3 0 0 0) zeroRot spacingScale "hexagon_white"
, createBox (L.V3 (1*0.5*hexLength) 0 (1*0.75*hexWidth)) zeroRot spacingScale "hexagon_white"
, createBox (L.V3 (-1*0.5*hexLength) 0 (1*0.75*hexWidth)) zeroRot spacingScale "hexagon_white"
, createBox (L.V3 (1*0.5*hexLength) 0 (-1*0.75*hexWidth)) zeroRot spacingScale "hexagon_white"
, createBox (L.V3 (-1*0.5*hexLength) 0 (-1*0.75*hexWidth)) zeroRot spacingScale "hexagon_white"
, createBox (L.V3 (2*0.5*hexLength) 0 (2*0.75*hexWidth)) zeroRot spacingScale "hexagon_white"
, createBox (L.V3 (2*0.5*hexLength) 0 (-2*0.75*hexWidth)) zeroRot spacingScaleTall "hexagon_gray"
]
where zeroRot = L.V3 0 0 0
oneScale = L.V3 1 1 1
spacingScale = L.V3 (1.0-spacing) 1.0 (1.0-spacing)
spacingScaleTall = L.V3 (1.0-spacing) 2.0 (1.0-spacing)
createBox :: Translation -> Rotation -> Scale -> String -> ObjectUnloaded
createBox pos rot scale entName =
ObjectUnloaded pos rot scale [entName]
hexWidth, hexLength, spacing :: GLfloat
hexLength = 0.87
hexWidth = 1
spacing = 0.1
| halvorgb/AO2D | src/Game/Setup.hs | gpl-3.0 | 4,384 | 0 | 12 | 1,517 | 1,306 | 718 | 588 | 95 | 1 |
module Handler.ScreenCaptureDetections (
postScreenCaptureDetectionsR) where
import Data.Aeson
import Handler.Extension
import Import
import Model.Device
import Model.PushNotification
data POSTRequest = POSTRequest ByteString Text
instance FromJSON POSTRequest where
parseJSON = withObject "post screen capture notification request" $ \o ->
POSTRequest
<$> o .: "recipientKeyFingerprint"
<*> o .: "recordingUID"
postScreenCaptureDetectionsR :: Handler Value
postScreenCaptureDetectionsR = do
(POSTRequest keyFingerprint recordingUID) <- requireJsonBody
(detection', devicesAndUnseenCounts') <- runDB $ do
detection <- insertUnique (ScreenCaptureDetection keyFingerprint recordingUID)
devicesAndUnseenCounts <- buildDeviceUnseenCounts keyFingerprint
return (detection, devicesAndUnseenCounts)
when (isNothing detection')
$ $(logWarn) "Failed to insert screen capture detection, it probably already exists?"
sequence_ $ flip map devicesAndUnseenCounts' $ \(device, unseenCount) ->
forkAndSendPushNotificationI MsgScreenCaptureDetected (max 1 unseenCount) device
sendResponseStatus status201 emptyResponse
| rumuki/rumuki-server | src/Handler/ScreenCaptureDetections.hs | gpl-3.0 | 1,207 | 0 | 14 | 213 | 244 | 123 | 121 | -1 | -1 |
{- Chapter 2
-}
-- What is the difference between -> and <-?
removeNonUppercase :: [Char] -> [Char]
removeNonUppercase st = [s | s <- st, elem s ['A'..'Z']]
addThree :: Int -> Int -> Int -> Int
addThree x y z = x + y + z
-- The difference between Integer and Int is that Integer has BIG numbers...
factorial :: Integer -> Integer
factorial n = product [1..n]
-- OK.. The difference between Float and Double is that Float is a real floating
-- point has single point precision but Double has double.. (?!)
circumference :: Float -> Float
-- circumference :: Double -> Double
circumference r = 2 * pi * r
-- show is a function that takes a parameter that is of typeclass Show and
-- return it in String
--show 3
--show 5.334
-- read is a function that takes a String and returns a Read typeclass
| medik/lang-hack | Haskell/LearnYouAHaskell/c02/chapter2.hs | gpl-3.0 | 800 | 0 | 8 | 160 | 147 | 82 | 65 | 8 | 1 |
module Fathens.Bitcoin.Wallet.Address (
Prefix_(isTestnet)
, Prefix(..)
, isCompressing
, findBySymbol
, getPayload
, appendPayload
) where
import Control.Applicative
import Control.Monad
import Data.ByteString.Lazy (ByteString)
import qualified Data.ByteString.Lazy as BS
import Data.List
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as T
import Fathens.Bitcoin.Binary.Base58
-- Data
data Prefix
= PrefixP2PKH Bool
| PrefixP2SH Bool
| PrefixPRV Bool
| PrefixCPRV Bool
| PrefixXPUB Bool
| PrefixXPRV Bool
deriving (Show, Eq)
instance Prefix_ Prefix where
isTestnet (PrefixP2PKH b) = b
isTestnet (PrefixP2SH b) = b
isTestnet (PrefixPRV b) = b
isTestnet (PrefixCPRV b) = b
isTestnet (PrefixXPUB b) = b
isTestnet (PrefixXPRV b) = b
symbols p@(PrefixP2PKH _) | isTestnet p = ["m", "n"]
| otherwise = ["1"]
symbols p@(PrefixP2SH _) | isTestnet p = ["2"]
| otherwise = ["3"]
symbols p@(PrefixPRV _) | isTestnet p = ["9"]
| otherwise = ["5"]
symbols p@(PrefixCPRV _) | isTestnet p = ["c"]
| otherwise = ["K", "L"]
symbols p@(PrefixXPUB _) | isTestnet p = ["tpub"]
| otherwise = ["xpub"]
symbols p@(PrefixXPRV _) | isTestnet p = ["tprv"]
| otherwise = ["xprv"]
prefix p@(PrefixP2PKH _) | isTestnet p = BS.singleton 0x6f
| otherwise = BS.singleton 0x00
prefix p@(PrefixP2SH _) | isTestnet p = BS.singleton 0xc4
| otherwise = BS.singleton 0x05
prefix p@(PrefixPRV _) | isTestnet p = BS.singleton 0xef
| otherwise = BS.singleton 0x80
prefix p@(PrefixCPRV _) | isTestnet p = BS.singleton 0xef
| otherwise = BS.singleton 0x80
prefix p@(PrefixXPUB _) | isTestnet p = BS.pack [0x04, 0x35, 0x87, 0xcf]
| otherwise = BS.pack [0x04, 0x88, 0xb2, 0x1e]
prefix p@(PrefixXPRV _) | isTestnet p = BS.pack [0x04, 0x35, 0x83, 0x94]
| otherwise = BS.pack [0x04, 0x88, 0xad, 0xe4]
suffix (PrefixCPRV b) = BS.singleton 0x01
suffix _ = BS.empty
-- Classes
class Prefix_ a where
isTestnet :: a -> Bool
symbols :: a -> [String]
prefix :: a -> ByteString
suffix :: a -> ByteString
-- Functions
isCompressing :: Prefix -> Maybe Bool
isCompressing (PrefixPRV _) = Just False
isCompressing (PrefixCPRV _) = Just True
isCompressing _ = Nothing
findBySymbol :: [Bool -> Prefix] -> Base58 -> Maybe Prefix
findBySymbol s b = find (flip isMatchSymbol t) pres
where
t = base58Text b
pres = s <*> [True, False]
getPayload :: Prefix_ a => a -> ByteString -> Maybe ByteString
getPayload p src = do
guard $ isMatchPayload p src
return $ BS.take net $ BS.drop lenP src
where
lenP = BS.length $ prefix p
lenS = BS.length $ suffix p
net = BS.length src - lenP - lenS
appendPayload :: Prefix_ a => a -> ByteString -> ByteString
appendPayload p src = BS.concat [prefix p, src, suffix p]
-- Utilities
isMatchSymbol :: Prefix_ a => a -> Text -> Bool
isMatchSymbol p t = any isPrefix pres
where
isPrefix = flip T.isPrefixOf t
pres = map T.pack $ symbols p
isMatchPayload :: Prefix_ a => a -> ByteString -> Bool
isMatchPayload p s = isPre && isSuf
where
isPre = BS.isPrefixOf (prefix p) s
isSuf = BS.isSuffixOf (suffix p) s
| sawatani/bitcoin-hall | src/Fathens/Bitcoin/Wallet/Address.hs | gpl-3.0 | 3,573 | 0 | 10 | 1,079 | 1,315 | 670 | 645 | 88 | 1 |
----------------------------------------------------------------------
-- |
-- Module : Text.Bib.Reader.BibTeX
-- Copyright : 2015-2017 Mathias Schenner,
-- 2015-2016 Language Science Press.
-- License : GPL-3
--
-- Maintainer : mschenner.dev@gmail.com
-- Stability : experimental
-- Portability : GHC
--
-- Main internal interface to BibTeX parser.
--
-- The BibTeX parser is organized in three layers:
--
-- * layer 1 (Structure): parse entry structure and interpret \@string macros,
-- * layer 2 (Reference): interpret reference entries as BibDB types,
-- * layer 3 (Inheritance): resolve crossreferences and inherited data.
----------------------------------------------------------------------
module Text.Bib.Reader.BibTeX
( -- * Parser
fromBibTeX
, fromBibTeXFile
) where
import Data.Text (Text)
import qualified Data.Text.IO as T
import Text.Bib.Types (BibDB)
import Text.Bib.Filter (normalizeBibLaTeX)
import Text.Bib.Reader.BibTeX.Structure (parseBibTeX)
import Text.Bib.Reader.BibTeX.Reference (parseBib)
import Text.Bib.Reader.BibTeX.Inheritance (resolve)
-- | Parse bibliographic entries from BibTeX file.
fromBibTeXFile :: String -> FilePath -> IO (Either String BibDB)
fromBibTeXFile label filename = fromBibTeX label `fmap` T.readFile filename
-- | Parse bibliographic entries from BibTeX file content.
fromBibTeX :: String -> Text -> Either String BibDB
fromBibTeX label text = case parseBibTeX label text of
Left err -> Left (show err)
Right db -> return (normalizeBibLaTeX (resolve (parseBib db)))
| synsem/texhs | src/Text/Bib/Reader/BibTeX.hs | gpl-3.0 | 1,572 | 0 | 14 | 245 | 251 | 151 | 100 | 17 | 2 |
module Cortex.Miranda.GrandMonadStack
( GrandMonadStack
, LesserMonadStack
) where
-- Functional dependencies with multiple monads of the same type (State monads
-- in this instance) suck big time. GHC wasn't able to compile the code, so
-- instead this ugly static monad stack is used.
import Control.Monad.State (StateT)
import Control.Monad.Error (ErrorT)
import Control.Concurrent.Lifted (MVar)
import Cortex.Miranda.ValueStorage (ValueStorage)
type LesserMonadStack = ErrorT String IO
-- First state holds storage location. Second one holds the timestamp of last
-- squash operation (time of an initiated operation, not a mirrored squash) and
-- the value storage.
type GrandMonadStack = StateT String (StateT (MVar String, MVar ValueStorage) LesserMonadStack)
| maarons/Cortex | Miranda/GrandMonadStack.hs | agpl-3.0 | 786 | 0 | 9 | 123 | 107 | 66 | 41 | 9 | 0 |
{-# LANGUAGE BangPatterns
, CPP
, FlexibleContexts
, FlexibleInstances
, GADTs
, MultiParamTypeClasses
, TypeFamilies
, TupleSections
, ScopedTypeVariables #-}
-- | Provides high level functions to define and apply filters on images.
--
-- Filters are operations on images on which the surrounding of each processed
-- pixel is considered according to a kernel.
--
-- Please use 'Vision.Image.Filter' if you only want to apply filter to images.
--
-- To apply a filter to an image, use the 'apply' method:
--
-- @
-- let -- Creates a filter which will blur the image. Uses a 'Double' as
-- -- accumulator of the Gaussian kernel.
-- filter :: 'Blur' GreyPixel Double GreyPixel
-- filter = 'gaussianBlur' 2 Nothing
-- in 'apply' filter img :: Grey
-- @
--
-- The @radius@ argument of some filters is used to determine the kernel size.
-- A radius as of 1 means a kernel of size 3, 2 a kernel of size 5 and so on.
--
-- The @acc@ type argument of some filters defines the type which will be used
-- to store the accumulated value of the kernel (e.g. by setting @acc@ to
-- 'Double' in the computation of a Gaussian blur, the kernel average will be
-- computed using a 'Double').
module Vision.Image.Filter.Internal (
-- * Types
Filterable (..), Filter (..)
, BoxFilter, BoxFilter1, SeparableFilter, SeparableFilter1
, KernelAnchor (..)
, Kernel (..)
, SeparableKernel (..), SeparatelyFiltrable (..)
, FilterFold (..), FilterFold1 (..)
, BorderInterpolate (..)
-- * Functions
, kernelAnchor, borderInterpolate
-- * Filters
-- ** Morphological operators
, Morphological, dilate, erode
-- ** Blur
, Blur, blur, gaussianBlur
-- ** Derivation
, Derivative, DerivativeType (..), scharr, sobel
-- ** Others
, Mean, mean
) where
#if __GLASGOW_HASKELL__ < 710
import Data.Word
#endif
import Data.List
import Data.Ratio
import Foreign.Storable (Storable)
import qualified Data.Vector.Storable as V
import Vision.Image.Class (MaskedImage (..), Image (..), FromFunction (..), (!))
import Vision.Image.Type (Manifest, Delayed)
import Vision.Primitive (Z (..), (:.) (..), DIM1, Point, Size, ix1, ix2)
-- Types -----------------------------------------------------------------------
-- | Provides an implementation to execute a type of filter.
--
-- 'src' is the original image, 'res' the resulting image and 'f' the filter.
class Filterable src res f where
-- | Applies the given filter on the given image.
apply :: f -> src -> res
data Filter src kernel init fold acc res = Filter {
fKernelSize :: !Size
, fKernelCenter :: !KernelAnchor
-- | See 'Kernel' and 'SeparableKernel'.
, fKernel :: !kernel
-- | Computes a constant value for each pixel before applying the kernel.
--
-- This value will be passed to 'fKernel' functions and to the 'fPost'
-- function.
-- For most filters, @fInit@ will be @\_ _ -> ()@.
, fInit :: !(Point -> src -> init)
-- | Defines how the accumulated value is initialized.
--
-- See 'FilterFold' and 'FilterFold1'.
, fFold :: !fold
-- | This function will be executed after the iteration of the kernel on a
-- given point.
--
-- Can be used to normalize the accumulated value, for example.
, fPost :: !(Point -> src -> init -> acc -> res)
, fInterpol :: !(BorderInterpolate src)
}
-- | 2D filters which are initialized with a value.
type BoxFilter src init acc res = Filter src (Kernel src init acc) init
(FilterFold acc) acc res
-- | 2D filters which are not initialized with a value.
type BoxFilter1 src init res = Filter src (Kernel src init src) init
FilterFold1 src res
-- | Separable 2D filters which are initialized with a value.
type SeparableFilter src init acc res = Filter src
(SeparableKernel src init acc)
init (FilterFold acc) acc res
-- | Separable 2D filters which are not initialized with a value.
type SeparableFilter1 src init res = Filter src
(SeparableKernel src init src)
init FilterFold1 src res
-- | Defines how the center of the kernel will be determined.
data KernelAnchor = KernelAnchor !Point | KernelAnchorCenter
-- | A simple 2D kernel.
--
-- The kernel function accepts the coordinates in the kernel, the value of the
-- pixel at these coordinates ('src'), the current accumulated value and returns
-- a new accumulated value.
--
-- Non-separable filters computational complexity grows quadratically according
-- to the size of the sides of the kernel.
newtype Kernel src init acc = Kernel (init -> Point -> src -> acc -> acc)
-- | Some kernels can be factorized in two uni-dimensional kernels (horizontal
-- and vertical).
--
-- Separable filters computational complexity grows linearly according to the
-- size of the sides of the kernel.
--
-- See <http://http://en.wikipedia.org/wiki/Separable_filter>.
data SeparableKernel src init acc = SeparableKernel {
-- | Vertical (column) kernel.
skVertical :: !(init -> DIM1 -> src -> acc -> acc)
-- | Horizontal (row) kernel.
, skHorizontal :: !(init -> DIM1 -> acc -> acc -> acc)
}
-- | Used to determine the type of the accumulator image used when computing
-- separable filters.
--
-- 'src' and 'res' are respectively the source and the result image types while
-- 'acc' is the pixel type of the accumulator.
class ( Image (SeparableFilterAccumulator src res acc)
, ImagePixel (SeparableFilterAccumulator src res acc) ~ acc
, FromFunction (SeparableFilterAccumulator src res acc)
, FromFunctionPixel (SeparableFilterAccumulator src res acc) ~ acc)
=> SeparatelyFiltrable src res acc where
type SeparableFilterAccumulator src res acc
instance Storable acc => SeparatelyFiltrable src (Manifest p) acc where
type SeparableFilterAccumulator src (Manifest p) acc = Manifest acc
instance Storable acc => SeparatelyFiltrable src (Delayed p) acc where
type SeparableFilterAccumulator src (Delayed p) acc = Delayed acc
-- | Uses the result of the provided function as the initial value of the
-- kernel's accumulator, depending on the center coordinates in the image.
--
-- For most filters, the function will always return the same value (i.e.
-- defined as @const 0@), but this kind of initialization could be required for
-- some filters.
data FilterFold acc = FilterFold (Point -> acc)
-- | Uses the first pixel in the kernel as initial value. The kernel must not be
-- empty and the accumulator type must be the same as the source pixel type.
--
-- This kind of initialization is needed by morphological filters.
data FilterFold1 = FilterFold1
-- | Defines how image boundaries are extrapolated by the algorithms.
--
-- '|' characters in examples are image borders.
data BorderInterpolate a =
-- | Replicates the first and last pixels of the image.
--
-- > aaaaaa|abcdefgh|hhhhhhh
BorderReplicate
-- | Reflects the border of the image.
--
-- > fedcba|abcdefgh|hgfedcb
| BorderReflect
-- | Considers that the last pixel of the image is before the first one.
--
-- > cdefgh|abcdefgh|abcdefg
| BorderWrap
-- | Assigns a constant value to out of image pixels.
--
-- > iiiiii|abcdefgh|iiiiiii with some specified 'i'
| BorderConstant !a
-- Instances -------------------------------------------------------------------
-- Following implementations share a lot of similar processing. However, GHC
-- fails to specialise and optimise correctly when goXXX functions are top-level
-- functions, even with static argument transformations.
-- | Box filters initialized with a given value.
instance (Image src, FromFunction res, src_pix ~ ImagePixel src
, res_pix ~ FromFunctionPixel res)
=> Filterable src res (BoxFilter src_pix init acc res_pix) where
apply !(Filter ksize anchor (Kernel kernel) initF fold post interpol) !img =
let !(FilterFold fAcc) = fold
in fromFunction size $ \(!pt@(Z :. iy :. ix)) ->
let pix = img ! pt
!ini = initF pt pix
!acc = fAcc pt
!iy0 = iy - kcy
!ix0 = ix - kcx
!safe = iy0 >= 0 && iy0 + kh <= ih
&& ix0 >= 0 && ix0 + kw <= iw
in post pt pix ini $!
if safe then goColumnSafe ini (iy0 * iw) ix0 0 acc
else goColumn ini iy0 ix0 0 acc
where
!size@(Z :. ih :. iw) = shape img
!(Z :. kh :. kw) = ksize
!(Z :. kcy :. kcx) = kernelAnchor anchor ksize
goColumn !ini !iy !ix !ky !acc
| ky < kh = case borderInterpolate interpol ih iy of
Left iy' -> goLine ini iy (iy' * iw) ix ix ky 0 acc
Right val -> goLineConst ini iy ix ky 0 val acc
| otherwise = acc
goColumnSafe !ini !linearIY !ix !ky !acc
| ky < kh = goLineSafe ini linearIY ix ix ky 0 acc
| otherwise = acc
goLine !ini !iy !linearIY !ix0 !ix !ky !kx !acc
| kx < kw =
let !val = case borderInterpolate interpol iw ix of
Left ix' -> img `linearIndex` (linearIY + ix')
Right val' -> val'
!acc' = kernel ini (ix2 ky kx) val acc
in goLine ini iy linearIY ix0 (ix + 1) ky (kx + 1) acc'
| otherwise = goColumn ini (iy + 1) ix0 (ky + 1) acc
goLineSafe !ini !linearIY !ix0 !ix !ky !kx !acc
| kx < kw =
let !val = img `linearIndex` (linearIY + ix)
!acc' = kernel ini (ix2 ky kx) val acc
in goLineSafe ini linearIY ix0 (ix + 1) ky (kx + 1) acc'
| otherwise = goColumnSafe ini (linearIY + iw) ix0 (ky + 1) acc
goLineConst !ini !iy !ix !ky !kx !val !acc
| kx < kw = let !acc' = kernel ini (ix2 ky kx) val acc
in goLineConst ini iy ix ky (kx + 1) val acc'
| otherwise = goColumn ini (iy + 1) ix (ky + 1) acc
{-# INLINE apply #-}
-- | Box filters initialized using the first pixel of the kernel.
instance (Image src, FromFunction res, src_pix ~ ImagePixel src
, res_pix ~ FromFunctionPixel res)
=> Filterable src res (BoxFilter1 src_pix init res_pix) where
apply !(Filter ksize anchor (Kernel kernel) initF _ post interpol) !img
| kh == 0 || kw == 0 =
error "Using FilterFold1 with an empty kernel."
| otherwise =
fromFunction size $ \(!pt@(Z :. iy :. ix)) ->
let pix = img ! pt
!ini = initF pt pix
!iy0 = iy - kcy
!ix0 = ix - kcx
!safe = iy0 >= 0 && iy0 + kh <= ih
&& ix0 >= 0 && ix0 + kw <= iw
in post pt pix ini $! if safe then goColumn1Safe ini iy0 ix0
else goColumn1 ini iy0 ix0
where
!size@(Z :. ih :. iw) = shape img
!(Z :. kh :. kw) = ksize
!(Z :. kcy :. kcx) = kernelAnchor anchor ksize
goColumn1 !ini !iy !ix =
case borderInterpolate interpol ih iy of
Left iy' ->
let !linearIY = iy' * iw
!acc = safeIndex linearIY ix
in goLine ini iy linearIY ix (ix + 1) 0 1 acc
Right val -> goLineConst ini iy ix 0 1 val val
goColumn1Safe !ini !iy !ix =
let !linearIY = iy * iw
!acc = img `linearIndex` (linearIY + ix)
in goLineSafe ini linearIY ix (ix + 1) 0 1 acc
goColumn !ini !iy !ix !ky !acc
| ky < kh = case borderInterpolate interpol ih iy of
Left iy' -> goLine ini iy (iy' * iw) ix ix ky 0 acc
Right val -> goLineConst ini iy ix ky 0 val acc
| otherwise = acc
goColumnSafe !ini !linearIY !ix !ky !acc
| ky < kh = goLineSafe ini linearIY ix ix ky 0 acc
| otherwise = acc
goLine !ini !iy !linearIY !ix0 !ix !ky !kx !acc
| kx < kw =
let !val = safeIndex linearIY ix
!acc' = kernel ini (ix2 ky kx) val acc
in goLine ini iy linearIY ix0 (ix + 1) ky (kx + 1) acc'
| otherwise = goColumn ini (iy + 1) ix0 (ky + 1) acc
goLineSafe !ini !linearIY !ix0 !ix !ky !kx !acc
| kx < kw =
let !val = img `linearIndex` (linearIY + ix)
!acc' = kernel ini (ix2 ky kx) val acc
in goLineSafe ini linearIY ix0 (ix + 1) ky (kx + 1) acc'
| otherwise = goColumnSafe ini (linearIY + iw) ix0 (ky + 1) acc
goLineConst !ini !iy !ix !ky !kx !val !acc
| kx < kw = let !acc' = kernel ini (ix2 ky kx) val acc
in goLineConst ini iy ix ky (kx + 1) val acc'
| otherwise = goColumn ini (iy + 1) ix (ky + 1) acc
safeIndex !linearIY !ix =
case borderInterpolate interpol iw ix of
Left ix' -> img `linearIndex` (linearIY + ix')
Right val -> val
{-# INLINE apply #-}
-- | Separable filters initialized with a given value.
instance ( Image src, FromFunction res
, src_pix ~ ImagePixel src
, res_pix ~ FromFunctionPixel res
, SeparatelyFiltrable src res acc)
=> Filterable src res (SeparableFilter src_pix init acc res_pix)
where
apply !f !img =
fst $! wrapper img f
where
wrapper :: (Image src, FromFunction res)
=> src
-> SeparableFilter (ImagePixel src) init acc (FromFunctionPixel res)
-> (res, SeparableFilterAccumulator src res acc)
wrapper !src !(Filter ksize anchor kernel initF fold post interpol) =
(res, tmp)
where
!size@(Z :. ih :. iw) = shape src
!(Z :. kh :. kw) = ksize
!(Z :. kcy :. kcx) = kernelAnchor anchor ksize
!(SeparableKernel vert horiz) = kernel
!(FilterFold fAcc) = fold
!tmp = fromFunction size $ \(!pt@(Z :. iy :. ix)) ->
let pix = src ! pt
!ini = initF pt pix
!acc0 = fAcc pt
!iy0 = iy - kcy
in if iy0 >= 0 && iy0 + kh <= ih
then goColumnSafe ini iy0 ix 0 acc0
else goColumn ini iy0 ix 0 acc0
!res = fromFunction size $ \(!pt@(Z :. iy :. ix)) ->
let pix = src ! pt
!ini = initF pt pix
!acc0 = fAcc pt
!ix0 = ix - kcx
in post pt pix ini $!
if ix0 >= 0 && ix0 + kw <= iw
then goLineSafe ini (iy * iw) ix0 0 acc0
else goLine ini acc0 (iy * iw) ix0 0
acc0
goColumn !ini !iy !ix !ky !acc
| ky < kh =
let !val = case borderInterpolate interpol ih iy of
Left iy' -> src ! ix2 iy' ix
Right val' -> val'
!acc' = vert ini (ix1 ky) val acc
in goColumn ini (iy + 1) ix (ky + 1) acc'
| otherwise = acc
goColumnSafe !ini !iy !ix !ky !acc
| ky < kh =
let !val = src ! ix2 iy ix
!acc' = vert ini (ix1 ky) val acc
in goColumnSafe ini (iy + 1) ix (ky + 1) acc'
| otherwise = acc
goLine !ini !acc0 !linearIY !ix !kx !acc
| kx < kw =
let !val =
case borderInterpolate interpol iw ix of
Left ix' -> tmp `linearIndex` (linearIY + ix')
Right val' -> constCol ini acc0 val'
!acc' = horiz ini (ix1 kx) val acc
in goLine ini acc0 linearIY (ix + 1) (kx + 1) acc'
| otherwise = acc
goLineSafe !ini !linearIY !ix !kx !acc
| kx < kw =
let !val = tmp `linearIndex` (linearIY + ix)
!acc' = horiz ini (ix1 kx) val acc
in goLineSafe ini linearIY (ix + 1) (kx + 1) acc'
| otherwise = acc
-- Computes the value of an out of image column when the
-- interpolation method is BorderConstant.
constCol !ini !acc0 !constVal =
foldl' (\acc ky -> vert ini (ix1 ky) constVal acc) acc0
[0..kh-1]
{-# INLINE wrapper #-}
{-# INLINE apply #-}
-- | Separable filters initialized using the first pixel of the kernel.
instance ( Image src, FromFunction res
, src_pix ~ ImagePixel src
, res_pix ~ FromFunctionPixel res
, SeparatelyFiltrable src res src_pix)
=> Filterable src res (SeparableFilter1 src_pix init res_pix)
where
apply !f !img =
fst $! wrapper img f
where
wrapper :: (Image src, FromFunction res, acc ~ ImagePixel src
, FromFunction (SeparableFilterAccumulator src res acc)
, FromFunctionPixel (SeparableFilterAccumulator src res acc) ~ acc
, Image (SeparableFilterAccumulator src res acc)
, ImagePixel (SeparableFilterAccumulator src res acc) ~ acc)
=> src
-> SeparableFilter1 (ImagePixel src) init (FromFunctionPixel res)
-> (res, SeparableFilterAccumulator src res acc)
wrapper !src !(Filter ksize anchor kernel initF _ post interpol)
| kh == 0 || kw == 0 =
error "Using FilterFold1 with an empty kernel."
| otherwise =
(res, tmp)
where
!size@(Z :. ih :. iw) = shape src
!(Z :. kh :. kw) = ksize
!(Z :. kcy :. kcx) = kernelAnchor anchor ksize
!(SeparableKernel vert horiz) = kernel
!tmp = fromFunction size $ \(!pt@(Z :. iy :. ix)) ->
let pix = src ! pt
!ini = initF pt pix
!iy0 = iy - kcy
in if iy0 >= 0 && iy0 + kh <= ih
then goColumn1Safe ini iy0 ix
else goColumn1 ini iy0 ix
!res = fromFunction size $ \(!pt@(Z :. iy :. ix)) ->
let pix = src ! pt
!ini = initF pt pix
!ix0 = ix - kcx
in post pt pix ini $!
if ix0 >= 0 && ix0 + kw <= iw
then goLine1Safe ini (iy * iw) ix0
else goLine1 ini (iy * iw) ix0
goColumn1 !ini !iy !ix =
case borderInterpolate interpol ih iy of
Left iy' ->
let !acc = src ! ix2 iy' ix
in goColumn ini (iy + 1) ix 1 acc
Right val ->
goColumn ini (iy + 1) ix 1 val
goColumn1Safe !ini !iy !ix =
let !linearIY = iy * iw
!acc = src `linearIndex` (linearIY + ix)
in goColumnSafe ini (linearIY + iw) ix 1 acc
goColumn !ini !iy !ix !ky !acc
| ky < kh =
let !val = case borderInterpolate interpol ih iy of
Left iy' -> src ! ix2 iy' ix
Right val' -> val'
!acc' = vert ini (ix1 ky) val acc
in goColumn ini (iy + 1) ix (ky + 1) acc'
| otherwise = acc
goColumnSafe !ini !linearIY !ix !ky !acc
| ky < kh =
let !val = src `linearIndex` (linearIY + ix)
!acc' = vert ini (ix1 ky) val acc
in goColumnSafe ini (linearIY + iw) ix (ky + 1) acc'
| otherwise = acc
goLine1 !ini !linearIY !ix =
let !acc =
case borderInterpolate interpol iw ix of
Left ix' -> tmp `linearIndex` (linearIY + ix')
Right val -> columnConst ini val
in goLine ini linearIY (ix + 1) 1 acc
goLine1Safe !ini !linearIY !ix =
let !linearIX = linearIY + ix
!acc = tmp `linearIndex` linearIX
in goLineSafe ini (linearIX + 1) 1 acc
goLine !ini !linearIY !ix !kx !acc
| kx < kw =
let !val =
case borderInterpolate interpol iw ix of
Left ix' -> tmp `linearIndex` (linearIY + ix')
Right val' -> columnConst ini val'
!acc' = horiz ini (ix1 kx) val acc
in goLine ini linearIY (ix + 1) (kx + 1) acc'
| otherwise = acc
goLineSafe !ini !linearIX !kx !acc
| kx < kw =
let !val = tmp `linearIndex` linearIX
!acc' = horiz ini (ix1 kx) val acc
in goLineSafe ini (linearIX + 1) (kx + 1) acc'
| otherwise = acc
columnConst !ini !constVal = goColumnConst ini 1 constVal constVal
goColumnConst !ini !ky !constVal !acc
| ky < kh = goColumnConst ini (ky + 1) constVal
(vert ini (ix1 ky) acc constVal)
| otherwise = acc
{-# INLINE wrapper #-}
{-# INLINE apply #-}
-- Functions -------------------------------------------------------------------
-- | Given a method to compute the kernel anchor and the size of the kernel,
-- returns the anchor of the kernel as coordinates.
kernelAnchor :: KernelAnchor -> Size -> Point
kernelAnchor (KernelAnchor ix) _ = ix
kernelAnchor (KernelAnchorCenter) (Z :. kh :. kw) = ix2 (round $ (kh - 1) % 2)
(round $ (kw - 1) % 2)
-- | Given a method of interpolation, the number of pixel in the dimension and
-- an index in this dimension, returns either the index of the interpolated
-- pixel or a constant value.
borderInterpolate :: BorderInterpolate a
-> Int -- ^ The size of the dimension.
-> Int -- ^ The index in the dimension.
-> Either Int a
borderInterpolate !interpol !len !ix
| word ix < word len = Left ix
| otherwise =
case interpol of
BorderReplicate | ix < 0 -> Left 0
| otherwise -> Left $! len - 1
BorderReflect -> Left $! goReflect ix
BorderWrap -> Left $! ix `mod` len
BorderConstant i -> Right i
where
goReflect !ix' | ix' < 0 = goReflect (-ix' - 1)
| ix' >= len = goReflect ((len - 1) - (ix' - len))
| otherwise = ix'
{-# INLINE borderInterpolate #-}
-- Morphological operators -----------------------------------------------------
type Morphological pix = SeparableFilter1 pix () pix
dilate :: Ord pix => Int -> Morphological pix
dilate radius =
Filter (ix2 size size) KernelAnchorCenter (SeparableKernel kernel kernel)
(\_ _ -> ()) FilterFold1 (\_ _ _ !acc -> acc) BorderReplicate
where
!size = radius * 2 + 1
kernel _ _ = max
{-# INLINE dilate #-}
erode :: Ord pix => Int -> Morphological pix
erode radius =
Filter (ix2 size size) KernelAnchorCenter (SeparableKernel kernel kernel)
(\_ _ -> ()) FilterFold1 (\_ _ _ !acc -> acc) BorderReplicate
where
!size = radius * 2 + 1
kernel _ _ = min
{-# INLINE erode #-}
-- Blur ------------------------------------------------------------------------
type Blur src acc res = SeparableFilter src () acc res
-- | Blurs the image by averaging the pixel inside the kernel.
--
-- Considers using a type for 'acc' with
-- @maxBound acc >= maxBound src * (kernel size)²@.
blur :: (Integral src, Integral acc, Num res)
=> Int -- ^ Blur radius.
-> Blur src acc res
blur radius =
Filter (ix2 size size) KernelAnchorCenter (SeparableKernel vert horiz)
(\_ _ -> ()) (FilterFold (const 0)) post BorderReplicate
where
!size = radius * 2 + 1
!nPixs = fromIntegral $ square size
vert _ _ !val !acc = acc + fromIntegral val
horiz _ _ !acc' !acc = acc + acc'
post _ _ _ !acc = fromIntegral $ acc `div` nPixs
{-# INLINE blur #-}
-- | Blurs the image by averaging the pixel inside the kernel using a Gaussian
-- function.
--
-- See <http://en.wikipedia.org/wiki/Gaussian_blur>
gaussianBlur :: (Integral src, Floating acc, RealFrac acc, Storable acc
, Integral res)
=> Int -- ^ Blur radius.
-> Maybe acc
-- ^ Sigma value of the Gaussian function. If not given, will be
-- automatically computed from the radius so that the kernel
-- fits 3σ of the distribution.
-> Blur src acc res
gaussianBlur !radius !mSig =
Filter (ix2 size size) KernelAnchorCenter (SeparableKernel vert horiz)
(\_ _ -> ()) (FilterFold (const 0)) (\_ _ _ !acc -> round acc)
BorderReplicate
where
!size = radius * 2 + 1
-- If σ is not provided, tries to fit 3σ in the kernel.
!sig = case mSig of Just s -> s
Nothing -> (0.5 + fromIntegral radius) / 3
vert _ !(Z :. y) !val !acc = let !coeff = kernelVec V.! y
in acc + fromIntegral val * coeff
horiz _ !(Z :. x) !val !acc = let !coeff = kernelVec V.! x
in acc + val * coeff
!kernelVec =
-- Creates a vector of Gaussian values and normalizes it so its sum
-- equals 1.
let !unormalized = V.generate size $ \x ->
gaussian $! fromIntegral $! abs $! x - radius
!kernelSum = V.sum unormalized
in V.map (/ kernelSum) unormalized
gaussian !x = invSigSqrt2Pi * exp (inv2xSig2 * square x)
-- Pre-computed terms of the Gaussian function.
!invSigSqrt2Pi = 1 / (sig * sqrt (2 * pi))
!inv2xSig2 = -1 / (2 * square sig)
{-# INLINE gaussianBlur #-}
-- Derivation ------------------------------------------------------------------
type Derivative src res = SeparableFilter src () res res
data DerivativeType = DerivativeX | DerivativeY
-- | Estimates the first derivative using the Scharr's 3x3 kernel.
--
-- Convolves the following kernel for the X derivative:
--
-- @
-- -3 0 3
-- -10 0 10
-- -3 0 3
-- @
--
-- And this kernel for the Y derivative:
--
-- @
-- -3 -10 -3
-- 0 0 0
-- 3 10 3
-- @
--
-- Considers using a signed integer type for 'res' with
-- @maxBound res >= 16 * maxBound src@.
scharr :: (Integral src, Integral res)
=> DerivativeType -> Derivative src res
scharr der =
let !kernel =
case der of
DerivativeX -> SeparableKernel kernel1 kernel2
DerivativeY -> SeparableKernel kernel2 kernel1
in Filter (ix2 3 3) KernelAnchorCenter kernel (\_ _ -> ())
(FilterFold (const 0)) (\_ _ _ !acc -> acc) BorderReplicate
where
kernel1 _ !(Z :. 1) !val !acc = acc + 10 * fromIntegral val
kernel1 _ !(Z :. _) !val !acc = acc + 3 * fromIntegral val
kernel2 _ !(Z :. 0) !val !acc = acc - fromIntegral val
kernel2 _ !(Z :. 1) !_ !acc = acc
kernel2 _ !(Z :. ~2) !val !acc = acc + fromIntegral val
{-# INLINE scharr #-}
-- | Estimates the first derivative using a Sobel's kernel.
--
-- Prefer 'scharr' when radius equals @1@ as Scharr's kernel is more accurate
-- and is implemented faster.
--
-- Considers using a signed integer type for 'res' which is significantly larger
-- than 'src', especially for large kernels.
sobel :: (Integral src, Integral res, Storable res)
=> Int -- ^ Kernel radius.
-> DerivativeType
-> Derivative src res
sobel radius der =
Filter (ix2 size size) KernelAnchorCenter (SeparableKernel vert horiz)
(\_ _ -> ()) (FilterFold (const 0)) (\_ _ _ !acc -> acc)
BorderReplicate
where
!size = radius * 2 + 1
vert _ !(Z :. x) !val !acc = let !coeff = vec1 V.! x
in acc + fromIntegral val * coeff
horiz _ !(Z :. x) !val !acc = let !coeff = vec2 V.! x
in acc + fromIntegral val * coeff
!radius' = fromIntegral radius
(!vec1, !vec2) = case der of DerivativeX -> (vec1', vec2')
DerivativeY -> (vec2', vec1')
!vec1' = let pows = [ 2^i | i <- [0..radius'] ]
in V.fromList $ pows ++ (tail (reverse pows))
!vec2' = V.fromList $ map negate [1..radius'] ++ [0] ++ reverse [1..radius']
{-# INLINE sobel #-}
-- Others ----------------------------------------------------------------------
type Mean src acc res = SeparableFilter src () acc res
-- | Computes the average of a kernel of the given size.
--
-- This is similar to 'blur' but with a rectangular kernel and a 'Fractional'
-- result.
mean :: (Integral src, Integral acc, Fractional res)
=> Size -> SeparableFilter src () acc res
mean size@(Z :. h :. w) =
Filter size KernelAnchorCenter (SeparableKernel vert horiz) (\_ _ -> ())
(FilterFold (const 0)) post BorderReplicate
where
vert _ _ !val !acc = acc + fromIntegral val
horiz _ _ !acc' !acc = acc + acc'
!nPixsFactor = 1 / (fromIntegral $! h * w)
post _ _ _ !acc = fromIntegral acc * nPixsFactor
{-# INLINE mean #-}
-- -----------------------------------------------------------------------------
square :: Num a => a -> a
square a = a * a
word :: Integral a => a -> Word
word = fromIntegral
| RaphaelJ/friday | src/Vision/Image/Filter/Internal.hs | lgpl-3.0 | 30,964 | 0 | 22 | 11,293 | 8,128 | 4,044 | 4,084 | 491 | 5 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- | Hashing functions and HMAC DRBG definition
module Network.Haskoin.Crypto.Hash
( Hash512(getHash512)
, Hash256(getHash256)
, Hash160(getHash160)
, CheckSum32(getCheckSum32)
, hash512
, hash256
, hash160
, hashSHA1
, doubleHash256
, addressHash
, checkSum32
, hmac512
, hmac256
, split512
, join512
, hmacDRBGNew
, hmacDRBGUpd
, hmacDRBGRsd
, hmacDRBGGen
, WorkingState
) where
import Control.DeepSeq (NFData)
import Crypto.Hash (RIPEMD160 (..), SHA1 (..),
SHA256 (..), SHA512 (..), hashWith)
import Crypto.MAC.HMAC (HMAC, hmac)
import Data.ByteArray (ByteArrayAccess)
import qualified Data.ByteArray as BA
import Data.ByteString (ByteString)
import qualified Data.ByteString as BS
import Data.ByteString.Short (ShortByteString)
import qualified Data.ByteString.Short as BSS
import Data.Either (fromRight)
import Data.Hashable (Hashable)
import Data.Serialize (Serialize (..), decode)
import qualified Data.Serialize.Get as Get
import qualified Data.Serialize.Put as Put
import Data.String (IsString, fromString)
import Data.String.Conversions (cs)
import Data.Word (Word16, Word32)
import Network.Haskoin.Util
newtype CheckSum32 = CheckSum32 { getCheckSum32 :: Word32 }
deriving (Eq, Ord, Serialize, NFData, Show, Hashable)
newtype Hash512 = Hash512 { getHash512 :: ShortByteString }
deriving (Eq, Ord, NFData, Hashable)
newtype Hash256 = Hash256 { getHash256 :: ShortByteString }
deriving (Eq, Ord, NFData, Hashable)
newtype Hash160 = Hash160 { getHash160 :: ShortByteString }
deriving (Eq, Ord, NFData, Hashable)
instance Show Hash512 where
show = cs . encodeHex . BSS.fromShort . getHash512
instance Show Hash256 where
show = cs . encodeHex . BSS.fromShort . getHash256
instance Show Hash160 where
show = cs . encodeHex . BSS.fromShort . getHash160
instance IsString Hash512 where
fromString str =
case decodeHex $ cs str of
Nothing -> e
Just bs ->
case BS.length bs of
64 -> Hash512 (BSS.toShort bs)
_ -> e
where
e = error "Could not decode hash from hex string"
instance Serialize Hash512 where
get = Hash512 <$> Get.getShortByteString 64
put = Put.putShortByteString . getHash512
instance IsString Hash256 where
fromString str =
case decodeHex $ cs str of
Nothing -> e
Just bs ->
case BS.length bs of
32 -> Hash256 (BSS.toShort bs)
_ -> e
where
e = error "Could not decode hash from hex string"
instance Serialize Hash256 where
get = Hash256 <$> Get.getShortByteString 32
put = Put.putShortByteString . getHash256
instance IsString Hash160 where
fromString str =
case decodeHex $ cs str of
Nothing -> e
Just bs ->
case BS.length bs of
20 -> Hash160 (BSS.toShort bs)
_ -> e
where
e = error "Could not decode hash from hex string"
instance Serialize Hash160 where
get = Hash160 <$> Get.getShortByteString 20
put = Put.putShortByteString . getHash160
hash512 :: ByteArrayAccess b => b -> Hash512
hash512 = Hash512 . BSS.toShort . BA.convert . hashWith SHA512
hash256 :: ByteArrayAccess b => b -> Hash256
hash256 = Hash256 . BSS.toShort . BA.convert . hashWith SHA256
hash160 :: ByteArrayAccess b => b -> Hash160
hash160 = Hash160 . BSS.toShort . BA.convert. hashWith RIPEMD160
hashSHA1 :: ByteArrayAccess b => b -> Hash160
hashSHA1 = Hash160 . BSS.toShort . BA.convert . hashWith SHA1
-- | Compute two rounds of SHA-256.
doubleHash256 :: ByteArrayAccess b => b -> Hash256
doubleHash256 =
Hash256 . BSS.toShort . BA.convert . hashWith SHA256 . hashWith SHA256
-- | Compute SHA-256 followed by RIPMED-160.
addressHash :: ByteArrayAccess b => b -> Hash160
addressHash =
Hash160 . BSS.toShort . BA.convert . hashWith RIPEMD160 . hashWith SHA256
{- CheckSum -}
-- | Computes a 32 bit checksum.
checkSum32 :: ByteArrayAccess b => b -> CheckSum32
checkSum32 = fromRight (error "Colud not decode bytes as CheckSum32")
. decode
. BS.take 4
. BA.convert
. hashWith SHA256
. hashWith SHA256
{- HMAC -}
-- | Computes HMAC over SHA-512.
hmac512 :: ByteString -> ByteString -> Hash512
hmac512 key msg =
Hash512 $ BSS.toShort $ BA.convert (hmac key msg :: HMAC SHA512)
-- | Computes HMAC over SHA-256.
hmac256 :: (ByteArrayAccess k, ByteArrayAccess m) => k -> m -> Hash256
hmac256 key msg =
Hash256 $ BSS.toShort $ BA.convert (hmac key msg :: HMAC SHA256)
-- | Split a 'Hash512' into a pair of 'Hash256'.
split512 :: Hash512 -> (Hash256, Hash256)
split512 h =
(Hash256 (BSS.toShort a), Hash256 (BSS.toShort b))
where
(a, b) = BS.splitAt 32 . BSS.fromShort $ getHash512 h
-- | Join a pair of 'Hash256' into a 'Hash512'.
join512 :: (Hash256, Hash256) -> Hash512
join512 (a, b) =
Hash512 .
BSS.toShort $
BSS.fromShort (getHash256 a) `BS.append` BSS.fromShort (getHash256 b)
{- 10.1.2 HMAC_DRBG with HMAC-SHA256
http://csrc.nist.gov/publications/nistpubs/800-90A/SP800-90A.pdf
Constants are based on recommentations in Appendix D section 2 (D.2)
-}
type WorkingState = (ByteString, ByteString, Word16)
type AdditionalInput = ByteString
type ProvidedData = ByteString
type EntropyInput = ByteString
type Nonce = ByteString
type PersString = ByteString
-- 10.1.2.2 HMAC DRBG Update FUnction
hmacDRBGUpd :: ProvidedData
-> ByteString
-> ByteString
-> (ByteString, ByteString)
hmacDRBGUpd info k0 v0
| BS.null info = (k1, v1) -- 10.1.2.2.3
| otherwise = (k2, v2) -- 10.1.2.2.6
where
-- 10.1.2.2.1
k1 = BSS.fromShort . getHash256 . hmac256 k0 $ v0 `BS.append` (0 `BS.cons` info)
-- 10.1.2.2.2
v1 = BSS.fromShort . getHash256 $ hmac256 k1 v0
-- 10.1.2.2.4
k2 = BSS.fromShort . getHash256 $ hmac256 k1 $ v1 `BS.append` (1 `BS.cons` info)
-- 10.1.2.2.5
v2 = BSS.fromShort . getHash256 $ hmac256 k2 v1
-- 10.1.2.3 HMAC DRBG Instantiation
hmacDRBGNew :: EntropyInput -> Nonce -> PersString -> WorkingState
hmacDRBGNew seed nonce info
| (BS.length seed + BS.length nonce) * 8 < 384 = error
"Entropy + nonce input length must be at least 384 bit"
| (BS.length seed + BS.length nonce) * 8 > 1000 = error
"Entropy + nonce input length can not be greater than 1000 bit"
| BS.length info * 8 > 256 = error
"Maximum personalization string length is 256 bit"
| otherwise = (k1, v1, 1) -- 10.1.2.3.6
where
s = BS.concat [seed, nonce, info] -- 10.1.2.3.1
k0 = BS.replicate 32 0 -- 10.1.2.3.2
v0 = BS.replicate 32 1 -- 10.1.2.3.3
(k1,v1) = hmacDRBGUpd s k0 v0 -- 10.1.2.3.4
-- 10.1.2.4 HMAC DRBG Reseeding
hmacDRBGRsd :: WorkingState -> EntropyInput -> AdditionalInput -> WorkingState
hmacDRBGRsd (k, v, _) seed info
| BS.length seed * 8 < 256 = error
"Entropy input length must be at least 256 bit"
| BS.length seed * 8 > 1000 = error
"Entropy input length can not be greater than 1000 bit"
| otherwise = (k0, v0, 1) -- 10.1.2.4.4
where
s = seed `BS.append` info -- 10.1.2.4.1
(k0, v0) = hmacDRBGUpd s k v -- 10.1.2.4.2
-- 10.1.2.5 HMAC DRBG Generation
hmacDRBGGen :: WorkingState
-> Word16
-> AdditionalInput
-> (WorkingState, Maybe ByteString)
hmacDRBGGen (k0, v0, c0) bytes info
| bytes * 8 > 7500 = error "Maximum bits per request is 7500"
| c0 > 10000 = ((k0, v0, c0), Nothing) -- 10.1.2.5.1
| otherwise = ((k2, v3, c1), Just res) -- 10.1.2.5.8
where
(k1, v1) | BS.null info = (k0, v0)
| otherwise = hmacDRBGUpd info k0 v0 -- 10.1.2.5.2
(tmp, v2) = go (fromIntegral bytes) k1 v1 BS.empty -- 10.1.2.5.3/4
res = BS.take (fromIntegral bytes) tmp -- 10.1.2.5.5
(k2, v3) = hmacDRBGUpd info k1 v2 -- 10.1.2.5.6
c1 = c0 + 1 -- 10.1.2.5.7
go l k v acc | BS.length acc >= l = (acc, v)
| otherwise = let vn = BSS.fromShort . getHash256 $ hmac256 k v
in go l k vn (acc `BS.append` vn)
| plaprade/haskoin | haskoin-core/src/Network/Haskoin/Crypto/Hash.hs | unlicense | 8,764 | 0 | 15 | 2,552 | 2,406 | 1,302 | 1,104 | 192 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
module Paths_agora (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import Foreign
import Foreign.C
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
prefix, bindirrel :: FilePath
prefix = "C:\\Users\\Ben Elliott\\AppData\\Roaming\\cabal"
bindirrel = "bin"
getBinDir :: IO FilePath
getBinDir = getPrefixDirRel bindirrel
getLibDir :: IO FilePath
getLibDir = getPrefixDirRel "x86_64-windows-ghc-7.8.3\\agora-0.1.0.0"
getDataDir :: IO FilePath
getDataDir = catchIO (getEnv "agora_datadir") (\_ -> getPrefixDirRel "x86_64-windows-ghc-7.8.3\\agora-0.1.0.0")
getLibexecDir :: IO FilePath
getLibexecDir = getPrefixDirRel "agora-0.1.0.0"
getSysconfDir :: IO FilePath
getSysconfDir = getPrefixDirRel "etc"
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir `joinFileName` name)
getPrefixDirRel :: FilePath -> IO FilePath
getPrefixDirRel dirRel = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
where
try_size size = allocaArray (fromIntegral size) $ \buf -> do
ret <- c_GetModuleFileName nullPtr buf size
case ret of
0 -> return (prefix `joinFileName` dirRel)
_ | ret < size -> do
exePath <- peekCWString buf
let (bindir,_) = splitFileName exePath
return ((bindir `minusFileName` bindirrel) `joinFileName` dirRel)
| otherwise -> try_size (size * 2)
foreign import ccall unsafe "windows.h GetModuleFileNameW"
c_GetModuleFileName :: Ptr () -> CWString -> Int32 -> IO Int32
minusFileName :: FilePath -> String -> FilePath
minusFileName dir "" = dir
minusFileName dir "." = dir
minusFileName dir suffix =
minusFileName (fst (splitFileName dir)) (fst (splitFileName suffix))
joinFileName :: String -> String -> FilePath
joinFileName "" fname = fname
joinFileName "." fname = fname
joinFileName dir "" = dir
joinFileName dir fname
| isPathSeparator (last dir) = dir++fname
| otherwise = dir++pathSeparator:fname
splitFileName :: FilePath -> (String, String)
splitFileName p = (reverse (path2++drive), reverse fname)
where
(path,drive) = case p of
(c:':':p') -> (reverse p',[':',c])
_ -> (reverse p ,"")
(fname,path1) = break isPathSeparator path
path2 = case path1 of
[] -> "."
[_] -> path1 -- don't remove the trailing slash if
-- there is only one character
(c:path') | isPathSeparator c -> path'
_ -> path1
pathSeparator :: Char
pathSeparator = '\\'
isPathSeparator :: Char -> Bool
isPathSeparator c = c == '/' || c == '\\'
| Lacaranian/hserv | dist/build/autogen/Paths_agora.hs | apache-2.0 | 3,043 | 0 | 21 | 737 | 889 | 467 | 422 | 72 | 5 |
import Test.Say
import Test.Answer
import SimpleJson
run :: String
run = sayHi ++ " " ++ answer
| EricYT/Haskell | src/test.hs | apache-2.0 | 97 | 0 | 6 | 18 | 32 | 18 | 14 | 5 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fwarn-typed-holes #-}
module Main where
import Codec.Picture
import Codec.Picture.Types
import Control.Error
import Control.Monad
import Control.Monad.IO.Class
import Control.Monad.Logger
import Data.Aeson
import Data.Bifunctor
import qualified Data.ByteString.Lazy as BSL
import qualified Data.Text as T
import qualified Data.Text.IO as TIO
import Filesystem hiding (writeFile)
import Filesystem.Path.CurrentOS hiding (decode)
import Prelude hiding (FilePath, writeFile)
import System.Random.MWC
import Text.XML
import ID.Fitness
import ID.GP.Types
import ID.Html5
import ID.Opts
import ID.Types
outputDir :: FilePath
outputDir = "output"
targetFile :: FilePath
targetFile = "plain.png"
wrapEl :: Element -> Document
wrapEl el = Document (Prologue [] Nothing []) el []
procFile :: GenIO -> (FilePath, Image PixelRGBA8) -> Int -> FitnessM ()
procFile g target i = do
let i' = T.justifyRight 5 '0' . T.pack $ show i
instDir = outputDir </> fromText i'
score = instDir </> fromText i' <.> "txt"
el <- liftIO $ createDirectory True instDir >> generateElement 0.4 10 g
fitness <- matchScreen target instDir $ Gene i' Spontaneous el
liftIO . TIO.writeFile (encodeString score) . T.pack $ show fitness
generateRandom :: IO ()
generateRandom = withSystemRandom $ \g -> eitherT onError onOK $ do
target <- EitherT . fmap (join . bimap T.pack getRGB8) . readImage
$ encodeString targetFile
let target' = promoteImage target
forM_ [1..100] $ procFile g (targetFile, target')
where onError = TIO.putStrLn
onOK = const $ return ()
main :: IO ()
main = do
opts <- execParser options
cfg' <- fmap decodeConfig . BSL.readFile $ optConfig opts
case cfg' of
Just cfg -> do
print cfg
void $ runID greetings cfg "output"
Nothing -> putStrLn "<ERROR>"
where decodeConfig :: BSL.ByteString -> Maybe IDConfig
decodeConfig = decode
greetings :: ID ()
greetings = $(logInfo) "How can I do something."
| erochest/intelligent-design | Main.hs | apache-2.0 | 2,394 | 0 | 18 | 720 | 657 | 344 | 313 | 60 | 2 |
{-# LANGUAGE MultiParamTypeClasses
, TemplateHaskell
, ScopedTypeVariables
, FlexibleInstances
, FlexibleContexts
, UndecidableInstances
#-}
import Unbound.LocallyNameless
--import Control.Applicative
import Control.Arrow ((+++))
import Control.Monad
import Control.Monad.Trans.Maybe
import Data.List as L
import Data.Set as S
import Data.Maybe
-- import Control.Monad.Trans.Error
import qualified Text.ParserCombinators.Parsec as P
import Text.ParserCombinators.Parsec ((<|>),many)
import qualified Text.ParserCombinators.Parsec.Token as T
import Text.ParserCombinators.Parsec.Language
import qualified Text.PrettyPrint as PP
import Text.PrettyPrint (render,(<+>),hsep,punctuate,brackets,(<>),text,Doc)
data Channel
type ChName = Name Channel
type EqnName = Name GoType
data GoType = Send ChName GoType
| Recv ChName GoType
| Tau GoType
| IChoice GoType GoType -- Just two things?
| OChoice [GoType]
| Par [GoType]
| New (Bind ChName GoType)
| Null
| Close ChName GoType
| TVar EqnName
| ChanInst GoType [ChName] -- P(c)
| ChanAbst (Bind [ChName] GoType) -- \c.P
deriving Show
data Eqn = EqnSys (Bind (Rec [(EqnName , Embed GoType)]) GoType)
deriving Show
-- inner Proc will always be ChanAbst
$(derive [''Channel,''GoType,''Eqn])
--instance Alpha Channel
instance Alpha GoType
instance Alpha Eqn
instance Subst GoType Eqn
--instance Subst String GoType
--instance Subst String Eqn
instance Subst GoType GoType where
isvar (TVar x) = Just (SubstName x)
isvar _ = Nothing
type M a = FreshM a
-- Free name/var wrappers --
fnTyp :: GoType -> [ChName]
fnTyp t = fv t
fvTyp :: GoType -> [EqnName]
fvTyp t = fv t
fnEqn :: Eqn -> [ChName]
fnEqn e = fv e
fvEqn :: Eqn -> [EqnName]
fvEqn e = fv e
-- GoType Combinators (TVars, New, Chan Abs and Inst) --
tvar :: String -> GoType
tvar = TVar . s2n
new :: String -> GoType -> GoType
new s t = New $ bind (s2n s) t
chanAbst :: String -> GoType -> GoType
chanAbst s t = ChanAbst $ bind ([s2n s]) t
chanAbstL :: [String] -> GoType -> GoType
chanAbstL l t = ChanAbst $ bind (L.map s2n l) t
chanInst :: String -> String -> GoType
chanInst s c = ChanInst (tvar s) ([s2n c])
chanInstL :: String -> [String] -> GoType
chanInstL s l = ChanInst (tvar s) (L.map s2n l)
------------------------------
-- Equation System Combinators --
eqn' :: String -> GoType -> GoType -> Eqn
eqn' s t1 t2 = EqnSys (bind (rec [(s2n s , Embed(t1) )]) t2)
eqn :: String -> String -> GoType -> GoType -> Eqn
eqn s c t1 t2 = eqn' s (chanAbst c t1) t2
eqnl :: [(String,[String],GoType)] -> GoType -> Eqn
eqnl l t = EqnSys (bind (rec (L.map (\(var,plist,def) ->
(s2n var , Embed(chanAbstL plist def))
) l)) t)
----------------------------------------
-- Structural Congruence --
-- Flatten out Pars in Par (i.e. T | (S | R) == (T | S) | R)--
flattenPar :: GoType -> GoType
flattenPar (Par l) = Par (flattenPar' l)
where flattenPar' (x:xs) =
case x of
Par l -> (flattenPar x):(flattenPar' xs)
_ -> x:(flattenPar' xs)
flattenPar' [] = []
flattenPar t = t
-- Remove Nulls from Par (i.e. T | 0 == T)--
gcNull :: GoType -> GoType
gcNull (Par l) = let res = gcNull' l in
if (L.null res) then Null else Par res
where gcNull' (x:xs) =
case x of
Null -> gcNull' xs
_ -> x:(gcNull' xs)
gcNull' [] = []
gcNull t = t
-- GC unused bound names --
gcBNames' :: GoType -> M GoType
gcBNames' (Send c t) = do
t' <- gcBNames' t
return $ Send c t'
gcBNames' (Recv c t) = do
t' <- gcBNames' t
return $ Recv c t'
gcBNames' (Tau t) = do
t' <- gcBNames' t
return $ Tau t'
gcBNames' (IChoice t1 t2) = do
t1' <- gcBNames' t1
t2' <- gcBNames' t2
return $ IChoice t1' t2'
gcBNames' (OChoice l) = do
lm' <- mapM gcBNames' l
return $ OChoice lm'
gcBNames' (Par l) = do
lm' <- mapM gcBNames' l
return $ Par lm'
gcBNames' (New bnd) = do
(c,t) <- unbind bnd
t' <- gcBNames' t
-- GC if c not used
if c `S.notMember` fv t'
then return t'
else return (New (bind c t'))
gcBNames' (Null) = return Null
gcBNames' (Close c t) = do
t' <- gcBNames' t
return $ Close c t'
gcBNames' (TVar x) = return $ TVar x
gcBNames' (ChanInst t lc) = do -- P(~c)
t' <- gcBNames' t
return $ ChanInst t' lc
gcBNames' (ChanAbst bnd) = do
(c,t) <- unbind bnd
t' <- gcBNames' t
return $ ChanAbst (bind c t')
gcBNames :: GoType -> GoType
gcBNames = runFreshM . gcBNames'
-- Open top-level bound names in a list of parallel types --
-- return is a list of (mc,t) where mc is Nothing if t is
-- closed and Just(c) otherwise.
openBNames :: [GoType] -> M [(Maybe ChName,GoType)]
openBNames l = do
res <- openBNames' l
return $ (init res)
openBNames' (x:xs) =
case x of
New bnd -> do
(c,t) <- unbind bnd
rest <- openBNames' xs
return $ (Just(c),t):rest
_ -> do
res <- openBNames' xs
return $ (Nothing,x):res
openBNames' [] = return $ [(Nothing,Null)]
-- Reconstructs the appropriate GoType from calls
-- to openBNames
closeBNames :: M [(Maybe ChName,GoType)] -> M GoType
closeBNames m = do
l <- m
let (names,ts) = unzip l
return $ L.foldr (\mc end ->
case mc of
Just(c) -> New (bind c end)
Nothing -> end) (Par ts) names
-- Composes open/close and escapes the freshness monad --
pullBNamesPar :: GoType -> GoType
pullBNamesPar (Par l) =
runFreshM (closeBNames . openBNames $ l)
pullBNamesPar t = t
nf :: GoType -> GoType
nf = id
structCong :: GoType -> GoType -> Bool
structCong t1 t2 = (nf t1) `aeq` (nf t2)
-----------
-- Pretty Printing --
class Pretty p where
ppr :: (Applicative m, LFresh m) => p -> m Doc
instance Pretty (Name a) where
ppr = return . text . show
dot = text "."
bang = text "!"
qmark = text "?"
oplus = text "+"
amper = text "&"
tau = text "tau"
instance Pretty GoType where
ppr (Send c t) = do
t' <- ppr t
c' <- ppr c
return $ c' <> bang <> PP.semi <> t'
ppr (Recv c t) = do
t' <- ppr t
c' <- ppr c
return $ c' <> qmark <> PP.semi <> t'
ppr (Tau t) = do
t' <- ppr t
return $ tau <> PP.semi <> t'
ppr (IChoice t1 t2) = do
t1' <- ppr t1
t2' <- ppr t2
return $ oplus <> PP.braces (t1' <+> PP.comma <+> t2')
ppr (OChoice l) = do
l' <- mapM ppr l
let prettyl = punctuate PP.comma l'
return $ amper <> PP.braces (hsep prettyl)
ppr (Par l) = do
l' <- mapM ppr l
let prettyl = punctuate (PP.text "|") l'
return $ (hsep prettyl)
ppr (New bnd) = lunbind bnd $ \(c,t) -> do
c' <- ppr c
t' <- ppr t
return $ PP.text "new" <+> c' <> dot <> (PP.parens t')
ppr (Null) = return $ text "0"
ppr (Close c t) = do
t' <- ppr t
c' <- ppr c
return $ PP.text "close " <> c' <> PP.semi <> t'
ppr (TVar x) = ppr x
ppr (ChanInst t plist) = do
t' <- ppr t
l' <- mapM ppr plist
let plist' = punctuate PP.comma l'
return $ t' <+> PP.char '<' <> (hsep plist') <> PP.char '>'
ppr (ChanAbst bnd) = lunbind bnd $ \(lc,t) -> do
t' <- ppr t
l' <- mapM ppr lc
let plist' = punctuate PP.comma l'
return $ brackets (hsep plist') <+> t'
instance Pretty Eqn where
ppr (EqnSys bnd) = lunbind bnd $ \(r,t) -> do
t' <- ppr t
let defs = unrec r
pdefs <- mapM (\(n,Embed(t0)) -> do
n' <- ppr n
t0' <- ppr t0
return $ n' <+> PP.text "=" <+> t0') defs
let pdefs' = punctuate PP.comma pdefs
return $ PP.braces (hsep pdefs') <+> PP.space <+> PP.text "in" <+> PP.space <+> t'
-- Pretty printing conveniences --
pprintEqn :: Eqn -> String
pprintEqn e = render . runLFreshM . ppr $ e
pprintType :: GoType -> String
pprintType t = render . runLFreshM . ppr $ t
-------
-- Lexer --
lexer :: T.TokenParser ()
ldef = emptyDef { T.identStart = P.letter
, T.identLetter = P.alphaNum
, T.reservedNames = [ "def"
, "call"
, "close"
, "spawn"
, "let"
, "newchan"
, "select"
, "case"
, "endselect"
, "if"
, "else"
, "endif"
, "tau"
, "send"
, "recv" ] }
lexer = T.makeTokenParser ldef
whiteSpace = T.whiteSpace lexer
reserved = T.reserved lexer
parens = T.parens lexer
identifier = T.identifier lexer
natural = T.natural lexer
integer = T.integer lexer
semi = T.semi lexer
symbol = T.symbol lexer
-- Parser --
data Prog = P [Def]
deriving (Eq, Show)
data Def = D String [String] Interm
deriving (Eq, Show)
data Interm = Seq [Interm]
| Call String [String]
| Cl String
| Spawn String [String]
| NewChan String String Integer
| If Interm Interm
| Select [Interm]
| T
| S String
| R String
| Zero
deriving (Eq, Show)
seqInterm :: P.Parser Interm
seqInterm = do
list <- P.sepBy1 itparser semi
return $ if L.length list == 1 then head list else Seq list
pparser :: P.Parser Prog
pparser = do
l <- many dparser
return $ P l
dparser :: P.Parser Def
dparser = do
{ reserved "def"
; x <- identifier
; list <- parens (P.sepBy1 identifier (P.char ','))
; symbol ":"
; d <- seqInterm
; return $ D x list d
}
itparser :: P.Parser Interm
itparser =
do { reserved "close"
; c <- identifier
; return $ (Cl c) }
<|>
do { reserved "spawn"
; x <- identifier
; list <- parens (P.sepBy1 identifier (P.char ','))
; return $ Spawn x list }
<|>
do { reserved "select"
; l <- many (reserved "case" *> seqInterm)
; reserved "endselect"
; return $ Select l }
<|>
do { reserved "let"
; x <- identifier
; symbol "="
; reserved "newchan"
; t <- identifier
; n <- natural
; return $ NewChan x t n }
<|>
do { reserved "if"
; t <- seqInterm
; reserved "else"
; e <- seqInterm
; reserved "endif"
; return $ If t e }
<|>
do { reserved "tau"
; return $ T }
<|>
do { reserved "send"
; c <- identifier
; return $ S c }
<|>
do { reserved "recv"
; c <- identifier
; return $ R c }
<|>
do { reserved "call"
; c <- identifier
; list <- parens (P.sepBy1 identifier (P.char ','))
; return $ Call c list }
<|>
do { return $ Zero }
mainparser :: P.Parser Prog
mainparser = whiteSpace >> pparser <* P.eof
parseprog :: String -> Either P.ParseError Prog
parseprog inp = P.parse mainparser "" inp
parseTest s =
case parseprog s of
Left err -> print err
Right s -> print s
-------
-- Once unfoldings of GoTypes and EquationSys --
unfoldType :: GoType -> M GoType
unfoldType (Send c t) = do
t' <- unfoldType t
return $ Send c t'
unfoldType (Recv c t) = do
t' <- unfoldType t
return $ Recv c t'
unfoldType (Tau t) = do
t' <- unfoldType t
return $ Tau t'
unfoldType (IChoice t1 t2) = do
t1' <- unfoldType t1
t2' <- unfoldType t2
return $ IChoice t1' t2'
unfoldType (OChoice l) = do
lm' <- mapM unfoldType l
return $ OChoice lm'
unfoldType (Par l) = do
lm' <- mapM unfoldType l
return $ Par lm'
unfoldType (New bnd) = do
(c,t) <- unbind bnd
t' <- unfoldType t
-- GC if c not used
if c `S.notMember` fv t'
then return t'
else return (New (bind c t'))
unfoldType (Null) = return Null
unfoldType (Close c t) = do
t' <- unfoldType t
return $ Close c t'
unfoldType (TVar x) = return $ TVar x
unfoldType (ChanInst t lc) = do -- P(~c)
t' <- unfoldType t
case t' of
ChanAbst bnd -> do -- P == (\~d.P)(~c)
(ld,t0) <- unbind bnd
let perm = L.foldr (\(d,c) acc -> compose acc (single (AnyName d) (AnyName c)) ) (Unbound.LocallyNameless.empty) (zip ld lc)
return $ swaps perm t0
otherwise -> return $ ChanInst t' lc
unfoldType (ChanAbst bnd) = do
(c,t) <- unbind bnd
t' <- unfoldType t
return $ ChanAbst (bind c t')
unfoldEqn :: Eqn -> M Eqn
unfoldEqn (EqnSys bnd) = do
(r,body) <- unbind bnd
let vars = unrec r
let newbody = L.foldr (\(x,Embed rhs) body -> subst x rhs body) body vars
return $ EqnSys (bind (rec vars) newbody)
unfoldTop :: Eqn -> M Eqn
unfoldTop (EqnSys bnd) = do
(r,body) <- unbind bnd
let vars = unrec r
let newbody = L.foldr (\(x,Embed rhs) body -> subst x rhs body) body vars
bla <- unfoldType newbody
return $ EqnSys (bind (rec vars) bla)
---- Testing Area: Please stand back -----
simpleEx = eqn "t" "c" (Send (s2n "c") (new "d" (chanInst "t" "d"))) (chanInst "t" "c")
twored = do
t <- unfoldTop simpleEx
unfoldTop t
twored' = do
t <- twored
return $ pprintEqn t
-- -- Testing stuff --
--eqnl :: [(String,[String],GoType)] -> GoType -> Eqn
--eqnl l t = EqnSys (bind (rec (map (\(s,c,t1) -> (string2Name s ,Embed(bind (map string2Name c) t1) )) l)) t)
--testSubst = tvar "s" "c"
-- test1 = eqn "t" "c" (Send (namify "c") (tvar "t" "c")) (new "c" (tvar "t" "c"))
-- -- Testing re-use of a in eq s. Should be free [OK]
-- test2 = eqnl [("t",["a"] , (Send (namify "a") (tvar "t" "a")) ) ,
-- ("s" ,["b"] ,(Recv (namify "a") (tvar "s" "b")) ) ] (new "c" (Par (tvar "t" "c") (tvar "s" "c")))
-- -- Baseline for recursive stuff [OK]
-- test3 = eqnl [("t",["a"] , (Send (namify "a") (tvar "t" "a")) ) ,
-- ("s" ,["b"] ,(Recv (namify "b") (tvar "s" "b")) ) ] (new "c" (Par (tvar "t" "c") (tvar "s" "c")))
-- -- Testing mutually recursive binders [OK]
-- test4 = eqnl [("t",["a"] , (Send (namify "a") (tvar "s" "a")) ) ,
-- ("s" ,["b"] ,(Recv (namify "b") (tvar "t" "b")) ) ] (new "c" (Par (tvar "t" "c") (tvar "s" "c")))
-- -- Testing for free "a" in main [OK]
-- test5 = eqnl [("t",["a"] , (Send (namify "a") (tvar "t" "a")) ) ,
-- ("s" ,["b"] ,(Recv (namify "b") (tvar "s" "b")) ) ] (new "c" (Par (tvar "t" "a") (tvar "s" "c")))
-- -- Testing for free rec var in main [OK]
-- test6 = eqnl [("t",["a"] , (Send (namify "a") (tvar "t" "a")) ) ,
-- ("s" ,["b"] ,(Recv (namify "b") (tvar "s" "b")) ) ] (new "c" (Par (tvar "d" "a") (tvar "s" "c")))
-- -- All should be aeq to test3 [OK All]
-- test3aeq1 = eqnl [("t",["a"] , (Send (namify "a") (tvar "t" "a")) ) ,
-- ("s" ,["b"] ,(Recv (namify "b") (tvar "s" "b")) ) ] (new "d" (Par (tvar "t" "d") (tvar "s" "d")))
-- test3aeq2 = eqnl [("xpto",["a"] , (Send (namify "a") (tvar "xpto" "a")) ) ,
-- ("s" ,["b"] ,(Recv (namify "b") (tvar "s" "b")) ) ] (new "d" (Par (tvar "xpto" "d") (tvar "s" "d")))
-- test3aeq3 = eqnl [("t",["b"] , (Send (namify "b") (tvar "t" "b")) ) ,
-- ("s" ,["b"] ,(Recv (namify "b") (tvar "s" "b")) ) ] (new "d" (Par (tvar "t" "d") (tvar "s" "d")))
-- -- Won't be
-- test3aeq4 = eqnl [("s" ,["b"] ,(Recv (namify "b") (tvar "s" "b")) ) ,
-- ("t",["a"] , (Send (namify "a") (tvar "t" "a")) ) ] (new "c" (Par (tvar "t" "c") (tvar "s" "c")))
-- Unfolding Test --
--(Bind (Rec [(Name GoType, Embed (Bind [Name String] GoType))]) GoType)
assert :: String -> Bool -> IO ()
assert s True = return ()
assert s False = print ("Assertion " ++ s ++ " failed")
--eqn :: String -> GoType -> GoType -> Eqn
--eqn s t1 t2 = EqnSys (bind (rec (string2Name s , Embed(t1) )) t2)
--eqnSys :: [(String,GoType)] -> GoType -> Eqn
--eqnSys l t2 = EqnSys (bind (rec ( map (\(s,t1) -> (string2Name s, Embed(t1))) l )) t2)
| nickng/gong | StuffParams.hs | apache-2.0 | 16,336 | 0 | 22 | 5,029 | 5,304 | 2,670 | 2,634 | -1 | -1 |
module Poset.A332809 (a332809, a332809_list) where
import Poset.Wichita (wichitaRanks)
import Data.Set (Set)
import qualified Data.Set as Set
a332809 :: Integer -> Int
a332809 = sum . map Set.size . wichitaRanks
a332809_list :: [Int]
a332809_list = map a332809 [1..]
| peterokagey/haskellOEIS | src/Poset/A332809.hs | apache-2.0 | 269 | 0 | 8 | 39 | 90 | 53 | 37 | 8 | 1 |
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE FlexibleInstances #-}
module Data.Propagator.Cell where
import Control.Monad
import Control.Monad.ST
import Data.Foldable
import Data.Primitive.MutVar
import Data.Propagator.Class
-- TODO: use a real mutable hash table
data Cell s a = Cell
(a -> a -> Change a)
{-# UNPACK #-} !(MutVar s (Maybe a, a -> ST s ()))
instance Eq (Cell s a) where
Cell _ ra == Cell _ rb = ra == rb
cell :: Propagated a => ST s (Cell s a)
cell = cellWith merge
cellWith :: (a -> a -> Change a) -> ST s (Cell s a)
cellWith mrg = Cell mrg <$> newMutVar (Nothing, \_ -> return ())
known :: Propagated a => a -> ST s (Cell s a)
known a = Cell merge <$> newMutVar (Just a, \_ -> return ())
-- known a = do x <- cell; write x a
write :: Cell s a -> a -> ST s ()
write (Cell m r) a' = join $ atomicModifyMutVar' r $ \case
(Nothing, ns) -> ((Just a', ns), ns a')
old@(Just a, ns) -> case m a a' of
Contradiction e -> (old, fail e)
Change False _ -> (old, return ())
Change True a'' -> ((Just a'', ns), ns a'')
unify :: Cell s a -> Cell s a -> ST s ()
unify x y = do
watch x (write y)
watch y (write x)
require :: Cell s a -> ST s (Maybe a)
require (Cell _ c) = fst <$> readMutVar c
watch :: Cell s a -> (a -> ST s ()) -> ST s ()
watch (Cell _ r) k = join $ atomicModifyMutVar' r $ \case
(Nothing, ok) -> ((Nothing, \a -> k a >> ok a), return ())
(ma@(Just a), ok) -> ((ma, \a' -> k a' >> ok a'), k a)
with :: Cell s a -> (a -> ST s ()) -> ST s ()
with (Cell _ r) k = do
p <- readMutVar r
traverse_ k (fst p)
watch2 :: Cell s a -> Cell s b -> (a -> b -> ST s ()) -> ST s ()
watch2 x y f = do
watch x $ \a -> with y $ \b -> f a b
watch y $ \b -> with x $ \a -> f a b
lift1 :: (a -> b) -> Cell s a -> Cell s b -> ST s ()
lift1 f x y = watch x $ \a -> write y (f a)
lift2 :: (a -> b -> c) -> Cell s a -> Cell s b -> Cell s c -> ST s ()
lift2 f x y z = watch2 x y $ \a b -> write z (f a b)
| Icelandjack/propagators | src/Data/Propagator/Cell.hs | bsd-2-clause | 2,088 | 0 | 14 | 539 | 1,155 | 579 | 576 | 52 | 4 |
-- 153
import Euler(toDigitsBase)
kk = 1000
countLarger k = length $ filter moreDigits $ take k $ iterate genSqrt (3,2)
where moreDigits (n,d) = countDigits n > countDigits d
countDigits x = length $ toDigitsBase 10 x
genSqrt (n,d) = (d*2+n, n+d)
main = putStrLn $ show $ countLarger kk
| higgsd/euler | hs/57.hs | bsd-2-clause | 314 | 0 | 9 | 78 | 143 | 74 | 69 | 7 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Web.Pagure.Internal.Wreq
-- Copyright : (C) 2015 Ricky Elrod
-- License : BSD2 (see LICENSE file)
-- Maintainer : Ricky Elrod <relrod@redhat.com>
-- Stability : experimental
-- Portability : ghc (lens)
--
-- Low-level access to the Pagure API
----------------------------------------------------------------------------
module Web.Pagure.Internal.Wreq where
import Control.Lens
import Control.Monad.IO.Class
import Control.Monad.Trans.Reader
--import Data.Aeson (toJSON)
--import Data.Aeson.Lens (key, nth)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as BL
import Data.List (dropWhileEnd)
import Data.Monoid
import Network.Wreq
import Network.Wreq.Types (Postable)
import Web.Pagure.Types
-- | The version of the API we are targetting.
apiVersion :: Int
apiVersion = 0
-- | Construct an API URL path. Strips any preceeding slashes from the given
-- 'String' parameter as well as the '_baseUrl' of the 'PagureConfig'.
pagureUrl :: String -> PagureT String
pagureUrl s = do
(PagureConfig url _) <- ask
return $ dropWhileEnd (=='/') url ++ "/api/" ++ show apiVersion ++
"/" ++ dropWhile (== '/') s
-- | Set up a (possibly authenticated) request to the Pagure API.
pagureWreqOptions :: PagureT Options
pagureWreqOptions = do
pc <- ask
return $ case pc of
PagureConfig _ (Just k) ->
defaults & header "Authorization" .~ ["token " <> BS.pack k]
_ -> defaults
-- | Perform a @GET@ request to the API.
pagureGetWith :: Options -> String -> PagureT (Response BL.ByteString)
pagureGetWith opts path = do
path' <- pagureUrl path
liftIO $ getWith opts path'
-- | Perform a @GET@ request to the API with default options.
pagureGet :: String -> PagureT (Response BL.ByteString)
pagureGet s = pagureWreqOptions >>= flip pagureGetWith s
-- | Perform a @POST@ request to the API.
pagurePostWith :: Postable a => Options -> String -> a -> PagureT (Response BL.ByteString)
pagurePostWith opts path a = do
path' <- pagureUrl path
liftIO $ postWith opts path' a
-- | Perform a @POST@ request to the API with default options.
pagurePost :: Postable a => String -> a -> PagureT (Response BL.ByteString)
pagurePost s a = flip (`pagurePostWith` s) a =<< pagureWreqOptions
| fedora-infra/pagure-haskell | src/Web/Pagure/Internal/Wreq.hs | bsd-2-clause | 2,365 | 0 | 15 | 380 | 491 | 267 | 224 | 38 | 2 |
{-# LANGUAGE QuasiQuotes, TemplateHaskell, TypeFamilies, OverloadedStrings, ViewPatterns #-}
module TKYProf
( TKYProf (..)
, Route (..)
, resourcesTKYProf
, Handler
, Widget
, module Yesod.Core
, module Settings
, module StaticFiles
, module Model
, module Control.Monad.STM
, StaticRoute
, lift
) where
import Control.Monad (unless)
import Control.Monad.STM (STM, atomically)
import Control.Monad.Trans.Class (lift)
import Model
import Settings (hamletFile, luciusFile, juliusFile, widgetFile)
import StaticFiles
import System.Directory
import System.FilePath ((</>))
import Yesod.Core hiding (lift)
import Yesod.Static
import qualified Data.ByteString.Lazy as L
import qualified Data.Text as T
import qualified Settings
-- | The site argument for your application. This can be a good place to
-- keep settings and values requiring initialization before your application
-- starts running, such as database connections. Every handler will have
-- access to the data present here.
data TKYProf = TKYProf
{ getStatic :: Static -- ^ Settings for static file serving.
, getReports :: Reports
}
-- This is where we define all of the routes in our application. For a full
-- explanation of the syntax, please see:
-- http://docs.yesodweb.com/book/web-routes-quasi/
--
-- This function does three things:
--
-- * Creates the route datatype TKYProfRoute. Every valid URL in your
-- application can be represented as a value of this type.
-- * Creates the associated type:
-- type instance Route TKYProf = TKYProfRoute
-- * Creates the value resourcesTKYProf which contains information on the
-- resources declared below. This is used in Controller.hs by the call to
-- mkYesodDispatch
--
-- What this function does *not* do is create a YesodSite instance for
-- TKYProf. Creating that instance requires all of the handler functions
-- for our application to be in scope. However, the handler functions
-- usually require access to the TKYProfRoute datatype. Therefore, we
-- split these actions into two functions and place them in separate files.
mkYesodData "TKYProf" $(parseRoutesFile "config/routes")
-- Please see the documentation for the Yesod typeclass. There are a number
-- of settings which can be configured by overriding methods here.
instance Yesod TKYProf where
approot = ApprootRelative
defaultLayout widget = do
mmsg <- getMessage
(title, bcs) <- breadcrumbs
pc <- widgetToPageContent $ do
$(Settings.widgetFile "header")
widget
toWidget $(Settings.luciusFile "templates/default-layout.lucius")
withUrlRenderer $(Settings.hamletFile "templates/default-layout.hamlet")
-- This function creates static content files in the static folder
-- and names them based on a hash of their content. This allows
-- expiration dates to be set far in the future without worry of
-- users receiving stale content.
addStaticContent ext' _ content = do
let fn = base64md5 content ++ '.' : T.unpack ext'
let statictmp = Settings.staticdir </> "tmp/"
liftIO $ createDirectoryIfMissing True statictmp
let fn' = statictmp ++ fn
exists <- liftIO $ doesFileExist fn'
unless exists $ liftIO $ L.writeFile fn' content
return $ Just $ Right (StaticR $ StaticRoute ["tmp", T.pack fn] [], [])
maximumContentLength _ _ = Just $ 20*1024*1024
instance YesodBreadcrumbs TKYProf where
breadcrumb HomeR = return ("Home", Nothing)
breadcrumb ReportsR = return ("Reports", Just HomeR)
breadcrumb (ReportsIdTimeR rid _) = return ("Report #" `T.append` T.pack (show rid), Just ReportsR)
breadcrumb (ReportsIdAllocR rid _) = return ("Report #" `T.append` T.pack (show rid), Just ReportsR)
breadcrumb _ = return ("Not found", Just HomeR)
| maoe/tkyprof | TKYProf.hs | bsd-2-clause | 3,804 | 0 | 16 | 724 | 674 | 375 | 299 | 56 | 0 |
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Backends.Hoogle
-- Copyright : (c) Neil Mitchell 2006-2008
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
--
-- Write out Hoogle compatible documentation
-- http://www.haskell.org/hoogle/
-----------------------------------------------------------------------------
module Haddock.Backends.Hoogle (
ppHoogle
) where
import Haddock.GhcUtils
import Haddock.Types
import Haddock.Utils hiding (out)
import GHC
import Outputable
import Data.Char
import Data.List
import Data.Maybe
import System.FilePath
import System.IO
prefix :: [String]
prefix = ["-- Hoogle documentation, generated by Haddock"
,"-- See Hoogle, http://www.haskell.org/hoogle/"
,""]
ppHoogle :: String -> String -> String -> Maybe (Doc RdrName) -> [Interface] -> FilePath -> IO ()
ppHoogle package version synopsis prologue ifaces odir = do
let filename = package ++ ".txt"
contents = prefix ++
docWith (drop 2 $ dropWhile (/= ':') synopsis) prologue ++
["@package " ++ package] ++
["@version " ++ version | version /= ""] ++
concat [ppModule i | i <- ifaces, OptHide `notElem` ifaceOptions i]
h <- openFile (odir </> filename) WriteMode
hSetEncoding h utf8
hPutStr h (unlines contents)
hClose h
ppModule :: Interface -> [String]
ppModule iface = "" : doc (ifaceDoc iface) ++
["module " ++ moduleString (ifaceMod iface)] ++
concatMap ppExport (ifaceExportItems iface) ++
concatMap ppInstance (ifaceInstances iface)
---------------------------------------------------------------------
-- Utility functions
dropHsDocTy :: HsType a -> HsType a
dropHsDocTy = f
where
g (L src x) = L src (f x)
f (HsForAllTy a b c d) = HsForAllTy a b c (g d)
f (HsBangTy a b) = HsBangTy a (g b)
f (HsAppTy a b) = HsAppTy (g a) (g b)
f (HsFunTy a b) = HsFunTy (g a) (g b)
f (HsListTy a) = HsListTy (g a)
f (HsPArrTy a) = HsPArrTy (g a)
f (HsTupleTy a b) = HsTupleTy a (map g b)
f (HsOpTy a b c) = HsOpTy (g a) b (g c)
f (HsParTy a) = HsParTy (g a)
f (HsKindSig a b) = HsKindSig (g a) b
f (HsDocTy a _) = f $ unL a
f x = x
outHsType :: OutputableBndr a => HsType a -> String
outHsType = out . dropHsDocTy
makeExplicit :: HsType a -> HsType a
makeExplicit (HsForAllTy _ a b c) = HsForAllTy Explicit a b c
makeExplicit x = x
makeExplicitL :: LHsType a -> LHsType a
makeExplicitL (L src x) = L src (makeExplicit x)
dropComment :: String -> String
dropComment (' ':'-':'-':' ':_) = []
dropComment (x:xs) = x : dropComment xs
dropComment [] = []
out :: Outputable a => a -> String
out = f . unwords . map (dropWhile isSpace) . lines . showSDocUnqual . ppr
where
f xs | " <document comment>" `isPrefixOf` xs = f $ drop 19 xs
f (x:xs) = x : f xs
f [] = []
operator :: String -> String
operator (x:xs) | not (isAlphaNum x) && x `notElem` "_' ([{" = "(" ++ x:xs ++ ")"
operator x = x
---------------------------------------------------------------------
-- How to print each export
ppExport :: ExportItem Name -> [String]
ppExport (ExportDecl decl dc subdocs _) = doc (fst dc) ++ f (unL decl)
where
f (TyClD d@TyData{}) = ppData d subdocs
f (TyClD d@ClassDecl{}) = ppClass d
f (TyClD d@TySynonym{}) = ppSynonym d
f (ForD (ForeignImport name typ _)) = ppSig $ TypeSig name typ
f (ForD (ForeignExport name typ _)) = ppSig $ TypeSig name typ
f (SigD sig) = ppSig sig
f _ = []
ppExport _ = []
ppSig :: Sig Name -> [String]
ppSig (TypeSig name sig) = [operator (out name) ++ " :: " ++ outHsType typ]
where
typ = case unL sig of
HsForAllTy Explicit a b c -> HsForAllTy Implicit a b c
x -> x
ppSig _ = []
ppSynonym :: TyClDecl Name -> [String]
ppSynonym x = [out x]
-- note: does not yet output documentation for class methods
ppClass :: TyClDecl Name -> [String]
ppClass x = out x{tcdSigs=[]} :
concatMap (ppSig . addContext . unL) (tcdSigs x)
where
addContext (TypeSig name (L l sig)) = TypeSig name (L l $ f sig)
addContext _ = error "expected TypeSig"
f (HsForAllTy a b con d) = HsForAllTy a b (reL $ context : unL con) d
f t = HsForAllTy Implicit [] (reL [context]) (reL t)
context = reL $ HsClassP (unL $ tcdLName x)
(map (reL . HsTyVar . hsTyVarName . unL) (tcdTyVars x))
ppInstance :: Instance -> [String]
ppInstance x = [dropComment $ out x]
ppData :: TyClDecl Name -> [(Name, DocForDecl Name)] -> [String]
ppData x subdocs = showData x{tcdCons=[],tcdDerivs=Nothing} :
concatMap (ppCtor x subdocs . unL) (tcdCons x)
where
-- GHC gives out "data Bar =", we want to delete the equals
-- also writes data : a b, when we want data (:) a b
showData d = unwords $ map f $ if last xs == "=" then init xs else xs
where
xs = words $ out d
nam = out $ tcdLName d
f w = if w == nam then operator nam else w
-- | for constructors, and named-fields...
lookupCon :: [(Name, DocForDecl Name)] -> Located Name -> Maybe (Doc Name)
lookupCon subdocs (L _ name) = case lookup name subdocs of
Just (d, _) -> d
_ -> Nothing
ppCtor :: TyClDecl Name -> [(Name, DocForDecl Name)] -> ConDecl Name -> [String]
ppCtor dat subdocs con = doc (lookupCon subdocs (con_name con))
++ f (con_details con)
where
f (PrefixCon args) = [typeSig name $ args ++ [resType]]
f (InfixCon a1 a2) = f $ PrefixCon [a1,a2]
f (RecCon recs) = f (PrefixCon $ map cd_fld_type recs) ++ concat
[doc (lookupCon subdocs (cd_fld_name r)) ++
[out (unL $ cd_fld_name r) `typeSig` [resType, cd_fld_type r]]
| r <- recs]
funs = foldr1 (\x y -> reL $ HsFunTy (makeExplicitL x) (makeExplicitL y))
apps = foldl1 (\x y -> reL $ HsAppTy x y)
typeSig nm flds = operator nm ++ " :: " ++ outHsType (makeExplicit $ unL $ funs flds)
name = out $ unL $ con_name con
resType = case con_res con of
ResTyH98 -> apps $ map (reL . HsTyVar) $ unL (tcdLName dat) : [hsTyVarName v | v@UserTyVar {} <- map unL $ tcdTyVars dat]
ResTyGADT x -> x
---------------------------------------------------------------------
-- DOCUMENTATION
doc :: Outputable o => Maybe (Doc o) -> [String]
doc = docWith ""
docWith :: Outputable o => String -> Maybe (Doc o) -> [String]
docWith [] Nothing = []
docWith header d = ("":) $ zipWith (++) ("-- | " : repeat "-- ") $
[header | header /= ""] ++ ["" | header /= "" && isJust d] ++
maybe [] (showTags . markup markupTag) d
data Tag = TagL Char [Tags] | TagP Tags | TagPre Tags | TagInline String Tags | Str String
deriving Show
type Tags = [Tag]
box :: (a -> b) -> a -> [b]
box f x = [f x]
str :: String -> [Tag]
str a = [Str a]
-- want things like paragraph, pre etc to be handled by blank lines in the source document
-- and things like \n and \t converted away
-- much like blogger in HTML mode
-- everything else wants to be included as tags, neatly nested for some (ul,li,ol)
-- or inlne for others (a,i,tt)
-- entities (&,>,<) should always be appropriately escaped
markupTag :: Outputable o => DocMarkup o [Tag]
markupTag = Markup {
markupParagraph = box TagP,
markupEmpty = str "",
markupString = str,
markupAppend = (++),
markupIdentifier = box (TagInline "a") . str . out . head,
markupModule = box (TagInline "a") . str,
markupEmphasis = box (TagInline "i"),
markupMonospaced = box (TagInline "tt"),
markupPic = const $ str " ",
markupUnorderedList = box (TagL 'u'),
markupOrderedList = box (TagL 'o'),
markupDefList = box (TagL 'u') . map (\(a,b) -> TagInline "i" a : Str " " : b),
markupCodeBlock = box TagPre,
markupURL = box (TagInline "a") . str,
markupAName = const $ str "",
markupExample = box TagPre . str . unlines . (map exampleToString)
}
showTags :: [Tag] -> [String]
showTags = concat . intersperse [""] . map showBlock
where
showBlock :: Tag -> [String]
showBlock (TagP xs) = showInline xs
showBlock (TagL t xs) = ['<':t:"l>"] ++ mid ++ ['<':'/':t:"l>"]
where mid = concatMap (showInline . box (TagInline "li")) xs
showBlock (TagPre xs) = ["<pre>"] ++ showPre xs ++ ["</pre>"]
showBlock x = showInline [x]
asInline :: Tag -> Tags
asInline (TagP xs) = xs
asInline (TagPre xs) = [TagInline "pre" xs]
asInline (TagL t xs) = [TagInline (t:"l") $ map (TagInline "li") xs]
asInline x = [x]
showInline :: [Tag] -> [String]
showInline = unwordsWrap 70 . words . concatMap f
where
fs = concatMap f
f (Str x) = escape x
f (TagInline s xs) = "<"++s++">" ++ (if s == "li" then trim else id) (fs xs) ++ "</"++s++">"
f x = fs $ asInline x
trim = dropWhile isSpace . reverse . dropWhile isSpace . reverse
showPre :: [Tag] -> [String]
showPre = trimFront . trimLines . lines . concatMap f
where
trimLines = dropWhile null . reverse . dropWhile null . reverse
trimFront xs = map (drop i) xs
where
ns = [length a | x <- xs, let (a,b) = span isSpace x, b /= ""]
i = if null ns then 0 else minimum ns
fs = concatMap f
f (Str x) = escape x
f (TagInline s xs) = "<"++s++">" ++ fs xs ++ "</"++s++">"
f x = fs $ asInline x
unwordsWrap :: Int -> [String] -> [String]
unwordsWrap n = f n []
where
f _ s [] = [g s | s /= []]
f i s (x:xs) | nx > i = g s : f (n - nx - 1) [x] xs
| otherwise = f (i - nx - 1) (x:s) xs
where nx = length x
g = unwords . reverse
escape :: String -> String
escape = concatMap f
where
f '<' = "<"
f '>' = ">"
f '&' = "&"
f x = [x]
| nominolo/haddock2 | src/Haddock/Backends/Hoogle.hs | bsd-2-clause | 10,311 | 0 | 18 | 2,949 | 4,030 | 2,059 | 1,971 | 198 | 12 |
{-
Problem 24
What is the 10^6th permutation of 0123456789?
Result
2783915460
4.42 s
-}
module Problem24 (solution) where
import Data.Permute
import CommonFunctions
import Data.Maybe
start = listPermute 10 [0..9]
nextN :: (Integral i) => i -> Permute -> Maybe Permute
nextN n p | n == 0 = Just p
| otherwise = next p >>= nextN (n-1)
millionthPermutation = fromJust . nextN (10^6-1) $ start
solution :: Integer
solution = implodeInt 10 . map fromIntegral . elems $ millionthPermutation | quchen/HaskellEuler | src/Problem24.hs | bsd-3-clause | 552 | 0 | 10 | 148 | 167 | 86 | 81 | 11 | 1 |
module Listen (listenSocket) where
import Network.Socket
listenQueueLength :: Int
listenQueueLength = 2048
listenSocket :: String -> IO Socket
listenSocket portNumber = do
let hint = defaultHints {addrFlags = [AI_PASSIVE]}
addrinfos <- getAddrInfo (Just hint) Nothing (Just portNumber)
let serveraddr = head addrinfos
listenSock <- socket (addrFamily serveraddr) Stream defaultProtocol
bindSocket listenSock $ addrAddress serveraddr
setSocketOption listenSock ReuseAddr 1
setSocketOption listenSock NoDelay 1
listen listenSock listenQueueLength
return listenSock
| kazu-yamamoto/witty | src/Listen.hs | bsd-3-clause | 602 | 0 | 12 | 106 | 169 | 80 | 89 | 15 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.Yall.Lenq
-- Copyright : (c) 2012 Michael Sloan
-- License : BSD-style (see the LICENSE file)
-- Maintainer : Michael Sloan <mgsloan@gmail.com>
-- Stability : experimental
-- Portability : GHC only
--
-- This is a convenience module providing "Yet Another Lens Library"
-- quasi-quoters.
--
-- The exported quasi-quoters allow for convenient construction of
-- lenses and bijections. These are expressed by writing a getter, using a
-- restricted subset of Haskell, such that deriving a setter is possible.
--
-- See "Language.Lenq" for documentation.
--
-----------------------------------------------------------------------------
module Data.Yall.Lenq ( bijq, lenq ) where
import Language.Lenq
import Language.Haskell.TH.Quote ( QuasiQuoter )
--TODO: partiality
lenq, bijq :: QuasiQuoter
lenq = lenqQuoter $ mkLenqConf "lens" "get" "set"
bijq = bijqQuoter $ mkBijqConf "iso" "$-" "-$"
| mgsloan/lenq | src/Data/Yall/Lenq.hs | bsd-3-clause | 1,014 | 0 | 6 | 156 | 91 | 62 | 29 | 6 | 1 |
{-# LANGUAGE PatternSynonyms #-}
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.GL.EXT.StencilTwoSide
-- Copyright : (c) Sven Panne 2019
-- License : BSD3
--
-- Maintainer : Sven Panne <svenpanne@gmail.com>
-- Stability : stable
-- Portability : portable
--
--------------------------------------------------------------------------------
module Graphics.GL.EXT.StencilTwoSide (
-- * Extension Support
glGetEXTStencilTwoSide,
gl_EXT_stencil_two_side,
-- * Enums
pattern GL_ACTIVE_STENCIL_FACE_EXT,
pattern GL_STENCIL_TEST_TWO_SIDE_EXT,
-- * Functions
glActiveStencilFaceEXT
) where
import Graphics.GL.ExtensionPredicates
import Graphics.GL.Tokens
import Graphics.GL.Functions
| haskell-opengl/OpenGLRaw | src/Graphics/GL/EXT/StencilTwoSide.hs | bsd-3-clause | 774 | 0 | 5 | 105 | 62 | 46 | 16 | 10 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MagicHash #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE UnboxedTuples #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Numeric.DataFrame.Internal.Backend.Family.FloatX4 (FloatX4 (..)) where
import GHC.Base
import Numeric.DataFrame.Internal.PrimArray
import Numeric.DataFrame.SubSpace
import Numeric.Dimensions
import Numeric.PrimBytes
import Numeric.ProductOrd
import qualified Numeric.ProductOrd.NonTransitive as NonTransitive
import qualified Numeric.ProductOrd.Partial as Partial
import Unsafe.Coerce (unsafeCoerce)
data FloatX4 = FloatX4# Float# Float# Float# Float#
-- | Since @Bounded@ is not implemented for floating point types, this instance
-- has an unresolvable constraint.
-- Nevetheless, it is good to have it here for nicer error messages.
instance Bounded Float => Bounded FloatX4 where
maxBound = case maxBound of F# x -> FloatX4# x x x x
minBound = case minBound of F# x -> FloatX4# x x x x
instance Eq FloatX4 where
FloatX4# a1 a2 a3 a4 == FloatX4# b1 b2 b3 b4 =
isTrue#
( (a1 `eqFloat#` b1)
`andI#` (a2 `eqFloat#` b2)
`andI#` (a3 `eqFloat#` b3)
`andI#` (a4 `eqFloat#` b4)
)
{-# INLINE (==) #-}
FloatX4# a1 a2 a3 a4 /= FloatX4# b1 b2 b3 b4 =
isTrue#
( (a1 `neFloat#` b1)
`orI#` (a2 `neFloat#` b2)
`orI#` (a3 `neFloat#` b3)
`orI#` (a4 `neFloat#` b4)
)
{-# INLINE (/=) #-}
cmp' :: Float# -> Float# -> PartialOrdering
cmp' a b
| isTrue# (a `gtFloat#` b) = PGT
| isTrue# (a `ltFloat#` b) = PLT
| otherwise = PEQ
instance ProductOrder FloatX4 where
cmp (FloatX4# a1 a2 a3 a4) (FloatX4# b1 b2 b3 b4)
= cmp' a1 b1 <> cmp' a2 b2 <> cmp' a3 b3 <> cmp' a4 b4
{-# INLINE cmp #-}
instance Ord (NonTransitive.ProductOrd FloatX4) where
NonTransitive.ProductOrd x > NonTransitive.ProductOrd y = cmp x y == PGT
{-# INLINE (>) #-}
NonTransitive.ProductOrd x < NonTransitive.ProductOrd y = cmp x y == PLT
{-# INLINE (<) #-}
(>=) (NonTransitive.ProductOrd (FloatX4# a1 a2 a3 a4))
(NonTransitive.ProductOrd (FloatX4# b1 b2 b3 b4)) = isTrue#
((a1 `geFloat#` b1) `andI#` (a2 `geFloat#` b2) `andI#` (a3 `geFloat#` b3) `andI#` (a4 `geFloat#` b4))
{-# INLINE (>=) #-}
(<=) (NonTransitive.ProductOrd (FloatX4# a1 a2 a3 a4))
(NonTransitive.ProductOrd (FloatX4# b1 b2 b3 b4)) = isTrue#
((a1 `leFloat#` b1) `andI#` (a2 `leFloat#` b2) `andI#` (a3 `leFloat#` b3) `andI#` (a4 `leFloat#` b4))
{-# INLINE (<=) #-}
compare (NonTransitive.ProductOrd a) (NonTransitive.ProductOrd b)
= NonTransitive.toOrdering $ cmp a b
{-# INLINE compare #-}
min (NonTransitive.ProductOrd (FloatX4# a1 a2 a3 a4))
(NonTransitive.ProductOrd (FloatX4# b1 b2 b3 b4))
= NonTransitive.ProductOrd
( FloatX4#
(if isTrue# (a1 `gtFloat#` b1) then b1 else a1)
(if isTrue# (a2 `gtFloat#` b2) then b2 else a2)
(if isTrue# (a3 `gtFloat#` b3) then b3 else a3)
(if isTrue# (a4 `gtFloat#` b4) then b4 else a4)
)
{-# INLINE min #-}
max (NonTransitive.ProductOrd (FloatX4# a1 a2 a3 a4))
(NonTransitive.ProductOrd (FloatX4# b1 b2 b3 b4))
= NonTransitive.ProductOrd
( FloatX4#
(if isTrue# (a1 `ltFloat#` b1) then b1 else a1)
(if isTrue# (a2 `ltFloat#` b2) then b2 else a2)
(if isTrue# (a3 `ltFloat#` b3) then b3 else a3)
(if isTrue# (a4 `ltFloat#` b4) then b4 else a4)
)
{-# INLINE max #-}
instance Ord (Partial.ProductOrd FloatX4) where
Partial.ProductOrd x > Partial.ProductOrd y = cmp x y == PGT
{-# INLINE (>) #-}
Partial.ProductOrd x < Partial.ProductOrd y = cmp x y == PLT
{-# INLINE (<) #-}
(>=) (Partial.ProductOrd (FloatX4# a1 a2 a3 a4))
(Partial.ProductOrd (FloatX4# b1 b2 b3 b4)) = isTrue#
((a1 `geFloat#` b1) `andI#` (a2 `geFloat#` b2) `andI#` (a3 `geFloat#` b3) `andI#` (a4 `geFloat#` b4))
{-# INLINE (>=) #-}
(<=) (Partial.ProductOrd (FloatX4# a1 a2 a3 a4))
(Partial.ProductOrd (FloatX4# b1 b2 b3 b4)) = isTrue#
((a1 `leFloat#` b1) `andI#` (a2 `leFloat#` b2) `andI#` (a3 `leFloat#` b3) `andI#` (a4 `leFloat#` b4))
{-# INLINE (<=) #-}
compare (Partial.ProductOrd a) (Partial.ProductOrd b)
= Partial.toOrdering $ cmp a b
{-# INLINE compare #-}
min (Partial.ProductOrd (FloatX4# a1 a2 a3 a4))
(Partial.ProductOrd (FloatX4# b1 b2 b3 b4))
= Partial.ProductOrd
( FloatX4#
(if isTrue# (a1 `gtFloat#` b1) then b1 else a1)
(if isTrue# (a2 `gtFloat#` b2) then b2 else a2)
(if isTrue# (a3 `gtFloat#` b3) then b3 else a3)
(if isTrue# (a4 `gtFloat#` b4) then b4 else a4)
)
{-# INLINE min #-}
max (Partial.ProductOrd (FloatX4# a1 a2 a3 a4))
(Partial.ProductOrd (FloatX4# b1 b2 b3 b4))
= Partial.ProductOrd
( FloatX4#
(if isTrue# (a1 `ltFloat#` b1) then b1 else a1)
(if isTrue# (a2 `ltFloat#` b2) then b2 else a2)
(if isTrue# (a3 `ltFloat#` b3) then b3 else a3)
(if isTrue# (a4 `ltFloat#` b4) then b4 else a4)
)
{-# INLINE max #-}
instance Ord FloatX4 where
FloatX4# a1 a2 a3 a4 > FloatX4# b1 b2 b3 b4
| isTrue# (a1 `gtFloat#` b1) = True
| isTrue# (a1 `ltFloat#` b1) = False
| isTrue# (a2 `gtFloat#` b2) = True
| isTrue# (a2 `ltFloat#` b2) = False
| isTrue# (a3 `gtFloat#` b3) = True
| isTrue# (a3 `ltFloat#` b3) = False
| isTrue# (a4 `gtFloat#` b4) = True
| otherwise = False
{-# INLINE (>) #-}
FloatX4# a1 a2 a3 a4 < FloatX4# b1 b2 b3 b4
| isTrue# (a1 `ltFloat#` b1) = True
| isTrue# (a1 `gtFloat#` b1) = False
| isTrue# (a2 `ltFloat#` b2) = True
| isTrue# (a2 `gtFloat#` b2) = False
| isTrue# (a3 `ltFloat#` b3) = True
| isTrue# (a3 `gtFloat#` b3) = False
| isTrue# (a4 `ltFloat#` b4) = True
| otherwise = False
{-# INLINE (<) #-}
FloatX4# a1 a2 a3 a4 >= FloatX4# b1 b2 b3 b4
| isTrue# (a1 `ltFloat#` b1) = False
| isTrue# (a1 `gtFloat#` b1) = True
| isTrue# (a2 `ltFloat#` b2) = False
| isTrue# (a2 `gtFloat#` b2) = True
| isTrue# (a3 `ltFloat#` b3) = False
| isTrue# (a3 `gtFloat#` b3) = True
| isTrue# (a4 `ltFloat#` b4) = False
| otherwise = True
{-# INLINE (>=) #-}
FloatX4# a1 a2 a3 a4 <= FloatX4# b1 b2 b3 b4
| isTrue# (a1 `gtFloat#` b1) = False
| isTrue# (a1 `ltFloat#` b1) = True
| isTrue# (a2 `gtFloat#` b2) = False
| isTrue# (a2 `ltFloat#` b2) = True
| isTrue# (a3 `gtFloat#` b3) = False
| isTrue# (a3 `ltFloat#` b3) = True
| isTrue# (a4 `gtFloat#` b4) = False
| otherwise = True
{-# INLINE (<=) #-}
compare (FloatX4# a1 a2 a3 a4) (FloatX4# b1 b2 b3 b4)
| isTrue# (a1 `gtFloat#` b1) = GT
| isTrue# (a1 `ltFloat#` b1) = LT
| isTrue# (a2 `gtFloat#` b2) = GT
| isTrue# (a2 `ltFloat#` b2) = LT
| isTrue# (a3 `gtFloat#` b3) = GT
| isTrue# (a3 `ltFloat#` b3) = LT
| isTrue# (a4 `gtFloat#` b4) = GT
| isTrue# (a4 `ltFloat#` b4) = LT
| otherwise = EQ
{-# INLINE compare #-}
-- | element-wise operations for vectors
instance Num FloatX4 where
FloatX4# a1 a2 a3 a4 + FloatX4# b1 b2 b3 b4
= FloatX4# (plusFloat# a1 b1) (plusFloat# a2 b2) (plusFloat# a3 b3) (plusFloat# a4 b4)
{-# INLINE (+) #-}
FloatX4# a1 a2 a3 a4 - FloatX4# b1 b2 b3 b4
= FloatX4# (minusFloat# a1 b1) (minusFloat# a2 b2) (minusFloat# a3 b3) (minusFloat# a4 b4)
{-# INLINE (-) #-}
FloatX4# a1 a2 a3 a4 * FloatX4# b1 b2 b3 b4
= FloatX4# (timesFloat# a1 b1) (timesFloat# a2 b2) (timesFloat# a3 b3) (timesFloat# a4 b4)
{-# INLINE (*) #-}
negate (FloatX4# a1 a2 a3 a4) = FloatX4#
(negateFloat# a1) (negateFloat# a2) (negateFloat# a3) (negateFloat# a4)
{-# INLINE negate #-}
abs (FloatX4# a1 a2 a3 a4)
= FloatX4#
(if isTrue# (a1 `geFloat#` 0.0#) then a1 else negateFloat# a1)
(if isTrue# (a2 `geFloat#` 0.0#) then a2 else negateFloat# a2)
(if isTrue# (a3 `geFloat#` 0.0#) then a3 else negateFloat# a3)
(if isTrue# (a4 `geFloat#` 0.0#) then a4 else negateFloat# a4)
{-# INLINE abs #-}
signum (FloatX4# a1 a2 a3 a4)
= FloatX4# (if isTrue# (a1 `gtFloat#` 0.0#)
then 1.0#
else if isTrue# (a1 `ltFloat#` 0.0#) then -1.0# else 0.0# )
(if isTrue# (a2 `gtFloat#` 0.0#)
then 1.0#
else if isTrue# (a2 `ltFloat#` 0.0#) then -1.0# else 0.0# )
(if isTrue# (a3 `gtFloat#` 0.0#)
then 1.0#
else if isTrue# (a3 `ltFloat#` 0.0#) then -1.0# else 0.0# )
(if isTrue# (a4 `gtFloat#` 0.0#)
then 1.0#
else if isTrue# (a4 `ltFloat#` 0.0#) then -1.0# else 0.0# )
{-# INLINE signum #-}
fromInteger n = case fromInteger n of F# x -> FloatX4# x x x x
{-# INLINE fromInteger #-}
instance Fractional FloatX4 where
FloatX4# a1 a2 a3 a4 / FloatX4# b1 b2 b3 b4 = FloatX4#
(divideFloat# a1 b1) (divideFloat# a2 b2) (divideFloat# a3 b3) (divideFloat# a4 b4)
{-# INLINE (/) #-}
recip (FloatX4# a1 a2 a3 a4) = FloatX4#
(divideFloat# 1.0# a1) (divideFloat# 1.0# a2) (divideFloat# 1.0# a3) (divideFloat# 1.0# a4)
{-# INLINE recip #-}
fromRational r = case fromRational r of F# x -> FloatX4# x x x x
{-# INLINE fromRational #-}
instance Floating FloatX4 where
pi = FloatX4#
3.141592653589793238#
3.141592653589793238#
3.141592653589793238#
3.141592653589793238#
{-# INLINE pi #-}
exp (FloatX4# a1 a2 a3 a4) = FloatX4#
(expFloat# a1) (expFloat# a2) (expFloat# a3) (expFloat# a4)
{-# INLINE exp #-}
log (FloatX4# a1 a2 a3 a4) = FloatX4#
(logFloat# a1) (logFloat# a2) (logFloat# a3) (logFloat# a4)
{-# INLINE log #-}
sqrt (FloatX4# a1 a2 a3 a4) = FloatX4#
(sqrtFloat# a1) (sqrtFloat# a2) (sqrtFloat# a3) (sqrtFloat# a4)
{-# INLINE sqrt #-}
sin (FloatX4# a1 a2 a3 a4) = FloatX4#
(sinFloat# a1) (sinFloat# a2) (sinFloat# a3) (sinFloat# a4)
{-# INLINE sin #-}
cos (FloatX4# a1 a2 a3 a4) = FloatX4#
(cosFloat# a1) (cosFloat# a2) (cosFloat# a3) (cosFloat# a4)
{-# INLINE cos #-}
tan (FloatX4# a1 a2 a3 a4) = FloatX4#
(tanFloat# a1) (tanFloat# a2) (tanFloat# a3) (tanFloat# a4)
{-# INLINE tan #-}
asin (FloatX4# a1 a2 a3 a4) = FloatX4#
(asinFloat# a1) (asinFloat# a2) (asinFloat# a3) (asinFloat# a4)
{-# INLINE asin #-}
acos (FloatX4# a1 a2 a3 a4) = FloatX4#
(acosFloat# a1) (acosFloat# a2) (acosFloat# a3) (acosFloat# a4)
{-# INLINE acos #-}
atan (FloatX4# a1 a2 a3 a4) = FloatX4#
(atanFloat# a1) (atanFloat# a2) (atanFloat# a3) (atanFloat# a4)
{-# INLINE atan #-}
sinh (FloatX4# a1 a2 a3 a4) = FloatX4#
(sinhFloat# a1) (sinhFloat# a2) (sinhFloat# a3) (sinhFloat# a4)
{-# INLINE sinh #-}
cosh (FloatX4# a1 a2 a3 a4) = FloatX4#
(coshFloat# a1) (coshFloat# a2) (coshFloat# a3) (coshFloat# a4)
{-# INLINE cosh #-}
tanh (FloatX4# a1 a2 a3 a4) = FloatX4#
(tanhFloat# a1) (tanhFloat# a2) (tanhFloat# a3) (tanhFloat# a4)
{-# INLINE tanh #-}
FloatX4# a1 a2 a3 a4 ** FloatX4# b1 b2 b3 b4 = FloatX4#
(powerFloat# a1 b1) (powerFloat# a2 b2) (powerFloat# a3 b3) (powerFloat# a4 b4)
{-# INLINE (**) #-}
logBase x y = log y / log x
{-# INLINE logBase #-}
asinh x = log (x + sqrt (1.0+x*x))
{-# INLINE asinh #-}
acosh x = log (x + (x+1.0) * sqrt ((x-1.0)/(x+1.0)))
{-# INLINE acosh #-}
atanh x = 0.5 * log ((1.0+x) / (1.0-x))
{-# INLINE atanh #-}
-- offset in bytes is S times bigger than offset in prim elements,
-- when S is power of two, this is equal to shift
#define BOFF_TO_PRIMOFF(off) uncheckedIShiftRL# off 2#
#define ELEM_N 4
instance PrimBytes FloatX4 where
getBytes (FloatX4# a1 a2 a3 a4) = case runRW#
( \s0 -> case newByteArray# (byteSize @FloatX4 undefined) s0 of
(# s1, marr #) -> case writeFloatArray# marr 0# a1 s1 of
s2 -> case writeFloatArray# marr 1# a2 s2 of
s3 -> case writeFloatArray# marr 2# a3 s3 of
s4 -> case writeFloatArray# marr 3# a4 s4 of
s5 -> unsafeFreezeByteArray# marr s5
) of (# _, a #) -> a
{-# INLINE getBytes #-}
fromBytes off arr
| i <- BOFF_TO_PRIMOFF(off)
= FloatX4#
(indexFloatArray# arr i)
(indexFloatArray# arr (i +# 1#))
(indexFloatArray# arr (i +# 2#))
(indexFloatArray# arr (i +# 3#))
{-# INLINE fromBytes #-}
readBytes mba off s0
| i <- BOFF_TO_PRIMOFF(off)
= case readFloatArray# mba i s0 of
(# s1, a1 #) -> case readFloatArray# mba (i +# 1#) s1 of
(# s2, a2 #) -> case readFloatArray# mba (i +# 2#) s2 of
(# s3, a3 #) -> case readFloatArray# mba (i +# 3#) s3 of
(# s4, a4 #) -> (# s4, FloatX4# a1 a2 a3 a4 #)
{-# INLINE readBytes #-}
writeBytes mba off (FloatX4# a1 a2 a3 a4) s
| i <- BOFF_TO_PRIMOFF(off)
= writeFloatArray# mba (i +# 3#) a4
( writeFloatArray# mba (i +# 2#) a3
( writeFloatArray# mba (i +# 1#) a2
( writeFloatArray# mba i a1 s )))
{-# INLINE writeBytes #-}
readAddr addr s0
= case readFloatOffAddr# addr 0# s0 of
(# s1, a1 #) -> case readFloatOffAddr# addr 1# s1 of
(# s2, a2 #) -> case readFloatOffAddr# addr 2# s2 of
(# s3, a3 #) -> case readFloatOffAddr# addr 3# s3 of
(# s4, a4 #) -> (# s4, FloatX4# a1 a2 a3 a4 #)
{-# INLINE readAddr #-}
writeAddr (FloatX4# a1 a2 a3 a4) addr s
= writeFloatOffAddr# addr 3# a4
( writeFloatOffAddr# addr 2# a3
( writeFloatOffAddr# addr 1# a2
( writeFloatOffAddr# addr 0# a1 s )))
{-# INLINE writeAddr #-}
byteSize _ = byteSize @Float undefined *# ELEM_N#
{-# INLINE byteSize #-}
byteAlign _ = byteAlign @Float undefined
{-# INLINE byteAlign #-}
byteOffset _ = 0#
{-# INLINE byteOffset #-}
byteFieldOffset _ _ = negateInt# 1#
{-# INLINE byteFieldOffset #-}
indexArray ba off
| i <- off *# ELEM_N#
= FloatX4#
(indexFloatArray# ba i)
(indexFloatArray# ba (i +# 1#))
(indexFloatArray# ba (i +# 2#))
(indexFloatArray# ba (i +# 3#))
{-# INLINE indexArray #-}
readArray mba off s0
| i <- off *# ELEM_N#
= case readFloatArray# mba i s0 of
(# s1, a1 #) -> case readFloatArray# mba (i +# 1#) s1 of
(# s2, a2 #) -> case readFloatArray# mba (i +# 2#) s2 of
(# s3, a3 #) -> case readFloatArray# mba (i +# 3#) s3 of
(# s4, a4 #) -> (# s4, FloatX4# a1 a2 a3 a4 #)
{-# INLINE readArray #-}
writeArray mba off (FloatX4# a1 a2 a3 a4) s
| i <- off *# ELEM_N#
= writeFloatArray# mba (i +# 3#) a4
( writeFloatArray# mba (i +# 2#) a3
( writeFloatArray# mba (i +# 1#) a2
( writeFloatArray# mba i a1 s )))
{-# INLINE writeArray #-}
instance PrimArray Float FloatX4 where
broadcast# (F# x) = FloatX4# x x x x
{-# INLINE broadcast# #-}
ix# 0# (FloatX4# a1 _ _ _) = F# a1
ix# 1# (FloatX4# _ a2 _ _) = F# a2
ix# 2# (FloatX4# _ _ a3 _) = F# a3
ix# 3# (FloatX4# _ _ _ a4) = F# a4
ix# _ _ = undefined
{-# INLINE ix# #-}
gen# _ f s0 = case f s0 of
(# s1, F# a1 #) -> case f s1 of
(# s2, F# a2 #) -> case f s2 of
(# s3, F# a3 #) -> case f s3 of
(# s4, F# a4 #) -> (# s4, FloatX4# a1 a2 a3 a4 #)
upd# _ 0# (F# q) (FloatX4# _ y z w) = FloatX4# q y z w
upd# _ 1# (F# q) (FloatX4# x _ z w) = FloatX4# x q z w
upd# _ 2# (F# q) (FloatX4# x y _ w) = FloatX4# x y q w
upd# _ 3# (F# q) (FloatX4# x y z _) = FloatX4# x y z q
upd# _ _ _ x = x
{-# INLINE upd# #-}
withArrayContent# _ g x = g (CumulDims [ELEM_N, 1]) 0# (getBytes x)
{-# INLINE withArrayContent# #-}
offsetElems _ = 0#
{-# INLINE offsetElems #-}
uniqueOrCumulDims _ = Right (CumulDims [ELEM_N, 1])
{-# INLINE uniqueOrCumulDims #-}
fromElems# _ off ba = FloatX4#
(indexFloatArray# ba off)
(indexFloatArray# ba (off +# 1#))
(indexFloatArray# ba (off +# 2#))
(indexFloatArray# ba (off +# 3#))
{-# INLINE fromElems# #-}
--------------------------------------------------------------------------------
-- Rewrite rules to improve efficiency of algorithms
--
-- Here we don't have access to DataFrame constructors, because we cannot import
-- Numeric.DataFrame.Type module.
-- However, we know that all DataFrame instances are just newtype wrappers
-- (as well as Scalar). Thus, we can use unsafeCoerce# to get access to Arrays
-- inside DataFrames.
--
--------------------------------------------------------------------------------
getIdxOffset :: Idxs '[4] -> Int#
getIdxOffset is = case unsafeCoerce is of
~[w] -> case w of W# i -> word2Int# i
{-# INLINE getIdxOffset #-}
{-# RULES
"index/FloatX4" forall i . index @Float @'[4] @'[] @'[4] i
= unsafeCoerce (ix# @Float @FloatX4 (getIdxOffset i))
#-}
| achirkin/easytensor | easytensor/src-base/Numeric/DataFrame/Internal/Backend/Family/FloatX4.hs | bsd-3-clause | 17,779 | 0 | 25 | 5,187 | 6,256 | 3,280 | 2,976 | 383 | 1 |
{-|
Module : Omnifmt.Directory
Description : System directory utilities.
Copyright : (c) Henry J. Wylde, 2015
License : BSD3
Maintainer : public@hjwylde.com
System directory utilities.
-}
module Omnifmt.Directory (
-- * Changing directories
withCurrentDirectory,
) where
import Control.Monad.Catch (MonadMask, bracket)
import Control.Monad.Except
import System.Directory.Extra hiding (withCurrentDirectory)
-- | @withCurrentDirectory dir action@ performs @action@ with the current directory set to @dir@.
-- The current directory is reset back to what it was afterwards.
withCurrentDirectory :: (MonadIO m, MonadMask m) => FilePath -> m a -> m a
withCurrentDirectory dir action = bracket (liftIO getCurrentDirectory) (liftIO . setCurrentDirectory)
$ \_ -> liftIO (setCurrentDirectory dir) >> action
| hjwylde/omnifmt | src/Omnifmt/Directory.hs | bsd-3-clause | 833 | 0 | 10 | 138 | 132 | 75 | 57 | 8 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Example where
import Development.GitRev
panic :: String -> a
panic msg = error panicMsg
where panicMsg =
concat [ "[panic ", $(gitBranch), "@", $(gitHash)
, " (", $(gitCommitDate), ")"
, " (", $(gitCommitCount), " commits in HEAD)"
, dirty, "] ", msg ]
dirty | $(gitDirty) = " (uncommitted files present)"
| otherwise = ""
main = panic "oh no!"
| silky/gitrev | Example.hs | bsd-3-clause | 474 | 0 | 11 | 154 | 127 | 71 | 56 | 13 | 1 |
--file : Main.hs
--date : 17/01/18
--author : mi-na
--rational : main logic
--main logic
module Main where
--outer module(self-defined)
import FieldD
import InitializeO
import StatusO
import TurnO
import CliminalO
import AlgorithmO
--outer module(public)
import System.Random
import System.IO
import Control.Monad
--constant
isDebug :: Bool
isDebug = True
--implementation
main :: IO ()
main = do
putStrLn "use default map [Y/N] :>"
sameMapOrRandom <- getLine
gen <- getStdGen
let initCardSet = (["STATION", "STATION", "STATION", "STATION", "STATION", "STATION", "AIRPORT", "AIRPORT", "AIRPORT"], ["STATION", "STATION", "STATION", "STATION", "STATION", "STATION"])
mapGen = if sameMapOrRandom == "Y"
then (mkStdGen 100)
else gen
initStatus = gameSetup initCardSet 60 mapGen
(_, nList, _) = initStatus
(pData, _) = formatDataToOutput initStatus
--initStatus = gameSetup initCardSet 60 gen
writeFile "resource/map_data.txt" $ show nList
writeFile "resource/status.txt" "0\n"
forM (tail pData) $ \x -> do
appendFile "resource/status.txt" $ x ++ ['\n']
putStrLn $ show x
--clear the old game info
writeFile "resource/game_log.txt" ""
--for debug
writeFile "debug/storage/map_data.log" $ show nList
writeFile "debug/storage/turn_0.log" ""
putStrLn $ show nList
forM pData $ \x -> appendFile "debug/storage/turn_0.log" $ x ++ ['\n']
routine 1 initStatus
| mi-na/scotland_yard | app/Main.hs | bsd-3-clause | 1,558 | 0 | 13 | 389 | 364 | 194 | 170 | 35 | 2 |
import Control.Distributed.Process
import Control.Distributed.Process.Node (initRemoteTable)
import Control.Distributed.Process.Zookeeper
import Control.Monad (void)
import System.Environment (getArgs)
-- Run the program with "args" to request a job named "args" - run with no
-- args to startup a boss and each worker. Entering a new-line will
-- terminate Boss or Workers.
main :: IO ()
main =
bootstrapWith defaultConfig --{logTrace = sayTrace}
"localhost"
"0"
"localhost:2181"
initRemoteTable $
do args <- liftIO getArgs
case args of
job : more -> -- transient requestor - sends job and exits
do Just boss <- whereisGlobal "boss"
send boss (job ++ " " ++ unwords more)
_ -> -- will be a boss or boss candidate + worker
do say "Starting persistent process - press <Enter> to exit."
Right boss <- registerCandidate "boss" $
do say "I'm the boss!"
workers <- getCapable "worker"
case length workers of
0 -> say $ "I don't do any work! Start "
++ " a worker."
n -> say $ "I've got " ++ show n
++ " workers right now."
bossLoop 0
self <- getSelfNode
if self == processNodeId boss -- like a boss
then void $ liftIO getLine
else do worker <- getSelfPid
register "worker" worker
say "Worker waiting for task..."
void . spawnLocal $ --wait for exit
do void $ liftIO getLine
send worker "stop"
workLoop
-- Calling getCapable for every loop is no problem because the results
-- of this are cached until the worker node is updated in Zookeeper.
bossLoop :: Int -> Process ()
bossLoop i =
do job <- expect :: Process String
found <- getCapable "worker"
case found of
[] ->
do say "Where is my workforce?!"
bossLoop i
workers ->
do say $ "'Delegating' task: " ++ job ++ " to " ++ show (pick workers)
send (pick workers) job >> bossLoop (i + 1)
where pick workers
| length workers > 1 = head $ drop (mod i (length workers)) workers
| otherwise = head workers
workLoop :: Process ()
workLoop =
do work <- expect :: Process String
case take 4 work of
"stop" ->
say "No more work for me!"
_ ->
do say $ "Doing task: " ++ work
workLoop
| jeremyjh/distributed-process-zookeeper | examples/Boss.hs | bsd-3-clause | 2,950 | 0 | 22 | 1,290 | 590 | 277 | 313 | 61 | 4 |
module Main where
import System.Exit (exitFailure, exitSuccess)
import System.IO (hPutStrLn, stderr)
import qualified CabalBounds.Args as Args
import CabalBounds.Main (cabalBounds)
main :: IO ()
main = do
args <- Args.get
error <- cabalBounds args
case error of
Just err -> hPutStrLn stderr ("cabal-bounds: " ++ err) >> exitFailure
_ -> exitSuccess
| dan-t/cabal-bounds | exe/Main.hs | bsd-3-clause | 380 | 0 | 13 | 81 | 120 | 65 | 55 | 12 | 2 |
module Main (main) where
import Control.Monad
import Data.List
import DynFlags
import Language.Haskell.Extension
main :: IO ()
main = do
let ghcExtensions = map flagSpecName xFlags
cabalExtensions = map show [ toEnum 0 :: KnownExtension .. ]
ghcOnlyExtensions = ghcExtensions \\ cabalExtensions
cabalOnlyExtensions = cabalExtensions \\ ghcExtensions
check "GHC-only flags" expectedGhcOnlyExtensions ghcOnlyExtensions
check "Cabal-only flags" expectedCabalOnlyExtensions cabalOnlyExtensions
check :: String -> [String] -> [String] -> IO ()
check title expected got
= do let unexpected = got \\ expected
missing = expected \\ got
showProblems problemType problems
= unless (null problems) $
do putStrLn (title ++ ": " ++ problemType)
putStrLn "-----"
mapM_ putStrLn problems
putStrLn "-----"
putStrLn ""
showProblems "Unexpected flags" unexpected
showProblems "Missing flags" missing
expectedGhcOnlyExtensions :: [String]
expectedGhcOnlyExtensions = ["RelaxedLayout",
"AlternativeLayoutRule",
"AlternativeLayoutRuleTransitional",
"DeriveAnyClass",
"JavaScriptFFI",
"PatternSynonyms",
"PartialTypeSignatures",
"NamedWildcards",
"StaticPointers"]
expectedCabalOnlyExtensions :: [String]
expectedCabalOnlyExtensions = ["Generics",
"ExtensibleRecords",
"RestrictedTypeSynonyms",
"HereDocuments",
"NewQualifiedOperators",
"XmlSyntax",
"RegularPatterns",
"SafeImports",
"Safe",
"Unsafe",
"Trustworthy"]
| bitemyapp/ghc | testsuite/tests/driver/T4437.hs | bsd-3-clause | 2,172 | 0 | 16 | 923 | 345 | 183 | 162 | 48 | 1 |
module Main where
{-
- The purpose of this program is to provide a nice and easy way to split up multiple
- segments of one audio file, separated by 'quiet' times, into their own separate files.
-}
-- Currently I am thinking that downsampling, averaging and elevating again might be the
-- correct solution here.
-- What we want is a list of booleans to tell us which samples to split. We should ignore
-- massive runs of false in the array too and runs of true should end up in split files.
-- We have multiple channels, we should merge them all into the same channel by averaging
-- and then perform our logic.
import Control.Applicative ((<$>))
import Control.Monad (zipWithM_)
import Data.List (transpose, groupBy, foldr)
import Data.Maybe (fromMaybe)
import Data.Int
import qualified Data.Vector as V
import qualified Data.List.Split as S
import System.Environment (getArgs)
import System.Exit (exitWith, ExitCode(..))
import System.FilePath (splitExtension)
import Sound.Wav
import Sound.Wav.ChannelData
import VectorUtils
main = do
args <- getArgs
case args of
[] -> do
putStrLn "Need to provide a file to be split. Exiting."
exitWith (ExitFailure 1)
(x:_) -> splitFile x
-- TODO the best wayy to spot the spoken parts of the signal are to use the FFT output
splitFile :: FilePath -> IO ()
splitFile filePath = do
riffFile <- decodeWaveFile filePath
case splitWavFile riffFile of
Left error -> putStrLn error
Right files -> zipWithM_ encodeWaveFile filenames files
where
filenames = fmap filenameFor [1..]
filenameFor n = base ++ "." ++ show n ++ ext
(base, ext) = splitExtension filePath
-- TODO If a fact chunk is present then this function should update it
splitWavFile :: WaveFile -> Either WaveParseError [WaveFile]
splitWavFile originalFile = do
extractedData <- extractFloatingWaveData originalFile
return . fmap (encodeFloatingWaveData originalFile) $ splitChannels extractedData
retentionWidth :: Int
retentionWidth = 10
lowerBoundPercent = 0.05
-- Splits one set of channels into equal channel splits
splitChannels :: FloatingWaveData -> [FloatingWaveData]
splitChannels (FloatingWaveData channels) =
FloatingWaveData <$> [fmap zeroBadElements joinedChannels]
where
retain :: Int -> V.Vector Bool
retain x = expand x . valuableSections . squishChannel x . fmap abs $ head channels
joinedElements :: [V.Vector a] -> [V.Vector (Bool, a)]
joinedElements = fmap (V.zip retention)
where
retention = retain retentionWidth
zeroBadElements :: Num a => V.Vector (Bool, a) -> V.Vector a
zeroBadElements = fmap (\(keep, val) -> if keep then val else 0)
joinedChannels = joinedElements channels
trueIsElem :: [(Bool, a)] -> Bool
trueIsElem a = True `elem` fmap fst a
fstEqual :: Eq a => (a, b) -> (a, c) -> Bool
fstEqual a b = fst a == fst b
-- TODO doing this function as a vector was previously slow. Try and come up with a more
-- efficient way to write this method that does not require converting back and forth
-- between lists
expand :: Int -> V.Vector a -> V.Vector a
expand count = asList (expandList count)
expandList :: Int -> [a] -> [a]
expandList count = foldr ((++) . replicate count) []
-- | The purpose of this function is to break up the file into sections that look valuable
-- and then we can begin to only take the sections that look good.
valuableSections :: FloatingWaveChannel -> V.Vector Bool
valuableSections absSamples = fmap (> lowerBound) absSamples
where
(minSample, maxSample) = minMax absSamples
diff = maxSample - minSample
lowerBound = minSample + lowerBoundPercent * diff
squishChannel :: Int -> FloatingWaveChannel -> FloatingWaveChannel
squishChannel factor samples = fmap floatingAverage . joinVectors $ groupedSamples
where
groupedSamples = vectorChunksOf factor samples
floatingAverage :: Floating a => [a] -> a
floatingAverage xs = sum xs / fromIntegral (length xs)
average :: Integral a => [a] -> a
average xs = fromIntegral $ sum xs `div` fromIntegral (length xs)
| CIFASIS/wavy | src/Splitter.hs | bsd-3-clause | 4,127 | 0 | 14 | 836 | 997 | 528 | 469 | 68 | 2 |
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving, ConstraintKinds, PatternGuards, StandaloneDeriving #-}
#if !(MIN_VERSION_base(4,8,0))
{-# LANGUAGE OverlappingInstances #-}
#endif
module Idris.ParseHelpers where
import Prelude hiding (pi)
import Text.Trifecta.Delta
import Text.Trifecta hiding (span, stringLiteral, charLiteral, natural, symbol, char, string, whiteSpace)
import Text.Parser.LookAhead
import Text.Parser.Expression
import qualified Text.Parser.Token as Tok
import qualified Text.Parser.Char as Chr
import qualified Text.Parser.Token.Highlight as Hi
import Idris.AbsSyntax
import Idris.Core.TT
import Idris.Core.Evaluate
import Idris.Delaborate (pprintErr)
import Idris.Docstrings
import Idris.Output (iWarn)
import qualified Util.Pretty as Pretty (text)
import Control.Applicative
import Control.Monad
import Control.Monad.State.Strict
import Data.Maybe
import qualified Data.List.Split as Spl
import Data.List
import Data.Monoid
import Data.Char
import qualified Data.Map as M
import qualified Data.HashSet as HS
import qualified Data.Text as T
import qualified Data.ByteString.UTF8 as UTF8
import System.FilePath
import Debug.Trace
-- | Idris parser with state used during parsing
type IdrisParser = StateT IState IdrisInnerParser
newtype IdrisInnerParser a = IdrisInnerParser { runInnerParser :: Parser a }
deriving (Monad, Functor, MonadPlus, Applicative, Alternative, CharParsing, LookAheadParsing, DeltaParsing, MarkParsing Delta, Monoid, TokenParsing)
deriving instance Parsing IdrisInnerParser
#if MIN_VERSION_base(4,8,0)
instance {-# OVERLAPPING #-} TokenParsing IdrisParser where
#else
instance TokenParsing IdrisParser where
#endif
someSpace = many (simpleWhiteSpace <|> singleLineComment <|> multiLineComment) *> pure ()
token p = do s <- get
(FC fn (sl, sc) _) <- getFC --TODO: Update after fixing getFC
-- See Issue #1594
r <- p
(FC fn _ (el, ec)) <- getFC
whiteSpace
put (s { lastTokenSpan = Just (FC fn (sl, sc) (el, ec)) })
return r
-- | Generalized monadic parsing constraint type
type MonadicParsing m = (DeltaParsing m, LookAheadParsing m, TokenParsing m, Monad m)
class HasLastTokenSpan m where
getLastTokenSpan :: m (Maybe FC)
instance HasLastTokenSpan IdrisParser where
getLastTokenSpan = lastTokenSpan <$> get
-- | Helper to run Idris inner parser based stateT parsers
runparser :: StateT st IdrisInnerParser res -> st -> String -> String -> Result res
runparser p i inputname =
parseString (runInnerParser (evalStateT p i))
(Directed (UTF8.fromString inputname) 0 0 0 0)
highlightP :: FC -> OutputAnnotation -> IdrisParser ()
highlightP fc annot = do ist <- get
put ist { idris_parserHighlights = (fc, annot) : idris_parserHighlights ist}
noDocCommentHere :: String -> IdrisParser ()
noDocCommentHere msg =
optional (do fc <- getFC
docComment
ist <- get
put ist { parserWarnings = (fc, Msg msg) : parserWarnings ist}) *>
pure ()
clearParserWarnings :: Idris ()
clearParserWarnings = do ist <- getIState
putIState ist { parserWarnings = [] }
reportParserWarnings :: Idris ()
reportParserWarnings = do ist <- getIState
mapM_ (uncurry iWarn)
(map (\ (fc, err) -> (fc, pprintErr ist err)) .
reverse .
nub $
parserWarnings ist)
clearParserWarnings
{- * Space, comments and literals (token/lexing like parsers) -}
-- | Consumes any simple whitespace (any character which satisfies Char.isSpace)
simpleWhiteSpace :: MonadicParsing m => m ()
simpleWhiteSpace = satisfy isSpace *> pure ()
-- | Checks if a charcter is end of line
isEol :: Char -> Bool
isEol '\n' = True
isEol _ = False
-- | A parser that succeeds at the end of the line
eol :: MonadicParsing m => m ()
eol = (satisfy isEol *> pure ()) <|> lookAhead eof <?> "end of line"
{- | Consumes a single-line comment
@
SingleLineComment_t ::= '--' ~EOL_t* EOL_t ;
@
-}
singleLineComment :: MonadicParsing m => m ()
singleLineComment = (string "--" *>
many (satisfy (not . isEol)) *>
eol *> pure ())
<?> ""
{- | Consumes a multi-line comment
@
MultiLineComment_t ::=
'{ -- }'
| '{ -' InCommentChars_t
;
@
@
InCommentChars_t ::=
'- }'
| MultiLineComment_t InCommentChars_t
| ~'- }'+ InCommentChars_t
;
@
-}
multiLineComment :: MonadicParsing m => m ()
multiLineComment = try (string "{-" *> (string "-}") *> pure ())
<|> string "{-" *> inCommentChars
<?> ""
where inCommentChars :: MonadicParsing m => m ()
inCommentChars = string "-}" *> pure ()
<|> try (multiLineComment) *> inCommentChars
<|> string "|||" *> many (satisfy (not . isEol)) *> eol *> inCommentChars
<|> skipSome (noneOf startEnd) *> inCommentChars
<|> oneOf startEnd *> inCommentChars
<?> "end of comment"
startEnd :: String
startEnd = "{}-"
{-| Parses a documentation comment
@
DocComment_t ::= '|||' ~EOL_t* EOL_t
;
@
-}
docComment :: IdrisParser (Docstring (), [(Name, Docstring ())])
docComment = do dc <- pushIndent *> docCommentLine
rest <- many (indented docCommentLine)
args <- many $ do (name, first) <- indented argDocCommentLine
rest <- many (indented docCommentLine)
return (name, concat (intersperse "\n" (first:rest)))
popIndent
return (parseDocstring $ T.pack (concat (intersperse "\n" (dc:rest))),
map (\(n, d) -> (n, parseDocstring (T.pack d))) args)
where docCommentLine :: MonadicParsing m => m String
docCommentLine = try (do string "|||"
many (satisfy (==' '))
contents <- option "" (do first <- satisfy (\c -> not (isEol c || c == '@'))
res <- many (satisfy (not . isEol))
return $ first:res)
eol ; someSpace
return contents)-- ++ concat rest))
<?> ""
argDocCommentLine = do string "|||"
many (satisfy isSpace)
char '@'
many (satisfy isSpace)
n <- fst <$> name
many (satisfy isSpace)
docs <- many (satisfy (not . isEol))
eol ; someSpace
return (n, docs)
-- | Parses some white space
whiteSpace :: MonadicParsing m => m ()
whiteSpace = Tok.whiteSpace
-- | Parses a string literal
stringLiteral :: (MonadicParsing m, HasLastTokenSpan m) => m (String, FC)
stringLiteral = do str <- Tok.stringLiteral
fc <- getLastTokenSpan
return (str, fromMaybe NoFC fc)
-- | Parses a char literal
charLiteral :: (MonadicParsing m, HasLastTokenSpan m) => m (Char, FC)
charLiteral = do ch <- Tok.charLiteral
fc <- getLastTokenSpan
return (ch, fromMaybe NoFC fc)
-- | Parses a natural number
natural :: (MonadicParsing m, HasLastTokenSpan m) => m (Integer, FC)
natural = do n <- Tok.natural
fc <- getLastTokenSpan
return (n, fromMaybe NoFC fc)
-- | Parses an integral number
integer :: MonadicParsing m => m Integer
integer = Tok.integer
-- | Parses a floating point number
float :: (MonadicParsing m, HasLastTokenSpan m) => m (Double, FC)
float = do f <- Tok.double
fc <- getLastTokenSpan
return (f, fromMaybe NoFC fc)
{- * Symbols, identifiers, names and operators -}
-- | Idris Style for parsing identifiers/reserved keywords
idrisStyle :: MonadicParsing m => IdentifierStyle m
idrisStyle = IdentifierStyle _styleName _styleStart _styleLetter _styleReserved Hi.Identifier Hi.ReservedIdentifier
where _styleName = "Idris"
_styleStart = satisfy isAlpha <|> oneOf "_"
_styleLetter = satisfy isAlphaNum <|> oneOf "_'."
_styleReserved = HS.fromList ["let", "in", "data", "codata", "record", "corecord", "Type",
"do", "dsl", "import", "impossible",
"case", "of", "total", "partial", "mutual",
"infix", "infixl", "infixr", "rewrite",
"where", "with", "syntax", "proof", "postulate",
"using", "namespace", "class", "instance", "parameters",
"public", "private", "abstract", "implicit",
"quoteGoal", "constructor",
"if", "then", "else"]
char :: MonadicParsing m => Char -> m Char
char = Chr.char
string :: MonadicParsing m => String -> m String
string = Chr.string
-- | Parses a character as a token
lchar :: MonadicParsing m => Char -> m Char
lchar = token . char
-- | Parses a character as a token, returning the source span of the character
lcharFC :: MonadicParsing m => Char -> m FC
lcharFC ch = do (FC file (l, c) _) <- getFC
_ <- token (char ch)
return $ FC file (l, c) (l, c+1)
-- | Parses string as a token
symbol :: MonadicParsing m => String -> m String
symbol = Tok.symbol
symbolFC :: MonadicParsing m => String -> m FC
symbolFC str = do (FC file (l, c) _) <- getFC
Tok.symbol str
return $ FC file (l, c) (l, c + length str)
-- | Parses a reserved identifier
reserved :: MonadicParsing m => String -> m ()
reserved = Tok.reserve idrisStyle
-- | Parses a reserved identifier, computing its span. Assumes that
-- reserved identifiers never contain line breaks.
reservedFC :: MonadicParsing m => String -> m FC
reservedFC str = do (FC file (l, c) _) <- getFC
Tok.reserve idrisStyle str
return $ FC file (l, c) (l, c + length str)
-- | Parse a reserved identfier, highlighting its span as a keyword
reservedHL :: String -> IdrisParser ()
reservedHL str = reservedFC str >>= flip highlightP AnnKeyword
-- Taken from Parsec (c) Daan Leijen 1999-2001, (c) Paolo Martini 2007
-- | Parses a reserved operator
reservedOp :: MonadicParsing m => String -> m ()
reservedOp name = token $ try $
do string name
notFollowedBy (operatorLetter) <?> ("end of " ++ show name)
reservedOpFC :: MonadicParsing m => String -> m FC
reservedOpFC name = token $ try $ do (FC f (l, c) _) <- getFC
string name
notFollowedBy (operatorLetter) <?> ("end of " ++ show name)
return (FC f (l, c) (l, c + length name))
-- | Parses an identifier as a token
identifier :: (MonadicParsing m) => m (String, FC)
identifier = try(do (i, fc) <-
token $ do (FC f (l, c) _) <- getFC
i <- Tok.ident idrisStyle
return (i, FC f (l, c) (l, c + length i))
when (i == "_") $ unexpected "wildcard"
return (i, fc))
-- | Parses an identifier with possible namespace as a name
iName :: (MonadicParsing m, HasLastTokenSpan m) => [String] -> m (Name, FC)
iName bad = do (n, fc) <- maybeWithNS identifier False bad
return (n, fc)
<?> "name"
-- | Parses an string possibly prefixed by a namespace
maybeWithNS :: (MonadicParsing m, HasLastTokenSpan m) => m (String, FC) -> Bool -> [String] -> m (Name, FC)
maybeWithNS parser ascend bad = do
fc <- getFC
i <- option "" (lookAhead (fst <$> identifier))
when (i `elem` bad) $ unexpected "reserved identifier"
let transf = if ascend then id else reverse
(x, xs, fc) <- choice (transf (parserNoNS parser : parsersNS parser i))
return (mkName (x, xs), fc)
where parserNoNS :: MonadicParsing m => m (String, FC) -> m (String, String, FC)
parserNoNS parser = do startFC <- getFC
(x, nameFC) <- parser
return (x, "", spanFC startFC nameFC)
parserNS :: MonadicParsing m => m (String, FC) -> String -> m (String, String, FC)
parserNS parser ns = do startFC <- getFC
xs <- string ns
lchar '.'; (x, nameFC) <- parser
return (x, xs, spanFC startFC nameFC)
parsersNS :: MonadicParsing m => m (String, FC) -> String -> [m (String, String, FC)]
parsersNS parser i = [try (parserNS parser ns) | ns <- (initsEndAt (=='.') i)]
-- | Parses a name
name :: IdrisParser (Name, FC)
name = (<?> "name") $ do
keywords <- syntax_keywords <$> get
aliases <- module_aliases <$> get
(n, fc) <- iName keywords
return (unalias aliases n, fc)
where
unalias :: M.Map [T.Text] [T.Text] -> Name -> Name
unalias aliases (NS n ns) | Just ns' <- M.lookup ns aliases = NS n ns'
unalias aliases name = name
{- | List of all initial segments in ascending order of a list. Every
such initial segment ends right before an element satisfying the given
condition.
-}
initsEndAt :: (a -> Bool) -> [a] -> [[a]]
initsEndAt p [] = []
initsEndAt p (x:xs) | p x = [] : x_inits_xs
| otherwise = x_inits_xs
where x_inits_xs = [x : cs | cs <- initsEndAt p xs]
{- | Create a `Name' from a pair of strings representing a base name and its
namespace.
-}
mkName :: (String, String) -> Name
mkName (n, "") = sUN n
mkName (n, ns) = sNS (sUN n) (reverse (parseNS ns))
where parseNS x = case span (/= '.') x of
(x, "") -> [x]
(x, '.':y) -> x : parseNS y
opChars :: String
opChars = ":!#$%&*+./<=>?@\\^|-~"
operatorLetter :: MonadicParsing m => m Char
operatorLetter = oneOf opChars
commentMarkers :: [String]
commentMarkers = [ "--", "|||" ]
invalidOperators :: [String]
invalidOperators = [":", "=>", "->", "<-", "=", "?=", "|", "**", "==>", "\\", "%", "~", "?", "!"]
-- | Parses an operator
operator :: MonadicParsing m => m String
operator = do op <- token . some $ operatorLetter
when (op `elem` (invalidOperators ++ commentMarkers)) $
fail $ op ++ " is not a valid operator"
return op
-- | Parses an operator
operatorFC :: MonadicParsing m => m (String, FC)
operatorFC = do (op, fc) <- token $ do (FC f (l, c) _) <- getFC
op <- some operatorLetter
return (op, FC f (l, c) (l, c + length op))
when (op `elem` (invalidOperators ++ commentMarkers)) $
fail $ op ++ " is not a valid operator"
return (op, fc)
{- * Position helpers -}
{- | Get filename from position (returns "(interactive)" when no source file is given) -}
fileName :: Delta -> String
fileName (Directed fn _ _ _ _) = UTF8.toString fn
fileName _ = "(interactive)"
{- | Get line number from position -}
lineNum :: Delta -> Int
lineNum (Lines l _ _ _) = fromIntegral l + 1
lineNum (Directed _ l _ _ _) = fromIntegral l + 1
lineNum _ = 0
{- | Get column number from position -}
columnNum :: Delta -> Int
columnNum pos = fromIntegral (column pos) + 1
{- | Get file position as FC -}
getFC :: MonadicParsing m => m FC
getFC = do s <- position
let (dir, file) = splitFileName (fileName s)
let f = if dir == addTrailingPathSeparator "." then file else fileName s
return $ FC f (lineNum s, columnNum s) (lineNum s, columnNum s) -- TODO: Change to actual spanning
-- Issue #1594 on the Issue Tracker.
-- https://github.com/idris-lang/Idris-dev/issues/1594
{-* Syntax helpers-}
-- | Bind constraints to term
bindList :: (Name -> FC -> PTerm -> PTerm -> PTerm) -> [(Name, FC, PTerm)] -> PTerm -> PTerm
bindList b [] sc = sc
bindList b ((n, fc, t):bs) sc = b n fc t (bindList b bs sc)
{- * Layout helpers -}
-- | Push indentation to stack
pushIndent :: IdrisParser ()
pushIndent = do pos <- position
ist <- get
put (ist { indent_stack = (fromIntegral (column pos) + 1) : indent_stack ist })
-- | Pops indentation from stack
popIndent :: IdrisParser ()
popIndent = do ist <- get
let (x : xs) = indent_stack ist
put (ist { indent_stack = xs })
-- | Gets current indentation
indent :: IdrisParser Int
indent = liftM ((+1) . fromIntegral . column) position
-- | Gets last indentation
lastIndent :: IdrisParser Int
lastIndent = do ist <- get
case indent_stack ist of
(x : xs) -> return x
_ -> return 1
-- | Applies parser in an indented position
indented :: IdrisParser a -> IdrisParser a
indented p = notEndBlock *> p <* keepTerminator
-- | Applies parser to get a block (which has possibly indented statements)
indentedBlock :: IdrisParser a -> IdrisParser [a]
indentedBlock p = do openBlock
pushIndent
res <- many (indented p)
popIndent
closeBlock
return res
-- | Applies parser to get a block with at least one statement (which has possibly indented statements)
indentedBlock1 :: IdrisParser a -> IdrisParser [a]
indentedBlock1 p = do openBlock
pushIndent
res <- some (indented p)
popIndent
closeBlock
return res
-- | Applies parser to get a block with exactly one (possibly indented) statement
indentedBlockS :: IdrisParser a -> IdrisParser a
indentedBlockS p = do openBlock
pushIndent
res <- indented p
popIndent
closeBlock
return res
-- | Checks if the following character matches provided parser
lookAheadMatches :: MonadicParsing m => m a -> m Bool
lookAheadMatches p = do match <- lookAhead (optional p)
return $ isJust match
-- | Parses a start of block
openBlock :: IdrisParser ()
openBlock = do lchar '{'
ist <- get
put (ist { brace_stack = Nothing : brace_stack ist })
<|> do ist <- get
lvl' <- indent
-- if we're not indented further, it's an empty block, so
-- increment lvl to ensure we get to the end
let lvl = case brace_stack ist of
Just lvl_old : _ ->
if lvl' <= lvl_old then lvl_old+1
else lvl'
[] -> if lvl' == 1 then 2 else lvl'
_ -> lvl'
put (ist { brace_stack = Just lvl : brace_stack ist })
<?> "start of block"
-- | Parses an end of block
closeBlock :: IdrisParser ()
closeBlock = do ist <- get
bs <- case brace_stack ist of
[] -> eof >> return []
Nothing : xs -> lchar '}' >> return xs <?> "end of block"
Just lvl : xs -> (do i <- indent
isParen <- lookAheadMatches (char ')')
isIn <- lookAheadMatches (reserved "in")
if i >= lvl && not (isParen || isIn)
then fail "not end of block"
else return xs)
<|> (do notOpenBraces
eof
return [])
put (ist { brace_stack = bs })
-- | Parses a terminator
terminator :: IdrisParser ()
terminator = do lchar ';'; popIndent
<|> do c <- indent; l <- lastIndent
if c <= l then popIndent else fail "not a terminator"
<|> do isParen <- lookAheadMatches (oneOf ")}")
if isParen then popIndent else fail "not a terminator"
<|> lookAhead eof
-- | Parses and keeps a terminator
keepTerminator :: IdrisParser ()
keepTerminator = do lchar ';'; return ()
<|> do c <- indent; l <- lastIndent
unless (c <= l) $ fail "not a terminator"
<|> do isParen <- lookAheadMatches (oneOf ")}|")
isIn <- lookAheadMatches (reserved "in")
unless (isIn || isParen) $ fail "not a terminator"
<|> lookAhead eof
-- | Checks if application expression does not end
notEndApp :: IdrisParser ()
notEndApp = do c <- indent; l <- lastIndent
when (c <= l) (fail "terminator")
-- | Checks that it is not end of block
notEndBlock :: IdrisParser ()
notEndBlock = do ist <- get
case brace_stack ist of
Just lvl : xs -> do i <- indent
isParen <- lookAheadMatches (char ')')
when (i < lvl || isParen) (fail "end of block")
_ -> return ()
-- | Representation of an operation that can compare the current indentation with the last indentation, and an error message if it fails
data IndentProperty = IndentProperty (Int -> Int -> Bool) String
-- | Allows comparison of indent, and fails if property doesn't hold
indentPropHolds :: IndentProperty -> IdrisParser ()
indentPropHolds (IndentProperty op msg) = do
li <- lastIndent
i <- indent
when (not $ op i li) $ fail ("Wrong indention: " ++ msg)
-- | Greater-than indent property
gtProp :: IndentProperty
gtProp = IndentProperty (>) "should be greater than context indentation"
-- | Greater-than or equal to indent property
gteProp :: IndentProperty
gteProp = IndentProperty (>=) "should be greater than or equal context indentation"
-- | Equal indent property
eqProp :: IndentProperty
eqProp = IndentProperty (==) "should be equal to context indentation"
-- | Less-than indent property
ltProp :: IndentProperty
ltProp = IndentProperty (<) "should be less than context indentation"
-- | Less-than or equal to indent property
lteProp :: IndentProperty
lteProp = IndentProperty (<=) "should be less than or equal to context indentation"
-- | Checks that there are no braces that are not closed
notOpenBraces :: IdrisParser ()
notOpenBraces = do ist <- get
when (hasNothing $ brace_stack ist) $ fail "end of input"
where hasNothing :: [Maybe a] -> Bool
hasNothing = any isNothing
{- | Parses an accessibilty modifier (e.g. public, private) -}
accessibility :: IdrisParser Accessibility
accessibility = do reserved "public"; return Public
<|> do reserved "abstract"; return Frozen
<|> do reserved "private"; return Hidden
<?> "accessibility modifier"
-- | Adds accessibility option for function
addAcc :: Name -> Maybe Accessibility -> IdrisParser ()
addAcc n a = do i <- get
put (i { hide_list = (n, a) : hide_list i })
{- | Add accessbility option for data declarations
(works for classes too - 'abstract' means the data/class is visible but members not) -}
accData :: Maybe Accessibility -> Name -> [Name] -> IdrisParser ()
accData (Just Frozen) n ns = do addAcc n (Just Frozen)
mapM_ (\n -> addAcc n (Just Hidden)) ns
accData a n ns = do addAcc n a
mapM_ (`addAcc` a) ns
{- * Error reporting helpers -}
{- | Error message with possible fixes list -}
fixErrorMsg :: String -> [String] -> String
fixErrorMsg msg fixes = msg ++ ", possible fixes:\n" ++ (concat $ intersperse "\n\nor\n\n" fixes)
-- | Collect 'PClauses' with the same function name
collect :: [PDecl] -> [PDecl]
collect (c@(PClauses _ o _ _) : ds)
= clauses (cname c) [] (c : ds)
where clauses :: Maybe Name -> [PClause] -> [PDecl] -> [PDecl]
clauses j@(Just n) acc (PClauses fc _ _ [PClause fc' n' l ws r w] : ds)
| n == n' = clauses j (PClause fc' n' l ws r (collect w) : acc) ds
clauses j@(Just n) acc (PClauses fc _ _ [PWith fc' n' l ws r pn w] : ds)
| n == n' = clauses j (PWith fc' n' l ws r pn (collect w) : acc) ds
clauses (Just n) acc xs = PClauses (fcOf c) o n (reverse acc) : collect xs
clauses Nothing acc (x:xs) = collect xs
clauses Nothing acc [] = []
cname :: PDecl -> Maybe Name
cname (PClauses fc _ _ [PClause _ n _ _ _ _]) = Just n
cname (PClauses fc _ _ [PWith _ n _ _ _ _ _]) = Just n
cname (PClauses fc _ _ [PClauseR _ _ _ _]) = Nothing
cname (PClauses fc _ _ [PWithR _ _ _ _ _]) = Nothing
fcOf :: PDecl -> FC
fcOf (PClauses fc _ _ _) = fc
collect (PParams f ns ps : ds) = PParams f ns (collect ps) : collect ds
collect (PMutual f ms : ds) = PMutual f (collect ms) : collect ds
collect (PNamespace ns fc ps : ds) = PNamespace ns fc (collect ps) : collect ds
collect (PClass doc f s cs n nfc ps pdocs fds ds cn cd : ds')
= PClass doc f s cs n nfc ps pdocs fds (collect ds) cn cd : collect ds'
collect (PInstance doc argDocs f s cs n nfc ps t en ds : ds')
= PInstance doc argDocs f s cs n nfc ps t en (collect ds) : collect ds'
collect (d : ds) = d : collect ds
collect [] = []
| athanclark/Idris-dev | src/Idris/ParseHelpers.hs | bsd-3-clause | 26,092 | 0 | 25 | 8,581 | 7,488 | 3,824 | 3,664 | 439 | 8 |
module Day9 where
import Text.Megaparsec
import Text.Megaparsec.Lexer hiding (space)
import Text.Megaparsec.String
marker1 :: Parser Int
marker1 = do
_ <- char '('
numChars <- fromIntegral <$> integer
_ <- char 'x'
repCount <- fromIntegral <$> integer
_ <- char ')'
_ <- count numChars anyChar
return $ repCount * numChars
marker2 :: Parser Int
marker2 = do
_ <- char '('
numChars <- fromIntegral <$> integer
_ <- char 'x'
repCount <- fromIntegral <$> integer
_ <- char ')'
payload <- count numChars anyChar
let Right decodedPayload = parse decoder2 "foo" payload
return $ repCount * decodedPayload
bulk1 :: Parser Int
bulk1 = length <$> some (noneOf "(")
decoder1 :: Parser Int
decoder1 = sum <$> some (marker1 <|> bulk1)
decoder2 :: Parser Int
decoder2 = sum <$> some (marker2 <|> bulk1)
main :: IO ()
main = do
let inputFile = "input/day9.txt"
input <- filter (`notElem` " \t\r\n") <$> readFile inputFile
let Right part1 = parse decoder1 inputFile input
print part1
let Right part2 = parse decoder2 inputFile input
print part2
| liff/adventofcode-2016 | app/Day9.hs | bsd-3-clause | 1,110 | 0 | 10 | 252 | 402 | 189 | 213 | 37 | 1 |
-- | Calculates yield sizes using rewriting functions.
module ADP.Multi.Rewriting.YieldSize where
import Data.Map (Map)
import qualified Data.Map as Map
import Control.Monad (liftM2)
import ADP.Multi.Parser
import ADP.Multi.Rewriting.Model
type YieldAnalysisAlgorithm a = a -> [ParserInfo] -> ParserInfo
-- for dim1 we don't need the rewriting function to determine the yield size
-- it's kept as argument anyway to make it more consistent
determineYieldSize1 :: YieldAnalysisAlgorithm Dim1
determineYieldSize1 _ infos =
let elemInfo = buildYieldSizeMap infos
(yieldMin,yieldMax) = combineYields (Map.elems elemInfo)
in ParserInfo1 {
minYield = yieldMin,
maxYield = yieldMax
}
determineYieldSize2 :: YieldAnalysisAlgorithm Dim2
determineYieldSize2 f infos =
let elemInfo = buildYieldSizeMap infos
(left,right) = f (Map.keys elemInfo)
leftYields = map (\(i,j) -> elemInfo Map.! (i,j)) left
rightYields = map (\(i,j) -> elemInfo Map.! (i,j)) right
(leftMin,leftMax) = combineYields leftYields
(rightMin,rightMax) = combineYields rightYields
in ParserInfo2 {
minYield2 = (leftMin,rightMin),
maxYield2 = (leftMax,rightMax)
}
combineYields :: [YieldSize] -> YieldSize
combineYields = foldl (\(minY1,maxY1) (minY2,maxY2) ->
( minY1+minY2
, liftM2 (+) maxY1 maxY2
) ) (0,Just 0)
-- | min and max yield size
type YieldSize = (Int,Maybe Int)
-- | Maps each parser symbol to its yield size
-- (remember: a 2-dim parser has 2 symbols in a rewriting function)
type YieldSizeMap = Map (Int,Int) YieldSize
-- the input list is in reverse order, i.e. the first in the list is the last applied parser
buildYieldSizeMap :: [ParserInfo] -> YieldSizeMap
buildYieldSizeMap infos =
let parserCount = length infos
list = concatMap (\ (x,info) -> case info of
ParserInfo1 { minYield = minY, maxYield = maxY } ->
[ ((x,1), (minY, maxY) ) ]
ParserInfo2 { minYield2 = minY, maxYield2 = maxY } ->
[ ((x,1), (fst minY, fst maxY) )
, ((x,2), (snd minY, snd maxY) )
]
) $ zip [parserCount,parserCount-1..] infos
in Map.fromList list | adp-multi/adp-multi | src/ADP/Multi/Rewriting/YieldSize.hs | bsd-3-clause | 2,473 | 0 | 19 | 764 | 631 | 364 | 267 | 43 | 2 |
{- |
Module : ./THF/PrintTHF.hs
Description : A printer for the TPTP-THF Syntax
Copyright : (c) A. Tsogias, DFKI Bremen 2011
License : GPLv2 or higher, see LICENSE.txt
Maintainer : Alexis.Tsogias@dfki.de
Stability : provisional
Portability : portable
A printer for the TPTP-THF Input Syntax v5.1.0.2 taken from
<http://www.cs.miami.edu/~tptp/TPTP/SyntaxBNF.html>
-}
module THF.PrintTHF where
import THF.As
import Data.Char
import Common.Doc
import Common.DocUtils
import Common.Id (Token)
{- -----------------------------------------------------------------------------
Pretty Instances for the THF and THF0 Syntax.
Most methods match those of As.hs
----------------------------------------------------------------------------- -}
printTPTPTHF :: [TPTP_THF] -> Doc
printTPTPTHF [] = empty
printTPTPTHF (t : rt) = case t of
TPTP_THF_Annotated_Formula {} -> pretty t $++$ printTPTPTHF rt
_ -> pretty t $+$ printTPTPTHF rt
instance Pretty TPTP_THF where
pretty t = case t of
TPTP_THF_Annotated_Formula n fr f a ->
text "thf" <> parens (pretty n <> comma
<+> pretty fr <> comma
<+> pretty f <> pretty a)
<> text "."
TPTP_Include i -> pretty i
TPTP_Comment c -> pretty c
TPTP_Defined_Comment dc -> pretty dc
TPTP_System_Comment sc -> pretty sc
TPTP_Header h -> prettyHeader h
prettyHeader :: [Comment] -> Doc
prettyHeader = foldr (($+$) . pretty) empty
instance Pretty Comment where
pretty c = case c of
Comment_Line s -> text "%" <> (text . show) s
Comment_Block sl -> text "/*"
$+$ prettyCommentBlock (lines $ show sl)
$+$ text "*/"
instance Pretty DefinedComment where
pretty dc = case dc of
Defined_Comment_Line s -> text "%$" <> (text . show) s
Defined_Comment_Block sl -> text "/*$"
$+$ prettyCommentBlock (lines $ show sl)
$+$ text "*/"
instance Pretty SystemComment where
pretty sc = case sc of
System_Comment_Line s -> text "%$$" <> (text . show) s
System_Comment_Block sl -> text "/*$$"
$+$ prettyCommentBlock (lines $ show sl)
$+$ text "*/"
prettyCommentBlock :: [String] -> Doc
prettyCommentBlock = foldr (($+$) . text) empty
instance Pretty Include where
pretty (I_Include fn nl) = text "include" <> parens (prettySingleQuoted fn
<> maybe empty (\ c -> comma <+> prettyNameList c) nl) <> text "."
instance Pretty Annotations where
pretty a = case a of
Annotations s o -> comma <+> pretty s <> prettyOptionalInfo o
Null -> empty
instance Pretty FormulaRole where
pretty fr = text $ map toLower (show fr)
instance Pretty THFFormula where
pretty f = case f of
TF_THF_Logic_Formula lf -> pretty lf
TF_THF_Sequent s -> pretty s
T0F_THF_Typed_Const tc -> pretty tc
instance Pretty THFLogicFormula where
pretty lf = case lf of
TLF_THF_Binary_Formula bf -> pretty bf
TLF_THF_Unitary_Formula uf -> pretty uf
TLF_THF_Type_Formula tf -> pretty tf
TLF_THF_Sub_Type st -> pretty st
instance Pretty THFBinaryFormula where
pretty bf = case bf of
TBF_THF_Binary_Tuple bt -> pretty bt
TBF_THF_Binary_Type bt -> pretty bt
TBF_THF_Binary_Pair uf1 pc uf2 ->
pretty uf1 <+> pretty pc <+> pretty uf2
instance Pretty THFBinaryTuple where
pretty bt = case bt of
TBT_THF_Or_Formula ufl -> sepBy (map pretty ufl) orSign
TBT_THF_And_Formula ufl -> sepBy (map pretty ufl) andSign
TBT_THF_Apply_Formula ufl -> sepBy (map pretty ufl) applySign
instance Pretty THFUnitaryFormula where
pretty tuf = case tuf of
TUF_THF_Quantified_Formula qf -> pretty qf
TUF_THF_Unary_Formula uc lf -> pretty uc <+> parens (pretty lf)
TUF_THF_Atom a -> pretty a
TUF_THF_Tuple t -> prettyTuple t
TUF_THF_Conditional lf1 lf2 lf3 ->
text "$itef" <> parens (pretty lf1
<> comma <+> pretty lf2
<> comma <+> pretty lf3)
TUF_THF_Logic_Formula_Par l -> parens (pretty l)
T0UF_THF_Abstraction vl uf -> text "^" <+>
brackets (prettyVariableList vl) <+> text ":" <+> pretty uf
instance Pretty THFQuantifiedFormula where
pretty qf = case qf of
TQF_THF_Quantified_Formula tq vl uf -> pretty tq <+>
brackets (prettyVariableList vl) <+> text ":" <+> pretty uf
T0QF_THF_Quantified_Var q vl uf -> pretty q <+>
brackets (prettyVariableList vl) <+> text ":" <+> pretty uf
T0QF_THF_Quantified_Novar tq uf ->
pretty tq <+> parens (pretty uf)
prettyVariableList :: THFVariableList -> Doc
prettyVariableList vl = sepByCommas (map pretty vl)
instance Pretty THFVariable where
pretty v = case v of
TV_THF_Typed_Variable va tlt -> prettyUpperWord va
<+> text ":" <+> pretty tlt
TV_Variable var -> prettyUpperWord var
instance Pretty THFTypedConst where
pretty ttc = case ttc of
T0TC_Typed_Const c tlt -> prettyConstant c <+> text ":"
<+> pretty tlt
T0TC_THF_TypedConst_Par tc -> parens (pretty tc)
instance Pretty THFTypeFormula where
pretty ttf = case ttf of
TTF_THF_Type_Formula tf tlt -> pretty tf <+> text ":" <+> pretty tlt
TTF_THF_Typed_Const c tlt -> prettyConstant c <+> text ":"
<+> pretty tlt
instance Pretty THFTypeableFormula where
pretty tbf = case tbf of
TTyF_THF_Atom a -> pretty a
TTyF_THF_Tuple t -> prettyTuple t
TTyF_THF_Logic_Formula lf -> parens $ pretty lf
instance Pretty THFSubType where
pretty (TST_THF_Sub_Type c1 c2) =
prettyConstant c1 <+> text "<<" <+> prettyConstant c2
instance Pretty THFTopLevelType where
pretty tlt = case tlt of
TTLT_THF_Logic_Formula lf -> pretty lf
T0TLT_Constant c -> prettyConstant c
T0TLT_Variable v -> prettyUpperWord v
T0TLT_Defined_Type dt -> pretty dt
T0TLT_System_Type st -> prettyAtomicSystemWord st
T0TLT_THF_Binary_Type bt -> pretty bt
instance Pretty THFUnitaryType where
pretty ut = case ut of
TUT_THF_Unitary_Formula uf -> pretty uf
T0UT_Constant c -> prettyConstant c
T0UT_Variable v -> prettyUpperWord v
T0UT_Defined_Type dt -> pretty dt
T0UT_System_Type st -> prettyAtomicSystemWord st
T0UT_THF_Binary_Type_Par bt -> parens (pretty bt)
instance Pretty THFBinaryType where
pretty tbt = case tbt of
TBT_THF_Mapping_Type utl -> sepBy (map pretty utl) arrowSign
TBT_THF_Xprod_Type utl -> sepBy (map pretty utl) starSign
TBT_THF_Union_Type utl -> sepBy (map pretty utl) plusSign
T0BT_THF_Binary_Type_Par bt -> parens (pretty bt)
instance Pretty THFAtom where
pretty a = case a of
TA_Term t -> pretty t
TA_THF_Conn_Term ct -> pretty ct
TA_Defined_Type dt -> pretty dt
TA_Defined_Plain_Formula dp -> pretty dp
TA_System_Type st -> prettyAtomicSystemWord st
TA_System_Atomic_Formula st -> pretty st
T0A_Constant c -> prettyConstant c
T0A_Defined_Constant dc -> prettyAtomicDefinedWord dc
T0A_System_Constant sc -> prettyAtomicSystemWord sc
T0A_Variable v -> prettyUpperWord v
prettyTuple :: THFTuple -> Doc
prettyTuple ufl = brackets $ sepByCommas (map pretty ufl)
instance Pretty THFSequent where
pretty (TS_THF_Sequent_Par s) = parens $ pretty s
pretty (TS_THF_Sequent t1 t2) =
prettyTuple t1 <+> text "-->" <+> prettyTuple t2
instance Pretty THFConnTerm where
pretty ct = case ct of
TCT_THF_Pair_Connective pc -> pretty pc
TCT_Assoc_Connective ac -> pretty ac
TCT_THF_Unary_Connective uc -> pretty uc
T0CT_THF_Quantifier q -> pretty q
instance Pretty THFQuantifier where
pretty q = case q of
TQ_ForAll -> text "!"
TQ_Exists -> text "?"
TQ_Lambda_Binder -> text "^"
TQ_Dependent_Product -> text "!>"
TQ_Dependent_Sum -> text "?*"
TQ_Indefinite_Description -> text "@+"
TQ_Definite_Description -> text "@-"
T0Q_PiForAll -> text "!!"
T0Q_SigmaExists -> text "??"
instance Pretty Quantifier where
pretty q = case q of
T0Q_ForAll -> text "!"
T0Q_Exists -> text "?"
instance Pretty THFPairConnective where
pretty pc = case pc of
Infix_Equality -> text "="
Infix_Inequality -> text "!="
Equivalent -> text "<=>"
Implication -> text "=>"
IF -> text "<="
XOR -> text "<~>"
NOR -> text "~|"
NAND -> text "~&"
instance Pretty THFUnaryConnective where
pretty uc = case uc of
Negation -> text "~"
PiForAll -> text "!!"
SigmaExists -> text "??"
instance Pretty AssocConnective where
pretty AND = text "&"
pretty OR = text "|"
instance Pretty DefinedType where
pretty DT_oType = text "$o"
pretty dt = text $ '$' : drop 3 (show dt)
instance Pretty DefinedPlainFormula where
pretty dpf = case dpf of
DPF_Defined_Prop dp -> pretty dp
DPF_Defined_Formula dp a -> pretty dp <> parens (prettyArguments a)
instance Pretty DefinedProp where
pretty DP_True = text "$true"
pretty DP_False = text "$false"
instance Pretty DefinedPred where
pretty dp = text $ '$' : map toLower (show dp)
instance Pretty Term where
pretty t = case t of
T_Function_Term ft -> pretty ft
T_Variable v -> prettyUpperWord v
instance Pretty FunctionTerm where
pretty ft = case ft of
FT_Plain_Term pt -> pretty pt
FT_Defined_Term dt -> pretty dt
FT_System_Term st -> pretty st
instance Pretty PlainTerm where
pretty pt = case pt of
PT_Constant c -> prettyConstant c
PT_Plain_Term f a -> pretty f <> parens (prettyArguments a)
prettyConstant :: Constant -> Doc
prettyConstant = pretty
instance Pretty DefinedTerm where
pretty dt = case dt of
DT_Defined_Atom da -> pretty da
DT_Defined_Atomic_Term dpt -> pretty dpt
instance Pretty DefinedAtom where
pretty da = case da of
DA_Number n -> pretty n
DA_Distinct_Object dio -> prettyDistinctObject dio
instance Pretty DefinedPlainTerm where
pretty dpt = case dpt of
DPT_Defined_Constant df -> pretty df
DPT_Defined_Function df a -> pretty df <> parens (prettyArguments a)
instance Pretty DefinedFunctor where
pretty df = text $ '$' : map toLower (show df)
instance Pretty SystemTerm where
pretty st = case st of
ST_System_Constant sf -> prettyAtomicSystemWord sf
ST_System_Term sf a -> prettyAtomicSystemWord sf
<> parens (prettyArguments a)
prettyArguments :: Arguments -> Doc
prettyArguments = sepByCommas . map pretty
instance Pretty PrincipalSymbol where
pretty ps = case ps of
PS_Functor f -> pretty f
PS_Variable v -> prettyUpperWord v
instance Pretty Source where
pretty s = case s of
S_Dag_Source ds -> pretty ds
S_Internal_Source it oi -> text "introduced" <> parens (
pretty it <> prettyOptionalInfo oi)
S_External_Source es -> pretty es
S_Sources ss -> sepByCommas (map pretty ss)
S_Unknown -> text "unknown"
instance Pretty DagSource where
pretty ds = case ds of
DS_Name n -> pretty n
DS_Inference_Record aw ui pl -> text "inference"
<> parens (pretty aw <> comma <+> prettyUsefulInfo ui
<> comma <+> brackets (sepByCommas (map pretty pl)))
instance Pretty ParentInfo where
pretty (PI_Parent_Info s mgl) =
let gl = maybe empty (\ c -> text ":" <> prettyGeneralList c) mgl
in pretty s <> gl
instance Pretty IntroType where
pretty it = text (drop 3 (show it))
instance Pretty ExternalSource where
pretty es = case es of
ES_File_Source fs -> pretty fs
ES_Theory tn oi -> text "theory" <> parens (
pretty tn <> prettyOptionalInfo oi)
ES_Creator_Source aw oi -> text "creator" <> parens (
pretty aw <> prettyOptionalInfo oi)
instance Pretty FileSource where
pretty (FS_File fn mn) =
let n = maybe empty (\ c -> comma <+> pretty c) mn
in text "file" <> parens (prettySingleQuoted fn <> n)
instance Pretty TheoryName where
pretty tn = text $ map toLower (show tn)
prettyOptionalInfo :: OptionalInfo -> Doc
prettyOptionalInfo = maybe empty (\ ui -> comma <+> prettyUsefulInfo ui)
prettyUsefulInfo :: UsefulInfo -> Doc
prettyUsefulInfo = brackets . sepByCommas . map pretty
instance Pretty InfoItem where
pretty ii = case ii of
II_Formula_Item fi -> pretty fi
II_Inference_Item infi -> pretty infi
II_General_Function gf -> pretty gf
instance Pretty FormulaItem where
pretty fi = case fi of
FI_Description_Item aw -> text "description" <> parens (pretty aw)
FI_Iquote_Item aw -> text "iquote" <> parens (pretty aw)
instance Pretty InferenceItem where
pretty ii = case ii of
II_Inference_Status is -> pretty is
II_Assumptions_Record nl -> text "assumptions"
<> parens (brackets (prettyNameList nl))
II_New_Symbol_Record aw psl -> text "new_symbols" <> parens (pretty aw
<> comma <+> brackets (sepByCommas (map pretty psl)))
II_Refutation fs -> text "refutation" <> parens (pretty fs)
instance Pretty InferenceStatus where
pretty is = case is of
IS_Status s -> text "status" <> parens (pretty s)
IS_Inference_Info aw1 aw2 gl -> pretty aw1 <> parens (pretty aw2
<> comma <+> prettyGeneralList gl)
instance Pretty StatusValue where
pretty sv = text $ map toLower (show sv)
prettyNameList :: NameList -> Doc
prettyNameList = sepByCommas . map pretty
instance Pretty GeneralTerm where
pretty gt = case gt of
GT_General_Data gd -> pretty gd
GT_General_Data_Term gd gt1 -> pretty gd <+> text ":" <+> pretty gt1
GT_General_List gl -> prettyGeneralList gl
instance Pretty GeneralData where
pretty gd = case gd of
GD_Atomic_Word aw -> pretty aw
GD_General_Function gf -> pretty gf
GD_Variable v -> prettyUpperWord v
GD_Number n -> pretty n
GD_Distinct_Object dio -> prettyDistinctObject dio
GD_Formula_Data fd -> pretty fd
GD_Bind v fd -> text "bind" <> parens (
prettyUpperWord v <> comma <+> pretty fd)
instance Pretty GeneralFunction where
pretty (GF_General_Function aw gts) =
pretty aw <> parens (prettyGeneralTerms gts)
instance Pretty FormulaData where
pretty (THF_Formula thff) = text "$thf" <> parens (pretty thff)
prettyGeneralList :: GeneralList -> Doc
prettyGeneralList = brackets . prettyGeneralTerms
prettyGeneralTerms :: GeneralTerms -> Doc
prettyGeneralTerms = sepByCommas . map pretty
instance Pretty Name where
pretty n = case n of
N_Atomic_Word a -> pretty a
N_Integer s -> text $ show s
T0N_Unsigned_Integer s -> text $ show s
instance Pretty AtomicWord where
pretty a = case a of
A_Single_Quoted s -> prettySingleQuoted s
A_Lower_Word l -> prettyLowerWord l
prettyAtomicSystemWord :: Token -> Doc
prettyAtomicSystemWord asw = text ("$$" ++ show asw)
prettyAtomicDefinedWord :: Token -> Doc
prettyAtomicDefinedWord adw = text ('$' : show adw)
instance Pretty Number where
pretty n = case n of
Num_Integer i -> text $ show i
Num_Rational ra -> text $ show ra
Num_Real re -> text $ show re
prettySingleQuoted :: Token -> Doc
prettySingleQuoted s = text "\'" <> (text . show) s <> text "\'"
prettyDistinctObject :: Token -> Doc
prettyDistinctObject s = text "\"" <> (text . show) s <> text "\""
prettyLowerWord :: Token -> Doc
prettyLowerWord uw' = let uw = show uw' in text (toLower (head uw) : tail uw)
prettyUpperWord :: Token -> Doc
prettyUpperWord uw' = let uw = show uw' in text (toUpper (head uw) : tail uw)
orSign :: Doc
orSign = text "|"
andSign :: Doc
andSign = text "&"
applySign :: Doc
applySign = text "@"
arrowSign :: Doc
arrowSign = text ">"
starSign :: Doc
starSign = text "*"
plusSign :: Doc
plusSign = text "+"
sepBy :: [Doc] -> Doc -> Doc
sepBy ls s = case ls of
(c : []) -> c
(c : d) -> c <+> s <+> sepBy d s
[] -> empty
| spechub/Hets | THF/PrintTHF.hs | gpl-2.0 | 16,451 | 0 | 18 | 4,358 | 5,093 | 2,371 | 2,722 | 383 | 3 |
module Control.Schule.DB where
-- $Id$
import Control.SQL
import Control.Types
import Control.Schule.Typ
import qualified Control.Student.Type as CST
import qualified Control.Student.DB
import Prelude hiding ( all )
-- | get alle Schulen aus DB
-- TODO: implementiere filter
get :: IO [ Schule ]
get = get_from_where ( map reed [ "schule" ] ) $ ands []
get_unr :: UNr -> IO [ Schule ]
get_unr u = get_from_where
( map reed [ "schule" ] )
( equals ( reed "schule.UNr" ) ( toEx u ) )
get_from_where f w = do
conn <- myconnect
stat <- squery conn $ Query qq
[ From f , Where w ]
res <- common stat
disconnect conn
return res
qq = Select
$ map reed [ "schule.UNr as UNr"
, "schule.Name as Name"
, "schule.Mail_Suffix as Mail_Suffix"
]
common = collectRows $ \ state -> do
g_unr <- getFieldValue state "UNr"
g_name <- getFieldValue state "Name"
g_mail_suffix <- getFieldValue state "Mail_Suffix"
return $ Schule { unr = g_unr
, name = g_name
, mail_suffix = g_mail_suffix
}
-- | put into table:
put :: Maybe UNr
-> Schule
-> IO ()
put munr vor = do
conn <- myconnect
let common = [ ( reed "Name", toEx $ name vor )
, ( reed "Mail_Suffix", toEx $ mail_suffix vor )
]
case munr of
Nothing -> squery conn $ Query
( Insert (reed "schule") common )
[ ]
Just unr -> squery conn $ Query
( Update (reed "schule") common )
[ Where $ equals ( reed "schule.UNr" ) ( toEx unr ) ]
disconnect conn
-- | delete
delete :: UNr
-> IO ()
delete unr = do
conn <- myconnect
squery conn $ Query
( Delete ( reed "schule" ) )
[ Where $ equals ( reed "schule.UNr" ) ( toEx unr ) ]
disconnect conn
| florianpilz/autotool | src/Control/Schule/DB.hs | gpl-2.0 | 1,823 | 13 | 16 | 560 | 598 | 306 | 292 | 54 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Control.Applicative
-- Copyright : Conor McBride and Ross Paterson 2005
-- License : BSD-style (see the LICENSE file in the distribution)
--
-- Maintainer : ross@soi.city.ac.uk
-- Stability : experimental
-- Portability : portable
--
-- This module describes a structure intermediate between a functor and
-- a monad: it provides pure expressions and sequencing, but no binding.
-- (Technically, a strong lax monoidal functor.) For more details, see
-- /Applicative Programming with Effects/,
-- by Conor McBride and Ross Paterson, online at
-- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>.
--
-- This interface was introduced for parsers by Niklas Röjemo, because
-- it admits more sharing than the monadic interface. The names here are
-- mostly based on recent parsing work by Doaitse Swierstra.
--
-- This class is also useful with instances of the
-- 'Data.Traversable.Traversable' class.
module Control.Applicative (
-- * Applicative functors
Applicative(..),
-- * Alternatives
Alternative(..),
-- * Instances
Const(..), WrappedMonad(..), WrappedArrow(..), ZipList(..),
-- * Utility functions
(<$>), (<$), (*>), (<*), (<**>),
liftA, liftA2, liftA3,
optional, some, many
) where
#ifdef __HADDOCK__
import Prelude
#endif
import Control.Arrow
(Arrow(arr, (>>>), (&&&)), ArrowZero(zeroArrow), ArrowPlus((<+>)))
import Control.Monad (liftM, ap, MonadPlus(..))
import Control.Monad.Instances ()
import Data.Monoid (Monoid(..))
infixl 3 <|>
infixl 4 <$>, <$
infixl 4 <*>, <*, *>, <**>
-- | A functor with application.
--
-- Instances should satisfy the following laws:
--
-- [/identity/]
-- @'pure' 'id' '<*>' v = v@
--
-- [/composition/]
-- @'pure' (.) '<*>' u '<*>' v '<*>' w = u '<*>' (v '<*>' w)@
--
-- [/homomorphism/]
-- @'pure' f '<*>' 'pure' x = 'pure' (f x)@
--
-- [/interchange/]
-- @u '<*>' 'pure' y = 'pure' ('$' y) '<*>' u@
--
-- The 'Functor' instance should satisfy
--
-- @
-- 'fmap' f x = 'pure' f '<*>' x
-- @
--
-- If @f@ is also a 'Monad', define @'pure' = 'return'@ and @('<*>') = 'ap'@.
class Functor f => Applicative f where
-- | Lift a value.
pure :: a -> f a
-- | Sequential application.
(<*>) :: f (a -> b) -> f a -> f b
-- | A monoid on applicative functors.
class Applicative f => Alternative f where
-- | The identity of '<|>'
empty :: f a
-- | An associative binary operation
(<|>) :: f a -> f a -> f a
-- instances for Prelude types
instance Applicative Maybe where
pure = return
(<*>) = ap
instance Alternative Maybe where
empty = Nothing
Nothing <|> p = p
Just x <|> _ = Just x
instance Applicative [] where
pure = return
(<*>) = ap
instance Alternative [] where
empty = []
(<|>) = (++)
instance Applicative IO where
pure = return
(<*>) = ap
instance Applicative ((->) a) where
pure = const
(<*>) f g x = f x (g x)
instance Monoid a => Applicative ((,) a) where
pure x = (mempty, x)
(u, f) <*> (v, x) = (u `mappend` v, f x)
-- new instances
newtype Const a b = Const { getConst :: a }
instance Functor (Const m) where
fmap _ (Const v) = Const v
instance Monoid m => Applicative (Const m) where
pure _ = Const mempty
Const f <*> Const v = Const (f `mappend` v)
newtype WrappedMonad m a = WrapMonad { unwrapMonad :: m a }
instance Monad m => Functor (WrappedMonad m) where
fmap f (WrapMonad v) = WrapMonad (liftM f v)
instance Monad m => Applicative (WrappedMonad m) where
pure = WrapMonad . return
WrapMonad f <*> WrapMonad v = WrapMonad (f `ap` v)
instance MonadPlus m => Alternative (WrappedMonad m) where
empty = WrapMonad mzero
WrapMonad u <|> WrapMonad v = WrapMonad (u `mplus` v)
newtype WrappedArrow a b c = WrapArrow { unwrapArrow :: a b c }
instance Arrow a => Functor (WrappedArrow a b) where
fmap f (WrapArrow a) = WrapArrow (a >>> arr f)
instance Arrow a => Applicative (WrappedArrow a b) where
pure x = WrapArrow (arr (const x))
WrapArrow f <*> WrapArrow v = WrapArrow (f &&& v >>> arr (uncurry id))
instance (ArrowZero a, ArrowPlus a) => Alternative (WrappedArrow a b) where
empty = WrapArrow zeroArrow
WrapArrow u <|> WrapArrow v = WrapArrow (u <+> v)
-- | Lists, but with an 'Applicative' functor based on zipping, so that
--
-- @f '<$>' 'ZipList' xs1 '<*>' ... '<*>' 'ZipList' xsn = 'ZipList' (zipWithn f xs1 ... xsn)@
--
newtype ZipList a = ZipList { getZipList :: [a] }
instance Functor ZipList where
fmap f (ZipList xs) = ZipList (map f xs)
instance Applicative ZipList where
pure x = ZipList (repeat x)
ZipList fs <*> ZipList xs = ZipList (zipWith id fs xs)
-- extra functions
-- | A synonym for 'fmap'.
(<$>) :: Functor f => (a -> b) -> f a -> f b
f <$> a = fmap f a
-- | Replace the value.
(<$) :: Functor f => a -> f b -> f a
(<$) = (<$>) . const
-- | Sequence actions, discarding the value of the first argument.
(*>) :: Applicative f => f a -> f b -> f b
(*>) = liftA2 (const id)
-- | Sequence actions, discarding the value of the second argument.
(<*) :: Applicative f => f a -> f b -> f a
(<*) = liftA2 const
-- | A variant of '<*>' with the arguments reversed.
(<**>) :: Applicative f => f a -> f (a -> b) -> f b
(<**>) = liftA2 (flip ($))
-- | Lift a function to actions.
-- This function may be used as a value for `fmap` in a `Functor` instance.
liftA :: Applicative f => (a -> b) -> f a -> f b
liftA f a = pure f <*> a
-- | Lift a binary function to actions.
liftA2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
liftA2 f a b = f <$> a <*> b
-- | Lift a ternary function to actions.
liftA3 :: Applicative f => (a -> b -> c -> d) -> f a -> f b -> f c -> f d
liftA3 f a b c = f <$> a <*> b <*> c
-- | One or none.
optional :: Alternative f => f a -> f (Maybe a)
optional v = Just <$> v <|> pure Nothing
-- | One or more.
some :: Alternative f => f a -> f [a]
some v = some_v
where many_v = some_v <|> pure []
some_v = (:) <$> v <*> many_v
-- | Zero or more.
many :: Alternative f => f a -> f [a]
many v = many_v
where many_v = some_v <|> pure []
some_v = (:) <$> v <*> many_v
| alekar/hugs | packages/base/Control/Applicative.hs | bsd-3-clause | 6,090 | 18 | 11 | 1,272 | 1,885 | 1,034 | 851 | 99 | 1 |
--
-- Copyright (c) 2014 Joachim Breitner
--
module CallArity
( callArityAnalProgram
, callArityRHS -- for testing
) where
import VarSet
import VarEnv
import DynFlags ( DynFlags )
import BasicTypes
import CoreSyn
import Id
import CoreArity ( typeArity )
import CoreUtils ( exprIsCheap, exprIsTrivial )
--import Outputable
import UnVarGraph
import Demand
import Control.Arrow ( first, second )
{-
%************************************************************************
%* *
Call Arity Analyis
%* *
%************************************************************************
Note [Call Arity: The goal]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
The goal of this analysis is to find out if we can eta-expand a local function,
based on how it is being called. The motivating example is this code,
which comes up when we implement foldl using foldr, and do list fusion:
let go = \x -> let d = case ... of
False -> go (x+1)
True -> id
in \z -> d (x + z)
in go 1 0
If we do not eta-expand `go` to have arity 2, we are going to allocate a lot of
partial function applications, which would be bad.
The function `go` has a type of arity two, but only one lambda is manifest.
Furthermore, an analysis that only looks at the RHS of go cannot be sufficient
to eta-expand go: If `go` is ever called with one argument (and the result used
multiple times), we would be doing the work in `...` multiple times.
So `callArityAnalProgram` looks at the whole let expression to figure out if
all calls are nice, i.e. have a high enough arity. It then stores the result in
the `calledArity` field of the `IdInfo` of `go`, which the next simplifier
phase will eta-expand.
The specification of the `calledArity` field is:
No work will be lost if you eta-expand me to the arity in `calledArity`.
What we want to know for a variable
-----------------------------------
For every let-bound variable we'd like to know:
1. A lower bound on the arity of all calls to the variable, and
2. whether the variable is being called at most once or possible multiple
times.
It is always ok to lower the arity, or pretend that there are multiple calls.
In particular, "Minimum arity 0 and possible called multiple times" is always
correct.
What we want to know from an expression
---------------------------------------
In order to obtain that information for variables, we analyize expression and
obtain bits of information:
I. The arity analysis:
For every variable, whether it is absent, or called,
and if called, which what arity.
II. The Co-Called analysis:
For every two variables, whether there is a possibility that both are being
called.
We obtain as a special case: For every variables, whether there is a
possibility that it is being called twice.
For efficiency reasons, we gather this information only for a set of
*interesting variables*, to avoid spending time on, e.g., variables from pattern matches.
The two analysis are not completely independent, as a higher arity can improve
the information about what variables are being called once or multiple times.
Note [Analysis I: The arity analyis]
------------------------------------
The arity analysis is quite straight forward: The information about an
expression is an
VarEnv Arity
where absent variables are bound to Nothing and otherwise to a lower bound to
their arity.
When we analyize an expression, we analyize it with a given context arity.
Lambdas decrease and applications increase the incoming arity. Analysizing a
variable will put that arity in the environment. In lets or cases all the
results from the various subexpressions are lubed, which takes the point-wise
minimum (considering Nothing an infinity).
Note [Analysis II: The Co-Called analysis]
------------------------------------------
The second part is more sophisticated. For reasons explained below, it is not
sufficient to simply know how often an expression evalutes a variable. Instead
we need to know which variables are possibly called together.
The data structure here is an undirected graph of variables, which is provided
by the abstract
UnVarGraph
It is safe to return a larger graph, i.e. one with more edges. The worst case
(i.e. the least useful and always correct result) is the complete graph on all
free variables, which means that anything can be called together with anything
(including itself).
Notation for the following:
C(e) is the co-called result for e.
G₁∪G₂ is the union of two graphs
fv is the set of free variables (conveniently the domain of the arity analysis result)
S₁×S₂ is the complete bipartite graph { {a,b} | a ∈ S₁, b ∈ S₂ }
S² is the complete graph on the set of variables S, S² = S×S
C'(e) is a variant for bound expression:
If e is called at most once, or it is and stays a thunk (after the analysis),
it is simply C(e). Otherwise, the expression can be called multiple times
and we return (fv e)²
The interesting cases of the analysis:
* Var v:
No other variables are being called.
Return {} (the empty graph)
* Lambda v e, under arity 0:
This means that e can be evaluated many times and we cannot get
any useful co-call information.
Return (fv e)²
* Case alternatives alt₁,alt₂,...:
Only one can be execuded, so
Return (alt₁ ∪ alt₂ ∪...)
* App e₁ e₂ (and analogously Case scrut alts), with non-trivial e₂:
We get the results from both sides, with the argument evaluated at most once.
Additionally, anything called by e₁ can possibly be called with anything
from e₂.
Return: C(e₁) ∪ C(e₂) ∪ (fv e₁) × (fv e₂)
* App e₁ x:
As this is already in A-normal form, CorePrep will not separately lambda
bind (and hence share) x. So we conservatively assume multiple calls to x here
Return: C(e₁) ∪ (fv e₁) × {x} ∪ {(x,x)}
* Let v = rhs in body:
In addition to the results from the subexpressions, add all co-calls from
everything that the body calls together with v to everthing that is called
by v.
Return: C'(rhs) ∪ C(body) ∪ (fv rhs) × {v'| {v,v'} ∈ C(body)}
* Letrec v₁ = rhs₁ ... vₙ = rhsₙ in body
Tricky.
We assume that it is really mutually recursive, i.e. that every variable
calls one of the others, and that this is strongly connected (otherwise we
return an over-approximation, so that's ok), see note [Recursion and fixpointing].
Let V = {v₁,...vₙ}.
Assume that the vs have been analysed with an incoming demand and
cardinality consistent with the final result (this is the fixed-pointing).
Again we can use the results from all subexpressions.
In addition, for every variable vᵢ, we need to find out what it is called
with (call this set Sᵢ). There are two cases:
* If vᵢ is a function, we need to go through all right-hand-sides and bodies,
and collect every variable that is called together with any variable from V:
Sᵢ = {v' | j ∈ {1,...,n}, {v',vⱼ} ∈ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ C(body) }
* If vᵢ is a thunk, then its rhs is evaluated only once, so we need to
exclude it from this set:
Sᵢ = {v' | j ∈ {1,...,n}, j≠i, {v',vⱼ} ∈ C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪ C(body) }
Finally, combine all this:
Return: C(body) ∪
C'(rhs₁) ∪ ... ∪ C'(rhsₙ) ∪
(fv rhs₁) × S₁) ∪ ... ∪ (fv rhsₙ) × Sₙ)
Using the result: Eta-Expansion
-------------------------------
We use the result of these two analyses to decide whether we can eta-expand the
rhs of a let-bound variable.
If the variable is already a function (exprIsCheap), and all calls to the
variables have a higher arity than the current manifest arity (i.e. the number
of lambdas), expand.
If the variable is a thunk we must be careful: Eta-Expansion will prevent
sharing of work, so this is only safe if there is at most one call to the
function. Therefore, we check whether {v,v} ∈ G.
Example:
let n = case .. of .. -- A thunk!
in n 0 + n 1
vs.
let n = case .. of ..
in case .. of T -> n 0
F -> n 1
We are only allowed to eta-expand `n` if it is going to be called at most
once in the body of the outer let. So we need to know, for each variable
individually, that it is going to be called at most once.
Why the co-call graph?
----------------------
Why is it not sufficient to simply remember which variables are called once and
which are called multiple times? It would be in the previous example, but consider
let n = case .. of ..
in case .. of
True -> let go = \y -> case .. of
True -> go (y + n 1)
False > n
in go 1
False -> n
vs.
let n = case .. of ..
in case .. of
True -> let go = \y -> case .. of
True -> go (y+1)
False > n
in go 1
False -> n
In both cases, the body and the rhs of the inner let call n at most once.
But only in the second case that holds for the whole expression! The
crucial difference is that in the first case, the rhs of `go` can call
*both* `go` and `n`, and hence can call `n` multiple times as it recurses,
while in the second case find out that `go` and `n` are not called together.
Why co-call information for functions?
--------------------------------------
Although for eta-expansion we need the information only for thunks, we still
need to know whether functions are being called once or multiple times, and
together with what other functions.
Example:
let n = case .. of ..
f x = n (x+1)
in f 1 + f 2
vs.
let n = case .. of ..
f x = n (x+1)
in case .. of T -> f 0
F -> f 1
Here, the body of f calls n exactly once, but f itself is being called
multiple times, so eta-expansion is not allowed.
Note [Analysis type signature]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The work-hourse of the analysis is the function `callArityAnal`, with the
following type:
type CallArityRes = (UnVarGraph, VarEnv Arity)
callArityAnal ::
Arity -> -- The arity this expression is called with
VarSet -> -- The set of interesting variables
CoreExpr -> -- The expression to analyse
(CallArityRes, CoreExpr)
and the following specification:
((coCalls, callArityEnv), expr') = callArityEnv arity interestingIds expr
<=>
Assume the expression `expr` is being passed `arity` arguments. Then it holds that
* The domain of `callArityEnv` is a subset of `interestingIds`.
* Any variable from `interestingIds` that is not mentioned in the `callArityEnv`
is absent, i.e. not called at all.
* Every call from `expr` to a variable bound to n in `callArityEnv` has at
least n value arguments.
* For two interesting variables `v1` and `v2`, they are not adjacent in `coCalls`,
then in no execution of `expr` both are being called.
Furthermore, expr' is expr with the callArity field of the `IdInfo` updated.
Note [Which variables are interesting]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The analysis would quickly become prohibitive expensive if we would analyse all
variables; for most variables we simply do not care about how often they are
called, i.e. variables bound in a pattern match. So interesting are variables that are
* top-level or let bound
* and possibly functions (typeArity > 0)
Note [Taking boring variables into account]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
If we decide that the variable bound in `let x = e1 in e2` is not interesting,
the analysis of `e2` will not report anything about `x`. To ensure that
`callArityBind` does still do the right thing we have to take that into account
everytime we would be lookup up `x` in the analysis result of `e2`.
* Instead of calling lookupCallArityRes, we return (0, True), indicating
that this variable might be called many times with no arguments.
* Instead of checking `calledWith x`, we assume that everything can be called
with it.
* In the recursive case, when calclulating the `cross_calls`, if there is
any boring variable in the recursive group, we ignore all co-call-results
and directly go to a very conservative assumption.
The last point has the nice side effect that the relatively expensive
integration of co-call results in a recursive groups is often skipped. This
helped to avoid the compile time blowup in some real-world code with large
recursive groups (#10293).
Note [Recursion and fixpointing]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For a mutually recursive let, we begin by
1. analysing the body, using the same incoming arity as for the whole expression.
2. Then we iterate, memoizing for each of the bound variables the last
analysis call, i.e. incoming arity, whether it is called once, and the CallArityRes.
3. We combine the analysis result from the body and the memoized results for
the arguments (if already present).
4. For each variable, we find out the incoming arity and whether it is called
once, based on the the current analysis result. If this differs from the
memoized results, we re-analyse the rhs and update the memoized table.
5. If nothing had to be reanalized, we are done.
Otherwise, repeat from step 3.
Note [Thunks in recursive groups]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We never eta-expand a thunk in a recursive group, on the grounds that if it is
part of a recursive group, then it will be called multipe times.
This is not necessarily true, e.g. it would be safe to eta-expand t2 (but not
t1) in the following code:
let go x = t1
t1 = if ... then t2 else ...
t2 = if ... then go 1 else ...
in go 0
Detecting this would require finding out what variables are only ever called
from thunks. While this is certainly possible, we yet have to see this to be
relevant in the wild.
Note [Analysing top-level binds]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We can eta-expand top-level-binds if they are not exported, as we see all calls
to them. The plan is as follows: Treat the top-level binds as nested lets around
a body representing “all external calls”, which returns a pessimistic
CallArityRes (the co-call graph is the complete graph, all arityies 0).
Note [Trimming arity]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In the Call Arity papers, we are working on an untyped lambda calculus with no
other id annotations, where eta-expansion is always possible. But this is not
the case for Core!
1. We need to ensure the invariant
callArity e <= typeArity (exprType e)
for the same reasons that exprArity needs this invariant (see Note
[exprArity invariant] in CoreArity).
If we are not doing that, a too-high arity annotation will be stored with
the id, confusing the simplifier later on.
2. Eta-expanding a right hand side might invalidate existing annotations. In
particular, if an id has a strictness annotation of <...><...>b, then
passing two arguments to it will definitely bottom out, so the simplifier
will throw away additional parameters. This conflicts with Call Arity! So
we ensure that we never eta-expand such a value beyond the number of
arguments mentioned in the strictness signature.
See #10176 for a real-world-example.
Note [What is a thunk]
~~~~~~~~~~~~~~~~~~~~~~
Originally, everything that is not in WHNF (`exprIsWHNF`) is considered a
thunk, not eta-expanded, to avoid losing any sharing. This is also how the
published papers on Call Arity describe it.
In practice, there are thunks that do a just little work, such as
pattern-matching on a variable, and the benefits of eta-expansion likely
oughtweigh the cost of doing that repeatedly. Therefore, this implementation of
Call Arity considers everything that is not cheap (`exprIsCheap`) as a thunk.
-}
-- Main entry point
callArityAnalProgram :: DynFlags -> CoreProgram -> CoreProgram
callArityAnalProgram _dflags binds = binds'
where
(_, binds') = callArityTopLvl [] emptyVarSet binds
-- See Note [Analysing top-level-binds]
callArityTopLvl :: [Var] -> VarSet -> [CoreBind] -> (CallArityRes, [CoreBind])
callArityTopLvl exported _ []
= ( calledMultipleTimes $ (emptyUnVarGraph, mkVarEnv $ [(v, 0) | v <- exported])
, [] )
callArityTopLvl exported int1 (b:bs)
= (ae2, b':bs')
where
int2 = bindersOf b
exported' = filter isExportedId int2 ++ exported
int' = int1 `addInterestingBinds` b
(ae1, bs') = callArityTopLvl exported' int' bs
(ae2, b') = callArityBind (boringBinds b) ae1 int1 b
callArityRHS :: CoreExpr -> CoreExpr
callArityRHS = snd . callArityAnal 0 emptyVarSet
-- The main analysis function. See Note [Analysis type signature]
callArityAnal ::
Arity -> -- The arity this expression is called with
VarSet -> -- The set of interesting variables
CoreExpr -> -- The expression to analyse
(CallArityRes, CoreExpr)
-- How this expression uses its interesting variables
-- and the expression with IdInfo updated
-- The trivial base cases
callArityAnal _ _ e@(Lit _)
= (emptyArityRes, e)
callArityAnal _ _ e@(Type _)
= (emptyArityRes, e)
callArityAnal _ _ e@(Coercion _)
= (emptyArityRes, e)
-- The transparent cases
callArityAnal arity int (Tick t e)
= second (Tick t) $ callArityAnal arity int e
callArityAnal arity int (Cast e co)
= second (\e -> Cast e co) $ callArityAnal arity int e
-- The interesting case: Variables, Lambdas, Lets, Applications, Cases
callArityAnal arity int e@(Var v)
| v `elemVarSet` int
= (unitArityRes v arity, e)
| otherwise
= (emptyArityRes, e)
-- Non-value lambdas are ignored
callArityAnal arity int (Lam v e) | not (isId v)
= second (Lam v) $ callArityAnal arity (int `delVarSet` v) e
-- We have a lambda that may be called multiple times, so its free variables
-- can all be co-called.
callArityAnal 0 int (Lam v e)
= (ae', Lam v e')
where
(ae, e') = callArityAnal 0 (int `delVarSet` v) e
ae' = calledMultipleTimes ae
-- We have a lambda that we are calling. decrease arity.
callArityAnal arity int (Lam v e)
= (ae, Lam v e')
where
(ae, e') = callArityAnal (arity - 1) (int `delVarSet` v) e
-- Application. Increase arity for the called expression, nothing to know about
-- the second
callArityAnal arity int (App e (Type t))
= second (\e -> App e (Type t)) $ callArityAnal arity int e
callArityAnal arity int (App e1 e2)
= (final_ae, App e1' e2')
where
(ae1, e1') = callArityAnal (arity + 1) int e1
(ae2, e2') = callArityAnal 0 int e2
-- If the argument is trivial (e.g. a variable), then it will _not_ be
-- let-bound in the Core to STG transformation (CorePrep actually),
-- so no sharing will happen here, and we have to assume many calls.
ae2' | exprIsTrivial e2 = calledMultipleTimes ae2
| otherwise = ae2
final_ae = ae1 `both` ae2'
-- Case expression.
callArityAnal arity int (Case scrut bndr ty alts)
= -- pprTrace "callArityAnal:Case"
-- (vcat [ppr scrut, ppr final_ae])
(final_ae, Case scrut' bndr ty alts')
where
(alt_aes, alts') = unzip $ map go alts
go (dc, bndrs, e) = let (ae, e') = callArityAnal arity int e
in (ae, (dc, bndrs, e'))
alt_ae = lubRess alt_aes
(scrut_ae, scrut') = callArityAnal 0 int scrut
final_ae = scrut_ae `both` alt_ae
-- For lets, use callArityBind
callArityAnal arity int (Let bind e)
= -- pprTrace "callArityAnal:Let"
-- (vcat [ppr v, ppr arity, ppr n, ppr final_ae ])
(final_ae, Let bind' e')
where
int_body = int `addInterestingBinds` bind
(ae_body, e') = callArityAnal arity int_body e
(final_ae, bind') = callArityBind (boringBinds bind) ae_body int bind
-- Which bindings should we look at?
-- See Note [Which variables are interesting]
isInteresting :: Var -> Bool
isInteresting v = not $ null (typeArity (idType v))
interestingBinds :: CoreBind -> [Var]
interestingBinds = filter isInteresting . bindersOf
boringBinds :: CoreBind -> VarSet
boringBinds = mkVarSet . filter (not . isInteresting) . bindersOf
addInterestingBinds :: VarSet -> CoreBind -> VarSet
addInterestingBinds int bind
= int `delVarSetList` bindersOf bind -- Possible shadowing
`extendVarSetList` interestingBinds bind
-- Used for both local and top-level binds
-- Second argument is the demand from the body
callArityBind :: VarSet -> CallArityRes -> VarSet -> CoreBind -> (CallArityRes, CoreBind)
-- Non-recursive let
callArityBind boring_vars ae_body int (NonRec v rhs)
| otherwise
= -- pprTrace "callArityBind:NonRec"
-- (vcat [ppr v, ppr ae_body, ppr int, ppr ae_rhs, ppr safe_arity])
(final_ae, NonRec v' rhs')
where
is_thunk = not (exprIsCheap rhs) -- see note [What is a thunk]
-- If v is boring, we will not find it in ae_body, but always assume (0, False)
boring = v `elemVarSet` boring_vars
(arity, called_once)
| boring = (0, False) -- See Note [Taking boring variables into account]
| otherwise = lookupCallArityRes ae_body v
safe_arity | called_once = arity
| is_thunk = 0 -- A thunk! Do not eta-expand
| otherwise = arity
-- See Note [Trimming arity]
trimmed_arity = trimArity v safe_arity
(ae_rhs, rhs') = callArityAnal trimmed_arity int rhs
ae_rhs'| called_once = ae_rhs
| safe_arity == 0 = ae_rhs -- If it is not a function, its body is evaluated only once
| otherwise = calledMultipleTimes ae_rhs
called_by_v = domRes ae_rhs'
called_with_v
| boring = domRes ae_body
| otherwise = calledWith ae_body v `delUnVarSet` v
final_ae = addCrossCoCalls called_by_v called_with_v $ ae_rhs' `lubRes` resDel v ae_body
v' = v `setIdCallArity` trimmed_arity
-- Recursive let. See Note [Recursion and fixpointing]
callArityBind boring_vars ae_body int b@(Rec binds)
= -- (if length binds > 300 then
-- pprTrace "callArityBind:Rec"
-- (vcat [ppr (Rec binds'), ppr ae_body, ppr int, ppr ae_rhs]) else id) $
(final_ae, Rec binds')
where
-- See Note [Taking boring variables into account]
any_boring = any (`elemVarSet` boring_vars) [ i | (i, _) <- binds]
int_body = int `addInterestingBinds` b
(ae_rhs, binds') = fix initial_binds
final_ae = bindersOf b `resDelList` ae_rhs
initial_binds = [(i,Nothing,e) | (i,e) <- binds]
fix :: [(Id, Maybe (Bool, Arity, CallArityRes), CoreExpr)] -> (CallArityRes, [(Id, CoreExpr)])
fix ann_binds
| -- pprTrace "callArityBind:fix" (vcat [ppr ann_binds, ppr any_change, ppr ae]) $
any_change
= fix ann_binds'
| otherwise
= (ae, map (\(i, _, e) -> (i, e)) ann_binds')
where
aes_old = [ (i,ae) | (i, Just (_,_,ae), _) <- ann_binds ]
ae = callArityRecEnv any_boring aes_old ae_body
rerun (i, mbLastRun, rhs)
| i `elemVarSet` int_body && not (i `elemUnVarSet` domRes ae)
-- No call to this yet, so do nothing
= (False, (i, Nothing, rhs))
| Just (old_called_once, old_arity, _) <- mbLastRun
, called_once == old_called_once
, new_arity == old_arity
-- No change, no need to re-analize
= (False, (i, mbLastRun, rhs))
| otherwise
-- We previously analized this with a different arity (or not at all)
= let is_thunk = not (exprIsCheap rhs) -- see note [What is a thunk]
safe_arity | is_thunk = 0 -- See Note [Thunks in recursive groups]
| otherwise = new_arity
-- See Note [Trimming arity]
trimmed_arity = trimArity i safe_arity
(ae_rhs, rhs') = callArityAnal trimmed_arity int_body rhs
ae_rhs' | called_once = ae_rhs
| safe_arity == 0 = ae_rhs -- If it is not a function, its body is evaluated only once
| otherwise = calledMultipleTimes ae_rhs
in (True, (i `setIdCallArity` trimmed_arity, Just (called_once, new_arity, ae_rhs'), rhs'))
where
-- See Note [Taking boring variables into account]
(new_arity, called_once) | i `elemVarSet` boring_vars = (0, False)
| otherwise = lookupCallArityRes ae i
(changes, ann_binds') = unzip $ map rerun ann_binds
any_change = or changes
-- Combining the results from body and rhs, (mutually) recursive case
-- See Note [Analysis II: The Co-Called analysis]
callArityRecEnv :: Bool -> [(Var, CallArityRes)] -> CallArityRes -> CallArityRes
callArityRecEnv any_boring ae_rhss ae_body
= -- (if length ae_rhss > 300 then pprTrace "callArityRecEnv" (vcat [ppr ae_rhss, ppr ae_body, ppr ae_new]) else id) $
ae_new
where
vars = map fst ae_rhss
ae_combined = lubRess (map snd ae_rhss) `lubRes` ae_body
cross_calls
-- See Note [Taking boring variables into account]
| any_boring = completeGraph (domRes ae_combined)
-- Also, calculating cross_calls is expensive. Simply be conservative
-- if the mutually recursive group becomes too large.
| length ae_rhss > 25 = completeGraph (domRes ae_combined)
| otherwise = unionUnVarGraphs $ map cross_call ae_rhss
cross_call (v, ae_rhs) = completeBipartiteGraph called_by_v called_with_v
where
is_thunk = idCallArity v == 0
-- What rhs are relevant as happening before (or after) calling v?
-- If v is a thunk, everything from all the _other_ variables
-- If v is not a thunk, everything can happen.
ae_before_v | is_thunk = lubRess (map snd $ filter ((/= v) . fst) ae_rhss) `lubRes` ae_body
| otherwise = ae_combined
-- What do we want to know from these?
-- Which calls can happen next to any recursive call.
called_with_v
= unionUnVarSets $ map (calledWith ae_before_v) vars
called_by_v = domRes ae_rhs
ae_new = first (cross_calls `unionUnVarGraph`) ae_combined
-- See Note [Trimming arity]
trimArity :: Id -> Arity -> Arity
trimArity v a = minimum [a, max_arity_by_type, max_arity_by_strsig]
where
max_arity_by_type = length (typeArity (idType v))
max_arity_by_strsig
| isBotRes result_info = length demands
| otherwise = a
(demands, result_info) = splitStrictSig (idStrictness v)
---------------------------------------
-- Functions related to CallArityRes --
---------------------------------------
-- Result type for the two analyses.
-- See Note [Analysis I: The arity analyis]
-- and Note [Analysis II: The Co-Called analysis]
type CallArityRes = (UnVarGraph, VarEnv Arity)
emptyArityRes :: CallArityRes
emptyArityRes = (emptyUnVarGraph, emptyVarEnv)
unitArityRes :: Var -> Arity -> CallArityRes
unitArityRes v arity = (emptyUnVarGraph, unitVarEnv v arity)
resDelList :: [Var] -> CallArityRes -> CallArityRes
resDelList vs ae = foldr resDel ae vs
resDel :: Var -> CallArityRes -> CallArityRes
resDel v (g, ae) = (g `delNode` v, ae `delVarEnv` v)
domRes :: CallArityRes -> UnVarSet
domRes (_, ae) = varEnvDom ae
-- In the result, find out the minimum arity and whether the variable is called
-- at most once.
lookupCallArityRes :: CallArityRes -> Var -> (Arity, Bool)
lookupCallArityRes (g, ae) v
= case lookupVarEnv ae v of
Just a -> (a, not (v `elemUnVarSet` (neighbors g v)))
Nothing -> (0, False)
calledWith :: CallArityRes -> Var -> UnVarSet
calledWith (g, _) v = neighbors g v
addCrossCoCalls :: UnVarSet -> UnVarSet -> CallArityRes -> CallArityRes
addCrossCoCalls set1 set2 = first (completeBipartiteGraph set1 set2 `unionUnVarGraph`)
-- Replaces the co-call graph by a complete graph (i.e. no information)
calledMultipleTimes :: CallArityRes -> CallArityRes
calledMultipleTimes res = first (const (completeGraph (domRes res))) res
-- Used for application and cases
both :: CallArityRes -> CallArityRes -> CallArityRes
both r1 r2 = addCrossCoCalls (domRes r1) (domRes r2) $ r1 `lubRes` r2
-- Used when combining results from alternative cases; take the minimum
lubRes :: CallArityRes -> CallArityRes -> CallArityRes
lubRes (g1, ae1) (g2, ae2) = (g1 `unionUnVarGraph` g2, ae1 `lubArityEnv` ae2)
lubArityEnv :: VarEnv Arity -> VarEnv Arity -> VarEnv Arity
lubArityEnv = plusVarEnv_C min
lubRess :: [CallArityRes] -> CallArityRes
lubRess = foldl lubRes emptyArityRes
| olsner/ghc | compiler/simplCore/CallArity.hs | bsd-3-clause | 29,200 | 0 | 17 | 7,033 | 3,275 | 1,786 | 1,489 | 209 | 2 |
--{-# LANGUAGE NamedFieldPuns, Safe #-}
{-# LANGUAGE NamedFieldPuns #-}
import Control.Concurrent.MVar (takeMVar)
import Control.Monad (forM, forM_, replicateM)
import Data.List (group, intercalate)
import Debug.Trace (trace)
import RP ( RP, RPE, RPR, RPW, ThreadState(..), tid, runRP, forkRP, joinRP, synchronizeRP, threadDelayRP, readRP, writeRP
, SRef, readSRef, writeSRef, newSRef, copySRef )
data RPList a = Nil
| Cons a (SRef (RPList a))
snapshot :: RPList a -> RPR [a]
snapshot Nil = return []
snapshot (Cons x rn) = do
l <- readSRef rn
rest <- snapshot l
return $ x : rest
reader :: SRef (RPList a) -> RPR [a]
reader head = do
snapshot =<< readSRef head
--h <- readSRef head
--l <- snapshot h
--trace ("reader saw " ++ show l) $ return l
testList :: RP (SRef (RPList Char))
testList = do
tail <- newSRef Nil
c3 <- newSRef $ Cons 'D' tail
c2 <- newSRef $ Cons 'C' c3
c1 <- newSRef $ Cons 'B' c2
newSRef $ Cons 'A' c1
compactShow :: (Show a, Eq a) => [a] -> String
compactShow xs = intercalate ", " $ map (\xs -> show (length xs) ++ " x " ++ show (head xs)) $ group xs
moveBforward :: SRef (RPList a) -> RPW ()
moveBforward head = do
(Cons a rb) <- readSRef head
(Cons b rc) <- readSRef rb
cc@(Cons c rd) <- readSRef rc
-- duplicate the reference to D
rd' <- copySRef rd
-- link in a new B after C
writeSRef rd $ Cons b rd'
-- any reader who starts during this grace period
-- sees either "ABCD" or "ABCBD"
--synchronizeRP -- interaction of write order and traversal order means you don't need this
-- remove the old 'B'
writeSRef rb $ cc
-- any reader who starts during this grace period
-- sees either "ABCBD" or "ACBD"
moveCback :: SRef (RPList a) -> RPW ()
moveCback head = do
(Cons a rb) <- readSRef head
(Cons b rc) <- readSRef rb
-- duplicate pointer to B
rb' <- copySRef rb
(Cons c rd) <- readSRef rc
de <- readSRef rd
-- link in a new C after A
writeSRef rb $ Cons c rb'
-- any reader who starts during this grace period
-- sees either "ABCD" or "ACBCD"
synchronizeRP
-- unlink the old C
writeSRef rc $ de
-- any reader who starts during this grace period
-- sees either "ACBCD" or "ACBD"
moveCbackNoSync :: SRef (RPList a) -> RPW ()
moveCbackNoSync head = do
(Cons a rb) <- readSRef head
(Cons b rc) <- readSRef rb
-- duplicate reference to B
rb' <- copySRef rb
(Cons c rd) <- readSRef rc
de <- readSRef rd
-- link in a new C after A
writeSRef rb $ Cons c rb'
-- any reader who starts during this grace period
-- sees either "ABCD" or "ACBCD"
--synchronizeRP -- this operation is NOT safe to omit,
-- because write order and traversal order are the same
-- unlink the old C
writeSRef rc $ de
-- any reader who starts during this grace period
-- sees "ABD", "ACBCD", or "ACBD"
main :: IO ()
main = do
outs <- runRP $ do
-- initialize list
head <- testList
-- spawn 8 readers, each records 10000 snapshots of the list
rts <- replicateM 8 $ forkRP $ replicateM 400000 $ readRP $ reader head
-- spawn a writer to delete the middle node
--wt <- forkRP $ writeRP $ moveCback head
wt <- forkRP $ writeRP $ moveCbackNoSync head
--wt <- forkRP $ writeRP $ moveBforward head
--wt <- forkRP $ writeRP $ return ()
-- wait for the readers to finish and print snapshots
outs <- forM rts $ \rt@(ThreadState {tid}) -> do
v <- joinRP rt
return $ show tid ++ ": " ++ compactShow v
-- wait for the writer to finish
joinRP wt
return outs
forM_ outs putStrLn
| anthezium/MonadicRP | src/RPmoveCbackNoSyncTest.hs | gpl-3.0 | 3,714 | 0 | 19 | 1,006 | 1,030 | 511 | 519 | 66 | 1 |
{-# LANGUAGE ForeignFunctionInterface #-}
{-# LANGUAGE JavaScriptFFI #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-
Copyright 2017 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 Blockly.Workspace ( Workspace(..)
,setWorkspace
,workspaceToCode
,isTopBlock
,getById
,loadXml
,getTopBlocksLength
,getBlockById
,getTopBlocks
,getTopBlocksTrue
,isWarning
,disableOrphans
,warnOnInputs
,mainWorkspace
)
where
import GHCJS.Types
import Data.JSString (pack, unpack)
import GHCJS.Foreign
import GHCJS.Marshal
import Unsafe.Coerce
import qualified Data.Text as T
import Blockly.General
import Blockly.Block (Block(..))
import qualified JavaScript.Array as JA
import Data.JSString.Text
newtype Workspace = Workspace JSVal
instance IsJSVal Workspace
instance ToJSVal Workspace where
toJSVal (Workspace v) = return v
instance FromJSVal Workspace where
fromJSVal v = return $ Just $ Workspace v
setWorkspace :: String -> String -> IO Workspace
setWorkspace canvasId toolboxId = js_blocklyInject (pack canvasId) (pack toolboxId)
workspaceToCode :: Workspace -> IO String
workspaceToCode workspace = js_blocklyWorkspaceToCode workspace >>= return . unpack
getById :: UUID -> Workspace
getById (UUID uuidStr) = js_getById (pack uuidStr)
getBlockById :: Workspace -> UUID -> Maybe Block
getBlockById workspace (UUID uuidstr) = if isNull val then Nothing
else Just $ unsafeCoerce val
where val = js_getBlockById workspace (pack uuidstr)
isTopBlock :: Workspace -> Block -> Bool
isTopBlock = js_isTopBlock
isWarning :: Workspace -> IO (Block, T.Text)
isWarning ws = do
vals <- js_isWarning ws
let ls = JA.toList vals
return (Block (ls !! 0), textFromJSString $ (unsafeCoerce (ls !! 1) :: JSString))
getTopBlocksLength :: Workspace -> Int
getTopBlocksLength = js_getTopBlocksLength
getTopBlocks :: Workspace -> IO [Block]
getTopBlocks ws = do
vals :: JA.JSArray <- js_getTopBlocks ws
let vs = JA.toList vals
return $ map Block vs
getTopBlocksTrue :: Workspace -> IO [Block]
getTopBlocksTrue ws = do
vals :: JA.JSArray <- js_getTopBlocks_ ws
let vs = JA.toList vals
return $ map Block vs
mainWorkspace :: Workspace
mainWorkspace = js_getMainWorkspace
disableOrphans :: Workspace -> IO ()
disableOrphans = js_addDisableOrphans
warnOnInputs :: Workspace -> IO ()
warnOnInputs = js_addWarnOnInputs
loadXml :: Workspace -> JSString -> IO ()
loadXml workspace dat = js_loadXml workspace dat
--- FFI
-- TODO Maybe use a list of properties ?
foreign import javascript unsafe "Blockly.inject($1, { toolbox: document.getElementById($2), css: false, disable: false, comments: false, zoom:{wheel:true, controls: true}})"
js_blocklyInject :: JSString -> JSString -> IO Workspace
foreign import javascript unsafe "Blockly.FunBlocks.workspaceToCode($1)"
js_blocklyWorkspaceToCode :: Workspace -> IO JSString
foreign import javascript unsafe "$1.isTopBlock($2)"
js_isTopBlock :: Workspace -> Block -> Bool
foreign import javascript unsafe "$1.isWarning()"
js_isWarning :: Workspace -> IO JA.JSArray
foreign import javascript unsafe "Blockly.Workspace.getById($1)"
js_getById :: JSString -> Workspace
foreign import javascript unsafe "$1.getBlockById($2)"
js_getBlockById :: Workspace -> JSString -> JSVal
foreign import javascript unsafe "$1.getTopBlocks(false).length"
js_getTopBlocksLength :: Workspace -> Int
foreign import javascript unsafe "$1.getTopBlocks(false)"
js_getTopBlocks :: Workspace -> IO JA.JSArray
foreign import javascript unsafe "$1.getTopBlocks(true)"
js_getTopBlocks_ :: Workspace -> IO JA.JSArray
foreign import javascript unsafe "Blockly.Xml.domToWorkspace(Blockly.Xml.textToDom($2), $1)"
js_loadXml :: Workspace -> JSString -> IO ()
foreign import javascript unsafe "$1.addChangeListener(Blockly.Events.disableOrphans)"
js_addDisableOrphans :: Workspace -> IO ()
foreign import javascript unsafe "$1.addChangeListener(Blockly.Events.warnOnDisconnectedInputs)"
js_addWarnOnInputs :: Workspace -> IO ()
foreign import javascript unsafe "Blockly.getMainWorkspace()"
js_getMainWorkspace :: Workspace
| venkat24/codeworld | funblocks-client/src/Blockly/Workspace.hs | apache-2.0 | 5,029 | 31 | 14 | 1,086 | 1,010 | 526 | 484 | 96 | 2 |
{-# LANGUAGE Safe #-}
-----------------------------------------------------------------------------
-- |
-- Module : Text.ParserCombinators.Parsec.Pos
-- Copyright : (c) Paolo Martini 2007
-- License : BSD-style (see the LICENSE file)
--
-- Maintainer : derek.a.elkins@gmail.com
-- Stability : provisional
-- Portability : portable
--
-- Parsec compatibility module
--
-----------------------------------------------------------------------------
module Text.ParserCombinators.Parsec.Pos
( SourceName,
Line,
Column,
SourcePos,
sourceLine,
sourceColumn,
sourceName,
incSourceLine,
incSourceColumn,
setSourceLine,
setSourceColumn,
setSourceName,
newPos,
initialPos,
updatePosChar,
updatePosString
) where
import Text.Parsec.Pos
| aslatter/parsec | src/Text/ParserCombinators/Parsec/Pos.hs | bsd-2-clause | 848 | 0 | 4 | 191 | 78 | 57 | 21 | 19 | 0 |
{-|
Module : Idris.TypeSearch
Description : A Hoogle for Idris.
Copyright :
License : BSD3
Maintainer : The Idris Community.
-}
{-# LANGUAGE ScopedTypeVariables #-}
module Idris.TypeSearch (
searchByType
, searchPred
, defaultScoreFunction
) where
import Control.Applicative (Applicative (..), (<$>), (<*>), (<|>))
import Control.Arrow (first, second, (&&&), (***))
import Control.Monad (when, guard)
import Data.List (find, partition, (\\))
import Data.Map (Map)
import qualified Data.Map as M
import Data.Maybe (catMaybes, fromMaybe, isJust, maybeToList, mapMaybe)
import Data.Monoid (Monoid (mempty, mappend))
import Data.Ord (comparing)
import qualified Data.PriorityQueue.FingerTree as Q
import Data.Set (Set)
import qualified Data.Set as S
import qualified Data.Text as T (pack, isPrefixOf)
import Data.Traversable (traverse)
import Idris.AbsSyntax (addUsingConstraints, addImpl, getIState, putIState, implicit, logLvl)
import Idris.AbsSyntaxTree (class_instances, ClassInfo, defaultSyntax, eqTy, Idris
, IState (idris_classes, idris_docstrings, tt_ctxt, idris_outputmode),
implicitAllowed, OutputMode(..), PTerm, toplevel)
import Idris.Core.Evaluate (Context (definitions), Def (Function, TyDecl, CaseOp), normaliseC)
import Idris.Core.TT hiding (score)
import Idris.Core.Unify (match_unify)
import Idris.Delaborate (delabTy)
import Idris.Docstrings (noDocs, overview)
import Idris.Elab.Type (elabType)
import Idris.Output (iputStrLn, iRenderOutput, iPrintResult, iRenderError, iRenderResult, prettyDocumentedIst)
import Idris.IBC
import Prelude hiding (pred)
import Util.Pretty (text, char, vsep, (<>), Doc, annotate)
searchByType :: [String] -> PTerm -> Idris ()
searchByType pkgs pterm = do
i <- getIState -- save original
when (not (null pkgs)) $
iputStrLn $ "Searching packages: " ++ showSep ", " pkgs
mapM_ loadPkgIndex pkgs
pterm' <- addUsingConstraints syn emptyFC pterm
pterm'' <- implicit toplevel syn name pterm'
let pterm''' = addImpl [] i pterm''
ty <- elabType toplevel syn (fst noDocs) (snd noDocs) emptyFC [] name NoFC pterm'
let names = searchUsing searchPred i ty
let names' = take numLimit names
let docs =
[ let docInfo = (n, delabTy i n, fmap (overview . fst) (lookupCtxtExact n (idris_docstrings i))) in
displayScore theScore <> char ' ' <> prettyDocumentedIst i docInfo
| (n, theScore) <- names']
if (not (null docs))
then case idris_outputmode i of
RawOutput _ -> do mapM_ iRenderOutput docs
iPrintResult ""
IdeMode _ _ -> iRenderResult (vsep docs)
else iRenderError $ text "No results found"
putIState i -- don't actually make any changes
where
numLimit = 50
syn = defaultSyntax { implicitAllowed = True } -- syntax
name = sMN 0 "searchType" -- name
-- | Conduct a type-directed search using a given match predicate
searchUsing :: (IState -> Type -> [(Name, Type)] -> [(Name, a)])
-> IState -> Type -> [(Name, a)]
searchUsing pred istate ty = pred istate nty . concat . M.elems $
M.mapWithKey (\key -> M.toAscList . M.mapMaybe (f key)) (definitions ctxt)
where
nty = normaliseC ctxt [] ty
ctxt = tt_ctxt istate
f k x = do
guard $ not (special k)
type2 <- typeFromDef x
return $ normaliseC ctxt [] type2
special :: Name -> Bool
special (NS n _) = special n
special (SN _) = True
special (UN n) = T.pack "default#" `T.isPrefixOf` n
|| n `elem` map T.pack ["believe_me", "really_believe_me"]
special _ = False
-- | Our default search predicate.
searchPred :: IState -> Type -> [(Name, Type)] -> [(Name, Score)]
searchPred istate ty1 = matcher where
maxScore = 100
matcher = matchTypesBulk istate maxScore ty1
typeFromDef :: (Def, i, b, c, d) -> Maybe Type
typeFromDef (def, _, _, _, _) = get def where
get :: Def -> Maybe Type
get (Function ty _) = Just ty
get (TyDecl _ ty) = Just ty
-- get (Operator ty _ _) = Just ty
get (CaseOp _ ty _ _ _ _) = Just ty
get _ = Nothing
-- Replace all occurences of `Delayed s t` with `t` in a type
unLazy :: Type -> Type
unLazy typ = case typ of
App _ (App _ (P _ lazy _) _) ty | lazy == sUN "Delayed" -> unLazy ty
Bind name binder ty -> Bind name (fmap unLazy binder) (unLazy ty)
App s t1 t2 -> App s (unLazy t1) (unLazy t2)
Proj ty i -> Proj (unLazy ty) i
_ -> typ
-- | reverse the edges for a directed acyclic graph
reverseDag :: Ord k => [((k, a), Set k)] -> [((k, a), Set k)]
reverseDag xs = map f xs where
f ((k, v), _) = ((k, v), S.fromList . map (fst . fst) $ filter (S.member k . snd) xs)
-- run vToP first!
-- | Compute a directed acyclic graph corresponding to the
-- arguments of a function.
-- returns [(the name and type of the bound variable
-- the names in the type of the bound variable)]
computeDagP :: Ord n
=> (TT n -> Bool) -- ^ filter to remove some arguments
-> TT n
-> ([((n, TT n), Set n)], [(n, TT n)], TT n)
computeDagP removePred t = (reverse (map f arguments), reverse theRemovedArgs , retTy) where
f (n, ty) = ((n, ty), M.keysSet (usedVars ty))
(arguments, theRemovedArgs, retTy) = go [] [] t
-- NOTE : args are in reverse order
go args removedArgs (Bind n (Pi _ ty _) sc) = let arg = (n, ty) in
if removePred ty
then go args (arg : removedArgs) sc
else go (arg : args) removedArgs sc
go args removedArgs sc = (args, removedArgs, sc)
-- | Collect the names and types of all the free variables
-- The Boolean indicates those variables which are determined due to injectivity
-- I have not given nearly enough thought to know whether this is correct
usedVars :: Ord n => TT n -> Map n (TT n, Bool)
usedVars = f True where
f b (P Bound n t) = M.singleton n (t, b) `M.union` f b t
f b (Bind n binder t2) = (M.delete n (f b t2) `M.union`) $ case binder of
Let t v -> f b t `M.union` f b v
Guess t v -> f b t `M.union` f b v
bind -> f b (binderTy bind)
f b (App _ t1 t2) = f b t1 `M.union` f (b && isInjective t1) t2
f b (Proj t _) = f b t
f _ (V _) = error "unexpected! run vToP first"
f _ _ = M.empty
-- | Remove a node from a directed acyclic graph
deleteFromDag :: Ord n => n -> [((n, TT n), (a, Set n))] -> [((n, TT n), (a, Set n))]
deleteFromDag name [] = []
deleteFromDag name (((name2, ty), (ix, set)) : xs) = (if name == name2
then id
else (((name2, ty) , (ix, S.delete name set)) :) ) (deleteFromDag name xs)
deleteFromArgList :: Ord n => n -> [(n, TT n)] -> [(n, TT n)]
deleteFromArgList n = filter ((/= n) . fst)
-- | Asymmetric modifications to keep track of
data AsymMods = Mods
{ argApp :: !Int
, typeClassApp :: !Int
, typeClassIntro :: !Int
} deriving (Eq, Show)
-- | Homogenous tuples
data Sided a = Sided
{ left :: !a
, right :: !a
} deriving (Eq, Show)
sided :: (a -> a -> b) -> Sided a -> b
sided f (Sided l r) = f l r
-- | Could be a functor instance, but let's avoid name overloading
both :: (a -> b) -> Sided a -> Sided b
both f (Sided l r) = Sided (f l) (f r)
-- | Keeps a record of the modifications made to match one type
-- signature with another
data Score = Score
{ transposition :: !Int -- ^ transposition of arguments
, equalityFlips :: !Int -- ^ application of symmetry of equality
, asymMods :: !(Sided AsymMods) -- ^ "directional" modifications
} deriving (Eq, Show)
displayScore :: Score -> Doc OutputAnnotation
displayScore score = case both noMods (asymMods score) of
Sided True True -> annotated EQ "=" -- types are isomorphic
Sided True False -> annotated LT "<" -- found type is more general than searched type
Sided False True -> annotated GT ">" -- searched type is more general than found type
Sided False False -> text "_"
where
annotated ordr = annotate (AnnSearchResult ordr) . text
noMods (Mods app tcApp tcIntro) = app + tcApp + tcIntro == 0
-- | This allows the search to stop expanding on a certain state if its
-- score is already too high. Returns 'True' if the algorithm should keep
-- exploring from this state, and 'False' otherwise.
scoreCriterion :: Score -> Bool
scoreCriterion (Score _ _ amods) = not
( sided (&&) (both ((> 0) . argApp) amods)
|| sided (+) (both argApp amods) > 4
|| sided (||) (both (\(Mods _ tcApp tcIntro) -> tcApp > 3 || tcIntro > 3) amods)
)
-- | Convert a 'Score' to an 'Int' to provide an order for search results.
-- Lower scores are better.
defaultScoreFunction :: Score -> Int
defaultScoreFunction (Score trans eqFlip amods) =
trans + eqFlip + linearPenalty + upAndDowncastPenalty
where
-- prefer finding a more general type to a less general type
linearPenalty = (\(Sided l r) -> 3 * l + r)
(both (\(Mods app tcApp tcIntro) -> 3 * app + 4 * tcApp + 2 * tcIntro) amods)
-- it's very bad to have *both* upcasting and downcasting
upAndDowncastPenalty = 100 *
sided (*) (both (\(Mods app tcApp tcIntro) -> 2 * app + tcApp + tcIntro) amods)
instance Ord Score where
compare = comparing defaultScoreFunction
instance Monoid a => Monoid (Sided a) where
mempty = Sided mempty mempty
(Sided l1 r1) `mappend` (Sided l2 r2) = Sided (l1 `mappend` l2) (r1 `mappend` r2)
instance Monoid AsymMods where
mempty = Mods 0 0 0
(Mods a b c) `mappend` (Mods a' b' c') = Mods (a + a') (b + b') (c + c')
instance Monoid Score where
mempty = Score 0 0 mempty
(Score t e mods) `mappend` (Score t' e' mods') = Score (t + t') (e + e') (mods `mappend` mods')
-- | A directed acyclic graph representing the arguments to a function
-- The 'Int' represents the position of the argument (1st argument, 2nd, etc.)
type ArgsDAG = [((Name, Type), (Int, Set Name))]
-- | A list of typeclass constraints
type Classes = [(Name, Type)]
-- | The state corresponding to an attempted match of two types.
data State = State
{ holes :: ![(Name, Type)] -- ^ names which have yet to be resolved
, argsAndClasses :: !(Sided (ArgsDAG, Classes))
-- ^ arguments and typeclass constraints for each type which have yet to be resolved
, score :: !Score -- ^ the score so far
, usedNames :: ![Name] -- ^ all names that have been used
} deriving Show
modifyTypes :: (Type -> Type) -> (ArgsDAG, Classes) -> (ArgsDAG, Classes)
modifyTypes f = modifyDag *** modifyList
where
modifyDag = map (first (second f))
modifyList = map (second f)
findNameInArgsDAG :: Name -> ArgsDAG -> Maybe (Type, Maybe Int)
findNameInArgsDAG name = fmap ((snd . fst) &&& (Just . fst . snd)) . find ((name ==) . fst . fst)
findName :: Name -> (ArgsDAG, Classes) -> Maybe (Type, Maybe Int)
findName n (args, classes) = findNameInArgsDAG n args <|> ((,) <$> lookup n classes <*> Nothing)
deleteName :: Name -> (ArgsDAG, Classes) -> (ArgsDAG, Classes)
deleteName n (args, classes) = (deleteFromDag n args, filter ((/= n) . fst) classes)
tcToMaybe :: TC a -> Maybe a
tcToMaybe (OK x) = Just x
tcToMaybe (Error _) = Nothing
inArgTys :: (Type -> Type) -> ArgsDAG -> ArgsDAG
inArgTys = map . first . second
typeclassUnify :: Ctxt ClassInfo -> Context -> Type -> Type -> Maybe [(Name, Type)]
typeclassUnify classInfo ctxt ty tyTry = do
res <- tcToMaybe $ match_unify ctxt [] (ty, Nothing) (retTy, Nothing) [] theHoles []
guard $ null (theHoles \\ map fst res)
let argTys' = map (second $ foldr (.) id [ subst n t | (n, t) <- res ]) tcArgs
return argTys'
where
tyTry' = vToP tyTry
theHoles = map fst nonTcArgs
retTy = getRetTy tyTry'
(tcArgs, nonTcArgs) = partition (isTypeClassArg classInfo . snd) $ getArgTys tyTry'
isTypeClassArg :: Ctxt ClassInfo -> Type -> Bool
isTypeClassArg classInfo ty = not (null (getClassName clss >>= flip lookupCtxt classInfo)) where
(clss, args) = unApply ty
getClassName (P (TCon _ _) className _) = [className]
getClassName _ = []
-- | Compute the power set
subsets :: [a] -> [[a]]
subsets [] = [[]]
subsets (x : xs) = let ss = subsets xs in map (x :) ss ++ ss
-- not recursive (i.e., doesn't flip iterated identities) at the moment
-- recalls the number of flips that have been made
flipEqualities :: Type -> [(Int, Type)]
flipEqualities t = case t of
eq1@(App _ (App _ (App _ (App _ eq@(P _ eqty _) tyL) tyR) valL) valR) | eqty == eqTy ->
[(0, eq1), (1, app (app (app (app eq tyR) tyL) valR) valL)]
Bind n binder sc -> (\bind' (j, sc') -> (fst (binderTy bind') + j, Bind n (fmap snd bind') sc'))
<$> traverse flipEqualities binder <*> flipEqualities sc
App _ f x -> (\(i, f') (j, x') -> (i + j, app f' x'))
<$> flipEqualities f <*> flipEqualities x
t' -> [(0, t')]
where app = App Complete
--DONT run vToP first!
-- | Try to match two types together in a unification-like procedure.
-- Returns a list of types and their minimum scores, sorted in order
-- of increasing score.
matchTypesBulk :: forall info. IState -> Int -> Type -> [(info, Type)] -> [(info, Score)]
matchTypesBulk istate maxScore type1 types = getAllResults startQueueOfQueues where
getStartQueues :: (info, Type) -> Maybe (Score, (info, Q.PQueue Score State))
getStartQueues nty@(info, type2) = case mapMaybe startStates ty2s of
[] -> Nothing
xs -> Just (minimum (map fst xs), (info, Q.fromList xs))
where
ty2s = (\(i, dag) (j, retTy) -> (i + j, dag, retTy))
<$> flipEqualitiesDag dag2 <*> flipEqualities retTy2
flipEqualitiesDag dag = case dag of
[] -> [(0, [])]
((n, ty), (pos, deps)) : xs ->
(\(i, ty') (j, xs') -> (i + j , ((n, ty'), (pos, deps)) : xs'))
<$> flipEqualities ty <*> flipEqualitiesDag xs
startStates (numEqFlips, sndDag, sndRetTy) = do
state <- unifyQueue (State startingHoles
(Sided (dag1, typeClassArgs1) (sndDag, typeClassArgs2))
(mempty { equalityFlips = numEqFlips }) usedns) [(retTy1, sndRetTy)]
return (score state, state)
(dag2, typeClassArgs2, retTy2) = makeDag (uniqueBinders (map fst argNames1) type2)
argNames2 = map fst dag2
usedns = map fst startingHoles
startingHoles = argNames1 ++ argNames2
startingTypes = [(retTy1, retTy2)]
startQueueOfQueues :: Q.PQueue Score (info, Q.PQueue Score State)
startQueueOfQueues = Q.fromList $ mapMaybe getStartQueues types
getAllResults :: Q.PQueue Score (info, Q.PQueue Score State) -> [(info, Score)]
getAllResults q = case Q.minViewWithKey q of
Nothing -> []
Just ((nextScore, (info, stateQ)), q') ->
if defaultScoreFunction nextScore <= maxScore
then case nextStepsQueue stateQ of
Nothing -> getAllResults q'
Just (Left stateQ') -> case Q.minViewWithKey stateQ' of
Nothing -> getAllResults q'
Just ((newQscore,_), _) -> getAllResults (Q.add newQscore (info, stateQ') q')
Just (Right theScore) -> (info, theScore) : getAllResults q'
else []
ctxt = tt_ctxt istate
classInfo = idris_classes istate
(dag1, typeClassArgs1, retTy1) = makeDag type1
argNames1 = map fst dag1
makeDag :: Type -> (ArgsDAG, Classes, Type)
makeDag = first3 (zipWith (\i (ty, deps) -> (ty, (i, deps))) [0..] . reverseDag) .
computeDagP (isTypeClassArg classInfo) . vToP . unLazy
first3 f (a,b,c) = (f a, b, c)
-- update our state with the unification resolutions
resolveUnis :: [(Name, Type)] -> State -> Maybe (State, [(Type, Type)])
resolveUnis [] state = Just (state, [])
resolveUnis ((name, term@(P Bound name2 _)) : xs)
state | isJust findArgs = do
((ty1, ix1), (ty2, ix2)) <- findArgs
(state'', queue) <- resolveUnis xs state'
let transScore = fromMaybe 0 (abs <$> ((-) <$> ix1 <*> ix2))
return (inScore (\s -> s { transposition = transposition s + transScore }) state'', (ty1, ty2) : queue)
where
unresolved = argsAndClasses state
inScore f stat = stat { score = f (score stat) }
findArgs = ((,) <$> findName name (left unresolved) <*> findName name2 (right unresolved)) <|>
((,) <$> findName name2 (left unresolved) <*> findName name (right unresolved))
matchnames = [name, name2]
deleteArgs = deleteName name . deleteName name2
state' = state { holes = filter (not . (`elem` matchnames) . fst) (holes state)
, argsAndClasses = both (modifyTypes (subst name term) . deleteArgs) unresolved}
resolveUnis ((name, term) : xs)
state@(State hs unresolved _ _) = case both (findName name) unresolved of
Sided Nothing Nothing -> Nothing
Sided (Just _) (Just _) -> error "Idris internal error: TypeSearch.resolveUnis"
oneOfEach -> first (addScore (both scoreFor oneOfEach)) <$> nextStep
where
scoreFor (Just _) = mempty { argApp = 1 }
scoreFor Nothing = mempty { argApp = otherApplied }
-- find variables which are determined uniquely by the type
-- due to injectivity
matchedVarMap = usedVars term
bothT f (x, y) = (f x, f y)
(injUsedVars, notInjUsedVars) = bothT M.keys . M.partition id . M.filterWithKey (\k _-> k `elem` map fst hs) $ M.map snd matchedVarMap
varsInTy = injUsedVars ++ notInjUsedVars
toDelete = name : varsInTy
deleteMany = foldr (.) id (map deleteName toDelete)
otherApplied = length notInjUsedVars
addScore additions theState = theState { score = let s = score theState in
s { asymMods = asymMods s `mappend` additions } }
state' = state { holes = filter (not . (`elem` toDelete) . fst) hs
, argsAndClasses = both (modifyTypes (subst name term) . deleteMany) (argsAndClasses state) }
nextStep = resolveUnis xs state'
-- | resolve a queue of unification constraints
unifyQueue :: State -> [(Type, Type)] -> Maybe State
unifyQueue state [] = return state
unifyQueue state ((ty1, ty2) : queue) = do
--trace ("go: \n" ++ show state) True `seq` return ()
res <- tcToMaybe $ match_unify ctxt [ (n, Pi Nothing ty (TType (UVar [] 0))) | (n, ty) <- holes state]
(ty1, Nothing)
(ty2, Nothing) [] (map fst $ holes state) []
(state', queueAdditions) <- resolveUnis res state
guard $ scoreCriterion (score state')
unifyQueue state' (queue ++ queueAdditions)
possClassInstances :: [Name] -> Type -> [Type]
possClassInstances usedns ty = do
className <- getClassName clss
classDef <- lookupCtxt className classInfo
n <- class_instances classDef
def <- lookupCtxt (fst n) (definitions ctxt)
nty <- normaliseC ctxt [] <$> (case typeFromDef def of Just x -> [x]; Nothing -> [])
let ty' = vToP (uniqueBinders usedns nty)
return ty'
where
(clss, _) = unApply ty
getClassName (P (TCon _ _) className _) = [className]
getClassName _ = []
-- 'Just' if the computation hasn't totally failed yet, 'Nothing' if it has
-- 'Left' if we haven't found a terminal state, 'Right' if we have
nextStepsQueue :: Q.PQueue Score State -> Maybe (Either (Q.PQueue Score State) Score)
nextStepsQueue queue = do
((nextScore, next), rest) <- Q.minViewWithKey queue
Just $ if isFinal next
then Right nextScore
else let additions = if scoreCriterion nextScore
then Q.fromList [ (score state, state) | state <- nextSteps next ]
else Q.empty in
Left (Q.union rest additions)
where
isFinal (State [] (Sided ([], []) ([], [])) _ _) = True
isFinal _ = False
-- | Find all possible matches starting from a given state.
-- We go in stages rather than concatenating all three results in hopes of narrowing
-- the search tree. Once we advance in a phase, there should be no going back.
nextSteps :: State -> [State]
-- Stage 3 - match typeclasses
nextSteps (State [] unresolved@(Sided ([], c1) ([], c2)) scoreAcc usedns) =
if null results3 then results4 else results3
where
-- try to match a typeclass argument from the left with a typeclass argument from the right
results3 =
catMaybes [ unifyQueue (State []
(Sided ([], deleteFromArgList n1 c1)
([], map (second subst2for1) (deleteFromArgList n2 c2)))
scoreAcc usedns) [(ty1, ty2)]
| (n1, ty1) <- c1, (n2, ty2) <- c2, let subst2for1 = psubst n2 (P Bound n1 ty1)]
-- try to hunt match a typeclass constraint by replacing it with an instance
results4 = [ State [] (both (\(cs, _, _) -> ([], cs)) sds)
(scoreAcc `mappend` Score 0 0 (both (\(_, amods, _) -> amods) sds))
(usedns ++ sided (++) (both (\(_, _, hs) -> hs) sds))
| sds <- allMods ]
where
allMods = parallel defMod mods
mods :: Sided [( Classes, AsymMods, [Name] )]
mods = both (instanceMods . snd) unresolved
defMod :: Sided (Classes, AsymMods, [Name])
defMod = both (\(_, cs) -> (cs, mempty , [])) unresolved
parallel :: Sided a -> Sided [a] -> [Sided a]
parallel (Sided l r) (Sided ls rs) = map (flip Sided r) ls ++ map (Sided l) rs
instanceMods :: Classes -> [( Classes , AsymMods, [Name] )]
instanceMods classes = [ ( newClassArgs, mempty { typeClassApp = 1 }, newHoles )
| (_, ty) <- classes
, inst <- possClassInstances usedns ty
, newClassArgs <- maybeToList $ typeclassUnify classInfo ctxt ty inst
, let newHoles = map fst newClassArgs ]
-- Stage 1 - match arguments
nextSteps (State hs (Sided (dagL, c1) (dagR, c2)) scoreAcc usedns) = results where
results = concatMap takeSomeClasses results1
-- we only try to match arguments whose names don't appear in the types
-- of any other arguments
canBeFirst :: ArgsDAG -> [(Name, Type)]
canBeFirst = map fst . filter (S.null . snd . snd)
-- try to match an argument from the left with an argument from the right
results1 = catMaybes [ unifyQueue (State (filter (not . (`elem` [n1,n2]) . fst) hs)
(Sided (deleteFromDag n1 dagL, c1)
(inArgTys subst2for1 $ deleteFromDag n2 dagR, map (second subst2for1) c2))
scoreAcc usedns) [(ty1, ty2)]
| (n1, ty1) <- canBeFirst dagL, (n2, ty2) <- canBeFirst dagR
, let subst2for1 = psubst n2 (P Bound n1 ty1)]
-- Stage 2 - simply introduce a subset of the typeclasses
-- we've finished, so take some classes
takeSomeClasses (State [] unresolved@(Sided ([], _) ([], _)) scoreAcc usedns) =
map statesFromMods . prod $ both (classMods . snd) unresolved
where
swap (Sided l r) = Sided r l
statesFromMods :: Sided (Classes, AsymMods) -> State
statesFromMods sides = let classes = both (\(c, _) -> ([], c)) sides
mods = swap (both snd sides) in
State [] classes (scoreAcc `mappend` (mempty { asymMods = mods })) usedns
classMods :: Classes -> [(Classes, AsymMods)]
classMods cs = let lcs = length cs in
[ (cs', mempty { typeClassIntro = lcs - length cs' }) | cs' <- subsets cs ]
prod :: Sided [a] -> [Sided a]
prod (Sided ls rs) = [Sided l r | l <- ls, r <- rs]
-- still have arguments to match, so just be the identity
takeSomeClasses s = [s]
| ozgurakgun/Idris-dev | src/Idris/TypeSearch.hs | bsd-3-clause | 23,307 | 0 | 20 | 5,697 | 8,540 | 4,589 | 3,951 | 411 | 22 |
-------------------------------------------------------------------------------
-- |
-- Module : System.Hardware.Haskino.Compiler
-- Copyright : (c) University of Kansas
-- System.Hardware.Arduino (c) Levent Erkok
-- License : BSD3
-- Stability : experimental
--
-- 'C' code generator for the Haskino Library.
-------------------------------------------------------------------------------
{-# LANGUAGE GADTs #-}
{-# LANGUAGE ScopedTypeVariables #-}
module System.Hardware.Haskino.Compiler(compileProgram, compileProgramE) where
import Control.Monad.State
import Control.Remote.Applicative.Types as T
import Control.Remote.Monad
import Control.Remote.Monad.Types as T
import Data.Boolean
import Data.Char
import Data.Word (Word32, Word8)
import System.Hardware.Haskino.Data
import System.Hardware.Haskino.Expr
data CompileState = CompileState {level :: Int
, intTask :: Bool
, ix :: Int
, ib :: Int
, cmds :: String
, binds :: String
, releases :: String
, refs :: String
, forwards :: String
, cmdList :: [String]
, bindList :: [String]
, releaseList :: [String]
, bindsInside :: [Bool]
, tasksToDo :: [(Arduino (Expr ()), String, Bool)]
, tasksDone :: [String]
, errors :: [String]
, iterBinds :: [(Int, Int, Int)]
, ifEitherComp :: Integer
}
data CompileType =
UnitType
| BoolType
| Word8Type
| Word16Type
| Word32Type
| Int8Type
| Int16Type
| Int32Type
| IntType
| List8Type
| FloatType
deriving (Show, Eq)
compileTypeToString :: CompileType -> String
compileTypeToString UnitType = "uint8_t"
compileTypeToString BoolType = "bool"
compileTypeToString Word8Type = "uint8_t"
compileTypeToString Word16Type = "uint16_t"
compileTypeToString Word32Type = "uint32_t"
compileTypeToString Int8Type = "int8_t"
compileTypeToString Int16Type = "int16_t"
compileTypeToString Int32Type = "int32_t"
compileTypeToString IntType = "int32_t"
compileTypeToString List8Type = "uint8_t *"
compileTypeToString FloatType = "float"
refName :: String
refName = "ref"
bindName :: String
bindName = "bind"
indentString :: String
indentString = " "
mainEntry :: String
mainEntry = "haskinoMain"
stackSizeStr :: String
stackSizeStr = "_STACK_SIZE"
tcbStr :: String
tcbStr = "Tcb"
indent :: Int -> String
indent k = concat $ replicate k indentString
defaultTaskStackSize :: Int
defaultTaskStackSize = 64
contextTaskStackSize :: Int
contextTaskStackSize = 36
taskStackSize :: Int -> Int
taskStackSize bs = bs * 4 + defaultTaskStackSize + contextTaskStackSize;
nextBind :: State CompileState Int
nextBind = do
s <- get
put s {ib = (ib s) + 1}
return (ib s)
compileProgram :: Arduino () -> FilePath -> IO ()
compileProgram p f = compileProgramE (lit <$> p) f
compileProgramE :: Arduino (Expr ()) -> FilePath -> IO ()
compileProgramE p f = do
writeFile f prog
if (length $ errors st) == 0
then putStrLn "Compile Successful"
else putStrLn $ (show $ length $ errors st) ++ " Errors :"
mapM_ putStrLn $ errors st
where
(_, st) = runState compileTasks
(CompileState 0 False 0 0 "" "" "" "" "" [] [] [] [True] [(p, mainEntry, False)] [] [] [] 0)
prog = "#include \"HaskinoRuntime.h\"\n\n" ++
forwards st ++ "\n" ++
"void setup()\n" ++
" {\n" ++
" haskinoMemInit();\n" ++
" createTask(255, " ++ mainEntry ++ tcbStr ++ ", " ++
(map toUpper mainEntry) ++ stackSizeStr ++ ", " ++
mainEntry ++ ");\n" ++
" scheduleTask(255, 0);\n" ++
" startScheduler();\n" ++
" }\n\n" ++
"void loop()\n" ++
" {\n" ++
" }\n\n" ++
refs st ++ "\n" ++ (concat $ tasksDone st)
compileTasks :: State CompileState ()
compileTasks = do
s <- get
let tasks = tasksToDo s
if null tasks
then return ()
else do
put s {tasksToDo = tail tasks}
let (m, name, int) = head tasks
compileTask m name int
compileTasks
compileTask :: Arduino (Expr ()) -> String -> Bool -> State CompileState ()
compileTask t name int = do
s <- get
put s {level = 0, intTask = int, ib = 0, cmds = "",
binds = "", releases = "", cmdList = [], bindList = [], releaseList = []}
_ <- compileLine $ "void " ++ name ++ "()"
_ <- compileForward $ "void " ++ name ++ "();"
_ <- compileCodeBlock True "" t
_ <- compileInReleases
_ <- if not int
then compileLineIndent "taskComplete();"
else return LitUnit
_ <- compileLineIndent "}"
s' <- get
let defineStr = (map toUpper name) ++ stackSizeStr
_ <- compileForward $ "#define " ++ defineStr ++ " " ++
(show $ taskStackSize $ ib s')
_ <- compileForward $ "byte " ++ name ++ tcbStr ++ "[sizeof(TCB) + " ++
defineStr ++ "];"
s'' <- get
put s'' {tasksDone = cmds s'' : tasksDone s''}
return ()
compileLine :: String -> State CompileState (Expr ())
compileLine s = do
st <- get
put st { cmds = cmds st ++ (indent $ level st) ++ s ++ "\n"}
return LitUnit
compileLineIndent :: String -> State CompileState (Expr ())
compileLineIndent s = do
st <- get
put st { cmds = cmds st ++ (indent (level st + 1)) ++ s ++ "\n"}
return LitUnit
compileAllocBind :: String -> State CompileState (Expr ())
compileAllocBind s = do
st <- get
let ilvl = if head $ bindsInside st then level st else (level st) - 1
put st { binds = binds st ++ (indent ilvl) ++ s ++ "\n"}
return LitUnit
compileRelease :: String -> State CompileState (Expr ())
compileRelease s = do
st <- get
-- let ilvl = if head $ bindsInside st then level st else (level st) - 1
let ilvl = level st
put st { releases = releases st ++ (indent ilvl) ++ s ++ "\n"}
return LitUnit
compileAllocRef :: String -> State CompileState (Expr ())
compileAllocRef s = do
st <- get
put st { refs = refs st ++ s ++ "\n"}
return LitUnit
compileForward :: String -> State CompileState (Expr ())
compileForward s = do
st <- get
put st { forwards = forwards st ++ s ++ "\n"}
return LitUnit
compileError :: String -> String -> State CompileState (Expr ())
compileError s1 s2 = do
_ <- compileLine s1
st <- get
put st { errors = s2 : (errors st)}
return LitUnit
compileShallowPrimitiveError :: String -> State CompileState (Expr ())
compileShallowPrimitiveError s = do
_ <- compileError ("/* " ++ errmsg ++ " */") errmsg
return LitUnit
where
errmsg = "ERROR - " ++ s ++ " is a Shallow procedure, use Deep version instead."
compileUnsupportedError :: String -> State CompileState (Expr ())
compileUnsupportedError s = do
_ <- compileError ("/* " ++ errmsg ++ " */") errmsg
return LitUnit
where
errmsg = "ERROR - " ++ s ++ " not suppported by compiler."
compileNoExprCommand :: String -> State CompileState (Expr ())
compileNoExprCommand s = do
_ <- compileLine (s ++ "();")
return LitUnit
compile1ExprCommand :: String -> Expr a -> State CompileState (Expr ())
compile1ExprCommand s e = do
_ <- compileLine (s ++ "(" ++ compileExpr e ++ ");")
return LitUnit
compile2ExprCommand :: String -> Expr a -> Expr b -> State CompileState (Expr ())
compile2ExprCommand s e1 e2 = do
_ <- compileLine (s ++ "(" ++ compileExpr e1 ++ "," ++ compileExpr e2 ++ ");")
return LitUnit
compile3ExprCommand :: String -> Expr a -> Expr b -> Expr c -> State CompileState (Expr ())
compile3ExprCommand s e1 e2 e3 = do
_ <- compileLine (s ++ "(" ++ compileExpr e1 ++ "," ++
compileExpr e2 ++ "," ++
compileExpr e3 ++ ");")
return LitUnit
compileWriteRef :: Int -> Expr a -> State CompileState (Expr ())
compileWriteRef i e = do
_ <- compileLine $ refName ++ show i ++ " = " ++ compileExpr e ++ ";"
return LitUnit
compileWriteListRef :: Int -> Expr a -> State CompileState (Expr ())
compileWriteListRef i e = do
_ <- compileLine $ "listAssign(&" ++ refName ++ show i ++ ", " ++ compileExpr e ++ ");"
return LitUnit
compilePrimitive :: forall a . ArduinoPrimitive a -> State CompileState a
compilePrimitive prim = case knownResult prim of
Just _ -> compileCommand prim
Nothing -> compileProcedure prim
compileCommand :: ArduinoPrimitive a -> State CompileState a
compileCommand SystemResetE = compileNoExprCommand "soft_restart"
compileCommand (SetPinModeE p m) = compile2ExprCommand "pinMode" p m
compileCommand (DigitalWriteE p b) = compile2ExprCommand "digitalWrite" p b
compileCommand (DigitalPortWriteE p b m) =
compile3ExprCommand "digitalPortWrite" p b m
compileCommand (AnalogWriteE p w) = compile2ExprCommand "analogWrite" p w
compileCommand (ToneE p f (Just d)) = compile3ExprCommand "tone" p f d
compileCommand (ToneE p f Nothing) = compile3ExprCommand "tone" p f (lit (0::Word32))
compileCommand (NoToneE p) = compile1ExprCommand "noTone" p
compileCommand (I2CWriteE sa w8s) = compile2ExprCommand "i2cWrite" sa w8s
compileCommand I2CConfigE = compileNoExprCommand "i2cConfig"
compileCommand (SerialBeginE p r) = compile2ExprCommand "serialBegin" p r
compileCommand (SerialEndE p) = compile1ExprCommand "serialEnd" p
compileCommand (SerialWriteE p w) = compile2ExprCommand "serialWrite" p w
compileCommand (SerialWriteListE p w8s) = compile2ExprCommand "serialWriteList" p w8s
compileCommand (StepperSetSpeedE st sp) =
compile2ExprCommand "stepperSetSpeed" st sp
compileCommand (ServoDetachE sv) =
compile1ExprCommand "servoDetach" sv
compileCommand (ServoWriteE sv w) =
compile2ExprCommand "servoWrite" sv w
compileCommand (ServoWriteMicrosE sv w) =
compile2ExprCommand "servoWriteMicros" sv w
compileCommand (DeleteTask tid) = do
_ <- compileShallowPrimitiveError $ "deleteTask " ++ show tid
return ()
compileCommand (DeleteTaskE tid) =
compile1ExprCommand "deleteTask" tid
compileCommand (CreateTask tid _) = do
_ <- compileShallowPrimitiveError $ "createTask " ++ show tid
return ()
compileCommand (CreateTaskE (LitW8 tid) m) = do
let taskName = "task" ++ show tid
_ <- compileLine $ "createTask(" ++ show tid ++ ", " ++
taskName ++ tcbStr ++ ", " ++
(map toUpper taskName) ++ stackSizeStr ++ ", " ++
taskName ++ ");"
s <- get
put s {tasksToDo = (m, taskName, False) : (tasksToDo s)}
return LitUnit
compileCommand (ScheduleTask tid m) = do
_ <- compileShallowPrimitiveError $ "scheduleTask " ++ show tid ++ " " ++ show m
return ()
compileCommand (ScheduleTaskE tid tt) =
compile2ExprCommand "scheduleTask" tid tt
compileCommand ScheduleReset = do
_ <- compileShallowPrimitiveError $ "scheduleReset"
return ()
compileCommand ScheduleResetE =
compileNoExprCommand "scheduleReset"
compileCommand (AttachInt p t _) = do
_ <- compileShallowPrimitiveError $ "sttachInt " ++ show p ++ " " ++ show t
return ()
compileCommand (AttachIntE p t m) = do
let taskName = "task" ++ compileExpr t
s <- get
put s {tasksToDo = addIntTask (tasksToDo s) taskName}
compileLine ("attachInterrupt(digitalPinToInterrupt(" ++
compileExpr p ++ "), task" ++
compileExpr t ++ ", " ++
compileExpr m ++ ");")
where
addIntTask :: [(Arduino (Expr ()), String, Bool)] -> String -> [(Arduino (Expr ()), String, Bool)]
addIntTask [] _ = []
addIntTask (t':ts) tn = matchTask t' tn : addIntTask ts tn
matchTask :: (Arduino (Expr ()), String, Bool) -> String -> (Arduino (Expr ()), String, Bool)
matchTask (m', tn1, i) tn2 = if tn1 == tn2
then (m', tn1, True)
else (m', tn1, i)
compileCommand (DetachIntE p) =
compile1ExprCommand "detachInterrupt" p
compileCommand InterruptsE =
compileNoExprCommand "interrupts"
compileCommand NoInterruptsE =
compileNoExprCommand "noInterrupts"
compileCommand (GiveSemE i) =
compile1ExprCommand "giveSem" i
compileCommand (TakeSemE i) =
compile1ExprCommand "takeSem" i
compileCommand (WriteRemoteRefB (RemoteRefB i) e) = do
compileShallowPrimitiveError "writeRemoteRefB"
return ()
compileCommand (WriteRemoteRefBE (RemoteRefB i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefW8 (RemoteRefW8 i) e) = do
compileShallowPrimitiveError "writeRemoteRefW8"
return ()
compileCommand (WriteRemoteRefW8E (RemoteRefW8 i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefW16 (RemoteRefW16 i) e) = do
compileShallowPrimitiveError "writeRemoteRefW16"
return ()
compileCommand (WriteRemoteRefW16E (RemoteRefW16 i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefW32 (RemoteRefW32 i) e) = do
compileShallowPrimitiveError "writeRemoteRefW32"
return ()
compileCommand (WriteRemoteRefW32E (RemoteRefW32 i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefI8 (RemoteRefI8 i) e) = do
compileShallowPrimitiveError "writeRemoteRefI8"
return ()
compileCommand (WriteRemoteRefI8E (RemoteRefI8 i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefI16 (RemoteRefI16 i) e) = do
compileShallowPrimitiveError "writeRemoteRefI16"
return ()
compileCommand (WriteRemoteRefI16E (RemoteRefI16 i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefI32 (RemoteRefI32 i) e) = do
compileShallowPrimitiveError "writeRemoteRefI32"
return ()
compileCommand (WriteRemoteRefI32E (RemoteRefI32 i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefI (RemoteRefI i) e) = do
compileShallowPrimitiveError "writeRemoteRefI"
return ()
compileCommand (WriteRemoteRefIE (RemoteRefI i) e) = compileWriteRef i e
compileCommand (WriteRemoteRefL8 (RemoteRefL8 i) e) = do
compileShallowPrimitiveError "writeRemoteRefL8"
return ()
compileCommand (WriteRemoteRefL8E (RemoteRefL8 i) e) = compileWriteListRef i e
compileCommand (WriteRemoteRefFloat (RemoteRefFloat i) e) = do
compileShallowPrimitiveError "writeRemoteRefFloat"
return ()
compileCommand (WriteRemoteRefFloatE (RemoteRefFloat i) e) = compileWriteRef i e
compileCommand (ModifyRemoteRefBE (RemoteRefB i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefW8E (RemoteRefW8 i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefW16E (RemoteRefW16 i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefW32E (RemoteRefW32 i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefI8E (RemoteRefI8 i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefI16E (RemoteRefI16 i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefI32E (RemoteRefI32 i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefIE (RemoteRefI i) f) = compileWriteRef i f
compileCommand (ModifyRemoteRefL8E (RemoteRefL8 i) f) = compileWriteListRef i f
compileCommand (ModifyRemoteRefFloatE (RemoteRefFloat i) f) = compileWriteRef i f
compileCommand _ = error "compileCommand - Unknown command, it may actually be a procedure"
compileSimpleProcedure :: CompileType -> String -> State CompileState Int
compileSimpleProcedure t p = do
s <- get
let b = ib s
put s {ib = b + 1}
_ <- compileLine $ bindName ++ show b ++ " = " ++ p ++ ";"
_ <- compileAllocBind $ compileTypeToString t ++ " " ++ bindName ++ show b ++ ";"
return b
compileSimpleListProcedure :: String -> State CompileState Int
compileSimpleListProcedure p = do
s <- get
let b = ib s
put s {ib = b + 1}
_ <- compileLine $ "listAssign(&" ++ bindName ++ show b ++ ", " ++ p ++ ");"
_ <- compileAllocBind $ compileTypeToString List8Type ++ " " ++
bindName ++ show b ++ " = NULL;"
_ <- compileRelease $ "listRelease(&" ++ bindName ++ show b ++ ");"
return b
compileNoExprProcedure :: CompileType -> String -> State CompileState Int
compileNoExprProcedure t p = do
b <- compileSimpleProcedure t (p ++ "()")
return b
compile1ExprProcedure :: CompileType -> String -> Expr a -> State CompileState Int
compile1ExprProcedure t p e = do
b <- compileSimpleProcedure t (p ++ "(" ++ compileExpr e ++ ")")
return b
compile2ExprProcedure :: CompileType -> String ->
Expr a -> Expr a -> State CompileState Int
compile2ExprProcedure t p e1 e2 = do
b <- compileSimpleProcedure t (p ++ "(" ++ compileExpr e1 ++ "," ++
compileExpr e2 ++ ")")
return b
compile1ExprListProcedure :: String ->
Expr a -> State CompileState Int
compile1ExprListProcedure p e1 = do
b <- compileSimpleListProcedure (p ++ "(" ++ compileExpr e1 ++ ")")
return b
compile2ExprListProcedure :: String ->
Expr a -> Expr a -> State CompileState Int
compile2ExprListProcedure p e1 e2 = do
b <- compileSimpleListProcedure (p ++ "(" ++ compileExpr e1 ++ "," ++
compileExpr e2 ++ ")")
return b
compile3ExprProcedure :: CompileType -> String ->
Expr a -> Expr b -> Expr c -> State CompileState Int
compile3ExprProcedure t p e1 e2 e3 = do
b <- compileSimpleProcedure t (p ++ "(" ++ compileExpr e1 ++ "," ++
compileExpr e2 ++ "," ++
compileExpr e3 ++ ")")
return b
compile5ExprProcedure :: CompileType -> String -> Expr a -> Expr b ->
Expr c -> Expr d -> Expr e -> State CompileState Int
compile5ExprProcedure t p e1 e2 e3 e4 e5 = do
b <- compileSimpleProcedure t (p ++ "(" ++ compileExpr e1 ++ "," ++
compileExpr e2 ++ "," ++
compileExpr e3 ++ "," ++
compileExpr e4 ++ "," ++
compileExpr e5 ++ ")")
return b
compileNewRef :: CompileType -> Expr a -> State CompileState Int
compileNewRef t e = do
s <- get
let x = ix s
put s {ix = x + 1}
_ <- compileAllocRef $ compileTypeToString t ++ " " ++ refName ++ show x ++ ";"
_ <- compileLine $ refName ++ show x ++ " = " ++ compileExpr e ++ ";"
return x
compileNewListRef :: Expr a -> State CompileState Int
compileNewListRef e = do
s <- get
let x = ix s
put s {ix = x + 1}
_ <- compileAllocRef $ compileTypeToString List8Type ++
" " ++ refName ++ show x ++ " = NULL;"
_ <- compileLine $ "listAssign(&" ++ refName ++ show x ++
", " ++ compileExpr e ++ ");"
return x
compileReadRef :: CompileType -> Int -> State CompileState Int
compileReadRef t ix' = do
s <- get
let b = ib s
put s {ib = b + 1}
_ <- compileLine $ bindName ++ show b ++ " = " ++ refName ++ show ix' ++ ";"
_ <- compileAllocBind $ compileTypeToString t ++ " " ++ bindName ++ show b ++ ";"
return b
compileReadListRef :: Int -> State CompileState Int
compileReadListRef ix' = do
s <- get
let b = ib s
put s {ib = b + 1}
_ <- compileLine $ "listAssign(&" ++ bindName ++ show b ++ ", " ++
refName ++ show ix' ++ ");"
_ <- compileAllocBind $ compileTypeToString List8Type ++ " " ++
bindName ++ show b ++ " = NULL;"
_ <- compileRelease $ "listRelease(&" ++ bindName ++ show b ++ ");"
return b
compileProcedure :: ArduinoPrimitive a -> State CompileState a
compileProcedure QueryFirmware = do
_ <- compileShallowPrimitiveError "queryFirmware"
return 0
compileProcedure QueryFirmwareE = do
b <- compileNoExprProcedure Word16Type "queryFirmware"
return $ remBind b
compileProcedure QueryProcessor = do
_ <- compileShallowPrimitiveError "queryProcessor"
return 0
compileProcedure QueryProcessorE = do
b <- compileNoExprProcedure Word8Type "queryProcessor"
return $ remBind b
compileProcedure Millis = do
_ <- compileShallowPrimitiveError "millis"
return (0::Word32)
compileProcedure MillisE = do
b <- compileNoExprProcedure Word32Type "millis"
return $ remBind b
compileProcedure Micros = do
_ <- compileShallowPrimitiveError "micros"
return 0
compileProcedure MicrosE = do
b <- compileNoExprProcedure Word32Type "micros"
return $ remBind b
compileProcedure (DelayMillis ms) = do
_ <- compileShallowPrimitiveError $ "delayMillis " ++ show ms
return ()
compileProcedure (DelayMillisE ms) = do
_ <- compile1ExprCommand "delayMilliseconds" ms
return LitUnit
compileProcedure (DelayMicros ms) = do
_ <- compileShallowPrimitiveError $ "delayMicros " ++ show ms
return ()
compileProcedure (DelayMicrosE ms) = do
_ <- compile1ExprCommand "delayMicroseconds" ms
return LitUnit
compileProcedure (DigitalRead ms) = do
_ <- compileShallowPrimitiveError $ "digitalRead " ++ show ms
return False
compileProcedure (DigitalReadE p) = do
b <- compile1ExprProcedure BoolType "digitalRead" p
return $ remBind b
compileProcedure (DigitalPortRead p m) = do
_ <- compileShallowPrimitiveError $ "digitalPortRead " ++ show p ++ " " ++ show m
return 0
compileProcedure (DigitalPortReadE p m) = do
b <- compile2ExprProcedure Word8Type "digitalPortRead" p m
return $ remBind b
compileProcedure (AnalogRead p) = do
_ <- compileShallowPrimitiveError $ "analogRead " ++ show p
return 0
compileProcedure (AnalogReadE p) = do
b <- compile1ExprProcedure Word16Type "analogRead" p
return $ remBind b
compileProcedure (I2CRead p n) = do
_ <- compileShallowPrimitiveError $ "i2cRead " ++ show p ++ " " ++ show n
return []
compileProcedure (I2CReadE p n) = do
b <- compile2ExprListProcedure "i2cRead" p n
return $ remBind b
compileProcedure (SerialAvailable p) = do
_ <- compileShallowPrimitiveError $ "serialAvailable " ++ show p
return 0
compileProcedure (SerialAvailableE p) = do
b <- compile1ExprProcedure Word32Type "serialAvailable" p
return $ remBind b
compileProcedure (SerialRead p) = do
_ <- compileShallowPrimitiveError $ "serialRead " ++ show p
return 0
compileProcedure (SerialReadE p) = do
b <- compile1ExprProcedure Int32Type "serialRead" p
return $ remBind b
compileProcedure (SerialReadList p) = do
_ <- compileShallowPrimitiveError $ "serialReadList " ++ show p
return []
compileProcedure (SerialReadListE p) = do
b <- compile1ExprListProcedure "serialReadList" p
return $ remBind b
compileProcedure (Stepper2Pin s p1 p2) = do
_ <- compileShallowPrimitiveError $ "i2cRead " ++ show s ++ " " ++
show p1 ++ " " ++ show p2
return 0
compileProcedure (Stepper2PinE s p1 p2) = do
b <- compile3ExprProcedure Word8Type "stepper2Pin" s p1 p2
return $ remBind b
compileProcedure (Stepper4Pin s p1 p2 p3 p4) = do
_ <- compileShallowPrimitiveError $ "i2cRead " ++ show s ++ " " ++
show p1 ++ " " ++ show p2 ++
show p3 ++ " " ++ show p4
return 0
compileProcedure (Stepper4PinE s p1 p2 p3 p4) = do
b <- compile5ExprProcedure Word8Type "stepper4Pin" s p1 p2 p3 p4
return $ remBind b
compileProcedure (StepperStepE st s) = do
_ <- compile2ExprCommand "stepperStep" st s
return ()
compileProcedure (ServoAttach p) = do
_ <- compileShallowPrimitiveError $ "servoAttach " ++ show p
return 0
compileProcedure (ServoAttachE p) = do
b <- compile1ExprProcedure Word8Type "servoAttach" p
return $ remBind b
compileProcedure (ServoAttachMinMax p mi ma) = do
_ <- compileShallowPrimitiveError $ "servoAttachMinMax " ++
show p ++ " " ++ show mi ++ " " ++ show ma
return 0
compileProcedure (ServoAttachMinMaxE p mi ma) = do
b <- compile3ExprProcedure Word8Type "servoAttachMinMax" p mi ma
return $ remBind b
compileProcedure (ServoRead sv) = do
_ <- compileShallowPrimitiveError $ "servoRead " ++ show sv
return 0
compileProcedure (ServoReadE sv) = do
b <- compile1ExprProcedure Word16Type "servoRead" sv
return $ remBind b
compileProcedure (ServoReadMicros sv) = do
_ <- compileShallowPrimitiveError $ "servoReadMicros" ++ show sv
return 0
compileProcedure (ServoReadMicrosE sv) = do
b <- compile1ExprProcedure Word16Type "servoReadMicros" sv
return $ remBind b
compileProcedure QueryAllTasks = do
_ <- compileUnsupportedError "queryAllTasks"
return []
compileProcedure QueryAllTasksE = do
_ <- compileUnsupportedError "queryAllTasksE"
return (litStringE "")
compileProcedure (QueryTaskE _) = do
_ <- compileUnsupportedError "queryTaskE"
return Nothing
compileProcedure (QueryTask _) = do
_ <- compileUnsupportedError "queryTask"
return Nothing
compileProcedure (BootTaskE _) = do
_ <- compileUnsupportedError "bootTaskE"
return true
compileProcedure (Debug _) = do
return ()
compileProcedure (DebugE s) = do
_ <- compileLine ("debug((uint8_t *)" ++ compileExpr s ++ ");")
return ()
compileProcedure DebugListen = do
return ()
compileProcedure (Die _ _) = do
_ <- compileUnsupportedError "die"
return ()
compileProcedure (NewRemoteRefB e) = do
_ <- compileUnsupportedError "newRemoteRefB"
return $ RemoteRefB 0
compileProcedure (NewRemoteRefBE e) = do
x <- compileNewRef BoolType e
return $ RemoteRefB x
compileProcedure (NewRemoteRefW8 e) = do
_ <- compileUnsupportedError "newRemoteRefW8"
return $ RemoteRefW8 0
compileProcedure (NewRemoteRefW8E e) = do
x <- compileNewRef Word8Type e
return $ RemoteRefW8 x
compileProcedure (NewRemoteRefW16 e) = do
_ <- compileUnsupportedError "newRemoteRefW16"
return $ RemoteRefW16 0
compileProcedure (NewRemoteRefW16E e) = do
x <- compileNewRef Word16Type e
return $ RemoteRefW16 x
compileProcedure (NewRemoteRefW32 e) = do
_ <- compileUnsupportedError "newRemoteRefW32"
return $ RemoteRefW32 0
compileProcedure (NewRemoteRefW32E e) = do
x <- compileNewRef Word32Type e
return $ RemoteRefW32 x
compileProcedure (NewRemoteRefI8 e) = do
_ <- compileUnsupportedError "newRemoteRefI8"
return $ RemoteRefI8 0
compileProcedure (NewRemoteRefI8E e) = do
x <- compileNewRef Int8Type e
return $ RemoteRefI8 x
compileProcedure (NewRemoteRefI16 e) = do
_ <- compileUnsupportedError "newRemoteRefI16"
return $ RemoteRefI16 0
compileProcedure (NewRemoteRefI16E e) = do
x <- compileNewRef Int16Type e
return $ RemoteRefI16 x
compileProcedure (NewRemoteRefI32 e) = do
_ <- compileUnsupportedError "newRemoteRefI32"
return $ RemoteRefI32 0
compileProcedure (NewRemoteRefI32E e) = do
x <- compileNewRef Int32Type e
return $ RemoteRefI32 x
compileProcedure (NewRemoteRefI e) = do
_ <- compileUnsupportedError "newRemoteRefI"
return $ RemoteRefI 0
compileProcedure (NewRemoteRefIE e) = do
x <- compileNewRef IntType e
return $ RemoteRefI x
compileProcedure (NewRemoteRefL8 e) = do
_ <- compileUnsupportedError "newRemoteRefL8"
return $ RemoteRefL8 0
compileProcedure (NewRemoteRefL8E e) = do
x <- compileNewListRef e
return $ RemoteRefL8 x
compileProcedure (NewRemoteRefFloat e) = do
_ <- compileUnsupportedError "newRemoteRefFloat"
return $ RemoteRefFloat 0
compileProcedure (NewRemoteRefFloatE e) = do
x <- compileNewRef FloatType e
return $ RemoteRefFloat x
compileProcedure (ReadRemoteRefB _) = do
_ <- compileUnsupportedError "readRemoteRefB"
return False
compileProcedure (ReadRemoteRefBE (RemoteRefB i)) = do
b <- compileReadRef BoolType i
return $ remBind b
compileProcedure (ReadRemoteRefW8 _) = do
_ <- compileUnsupportedError "readRemoteRefW8"
return 0
compileProcedure (ReadRemoteRefW8E (RemoteRefW8 i)) = do
b <- compileReadRef Word8Type i
return $ remBind b
compileProcedure (ReadRemoteRefW16 _) = do
_ <- compileUnsupportedError "readRemoteRefW16"
return 0
compileProcedure (ReadRemoteRefW16E (RemoteRefW16 i)) = do
b <- compileReadRef Word16Type i
return $ remBind b
compileProcedure (ReadRemoteRefW32 _) = do
_ <- compileUnsupportedError "readRemoteRefW32"
return 0
compileProcedure (ReadRemoteRefW32E (RemoteRefW32 i)) = do
b <- compileReadRef Word32Type i
return $ remBind b
compileProcedure (ReadRemoteRefI8 _) = do
_ <- compileUnsupportedError "readRemoteRefI8"
return 0
compileProcedure (ReadRemoteRefI8E (RemoteRefI8 i)) = do
b <- compileReadRef Int8Type i
return $ remBind b
compileProcedure (ReadRemoteRefI16 _) = do
_ <- compileUnsupportedError "readRemoteRefI16"
return 0
compileProcedure (ReadRemoteRefI16E (RemoteRefI16 i)) = do
b <- compileReadRef Int16Type i
return $ remBind b
compileProcedure (ReadRemoteRefI32 _) = do
_ <- compileUnsupportedError "readRemoteRefI32"
return 0
compileProcedure (ReadRemoteRefI32E (RemoteRefI32 i)) = do
b <- compileReadRef Int32Type i
return $ remBind b
compileProcedure (ReadRemoteRefL8 _) = do
_ <- compileUnsupportedError "readRemoteRefL8"
return []
compileProcedure (ReadRemoteRefL8E (RemoteRefL8 i)) = do
b <- compileReadListRef i
return $ remBind b
compileProcedure (ReadRemoteRefFloat _) = do
_ <- compileUnsupportedError "readRemoteRefFloat"
return $ 0.0
compileProcedure (ReadRemoteRefFloatE (RemoteRefFloat i)) = do
b <- compileReadRef FloatType i
return $ remBind b
compileProcedure (IfThenElseUnitE e cb1 cb2) =
compileIfThenElseProcedure UnitType e cb1 cb2
compileProcedure (IfThenElseBoolE e cb1 cb2) =
compileIfThenElseProcedure BoolType e cb1 cb2
compileProcedure (IfThenElseWord8E e cb1 cb2) =
compileIfThenElseProcedure Word8Type e cb1 cb2
compileProcedure (IfThenElseWord16E e cb1 cb2) =
compileIfThenElseProcedure Word16Type e cb1 cb2
compileProcedure (IfThenElseWord32E e cb1 cb2) =
compileIfThenElseProcedure Word32Type e cb1 cb2
compileProcedure (IfThenElseInt8E e cb1 cb2) =
compileIfThenElseProcedure Int8Type e cb1 cb2
compileProcedure (IfThenElseInt16E e cb1 cb2) =
compileIfThenElseProcedure Int16Type e cb1 cb2
compileProcedure (IfThenElseInt32E e cb1 cb2) =
compileIfThenElseProcedure Int32Type e cb1 cb2
compileProcedure (IfThenElseIntE e cb1 cb2) =
compileIfThenElseProcedure IntType e cb1 cb2
compileProcedure (IfThenElseL8E e cb1 cb2) =
compileIfThenElseProcedure List8Type e cb1 cb2
compileProcedure (IfThenElseFloatE e cb1 cb2) =
compileIfThenElseProcedure FloatType e cb1 cb2
-- The following IfThenElse* functions generated by toold/GenEitherTypes.hs
compileProcedure (IfThenElseUnitUnit e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType UnitType e cb1 cb2
compileProcedure (IfThenElseUnitBool e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType BoolType e cb1 cb2
compileProcedure (IfThenElseUnitW8 e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType Word8Type e cb1 cb2
compileProcedure (IfThenElseUnitW16 e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType Word16Type e cb1 cb2
compileProcedure (IfThenElseUnitW32 e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType Word32Type e cb1 cb2
compileProcedure (IfThenElseUnitI8 e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType Int8Type e cb1 cb2
compileProcedure (IfThenElseUnitI16 e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType Int16Type e cb1 cb2
compileProcedure (IfThenElseUnitI32 e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType Int32Type e cb1 cb2
compileProcedure (IfThenElseUnitI e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType IntType e cb1 cb2
compileProcedure (IfThenElseUnitL8 e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType List8Type e cb1 cb2
compileProcedure (IfThenElseUnitFloat e cb1 cb2) =
compileIfThenElseEitherProcedure UnitType FloatType e cb1 cb2
compileProcedure (IfThenElseBoolUnit e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType UnitType e cb1 cb2
compileProcedure (IfThenElseBoolBool e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType BoolType e cb1 cb2
compileProcedure (IfThenElseBoolW8 e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType Word8Type e cb1 cb2
compileProcedure (IfThenElseBoolW16 e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType Word16Type e cb1 cb2
compileProcedure (IfThenElseBoolW32 e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType Word32Type e cb1 cb2
compileProcedure (IfThenElseBoolI8 e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType Int8Type e cb1 cb2
compileProcedure (IfThenElseBoolI16 e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType Int16Type e cb1 cb2
compileProcedure (IfThenElseBoolI32 e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType Int32Type e cb1 cb2
compileProcedure (IfThenElseBoolI e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType IntType e cb1 cb2
compileProcedure (IfThenElseBoolL8 e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType List8Type e cb1 cb2
compileProcedure (IfThenElseBoolFloat e cb1 cb2) =
compileIfThenElseEitherProcedure BoolType FloatType e cb1 cb2
compileProcedure (IfThenElseW8Unit e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type UnitType e cb1 cb2
compileProcedure (IfThenElseW8Bool e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type BoolType e cb1 cb2
compileProcedure (IfThenElseW8W8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type Word8Type e cb1 cb2
compileProcedure (IfThenElseW8W16 e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type Word16Type e cb1 cb2
compileProcedure (IfThenElseW8W32 e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type Word32Type e cb1 cb2
compileProcedure (IfThenElseW8I8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type Int8Type e cb1 cb2
compileProcedure (IfThenElseW8I16 e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type Int16Type e cb1 cb2
compileProcedure (IfThenElseW8I32 e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type Int32Type e cb1 cb2
compileProcedure (IfThenElseW8I e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type IntType e cb1 cb2
compileProcedure (IfThenElseW8L8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type List8Type e cb1 cb2
compileProcedure (IfThenElseW8Float e cb1 cb2) =
compileIfThenElseEitherProcedure Word8Type FloatType e cb1 cb2
compileProcedure (IfThenElseW16Unit e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type UnitType e cb1 cb2
compileProcedure (IfThenElseW16Bool e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type BoolType e cb1 cb2
compileProcedure (IfThenElseW16W8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type Word8Type e cb1 cb2
compileProcedure (IfThenElseW16W16 e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type Word16Type e cb1 cb2
compileProcedure (IfThenElseW16W32 e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type Word32Type e cb1 cb2
compileProcedure (IfThenElseW16I8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type Int8Type e cb1 cb2
compileProcedure (IfThenElseW16I16 e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type Int16Type e cb1 cb2
compileProcedure (IfThenElseW16I32 e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type Int32Type e cb1 cb2
compileProcedure (IfThenElseW16I e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type IntType e cb1 cb2
compileProcedure (IfThenElseW16L8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type List8Type e cb1 cb2
compileProcedure (IfThenElseW16Float e cb1 cb2) =
compileIfThenElseEitherProcedure Word16Type FloatType e cb1 cb2
compileProcedure (IfThenElseW32Unit e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type UnitType e cb1 cb2
compileProcedure (IfThenElseW32Bool e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type BoolType e cb1 cb2
compileProcedure (IfThenElseW32W8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type Word8Type e cb1 cb2
compileProcedure (IfThenElseW32W16 e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type Word16Type e cb1 cb2
compileProcedure (IfThenElseW32W32 e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type Word32Type e cb1 cb2
compileProcedure (IfThenElseW32I8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type Int8Type e cb1 cb2
compileProcedure (IfThenElseW32I16 e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type Int16Type e cb1 cb2
compileProcedure (IfThenElseW32I32 e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type Int32Type e cb1 cb2
compileProcedure (IfThenElseW32I e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type IntType e cb1 cb2
compileProcedure (IfThenElseW32L8 e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type List8Type e cb1 cb2
compileProcedure (IfThenElseW32Float e cb1 cb2) =
compileIfThenElseEitherProcedure Word32Type FloatType e cb1 cb2
compileProcedure (IfThenElseI8Unit e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type UnitType e cb1 cb2
compileProcedure (IfThenElseI8Bool e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type BoolType e cb1 cb2
compileProcedure (IfThenElseI8W8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type Word8Type e cb1 cb2
compileProcedure (IfThenElseI8W16 e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type Word16Type e cb1 cb2
compileProcedure (IfThenElseI8W32 e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type Word32Type e cb1 cb2
compileProcedure (IfThenElseI8I8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type Int8Type e cb1 cb2
compileProcedure (IfThenElseI8I16 e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type Int16Type e cb1 cb2
compileProcedure (IfThenElseI8I32 e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type Int32Type e cb1 cb2
compileProcedure (IfThenElseI8I e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type IntType e cb1 cb2
compileProcedure (IfThenElseI8L8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type List8Type e cb1 cb2
compileProcedure (IfThenElseI8Float e cb1 cb2) =
compileIfThenElseEitherProcedure Int8Type FloatType e cb1 cb2
compileProcedure (IfThenElseI16Unit e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type UnitType e cb1 cb2
compileProcedure (IfThenElseI16Bool e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type BoolType e cb1 cb2
compileProcedure (IfThenElseI16W8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type Word8Type e cb1 cb2
compileProcedure (IfThenElseI16W16 e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type Word16Type e cb1 cb2
compileProcedure (IfThenElseI16W32 e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type Word32Type e cb1 cb2
compileProcedure (IfThenElseI16I8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type Int8Type e cb1 cb2
compileProcedure (IfThenElseI16I16 e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type Int16Type e cb1 cb2
compileProcedure (IfThenElseI16I32 e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type Int32Type e cb1 cb2
compileProcedure (IfThenElseI16I e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type IntType e cb1 cb2
compileProcedure (IfThenElseI16L8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type List8Type e cb1 cb2
compileProcedure (IfThenElseI16Float e cb1 cb2) =
compileIfThenElseEitherProcedure Int16Type FloatType e cb1 cb2
compileProcedure (IfThenElseI32Unit e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type UnitType e cb1 cb2
compileProcedure (IfThenElseI32Bool e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type BoolType e cb1 cb2
compileProcedure (IfThenElseI32W8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type Word8Type e cb1 cb2
compileProcedure (IfThenElseI32W16 e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type Word16Type e cb1 cb2
compileProcedure (IfThenElseI32W32 e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type Word32Type e cb1 cb2
compileProcedure (IfThenElseI32I8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type Int8Type e cb1 cb2
compileProcedure (IfThenElseI32I16 e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type Int16Type e cb1 cb2
compileProcedure (IfThenElseI32I32 e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type Int32Type e cb1 cb2
compileProcedure (IfThenElseI32I e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type IntType e cb1 cb2
compileProcedure (IfThenElseI32L8 e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type List8Type e cb1 cb2
compileProcedure (IfThenElseI32Float e cb1 cb2) =
compileIfThenElseEitherProcedure Int32Type FloatType e cb1 cb2
compileProcedure (IfThenElseIUnit e cb1 cb2) =
compileIfThenElseEitherProcedure IntType UnitType e cb1 cb2
compileProcedure (IfThenElseIBool e cb1 cb2) =
compileIfThenElseEitherProcedure IntType BoolType e cb1 cb2
compileProcedure (IfThenElseIW8 e cb1 cb2) =
compileIfThenElseEitherProcedure IntType Word8Type e cb1 cb2
compileProcedure (IfThenElseIW16 e cb1 cb2) =
compileIfThenElseEitherProcedure IntType Word16Type e cb1 cb2
compileProcedure (IfThenElseIW32 e cb1 cb2) =
compileIfThenElseEitherProcedure IntType Word32Type e cb1 cb2
compileProcedure (IfThenElseII8 e cb1 cb2) =
compileIfThenElseEitherProcedure IntType Int8Type e cb1 cb2
compileProcedure (IfThenElseII16 e cb1 cb2) =
compileIfThenElseEitherProcedure IntType Int16Type e cb1 cb2
compileProcedure (IfThenElseII32 e cb1 cb2) =
compileIfThenElseEitherProcedure IntType Int32Type e cb1 cb2
compileProcedure (IfThenElseII e cb1 cb2) =
compileIfThenElseEitherProcedure IntType IntType e cb1 cb2
compileProcedure (IfThenElseIL8 e cb1 cb2) =
compileIfThenElseEitherProcedure IntType List8Type e cb1 cb2
compileProcedure (IfThenElseIFloat e cb1 cb2) =
compileIfThenElseEitherProcedure IntType FloatType e cb1 cb2
compileProcedure (IfThenElseL8Unit e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type UnitType e cb1 cb2
compileProcedure (IfThenElseL8Bool e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type BoolType e cb1 cb2
compileProcedure (IfThenElseL8W8 e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type Word8Type e cb1 cb2
compileProcedure (IfThenElseL8W16 e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type Word16Type e cb1 cb2
compileProcedure (IfThenElseL8W32 e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type Word32Type e cb1 cb2
compileProcedure (IfThenElseL8I8 e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type Int8Type e cb1 cb2
compileProcedure (IfThenElseL8I16 e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type Int16Type e cb1 cb2
compileProcedure (IfThenElseL8I32 e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type Int32Type e cb1 cb2
compileProcedure (IfThenElseL8I e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type IntType e cb1 cb2
compileProcedure (IfThenElseL8L8 e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type List8Type e cb1 cb2
compileProcedure (IfThenElseL8Float e cb1 cb2) =
compileIfThenElseEitherProcedure List8Type FloatType e cb1 cb2
compileProcedure (IfThenElseFloatUnit e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType UnitType e cb1 cb2
compileProcedure (IfThenElseFloatBool e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType BoolType e cb1 cb2
compileProcedure (IfThenElseFloatW8 e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType Word8Type e cb1 cb2
compileProcedure (IfThenElseFloatW16 e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType Word16Type e cb1 cb2
compileProcedure (IfThenElseFloatW32 e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType Word32Type e cb1 cb2
compileProcedure (IfThenElseFloatI8 e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType Int8Type e cb1 cb2
compileProcedure (IfThenElseFloatI16 e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType Int16Type e cb1 cb2
compileProcedure (IfThenElseFloatI32 e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType Int32Type e cb1 cb2
compileProcedure (IfThenElseFloatI e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType IntType e cb1 cb2
compileProcedure (IfThenElseFloatL8 e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType List8Type e cb1 cb2
compileProcedure (IfThenElseFloatFloat e cb1 cb2) =
compileIfThenElseEitherProcedure FloatType FloatType e cb1 cb2
-- The following Iterate*E functions generated by toold/GenEitherTypes.hs
compileProcedure (IterateUnitUnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure UnitType UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitBoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure UnitType BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitW8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure UnitType Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitW16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure UnitType Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitW32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure UnitType Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitI8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure UnitType Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitI16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure UnitType Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitI32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure UnitType Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitIE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure UnitType IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitL8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure UnitType List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateUnitFloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindUnit i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure UnitType FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolUnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure BoolType UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolBoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure BoolType BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolW8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure BoolType Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolW16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure BoolType Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolW32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure BoolType Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolI8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure BoolType Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolI16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure BoolType Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolI32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure BoolType Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolIE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure BoolType IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolL8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure BoolType List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateBoolFloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindB i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure BoolType FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8UnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure Word8Type UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8BoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure Word8Type BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8W8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure Word8Type Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8W16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure Word8Type Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8W32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure Word8Type Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8I8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure Word8Type Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8I16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure Word8Type Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8I32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure Word8Type Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8IE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure Word8Type IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8L8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure Word8Type List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW8FloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW8 i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure Word8Type FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16UnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure Word16Type UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16BoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure Word16Type BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16W8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure Word16Type Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16W16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure Word16Type Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16W32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure Word16Type Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16I8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure Word16Type Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16I16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure Word16Type Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16I32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure Word16Type Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16IE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure Word16Type IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16L8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure Word16Type List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW16FloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW16 i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure Word16Type FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32UnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure Word32Type UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32BoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure Word32Type BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32W8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure Word32Type Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32W16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure Word32Type Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32W32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure Word32Type Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32I8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure Word32Type Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32I16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure Word32Type Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32I32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure Word32Type Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32IE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure Word32Type IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32L8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure Word32Type List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateW32FloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindW32 i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure Word32Type FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8UnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure Int8Type UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8BoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure Int8Type BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8W8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure Int8Type Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8W16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure Int8Type Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8W32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure Int8Type Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8I8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure Int8Type Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8I16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure Int8Type Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8I32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure Int8Type Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8IE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure Int8Type IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8L8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure Int8Type List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI8FloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI8 i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure Int8Type FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16UnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure Int16Type UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16BoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure Int16Type BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16W8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure Int16Type Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16W16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure Int16Type Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16W32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure Int16Type Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16I8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure Int16Type Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16I16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure Int16Type Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16I32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure Int16Type Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16IE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure Int16Type IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16L8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure Int16Type List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI16FloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI16 i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure Int16Type FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32UnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure Int32Type UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32BoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure Int32Type BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32W8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure Int32Type Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32W16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure Int32Type Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32W32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure Int32Type Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32I8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure Int32Type Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32I16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure Int32Type Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32I32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure Int32Type Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32IE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure Int32Type IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32L8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure Int32Type List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateI32FloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI32 i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure Int32Type FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIUnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure IntType UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIBoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure IntType BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIW8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure IntType Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIW16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure IntType Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIW32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure IntType Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateII8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure IntType Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateII16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure IntType Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateII32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure IntType Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIIE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure IntType IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIL8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure IntType List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateIFloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindI i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure IntType FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8UnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure List8Type UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8BoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure List8Type BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8W8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure List8Type Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8W16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure List8Type Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8W32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure List8Type Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8I8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure List8Type Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8I16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure List8Type Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8I32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure List8Type Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8IE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure List8Type IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8L8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure List8Type List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateL8FloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindList8 i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure List8Type FloatType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatUnitE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindUnit j
_ <- compileIterateProcedure FloatType UnitType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatBoolE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindB j
_ <- compileIterateProcedure FloatType BoolType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatW8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindW8 j
_ <- compileIterateProcedure FloatType Word8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatW16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindW16 j
_ <- compileIterateProcedure FloatType Word16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatW32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindW32 j
_ <- compileIterateProcedure FloatType Word32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatI8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindI8 j
_ <- compileIterateProcedure FloatType Int8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatI16E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindI16 j
_ <- compileIterateProcedure FloatType Int16Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatI32E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindI32 j
_ <- compileIterateProcedure FloatType Int32Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatIE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindI j
_ <- compileIterateProcedure FloatType IntType b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatL8E br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindList8 j
_ <- compileIterateProcedure FloatType List8Type b bb br i bi j bj iv bf
return bj
compileProcedure (IterateFloatFloatE br iv bf) = do
b <- nextBind
let bb = RemBindI b
i <- nextBind
let bi = RemBindFloat i
j <- nextBind
let bj = RemBindFloat j
_ <- compileIterateProcedure FloatType FloatType b bb br i bi j bj iv bf
return bj
compileProcedure _ = error "compileProcedure - Unknown procedure, it may actually be a command"
compileIfThenElseProcedure :: ExprB a => CompileType -> Expr Bool -> Arduino (Expr a) -> Arduino (Expr a) -> State CompileState (Expr a)
compileIfThenElseProcedure t e cb1 cb2 = do
s <- get
let b = ib s
put s {ib = b + 1}
_ <- if t == UnitType
then return LitUnit
else if t == List8Type
then do
_ <- compileAllocBind $ compileTypeToString t ++ " " ++ bindName ++ show b ++ " = NULL;"
compileRelease $ "listRelease(&" ++ bindName ++ show b ++ ");"
else compileAllocBind $ compileTypeToString t ++ " " ++ bindName ++ show b ++ ";"
_ <- compileLine $ "if (" ++ compileExpr e ++ ")"
r1 <- compileCodeBlock True "" cb1
_ <- if t == UnitType
then return LitUnit
else if t == List8Type
then compileLineIndent $ "listAssign(&" ++ bindName ++ show b ++ ", " ++ compileExpr r1 ++ ");"
else compileLineIndent $ bindName ++ show b ++ " = " ++ compileExpr r1 ++ ";"
_ <- compileInReleases
_ <- compileLineIndent "}"
_ <- compileLine "else"
r2 <- compileCodeBlock True "" cb2
_ <- if t == UnitType
then return LitUnit
else if t == List8Type
then compileLineIndent $ "listAssign(&" ++ bindName ++ show b ++ ", " ++ compileExpr r2 ++ ");"
else compileLineIndent $ bindName ++ show b ++ " = " ++ compileExpr r2 ++ ";"
_ <- compileInReleases
_ <- compileLineIndent "}"
return $ remBind b
compileIfThenElseEitherProcedure :: (ExprB a, ExprB b) => CompileType -> CompileType -> Expr Bool -> Arduino (ExprEither a b) -> Arduino (ExprEither a b) -> State CompileState (ExprEither a b)
compileIfThenElseEitherProcedure t1 t2 e cb1 cb2 = do
s <- get
put s {ifEitherComp = 1 + ifEitherComp s}
let (ib1, ib2, ib3) = head $ iterBinds s
_ <- compileLine $ "if (" ++ compileExpr e ++ ")"
s' <- get
r1 <- compileCodeBlock True "" cb1
s'' <- get
_ <- if ifEitherComp s'' == ifEitherComp s'
then do
case r1 of
ExprLeft i a -> do
_ <- compileLineIndent $ bindName ++ show ib1 ++ " = " ++ compileExpr i ++ ";"
_ <- if t1 == UnitType then return LitUnit
else if t1 == List8Type then compileLineIndent $ "listAssign(&" ++ bindName ++ show ib2 ++ ", " ++ compileExpr a ++ ");"
else compileLineIndent $ bindName ++ show ib2 ++ " = " ++ compileExpr a ++ ";"
_ <- compileInReleases
return LitUnit
ExprRight b -> do
_ <- if t2 == UnitType then return LitUnit
else if t2 == List8Type then compileLineIndent $ "listAssign(&" ++ bindName ++ show ib3 ++ ", " ++ compileExpr b ++ ");"
else compileLineIndent $ bindName ++ show ib3 ++ " = " ++ compileExpr b ++ ";"
_ <- compileInReleases
compileLineIndent "break;"
else return LitUnit
_ <- compileLineIndent "}"
_ <- compileLine "else"
s''' <- get
r2 <- compileCodeBlock True "" cb2
s'''' <- get
-- Check if there is another ifThenElseEither block inside of this one.
-- If so, the else effects should only be compiled in the innermost ifThenElseEither
_ <- if ifEitherComp s'''' == ifEitherComp s'''
then do
case r2 of
ExprLeft i a -> do
_ <- compileLineIndent $ bindName ++ show ib1 ++ " = " ++ compileExpr i ++ ";"
_ <- if (t1 == UnitType) then return LitUnit
else if t1 == List8Type then compileLineIndent $ "listAssign(&" ++ bindName ++ show ib2 ++ ", " ++ compileExpr a ++ ");"
else compileLineIndent $ bindName ++ show ib2 ++ " = " ++ compileExpr a ++ ";"
compileInReleases
-- return LitUnit
ExprRight b -> do
_ <- if (t2 == UnitType) then return LitUnit
else if t2 == List8Type then compileLineIndent $ "listAssign(&" ++ bindName ++ show ib3 ++ ", " ++ compileExpr b ++ ");"
else compileLineIndent $ bindName ++ show ib3 ++ " = " ++ compileExpr b ++ ";"
_ <- compileInReleases
compileLineIndent "break;"
else return LitUnit
_ <- compileLineIndent "}"
return $ r2
compileIterateProcedure :: (ExprB a, ExprB b) => CompileType -> CompileType -> Int -> Expr Int -> Expr Int ->
Int -> Expr a -> Int -> Expr b -> Expr a ->
(Expr Int -> Expr a -> Arduino(ExprEither a b)) -> State CompileState (Expr b)
compileIterateProcedure ta tb b bb be b1 b1e b2 b2e iv bf = do
s <- get
put s {iterBinds = (b, b1, b2):iterBinds s}
_ <- compileAllocBind $ compileTypeToString IntType ++ " " ++ bindName ++ show b ++ ";"
_ <- if ta == UnitType
then return LitUnit
else if ta == List8Type
then do
_ <- compileAllocBind $ compileTypeToString ta ++ " " ++ bindName ++ show b1 ++ " = NULL;"
compileRelease $ "listRelease(&" ++ bindName ++ show b1 ++ ");"
else compileAllocBind $ compileTypeToString ta ++ " " ++ bindName ++ show b1 ++ ";"
_ <- if tb == UnitType
then return LitUnit
else if tb == List8Type
then do
_ <- compileAllocBind $ compileTypeToString tb ++ " " ++ bindName ++ show b2 ++ " = NULL;"
compileRelease $ "listRelease(&" ++ bindName ++ show b2 ++ ");"
else compileAllocBind $ compileTypeToString tb ++ " " ++ bindName ++ show b2 ++ ";"
_ <- if ta == List8Type
then compileLine $ "listAssign(&" ++ bindName ++ show b1 ++ ", " ++ compileExpr iv ++ ");"
else if ta == UnitType
then return LitUnit
else compileLine $ bindName ++ show b1 ++ " = " ++ compileExpr iv ++ ";"
_ <- compileLine $ bindName ++ show b ++ " = " ++ compileExpr be ++ ";"
_ <- compileCodeBlock False "while (1)\n" $ bf bb b1e
_ <- compileLineIndent "}"
s' <- get
put s' {iterBinds = tail $ iterBinds s'}
return b2e
compileInReleases :: State CompileState (Expr ())
compileInReleases = do
s <- get
put s {releaseList = tail $ releaseList s,
releases = head $ releaseList s,
cmds = (cmds s) ++ (releases s)}
return LitUnit
compileCodeBlock :: Bool -> String -> Arduino a -> State CompileState a
compileCodeBlock bInside prelude (Arduino commands) = do
s <- get
put s {bindList = (binds s) : (bindList s),
releaseList = (releases s) : (releaseList s),
cmdList = (cmds s) : (cmdList s),
binds = "",
releases = "",
bindsInside = bInside : (bindsInside s),
cmds = "",
level = level s + 1 }
r <- compileMonad commands
s' <- get
if bInside then
put s' {bindList = tail $ bindList s',
cmdList = tail $ cmdList s',
binds = head $ bindList s',
bindsInside = tail (bindsInside s'),
cmds = (head $ cmdList s') ++ (indent $ level s') ++ "{\n" ++
body (binds s') (cmds s'),
level = level s' - 1 }
else
put s' {bindList = tail $ bindList s',
releaseList = tail $ releaseList s',
cmdList = tail $ cmdList s',
binds = head $ bindList s',
releases = head $ releaseList s',
bindsInside = tail (bindsInside s'),
cmds = (head $ cmdList s') ++
binds s' ++
(indent $ (level s') - 1) ++ prelude ++
(indent $ level s') ++ "{\n" ++ (cmds s') ++ (releases s'),
level = level s' - 1 }
return r
where
body :: String -> String -> String
body [] cs = cs
body bs cs = bs ++ "\n" ++ cs
compileMonad :: RemoteMonad ArduinoPrimitive a ->
State CompileState a
compileMonad (T.Appl app) = compileAppl app
compileMonad (T.Bind m k) = do
r <- compileMonad m
compileMonad (k r)
compileMonad (T.Ap' m1 m2) = do
f <- compileMonad m1
g <- compileMonad m2
return (f g)
compileMonad (T.Alt' _ _) = error "compileMonad: \"Alt\" not supported"
compileMonad T.Empty' = error "compileMonad: \"Empty\" not supported"
compileMonad (T.Throw _) = error "compileMonad: \"Throw\" not supported"
compileMonad (T.Catch _ _) = error "compileMonad: \"Catch\" not supported"
compileAppl :: RemoteApplicative ArduinoPrimitive a ->
State CompileState a
compileAppl (T.Primitive p) = compilePrimitive p
compileAppl (T.Ap a1 a2) = do
f <- compileAppl a1
g <- compileAppl a2
return (f g)
compileAppl (T.Pure a) = return a
compileAppl (T.Alt _ _) = error "compileAppl: \"Alt\" not supported"
compileAppl T.Empty = error "compileAppl: \"Empty\" not supported"
compileSubExpr :: String -> Expr a -> String
compileSubExpr ec e = ec ++ "(" ++ compileExpr e ++ ")"
compileTwoSubExpr :: String -> Expr a -> Expr b -> String
compileTwoSubExpr ec e1 e2 = ec ++ "(" ++ compileExpr e1 ++
"," ++ compileExpr e2 ++ ")"
compileThreeSubExpr :: String -> Expr a -> Expr b -> Expr c -> String
compileThreeSubExpr ec e1 e2 e3 = ec ++ "(" ++ compileExpr e1 ++
"," ++ compileExpr e2 ++
"," ++ compileExpr e3 ++ ")"
compileInfixSubExpr :: String -> Expr a -> Expr b -> String
compileInfixSubExpr ec e1 e2 = "(" ++ compileExpr e1 ++ " " ++ ec ++
" " ++ compileExpr e2 ++ ")"
compileExprWithCast :: CompileType -> Expr a -> String
compileExprWithCast t e =
case e of
LitW8 _ -> compileExpr e
LitW16 _ -> compileExpr e
LitI8 _ -> compileExpr e
LitI16 _ -> compileExpr e
FromIntW8 _ -> compileExpr e
FromIntW16 _ -> compileExpr e
FromIntI8 _ -> compileExpr e
FromIntI16 _ -> compileExpr e
RemBindW8 _ -> compileExpr e
RemBindW16 _ -> compileExpr e
RemBindI8 _ -> compileExpr e
RemBindI16 _ -> compileExpr e
_ -> "((" ++ compileTypeToString t ++ ") " ++ compileExpr e ++ ")"
compileInfixSubExprWithCast :: String -> CompileType -> Expr a -> Expr b -> String
compileInfixSubExprWithCast ec et e1 e2 = "(" ++ compileExprWithCast et e1 ++ " " ++ ec ++
" " ++ compileExprWithCast et e2 ++ ")"
compileSign :: Expr a -> String
compileSign e = "(" ++ compileExpr e ++ " == 0 ? 0 : 1)"
compileIfSubExpr :: Expr a -> Expr b -> Expr b -> String
compileIfSubExpr e1 e2 e3 = compileExpr e1 ++ " ? " ++
compileExpr e2 ++ " : " ++ compileExpr e3
compileNeg :: Expr a -> String
compileNeg = compileSubExpr "-"
compileComp :: Expr a -> String
compileComp = compileSubExpr "~"
compileBind :: Int -> String
compileBind b = bindName ++ show b
compileBAnd :: Expr a -> Expr a -> String
compileBAnd = compileInfixSubExpr "&&"
compileBOr :: Expr a -> Expr a -> String
compileBOr = compileInfixSubExpr "||"
compileEqual :: Expr a -> Expr a -> String
compileEqual = compileInfixSubExpr "=="
compileLess :: Expr a -> Expr a -> String
compileLess = compileInfixSubExpr "<"
compileEqualWithCast :: CompileType -> Expr a -> Expr a -> String
compileEqualWithCast = compileInfixSubExprWithCast "=="
compileLessWithCast :: CompileType -> Expr a -> Expr a -> String
compileLessWithCast = compileInfixSubExprWithCast "<"
compileAdd :: Expr a -> Expr a -> String
compileAdd = compileInfixSubExpr "+"
compileSub :: Expr a -> Expr a -> String
compileSub = compileInfixSubExpr "-"
compileMult :: Expr a -> Expr a -> String
compileMult = compileInfixSubExpr "*"
compileDiv :: Expr a -> Expr a -> String
compileDiv = compileInfixSubExpr "/"
compileMod :: Expr a -> Expr a -> String
compileMod = compileInfixSubExpr "%"
compileAnd :: Expr a -> Expr a -> String
compileAnd = compileInfixSubExpr "&"
compileOr :: Expr a -> Expr a -> String
compileOr = compileInfixSubExpr "|"
compileXor :: Expr a -> Expr a -> String
compileXor = compileInfixSubExpr "^"
compileShiftLeft :: Expr a -> Expr b -> String
compileShiftLeft = compileInfixSubExpr "<<"
compileShiftRight :: Expr a -> Expr b -> String
compileShiftRight = compileInfixSubExpr ">>"
compileToInt :: Expr a -> String
compileToInt e = "((int32_t) " ++ compileExpr e ++ ")"
compileFromInt :: String -> Expr a -> String
compileFromInt t e = "((" ++ t ++ ") " ++ compileExpr e ++ ")"
compileRef :: Int -> String
compileRef n = refName ++ show n
compileExpr :: Expr a -> String
compileExpr LitUnit = "0"
compileExpr (ShowUnit _) = show ()
compileExpr (RemBindUnit b) = bindName ++ show b
compileExpr (LitPinMode m) = case m of
INPUT -> "INPUT"
OUTPUT -> "OUTPUT"
INPUT_PULLUP -> "INPUT_PULLUP"
compileExpr (ShowPinMode e) = compileSubExpr "showPinMode" e
compileExpr (RemBindPinMode b) = bindName ++ show b
compileExpr (EqPinMode e1 e2) = compileEqual e1 e2
compileExpr (IfPinMode e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (LitB b) = if b then "1" else "0"
compileExpr (ShowB e) = compileSubExpr "showBool" e
compileExpr (RefB n) = compileRef n
compileExpr (RemBindB b) = bindName ++ show b
compileExpr (NotB e) = compileSubExpr "!" e
compileExpr (AndB e1 e2) = compileBAnd e1 e2
compileExpr (OrB e1 e2) = compileBOr e1 e2
compileExpr (EqB e1 e2) = compileEqual e1 e2
compileExpr (LessB e1 e2) = compileLess e1 e2
compileExpr (IfB e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (EqW8 e1 e2) = compileEqualWithCast Word8Type e1 e2
compileExpr (LessW8 e1 e2) = compileLessWithCast Word8Type e1 e2
compileExpr (EqW16 e1 e2) = compileEqualWithCast Word16Type e1 e2
compileExpr (LessW16 e1 e2) = compileLessWithCast Word16Type e1 e2
compileExpr (EqW32 e1 e2) = compileEqual e1 e2
compileExpr (LessW32 e1 e2) = compileLess e1 e2
compileExpr (EqI8 e1 e2) = compileEqualWithCast Int8Type e1 e2
compileExpr (LessI8 e1 e2) = compileLessWithCast Int8Type e1 e2
compileExpr (EqI16 e1 e2) = compileEqualWithCast Int16Type e1 e2
compileExpr (LessI16 e1 e2) = compileLessWithCast Int16Type e1 e2
compileExpr (EqI32 e1 e2) = compileEqual e1 e2
compileExpr (LessI32 e1 e2) = compileLess e1 e2
compileExpr (EqI e1 e2) = compileEqual e1 e2
compileExpr (LessI e1 e2) = compileLess e1 e2
compileExpr (EqL8 e1 e2) = compileTwoSubExpr "list8Equal" e1 e2
compileExpr (LessL8 e1 e2) = compileTwoSubExpr "list8Less" e1 e2
compileExpr (EqFloat e1 e2) = compileEqual e1 e2
compileExpr (LessFloat e1 e2) = compileLess e1 e2
compileExpr (LitW8 w) = show w
compileExpr (ShowW8 e) = compileSubExpr "showWord8" e
compileExpr (RefW8 n) = compileRef n
compileExpr (RemBindW8 b) = compileBind b
compileExpr (FromIntW8 e) = compileFromInt "uint8_t" e
compileExpr (ToIntW8 e) = compileToInt e
compileExpr (NegW8 e) = compileNeg e -- ToDo: Check arduino compiler
compileExpr (SignW8 e) = compileSign e
compileExpr (AddW8 e1 e2) = compileAdd e1 e2
compileExpr (SubW8 e1 e2) = compileSub e1 e2
compileExpr (MultW8 e1 e2) = compileMult e1 e2
compileExpr (DivW8 e1 e2) = compileDiv e1 e2
compileExpr (RemW8 e1 e2) = compileMod e1 e2
compileExpr (QuotW8 e1 e2) = compileDiv e1 e2
compileExpr (ModW8 e1 e2) = compileMod e1 e2
compileExpr (AndW8 e1 e2) = compileAnd e1 e2
compileExpr (OrW8 e1 e2) = compileOr e1 e2
compileExpr (XorW8 e1 e2) = compileXor e1 e2
compileExpr (CompW8 e) = compileComp e
compileExpr (ShfLW8 e1 e2) = compileShiftLeft e1 e2
compileExpr (ShfRW8 e1 e2) = compileShiftRight e1 e2
compileExpr (IfW8 e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TestBW8 e1 e2) = compileTwoSubExpr "testBW8" e1 e2
compileExpr (SetBW8 e1 e2) = compileTwoSubExpr "setBW8" e1 e2
compileExpr (ClrBW8 e1 e2) = compileTwoSubExpr "clrBW8" e1 e2
compileExpr (LitW16 w) = show w
compileExpr (ShowW16 e) = compileSubExpr "showWord16" e
compileExpr (RefW16 n) = compileRef n
compileExpr (RemBindW16 b) = compileBind b
compileExpr (FromIntW16 e) = compileFromInt "uint16_t" e
compileExpr (ToIntW16 e) = compileToInt e
compileExpr (NegW16 e) = compileNeg e
compileExpr (SignW16 e) = compileSign e
compileExpr (AddW16 e1 e2) = compileAdd e1 e2
compileExpr (SubW16 e1 e2) = compileSub e1 e2
compileExpr (MultW16 e1 e2) = compileMult e1 e2
compileExpr (DivW16 e1 e2) = compileDiv e1 e2
compileExpr (RemW16 e1 e2) = compileMod e1 e2
compileExpr (QuotW16 e1 e2) = compileDiv e1 e2
compileExpr (ModW16 e1 e2) = compileMod e1 e2
compileExpr (AndW16 e1 e2) = compileAnd e1 e2
compileExpr (OrW16 e1 e2) = compileOr e1 e2
compileExpr (XorW16 e1 e2) = compileXor e1 e2
compileExpr (CompW16 e) = compileComp e
compileExpr (ShfLW16 e1 e2) = compileShiftLeft e1 e2
compileExpr (ShfRW16 e1 e2) = compileShiftRight e1 e2
compileExpr (IfW16 e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TestBW16 e1 e2) = compileTwoSubExpr "testBW16" e1 e2
compileExpr (SetBW16 e1 e2) = compileTwoSubExpr "setBW16" e1 e2
compileExpr (ClrBW16 e1 e2) = compileTwoSubExpr "clrBW16" e1 e2
compileExpr (LitW32 w) = show w
compileExpr (ShowW32 e) = compileSubExpr "showWord32" e
compileExpr (RefW32 n) = compileRef n
compileExpr (RemBindW32 b) = compileBind b
compileExpr (FromIntW32 e) = compileFromInt "uint32_t" e
compileExpr (ToIntW32 e) = compileToInt e
compileExpr (NegW32 e) = compileNeg e
compileExpr (SignW32 e) = compileSign e
compileExpr (AddW32 e1 e2) = compileAdd e1 e2
compileExpr (SubW32 e1 e2) = compileSub e1 e2
compileExpr (MultW32 e1 e2) = compileMult e1 e2
compileExpr (DivW32 e1 e2) = compileDiv e1 e2
compileExpr (RemW32 e1 e2) = compileMod e1 e2
compileExpr (QuotW32 e1 e2) = compileDiv e1 e2
compileExpr (ModW32 e1 e2) = compileMod e1 e2
compileExpr (AndW32 e1 e2) = compileAnd e1 e2
compileExpr (OrW32 e1 e2) = compileOr e1 e2
compileExpr (XorW32 e1 e2) = compileXor e1 e2
compileExpr (CompW32 e) = compileComp e
compileExpr (ShfLW32 e1 e2) = compileShiftLeft e1 e2
compileExpr (ShfRW32 e1 e2) = compileShiftRight e1 e2
compileExpr (IfW32 e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TestBW32 e1 e2) = compileTwoSubExpr "testBW32" e1 e2
compileExpr (SetBW32 e1 e2) = compileTwoSubExpr "setBW32" e1 e2
compileExpr (ClrBW32 e1 e2) = compileTwoSubExpr "clrBW32" e1 e2
compileExpr (LitI8 w) = show w
compileExpr (ShowI8 e) = compileSubExpr "showInt8" e
compileExpr (RefI8 n) = compileRef n
compileExpr (RemBindI8 b) = compileBind b
compileExpr (FromIntI8 e) = compileFromInt "int8_t" e
compileExpr (ToIntI8 e) = compileToInt e
compileExpr (NegI8 e) = compileNeg e
compileExpr (SignI8 e) = compileSubExpr "sign8" e
compileExpr (AddI8 e1 e2) = compileAdd e1 e2
compileExpr (SubI8 e1 e2) = compileSub e1 e2
compileExpr (MultI8 e1 e2) = compileMult e1 e2
compileExpr (DivI8 e1 e2) = compileTwoSubExpr "div8" e1 e2
compileExpr (RemI8 e1 e2) = compileMod e1 e2
compileExpr (QuotI8 e1 e2) = compileDiv e1 e2
compileExpr (ModI8 e1 e2) = compileTwoSubExpr "mod8" e1 e2
compileExpr (AndI8 e1 e2) = compileAdd e1 e2
compileExpr (OrI8 e1 e2) = compileOr e1 e2
compileExpr (XorI8 e1 e2) = compileXor e1 e2
compileExpr (CompI8 e) = compileComp e
compileExpr (ShfLI8 e1 e2) = compileShiftLeft e1 e2 -- ToDo: need runtinme??
compileExpr (ShfRI8 e1 e2) = compileShiftRight e1 e2
compileExpr (IfI8 e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TestBI8 e1 e2) = compileTwoSubExpr "testBI8" e1 e2
compileExpr (SetBI8 e1 e2) = compileTwoSubExpr "setBI8" e1 e2
compileExpr (ClrBI8 e1 e2) = compileTwoSubExpr "clrBI8" e1 e2
compileExpr (LitI16 w) = show w
compileExpr (ShowI16 e) = compileSubExpr "showInt16" e
compileExpr (RefI16 n) = compileRef n
compileExpr (RemBindI16 b) = compileBind b
compileExpr (FromIntI16 e) = compileFromInt "int16_t" e
compileExpr (ToIntI16 e) = compileToInt e
compileExpr (NegI16 e) = compileNeg e
compileExpr (SignI16 e) = compileSubExpr "sign16" e
compileExpr (AddI16 e1 e2) = compileAdd e1 e2
compileExpr (SubI16 e1 e2) = compileSub e1 e2
compileExpr (MultI16 e1 e2) = compileMult e1 e2
compileExpr (DivI16 e1 e2) = compileTwoSubExpr "div16" e1 e2
compileExpr (RemI16 e1 e2) = compileMod e1 e2
compileExpr (QuotI16 e1 e2) = compileDiv e1 e2
compileExpr (ModI16 e1 e2) = compileTwoSubExpr "mod16" e1 e2
compileExpr (AndI16 e1 e2) = compileAnd e1 e2
compileExpr (OrI16 e1 e2) = compileOr e1 e2
compileExpr (XorI16 e1 e2) = compileXor e1 e2
compileExpr (CompI16 e) = compileComp e
compileExpr (ShfLI16 e1 e2) = compileShiftLeft e1 e2
compileExpr (ShfRI16 e1 e2) = compileShiftRight e1 e2
compileExpr (IfI16 e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TestBI16 e1 e2) = compileTwoSubExpr "testBI16" e1 e2
compileExpr (SetBI16 e1 e2) = compileTwoSubExpr "setBI16" e1 e2
compileExpr (ClrBI16 e1 e2) = compileTwoSubExpr "clrBI16" e1 e2
compileExpr (LitI32 w) = show w
compileExpr (ShowI32 e) = compileSubExpr "showInt32" e
compileExpr (RefI32 n) = compileRef n
compileExpr (RemBindI32 b) = compileBind b
compileExpr (FromIntI32 e) = compileFromInt "int32_t" e
compileExpr (ToIntI32 e) = compileToInt e
compileExpr (NegI32 e) = compileNeg e
compileExpr (SignI32 e) = compileSubExpr "sign32" e
compileExpr (AddI32 e1 e2) = compileAdd e1 e2
compileExpr (SubI32 e1 e2) = compileSub e1 e2
compileExpr (MultI32 e1 e2) = compileMult e1 e2
compileExpr (DivI32 e1 e2) = compileTwoSubExpr "div32" e1 e2
compileExpr (RemI32 e1 e2) = compileMod e1 e2
compileExpr (QuotI32 e1 e2) = compileDiv e1 e2
compileExpr (ModI32 e1 e2) = compileTwoSubExpr "mod32" e1 e2
compileExpr (AndI32 e1 e2) = compileAnd e1 e2
compileExpr (OrI32 e1 e2) = compileOr e1 e2
compileExpr (XorI32 e1 e2) = compileXor e1 e2
compileExpr (CompI32 e) = compileComp e
compileExpr (ShfLI32 e1 e2) = compileShiftLeft e1 e2
compileExpr (ShfRI32 e1 e2) = compileShiftRight e1 e2
compileExpr (IfI32 e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TestBI32 e1 e2) = compileTwoSubExpr "testBI32" e1 e2
compileExpr (SetBI32 e1 e2) = compileTwoSubExpr "setBI32" e1 e2
compileExpr (ClrBI32 e1 e2) = compileTwoSubExpr "clrBI32" e1 e2
compileExpr (LitI w) = show w
compileExpr (ShowI e) = compileSubExpr "showInt32" e
compileExpr (RefI n) = compileRef n
compileExpr (RemBindI b) = compileBind b
compileExpr (NegI e) = compileNeg e
compileExpr (SignI e) = compileSubExpr "sign32" e
compileExpr (AddI e1 e2) = compileAdd e1 e2
compileExpr (SubI e1 e2) = compileSub e1 e2
compileExpr (MultI e1 e2) = compileMult e1 e2
compileExpr (DivI e1 e2) = compileTwoSubExpr "div32" e1 e2
compileExpr (RemI e1 e2) = compileMod e1 e2
compileExpr (QuotI e1 e2) = compileDiv e1 e2
compileExpr (ModI e1 e2) = compileTwoSubExpr "mod32" e1 e2
compileExpr (AndI e1 e2) = compileAnd e1 e2
compileExpr (OrI e1 e2) = compileOr e1 e2
compileExpr (XorI e1 e2) = compileXor e1 e2
compileExpr (CompI e) = compileComp e
compileExpr (ShfLI e1 e2) = compileShiftLeft e1 e2
compileExpr (ShfRI e1 e2) = compileShiftRight e1 e2
compileExpr (IfI e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TestBI e1 e2) = compileTwoSubExpr "testBI32" e1 e2
compileExpr (SetBI e1 e2) = compileTwoSubExpr "setBI32" e1 e2
compileExpr (ClrBI e1 e2) = compileTwoSubExpr "clrBI32" e1 e2
compileExpr (LitList8 ws) = "(uint8_t * ) (const byte[]) {255, " ++ (show $ length ws) ++ compListLit ws
where
compListLit :: [Word8] -> String
compListLit [] = "}"
compListLit (w : ws') = "," ++ show w ++ compListLit ws'
compileExpr (RefList8 n) = compileRef n
compileExpr (RemBindList8 b) = compileBind b
compileExpr (IfL8 e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (ConsList8 e1 e2) = compileTwoSubExpr "list8Cons" e1 e2
compileExpr (ApndList8 e1 e2) = compileTwoSubExpr "list8Apnd" e1 e2
compileExpr (RevList8 e) = compileSubExpr "list8Reverse" e
compileExpr (SliceList8 e1 e2 e3) = compileThreeSubExpr "list8Slice" e1 e2 e3
compileExpr (ElemList8 e1 e2) =
case e1 of
SliceList8 l st len -> compileTwoSubExpr "list8Elem" l (AddI st e2)
_ -> compileTwoSubExpr "list8Elem" e1 e2
compileExpr (LenList8 e) =
case e of
SliceList8 l st len -> compileSub (LenList8 l) st
RevList8 l -> compileSubExpr "list8Len" l
_ -> compileSubExpr "list8Len" e
-- ToDo:
-- compileExpr (PackList8 es) = [exprLCmdVal EXPRL_PACK, fromIntegral $ length es] ++ (foldl (++) [] (map compileExpr es))
compileExpr (LitFloat f) = show f -- ToDo: Is this correct?
compileExpr (ShowFloat e1 e2) = compileTwoSubExpr "showF" e1 e2
compileExpr (RefFloat n) = compileRef n
compileExpr (RemBindFloat b) = compileBind b
compileExpr (FromIntFloat e) = compileFromInt "float" e
compileExpr (NegFloat e) = compileNeg e
compileExpr (SignFloat e) = compileSubExpr "signF" e
compileExpr (AddFloat e1 e2) = compileAdd e1 e2
compileExpr (SubFloat e1 e2) = compileSub e1 e2
compileExpr (MultFloat e1 e2) = compileMult e1 e2
compileExpr (DivFloat e1 e2) = compileDiv e1 e2
compileExpr (IfFloat e1 e2 e3) = compileIfSubExpr e1 e2 e3
compileExpr (TruncFloat e) = compileSubExpr "trunc" e
compileExpr (FracFloat e) = compileSubExpr "frac" e
compileExpr (RoundFloat e) = compileSubExpr "round" e
compileExpr (CeilFloat e) = compileSubExpr "ceil" e
compileExpr (FloorFloat e) = compileSubExpr "floor" e
compileExpr PiFloat = "M_PI"
compileExpr (ExpFloat e) = compileSubExpr "exp" e
compileExpr (LogFloat e) = compileSubExpr "log" e
compileExpr (SqrtFloat e) = compileSubExpr "sqrt" e
compileExpr (SinFloat e) = compileSubExpr "sin" e
compileExpr (CosFloat e) = compileSubExpr "cos" e
compileExpr (TanFloat e) = compileSubExpr "tan" e
compileExpr (AsinFloat e) = compileSubExpr "asin" e
compileExpr (AcosFloat e) = compileSubExpr "acos" e
compileExpr (AtanFloat e) = compileSubExpr "atan" e
compileExpr (Atan2Float e1 e2) = compileTwoSubExpr "atan2" e1 e2
compileExpr (SinhFloat e) = compileSubExpr "sinh" e
compileExpr (CoshFloat e) = compileSubExpr "cosh" e
compileExpr (TanhFloat e) = compileSubExpr "tanh" e
compileExpr (PowerFloat e1 e2) = compileTwoSubExpr "pow" e1 e2
compileExpr (IsNaNFloat e) = compileSubExpr "isnan" e
compileExpr (IsInfFloat e) = compileSubExpr "isinf" e
compileExpr _ = error "compileExpr: Unsupported expression"
| ku-fpg/kansas-amber | System/Hardware/Haskino/Compiler.hs | bsd-3-clause | 104,124 | 0 | 30 | 25,595 | 36,355 | 16,844 | 19,511 | 2,585 | 13 |
-- !!! testing newTVarIO
import Control.Concurrent
import Control.Concurrent.STM
import System.IO.Unsafe
var = unsafePerformIO $ newTVarIO 3
main = do x <- atomically $ readTVar var; print x
| gridaphobe/packages-stm | tests/stm054.hs | bsd-3-clause | 194 | 0 | 9 | 30 | 57 | 30 | 27 | 5 | 1 |
module RefacWhereLet(refacWhereLet) where
import PrettyPrint
import PosSyntax
import AbstractIO
import Maybe
import TypedIds
import UniqueNames hiding (srcLoc)
import PNT
import TiPNT
import List
import RefacUtils hiding (getParams)
import PFE0 (findFile)
import MUtils (( # ))
import RefacLocUtils
import System
import IO
{- This refactoring converts a where into a let. Could potentially narrow the scrope of those involved bindings.
Copyright : (c) Christopher Brown 2008
Maintainer : cmb21@kent.ac.uk
Stability : provisional
Portability : portable
-}
refacWhereLet args
= do let fileName = ghead "filename" args
--fileName'= moduleName fileName
--modName = Module fileName'
row = read (args!!1)::Int
col = read (args!!2)::Int
modName <-fileNameToModName fileName
(inscps, exps, mod, tokList)<-parseSourceFile fileName
AbstractIO.putStrLn "Completed.\n" | kmate/HaRe | old/testing/removeCon/Untitled.hs | bsd-3-clause | 968 | 0 | 12 | 221 | 179 | 104 | 75 | 23 | 1 |
-- 1. Load a set of modules with "nothing" target
-- 2. Load it again with "interpreted" target
-- 3. Execute some code
-- a. If the recompilation checker is buggy this will die due to missing
-- code
-- b. If it's correct, it will recompile because the target has changed.
--
-- This program must be called with GHC's libdir as the single command line
-- argument.
module Main where
import GHC
import DynFlags
import MonadUtils ( MonadIO(..) )
import BasicTypes ( failed )
import Bag ( bagToList )
import System.Environment
import Control.Monad
import System.IO
main = do
libdir : args <- getArgs
runGhc (Just libdir) $ do
dflags0 <- getSessionDynFlags
(dflags, _, _) <- parseDynamicFlags dflags0
(map (mkGeneralLocated "on the commandline") args)
setSessionDynFlags $ dflags { hscTarget = HscNothing
, ghcLink = LinkInMemory
, verbosity = 0 -- silence please
}
root_mod <- guessTarget "A.hs" Nothing
setTargets [root_mod]
ok <- load LoadAllTargets
when (failed ok) $ error "Couldn't load A.hs in nothing mode"
prn "target nothing: ok"
dflags <- getSessionDynFlags
setSessionDynFlags $ dflags { hscTarget = HscInterpreted }
ok <- load LoadAllTargets
when (failed ok) $ error "Couldn't load A.hs in interpreted mode"
prn "target interpreted: ok"
-- set context to module "A"
mg <- getModuleGraph
let [mod] = [ ms_mod_name m | m <- mg, moduleNameString (ms_mod_name m) == "A" ]
setContext [IIModule mod]
liftIO $ hFlush stdout -- make sure things above are printed before
-- interactive output
r <- execStmt "main" execOptions
case r of
ExecComplete { execResult = Right _ } -> prn "ok"
ExecComplete { execResult = Left _ } -> prn "exception"
ExecBreak{} -> prn "breakpoint"
liftIO $ hFlush stdout
return ()
prn :: MonadIO m => String -> m ()
prn = liftIO . putStrLn
| olsner/ghc | testsuite/tests/ghc-api/apirecomp001/myghc.hs | bsd-3-clause | 2,032 | 0 | 18 | 561 | 475 | 236 | 239 | 41 | 3 |
module Measures where
{-@ data Wrapper a <p :: a -> Prop, r :: a -> a -> Prop >
= Wrap (rgref_ref :: a<p>) @-}
data Wrapper a = Wrap (a)
-- Two measures
{-@ measure fwdextends :: Int -> Int -> Prop @-}
{-@ measure actionP :: Int -> Prop @-}
{-@ data Wrapper2 = Wrapper2 (unwrapper :: (Wrapper<{\x -> (true)},{\x y -> (fwdextends y x)}> Int )) @-}
{- data Wrapper2 = Wrapper2 (unwrapper :: (Wrapper<{\x -> (actionP x)},{\x y -> (true)}> Int )) @-}
data Wrapper2 = Wrapper2 (Wrapper (Int) )
| abakst/liquidhaskell | tests/pos/Measures.hs | bsd-3-clause | 502 | 0 | 9 | 108 | 41 | 27 | 14 | 3 | 0 |
{-# LANGUAGE NamedFieldPuns #-}
data SomeRec = SomeRec { a :: Integer, b :: Integer } | Y | X deriving Show
fun :: SomeRec -> SomeRec
fun SomeRec{a} = SomeRec{a=a+1, b=10}
fun2 :: SomeRec -> SomeRec
fun2 r = let a = 5 in r{a}
main = do
let r = SomeRec{a=1, b=2}
print r
print (fun r)
print (fun2 r)
-- https://github.com/faylang/fay/issues/121
let t = Y
putStrLn $ case t of
SomeRec{a} -> "Bad"
Y -> "OK."
| beni55/ghcjs | test/fay/namedFieldPuns.hs | mit | 479 | 0 | 12 | 152 | 203 | 107 | 96 | 15 | 2 |
{-# LANGUAGE QuasiQuotes #-}
module MHMC.Display.Help
(
helpinfo,
help
) where
import Control.Monad.Trans.RWS.Lazy
import Data.Default
import Data.String.QQ
import Graphics.Vty
import MHMC.RWS
help :: Int -> Int -> Image
help height cursor = cropBottom (height - 4)
$ pad 0 0 0 height
$ foldl1 (<->)
$ map (string (def `withForeColor` white))
$ drop cursor
$ lines helpinfo
helpinfo = [s|
Keys - Movement
--------------------------------
Up : Move Cursor up
Down : Move Cursor down
1 : Help screen
2 : Playlist screen
3 : Browse screen
4 : Search engine
5 : Media library
6 : Playlist editor
7 : Tag editor
8 : Outputs
9 : Music visualizer
0 : Clock screen
@ : MPD server info
Keys - Global
--------------------------------
s : Stop
P : Pause/Play
Backspace : Play current track from the beginning
|] | killmous/MHMC | src/MHMC/Display/Help.hs | mit | 1,121 | 0 | 12 | 457 | 145 | 83 | 62 | 18 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Leankit.Types.CardHistoryItem where
import Control.Applicative ((<$>), (<*>))
import Control.Monad (mzero)
import Data.Aeson
import Leankit.Types.Common
data CardHistoryItem = CardHistoryItem {
_cardId :: CardID,
_overrideType :: Maybe String, -- TODO what's this?
_taskboardContainingCardId :: Maybe CardID,
_userName :: Maybe String,
_cardTitle :: Maybe String,
_gravatarLink :: Maybe String,
_timeDifference :: Maybe String,
_dateTime :: Maybe DateTime,
_lastDate :: Maybe Integer, -- TODO should be converted to datetime...
_type :: Maybe String,
_taskboardContainingCardTitle :: Maybe String,
_userFullName :: Maybe String,
_toLaneId :: Maybe LaneID,
_toLaneTitle :: Maybe String,
_details :: CardHistoryDetails
} deriving (Eq, Show)
instance FromJSON CardHistoryItem where
parseJSON (Object v) = CardHistoryItem
<$> v .: "CardId"
<*> v .:? "OverrideType"
<*> v .:? "TaskboardContainingCardId"
<*> v .:? "UserName"
<*> v .:? "CardTitle"
<*> v .:? "GravatarLink"
<*> v .:? "TimeDifference"
<*> v .:? "DateTime"
<*> v .:? "LastDate"
<*> v .:? "Type"
<*> v .:? "TaskboardContainingCardTitle"
<*> v .:? "UserFullName"
<*> v .:? "ToLaneId"
<*> v .:? "ToLaneTitle"
<*> parseJSON (Object v)
parseJSON _ = mzero
-- ===============
-- CardFieldChange
data CardFieldChange = CardFieldChange {
_fieldName :: String,
_newValue :: String,
_oldValue :: Maybe String,
_newDueDate :: Maybe String,
_oldDueDate :: Maybe String
} deriving (Eq, Show)
instance FromJSON CardFieldChange where
parseJSON (Object v) = CardFieldChange
<$> v .: "FieldName"
<*> v .: "NewValue"
<*> v .:? "OldValue"
<*> v .:? "NewDueDate"
<*> v .:? "OldDueDate"
parseJSON _ = mzero
-- ==================
-- CardHistoryDetails
data CardHistoryDetails = CardCreateEventDetails |
CardMoveEventDetails {
_fromLaneId :: LaneID,
_fromLaneTitle :: Maybe String
} |
UserAssignmentEventDetails {
_assignedUserId :: UserID,
_assignedUserEmailAddress :: Maybe String,
_assignedUserFullName :: Maybe String
} |
CardFieldChangedEventDetails {
_changes :: [CardFieldChange]
} |
UnknownEventDetails
deriving (Eq, Show)
instance FromJSON CardHistoryDetails where
parseJSON (Object v) = do
itemType <- v .: "Type"
case (itemType :: String) of -- TODO is this the proper place to give the type signature?
"CardCreationEventDTO" -> return CardCreateEventDetails
"CardMoveEventDTO" -> CardMoveEventDetails
<$> v .: "FromLaneId"
<*> v .:? "FromLaneTitle"
"UserAssignmentEventDTO" -> UserAssignmentEventDetails
<$> v .: "AssignedUserId"
<*> v .:? "AssignedUserEmailAddres" -- TYPO!!!
<*> v .:? "AssignedUserFullName"
"CardFieldsChangedEventDTO" -> CardFieldChangedEventDetails
<$> v .: "Changes"
_ -> return UnknownEventDetails -- fallback
parseJSON _ = mzero
| dtorok/leankit-hsapi | Leankit/Types/CardHistoryItem.hs | mit | 4,781 | 0 | 34 | 2,398 | 710 | 388 | 322 | 84 | 0 |
import Distribution.Simple
import System.Environment
-- Hacking this to work based on:
--
-- https://stackoverflow.com/a/39019781
--
-- Relies on `happy` existing at /usr/bin/happy; eg. on Arch Linux:
--
-- sudo pacman -S stack happy
main = do
args <- getArgs
let args' = if elem "configure" args
then args ++ [ "--with-happy=/usr/bin/happy" ]
else args
defaultMainWithArgs args'
| wincent/docvim | Setup.hs | mit | 402 | 0 | 12 | 78 | 65 | 36 | 29 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE UndecidableInstances #-}
module Betfair.APING.Types.KeyLineSelection
( KeyLineSelection(..)
) where
import Data.Aeson.TH (Options (omitNothingFields), defaultOptions,
deriveJSON)
import Protolude
import Text.PrettyPrint.GenericPretty
data KeyLineSelection = KeyLineSelection
{ selectionId :: Integer
, handicap :: Double
} deriving (Eq, Show, Generic, Pretty)
$(deriveJSON defaultOptions {omitNothingFields = True} ''KeyLineSelection)
| joe9/betfair-api | src/Betfair/APING/Types/KeyLineSelection.hs | mit | 716 | 0 | 9 | 136 | 116 | 73 | 43 | 18 | 0 |
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE CPP #-}
module IHaskell.Test.Eval (testEval) where
import Prelude
import Data.List (stripPrefix)
import Control.Monad (when, forM_)
import Data.IORef (newIORef, modifyIORef, readIORef)
import System.Directory (getTemporaryDirectory, setCurrentDirectory)
import Data.String.Here (hereLit)
import qualified GHC.Paths
import Test.Hspec
import IHaskell.Test.Util (strip)
import IHaskell.Eval.Evaluate (interpret, evaluate)
import IHaskell.Types (EvaluationResult(..), defaultKernelState, KernelState(..),
LintStatus(..), Display(..), extractPlain)
eval :: String -> IO ([Display], String)
eval string = do
outputAccum <- newIORef []
pagerAccum <- newIORef []
let publish evalResult =
case evalResult of
IntermediateResult{} -> return ()
FinalResult outs page [] -> do
modifyIORef outputAccum (outs :)
modifyIORef pagerAccum (page :)
noWidgetHandling s _ = return s
getTemporaryDirectory >>= setCurrentDirectory
let state = defaultKernelState { getLintStatus = LintOff }
interpret GHC.Paths.libdir False $ const $
IHaskell.Eval.Evaluate.evaluate state string publish noWidgetHandling
out <- readIORef outputAccum
pagerOut <- readIORef pagerAccum
return (reverse out, unlines . map extractPlain . reverse $ pagerOut)
becomes :: String -> [String] -> IO ()
becomes string expected = evaluationComparing comparison string
where
comparison :: ([Display], String) -> IO ()
comparison (results, pageOut) = do
when (length results /= length expected) $
expectationFailure $ "Expected result to have " ++ show (length expected)
++ " results. Got " ++ show results
forM_ (zip results expected) $ \(ManyDisplay [Display result], expected) -> case extractPlain result of
"" -> expectationFailure $ "No plain-text output in " ++ show result ++ "\nExpected: " ++ expected
str -> str `shouldBe` expected
evaluationComparing :: (([Display], String) -> IO b) -> String -> IO b
evaluationComparing comparison string = do
let indent (' ':x) = 1 + indent x
indent _ = 0
empty = null . strip
stringLines = filter (not . empty) $ lines string
minIndent = minimum (map indent stringLines)
newString = unlines $ map (drop minIndent) stringLines
eval newString >>= comparison
pages :: String -> [String] -> IO ()
pages string expected = evaluationComparing comparison string
where
comparison (results, pageOut) =
strip (stripHtml pageOut) `shouldBe` strip (fixQuotes $ unlines expected)
-- A very, very hacky method for removing HTML
stripHtml str = go str
where
go ('<':str) =
case stripPrefix "script" str of
Nothing -> go' str
Just str -> dropScriptTag str
go (x:xs) = x : go xs
go [] = []
go' ('>':str) = go str
go' (x:xs) = go' xs
go' [] = error $ "Unending bracket html tag in string " ++ str
dropScriptTag str =
case stripPrefix "</script>" str of
Just str -> go str
Nothing -> dropScriptTag $ tail str
fixQuotes :: String -> String
#if MIN_VERSION_ghc(7, 8, 0)
fixQuotes = id
#else
fixQuotes = map $ \char -> case char of
'\8216' -> '`'
'\8217' -> '\''
c -> c
#endif
testEval :: Spec
testEval =
describe "Code Evaluation" $ do
it "evaluates expressions" $ do
"3" `becomes` ["3"]
"3+5" `becomes` ["8"]
"print 3" `becomes` ["3"]
[hereLit|
let x = 11
z = 10 in
x+z
|] `becomes` ["21"]
it "evaluates flags" $ do
":set -package hello" `becomes` ["Warning: -package not supported yet"]
":set -XNoImplicitPrelude" `becomes` []
it "evaluates multiline expressions" $ do
[hereLit|
import Control.Monad
forM_ [1, 2, 3] $ \x ->
print x
|] `becomes` ["1\n2\n3"]
it "evaluates function declarations silently" $ do
[hereLit|
fun :: [Int] -> Int
fun [] = 3
fun (x:xs) = 10
fun [1, 2]
|] `becomes` ["10"]
it "evaluates data declarations" $ do
[hereLit|
data X = Y Int
| Z String
deriving (Show, Eq)
print [Y 3, Z "No"]
print (Y 3 == Z "No")
|] `becomes` ["[Y 3,Z \"No\"]", "False"]
it "evaluates do blocks in expressions" $ do
[hereLit|
show (show (do
Just 10
Nothing
Just 100))
|] `becomes` ["\"\\\"Nothing\\\"\""]
it "is silent for imports" $ do
"import Control.Monad" `becomes` []
"import qualified Control.Monad" `becomes` []
"import qualified Control.Monad as CM" `becomes` []
"import Control.Monad (when)" `becomes` []
it "prints Unicode characters correctly" $ do
"putStrLn \"Héllö, Üñiço∂e!\"" `becomes` ["Héllö, Üñiço∂e!"]
"putStrLn \"Привет!\"" `becomes` ["Привет!"]
it "evaluates directives" $ do
":typ 3" `becomes` ["3 :: forall t. Num t => t"]
":k Maybe" `becomes` ["Maybe :: * -> *"]
":in String" `pages` ["type String = [Char] \t-- Defined in \8216GHC.Base\8217"]
| sumitsahrawat/IHaskell | src/tests/IHaskell/Test/Eval.hs | mit | 5,445 | 0 | 17 | 1,618 | 1,402 | 737 | 665 | 111 | 9 |
module Game where
data GameState = EndGame | SomeResultantAction_ChangeMe deriving (Eq, Show)
data GameAction = SomeGameAction_ChangeMe
runGame [] = EndGame
runGame _ = SomeResultantAction_ChangeMe
| PolyglotSymposium/textual-game-hs | Game.hs | mit | 200 | 0 | 6 | 26 | 50 | 28 | 22 | 5 | 1 |
module Class4 where
data String
class Show a where
show :: a -> String
fn1 x y = (fn2 x, y)
where
fn2 x = show x
| Lemmih/haskell-tc | tests/Class4.hs | mit | 124 | 0 | 7 | 38 | 57 | 30 | 27 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-targetgroupsconfig.html
module Stratosphere.ResourceProperties.EC2SpotFleetTargetGroupsConfig where
import Stratosphere.ResourceImports
import Stratosphere.ResourceProperties.EC2SpotFleetTargetGroup
-- | Full data type definition for EC2SpotFleetTargetGroupsConfig. See
-- 'ec2SpotFleetTargetGroupsConfig' for a more convenient constructor.
data EC2SpotFleetTargetGroupsConfig =
EC2SpotFleetTargetGroupsConfig
{ _eC2SpotFleetTargetGroupsConfigTargetGroups :: [EC2SpotFleetTargetGroup]
} deriving (Show, Eq)
instance ToJSON EC2SpotFleetTargetGroupsConfig where
toJSON EC2SpotFleetTargetGroupsConfig{..} =
object $
catMaybes
[ (Just . ("TargetGroups",) . toJSON) _eC2SpotFleetTargetGroupsConfigTargetGroups
]
-- | Constructor for 'EC2SpotFleetTargetGroupsConfig' containing required
-- fields as arguments.
ec2SpotFleetTargetGroupsConfig
:: [EC2SpotFleetTargetGroup] -- ^ 'ecsftgcTargetGroups'
-> EC2SpotFleetTargetGroupsConfig
ec2SpotFleetTargetGroupsConfig targetGroupsarg =
EC2SpotFleetTargetGroupsConfig
{ _eC2SpotFleetTargetGroupsConfigTargetGroups = targetGroupsarg
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-spotfleet-targetgroupsconfig.html#cfn-ec2-spotfleet-targetgroupsconfig-targetgroups
ecsftgcTargetGroups :: Lens' EC2SpotFleetTargetGroupsConfig [EC2SpotFleetTargetGroup]
ecsftgcTargetGroups = lens _eC2SpotFleetTargetGroupsConfigTargetGroups (\s a -> s { _eC2SpotFleetTargetGroupsConfigTargetGroups = a })
| frontrowed/stratosphere | library-gen/Stratosphere/ResourceProperties/EC2SpotFleetTargetGroupsConfig.hs | mit | 1,727 | 0 | 13 | 162 | 177 | 105 | 72 | 24 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.