code
stringlengths 5
1.03M
| repo_name
stringlengths 5
90
| path
stringlengths 4
158
| license
stringclasses 15
values | size
int64 5
1.03M
| n_ast_errors
int64 0
53.9k
| ast_max_depth
int64 2
4.17k
| n_whitespaces
int64 0
365k
| n_ast_nodes
int64 3
317k
| n_ast_terminals
int64 1
171k
| n_ast_nonterminals
int64 1
146k
| loc
int64 -1
37.3k
| cycloplexity
int64 -1
1.31k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
{-# LANGUAGE CPP #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
-- Required for GHC >= 9
{-# OPTIONS_GHC -Wno-redundant-constraints #-}
-- |
-- Module : Pact.Types.Term
-- Copyright : (C) 2016 Stuart Popejoy
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Stuart Popejoy <[email protected]>
--
-- Term and related types.
--
module Pact.Types.Term
( Namespace(..), nsName, nsUser, nsAdmin,
Meta(..),mDocs,mModel,
PublicKey(..),
KeySet(..), mkKeySet,
KeySetName(..),
PactGuard(..),
PactId(..),
UserGuard(..),
ModuleGuard(..),
Guard(..),_GPact,_GKeySet,_GKeySetRef,_GModule,_GUser,
DefType(..),_Defun,_Defpact,_Defcap,
defTypeRep,
FunApp(..),faDefType,faDocs,faInfo,faModule,faName,faTypes,
Ref'(..),_Direct,_Ref,Ref,
NativeDFun(..),
BindType(..),
BindPair(..),bpArg,bpVal,toBindPairs,
Module(..),mName,mGovernance,mMeta,mCode,mHash,mBlessed,mInterfaces,mImports,
Interface(..),interfaceCode, interfaceMeta, interfaceName, interfaceImports,
ModuleDef(..),_MDModule,_MDInterface,moduleDefName,moduleDefCode,moduleDefMeta,
Governance(..),
ModuleHash(..), mhHash,
ConstVal(..),constTerm,
Use(..),
App(..),appFun,appArgs,appInfo,
Def(..),dDefBody,dDefName,dDefType,dMeta,dFunType,dInfo,dModule,dDefMeta,
Lam(..), lamArg, lamBindBody, lamTy, lamInfo,
DefMeta(..),
DefcapMeta(..),
Example(..),
derefDef,
ObjectMap(..),objectMapToListWith,
Object(..),oObject,oObjectType,oInfo,oKeyOrder,
FieldKey(..),
Step(..),sEntity,sExec,sRollback,sInfo,
ModRef(..),modRefName,modRefSpec,modRefInfo,
modRefTy,
Term(..),
tApp,tBindBody,tBindPairs,tBindType,tConstArg,tConstVal,
tDef,tMeta,tFields,tFunTypes,tHash,tInfo,tGuard,
tListType,tList,tLiteral,tModuleBody,tModuleDef,tModule,tUse,
tNativeDocs,tNativeFun,tNativeName,tNativeExamples,
tNativeTopLevelOnly,tObject,tSchemaName,
tTableName,tTableType,tVar,tStep,tModuleName,
tDynModRef,tDynMember,tModRef,tLam,
_TModule, _TList, _TDef, _TNative, _TConst, _TApp,
_TVar, _TBinding, _TLam, _TObject, _TSchema,
_TLiteral, _TGuard, _TUse, _TStep, _TModRef,
_TTable, _TDynamic,
ToTerm(..),
toTermList,toTObject,toTObjectMap,toTList,toTListV,
typeof,typeof',guardTypeOf,
canUnifyWith,
prettyTypeTerm,
pattern TLitString,pattern TLitInteger,pattern TLitBool,
tLit,tStr,termEq,termEq1,termRefEq,canEq,refEq,
Gas(..),
module Pact.Types.Names
) where
import Bound
import Control.Applicative
import Control.Arrow ((&&&))
import Control.DeepSeq
import Control.Lens hiding ((.=), DefName(..))
import Control.Monad
#if MIN_VERSION_aeson(1,4,3)
import Data.Aeson hiding (pairs,Object, (<?>))
#else
import Data.Aeson hiding (pairs,Object)
#endif
import Data.Decimal
import Data.Default
import Data.Eq.Deriving
import Data.Foldable
import Data.Functor.Classes (Eq1(..), Show1(..))
import Data.Function
import qualified Data.HashMap.Strict as HM
import qualified Data.HashSet as HS
import Data.Hashable
import Data.Int (Int64)
import Data.List
import qualified Data.Map.Strict as M
import Data.Maybe
import Data.Serialize (Serialize)
import Data.String
import Data.Text (Text)
import qualified Data.Text as T
import Pact.Time (UTCTime)
import Data.Vector (Vector)
import qualified Data.Vector as V
import Data.Word (Word64, Word32)
import GHC.Generics (Generic)
import Prelude
import Test.QuickCheck hiding (Success)
import Text.Show.Deriving
import Pact.Types.Codec
import Pact.Types.Exp
import Pact.Types.Hash
import Pact.Types.Info
import Pact.Types.KeySet
import Pact.Types.Names
import Pact.Types.Pretty hiding (dot)
import Pact.Types.SizeOf
import Pact.Types.Type
import Pact.Types.Util
-- -------------------------------------------------------------------------- --
-- Meta
data Meta = Meta
{ _mDocs :: !(Maybe Text) -- ^ docs
, _mModel :: ![Exp Info] -- ^ models
} deriving (Eq, Show, Generic)
instance Pretty Meta where
pretty (Meta (Just doc) model) = dquotes (pretty doc) <> line <> prettyModel model
pretty (Meta Nothing model) = prettyModel model
instance NFData Meta
instance SizeOf Meta
prettyModel :: [Exp Info] -> Doc
prettyModel [] = mempty
prettyModel props = "@model " <> list (pretty <$> props)
instance ToJSON Meta where toJSON = lensyToJSON 2
instance FromJSON Meta where parseJSON = lensyParseJSON 2
instance Default Meta where def = Meta def def
instance Semigroup Meta where
(Meta d m) <> (Meta d' m') = Meta (d <> d') (m <> m')
instance Monoid Meta where
mempty = Meta Nothing []
-- -------------------------------------------------------------------------- --
-- PactId
newtype PactId = PactId Text
deriving (Eq,Ord,Show,Pretty,AsString,IsString,FromJSON,ToJSON,Generic,NFData,SizeOf)
instance Arbitrary PactId where
arbitrary = PactId <$> hashToText <$> arbitrary
-- -------------------------------------------------------------------------- --
-- UserGuard
data UserGuard a = UserGuard
{ _ugFun :: !Name
, _ugArgs :: ![a]
} deriving (Eq,Generic,Show,Functor,Foldable,Traversable,Ord)
instance (Arbitrary a) => Arbitrary (UserGuard a) where
arbitrary = UserGuard <$> arbitrary <*> arbitrary
instance NFData a => NFData (UserGuard a)
instance Pretty a => Pretty (UserGuard a) where
pretty UserGuard{..} = "UserGuard" <+> commaBraces
[ "fun: " <> pretty _ugFun
, "args: " <> pretty _ugArgs
]
instance (SizeOf p) => SizeOf (UserGuard p) where
sizeOf (UserGuard n arr) =
(constructorCost 2) + (sizeOf n) + (sizeOf arr)
instance ToJSON a => ToJSON (UserGuard a) where toJSON = lensyToJSON 3
instance FromJSON a => FromJSON (UserGuard a) where parseJSON = lensyParseJSON 3
-- -------------------------------------------------------------------------- --
-- DefType
data DefType
= Defun
| Defpact
| Defcap
deriving (Eq,Show,Generic, Bounded, Enum)
instance FromJSON DefType
instance ToJSON DefType
instance NFData DefType
instance SizeOf DefType where
sizeOf _ = 0
defTypeRep :: DefType -> String
defTypeRep Defun = "defun"
defTypeRep Defpact = "defpact"
defTypeRep Defcap = "defcap"
instance Pretty DefType where
pretty = prettyString . defTypeRep
-- -------------------------------------------------------------------------- --
-- Gas
-- | Gas compute cost unit.
newtype Gas = Gas Int64
deriving (Eq,Ord,Num,Real,Integral,Enum,ToJSON,FromJSON,Generic,NFData)
instance Show Gas where show (Gas g) = show g
instance Pretty Gas where
pretty (Gas i) = pretty i
instance Semigroup Gas where
(Gas a) <> (Gas b) = Gas $ a + b
instance Monoid Gas where
mempty = 0
-- -------------------------------------------------------------------------- --
-- BindType
-- | Binding forms.
data BindType n =
-- | Normal "let" bind
BindLet |
-- | Schema-style binding, with string value for key
BindSchema { _bType :: !n }
deriving (Eq,Functor,Foldable,Traversable,Ord,Show,Generic)
instance (Pretty n) => Pretty (BindType n) where
pretty BindLet = "let"
pretty (BindSchema b) = "bind" <> pretty b
instance ToJSON n => ToJSON (BindType n) where
toJSON BindLet = "let"
toJSON (BindSchema s) = object [ "bind" .= s ]
instance FromJSON n => FromJSON (BindType n) where
parseJSON v =
withThisText "BindLet" "let" v (pure BindLet) <|>
withObject "BindSchema" (\o -> BindSchema <$> o .: "bind") v
instance NFData n => NFData (BindType n)
instance (SizeOf n) => SizeOf (BindType n)
-- -------------------------------------------------------------------------- --
-- BindPair
data BindPair n = BindPair
{ _bpArg :: !(Arg n)
, _bpVal :: !n }
deriving (Eq,Show,Functor,Traversable,Foldable,Generic)
toBindPairs :: BindPair n -> (Arg n,n)
toBindPairs (BindPair a v) = (a,v)
instance Pretty n => Pretty (BindPair n) where
pretty (BindPair arg body) = pretty arg <+> pretty body
instance NFData n => NFData (BindPair n)
instance ToJSON n => ToJSON (BindPair n) where toJSON = lensyToJSON 3
instance FromJSON n => FromJSON (BindPair n) where parseJSON = lensyParseJSON 3
instance (SizeOf n) => SizeOf (BindPair n)
-- -------------------------------------------------------------------------- --
-- App
data App t = App
{ _appFun :: !t
, _appArgs :: ![t]
, _appInfo :: !Info
} deriving (Functor,Foldable,Traversable,Eq,Show,Generic)
instance HasInfo (App t) where getInfo = _appInfo
instance ToJSON t => ToJSON (App t) where toJSON = lensyToJSON 4
instance FromJSON t => FromJSON (App t) where parseJSON = lensyParseJSON 4
instance Pretty n => Pretty (App n) where
pretty App{..} = parensSep $ pretty _appFun : map pretty _appArgs
instance NFData t => NFData (App t)
instance (SizeOf t) => SizeOf (App t)
-- -------------------------------------------------------------------------- --
-- Governance
newtype Governance g = Governance { _gGovernance :: Either KeySetName g }
deriving (Eq,Ord,Functor,Foldable,Traversable,Show,NFData, Generic)
instance (SizeOf g) => SizeOf (Governance g)
instance Pretty g => Pretty (Governance g) where
pretty = \case
Governance (Left k) -> pretty k
Governance (Right r) -> pretty r
instance ToJSON g => ToJSON (Governance g) where
toJSON (Governance g) = case g of
Left ks -> object [ "keyset" .= ks ]
Right c -> object [ "capability" .= c ]
instance FromJSON g => FromJSON (Governance g) where
parseJSON = withObject "Governance" $ \o ->
Governance <$> (Left <$> o .: "keyset" <|>
Right <$> o .: "capability")
-- -------------------------------------------------------------------------- --
-- ModuleHash
-- | Newtype wrapper differentiating 'Hash'es from module hashes
--
newtype ModuleHash = ModuleHash { _mhHash :: Hash }
deriving (Eq, Ord, Show, Generic, Hashable, Serialize, AsString, Pretty, ToJSON, FromJSON, ParseText)
deriving newtype (NFData, SizeOf)
instance Arbitrary ModuleHash where
-- Coin contract is about 20K characters
arbitrary = ModuleHash <$> resize 20000 arbitrary
-- -------------------------------------------------------------------------- --
-- DefcapMeta
-- | Metadata specific to Defcaps.
data DefcapMeta n =
DefcapManaged
{ _dcManaged :: !(Maybe (Text,n))
-- ^ "Auto" managed or user-managed by (param,function)
} |
DefcapEvent
-- ^ Eventing defcap.
deriving (Functor,Foldable,Traversable,Generic,Eq,Show,Ord)
instance NFData n => NFData (DefcapMeta n)
instance Pretty n => Pretty (DefcapMeta n) where
pretty (DefcapManaged m) = case m of
Nothing -> tag
Just (p,f) -> tag <> " " <> pretty p <> " " <> pretty f
where
tag = "@managed"
pretty DefcapEvent = "@event"
instance (ToJSON n,FromJSON n) => ToJSON (DefcapMeta n) where
toJSON (DefcapManaged (Just (p,f))) = object
[ "managerFun" .= f
, "managedParam" .= p
]
toJSON (DefcapManaged Nothing) = object [ "managerAuto" .= True ]
toJSON DefcapEvent = "event"
instance (ToJSON n,FromJSON n) => FromJSON (DefcapMeta n) where
parseJSON v = parseUser v <|> parseAuto v <|> parseEvent v
where
parseUser = withObject "DefcapMeta" $ \o -> (DefcapManaged . Just) <$>
((,) <$> o .: "managedParam" <*> o .: "managerFun")
parseAuto = withObject "DefcapMeta" $ \o -> do
b <- o .: "managerAuto"
if b then pure (DefcapManaged Nothing)
else fail "Expected True"
parseEvent = withText "DefcapMeta" $ \t ->
if t == "event" then pure DefcapEvent
else fail "Expected 'event'"
instance (SizeOf a) => SizeOf (DefcapMeta a)
-- | Def metadata specific to 'DefType'.
-- Currently only specified for Defcap.
data DefMeta n =
DMDefcap !(DefcapMeta n)
deriving (Functor,Foldable,Traversable,Generic,Eq,Show,Ord)
instance NFData n => NFData (DefMeta n)
instance Pretty n => Pretty (DefMeta n) where
pretty (DMDefcap m) = pretty m
instance (ToJSON n,FromJSON n) => ToJSON (DefMeta n) where
toJSON (DMDefcap m) = toJSON m
instance (ToJSON n,FromJSON n) => FromJSON (DefMeta n) where
parseJSON = fmap DMDefcap . parseJSON
instance (SizeOf a) => SizeOf (DefMeta a)
-- -------------------------------------------------------------------------- --
-- ConstVal
data ConstVal n =
CVRaw { _cvRaw :: !n } |
CVEval { _cvRaw :: !n
, _cvEval :: !n }
deriving (Eq,Functor,Foldable,Traversable,Generic,Show)
instance NFData n => NFData (ConstVal n)
instance ToJSON n => ToJSON (ConstVal n) where
toJSON (CVRaw n) = object [ "raw" .= n ]
toJSON (CVEval n m) = object [ "raw" .= n, "eval" .= m ]
instance FromJSON n => FromJSON (ConstVal n) where
parseJSON v =
(withObject "CVEval"
(\o -> CVEval <$> o .: "raw" <*> o .: "eval") v) <|>
(withObject "CVRaw"
(\o -> CVRaw <$> o .: "raw") v)
-- | A term from a 'ConstVal', preferring evaluated terms when available.
constTerm :: ConstVal a -> a
constTerm (CVRaw raw) = raw
constTerm (CVEval _raw eval) = eval
instance (SizeOf n) => SizeOf (ConstVal n)
-- -------------------------------------------------------------------------- --
-- Example
data Example
= ExecExample !Text
-- ^ An example shown as a good execution
| ExecErrExample !Text
-- ^ An example shown as a failing execution
| LitExample !Text
-- ^ An example shown as a literal
deriving (Eq, Show, Generic)
instance Pretty Example where
pretty = \case
ExecExample str -> annotate Example $ "> " <> pretty str
ExecErrExample str -> annotate BadExample $ "> " <> pretty str
LitExample str -> annotate Example $ pretty str
instance IsString Example where
fromString = ExecExample . fromString
instance NFData Example
instance SizeOf Example
-- -------------------------------------------------------------------------- --
-- FieldKey
-- | Label type for objects.
newtype FieldKey = FieldKey Text
deriving (Eq,Ord,IsString,AsString,ToJSON,FromJSON,Show,NFData,Generic,ToJSONKey,SizeOf)
instance Pretty FieldKey where
pretty (FieldKey k) = dquotes $ pretty k
instance Arbitrary FieldKey where
arbitrary = resize 50 (FieldKey <$> genBareText)
-- -------------------------------------------------------------------------- --
-- Step
data Step n = Step
{ _sEntity :: !(Maybe n)
, _sExec :: !n
, _sRollback :: !(Maybe n)
, _sInfo :: !Info
} deriving (Eq,Show,Generic,Functor,Foldable,Traversable)
instance NFData n => NFData (Step n)
instance ToJSON n => ToJSON (Step n) where toJSON = lensyToJSON 2
instance FromJSON n => FromJSON (Step n) where parseJSON = lensyParseJSON 2
instance HasInfo (Step n) where getInfo = _sInfo
instance Pretty n => Pretty (Step n) where
pretty = \case
Step mEntity exec Nothing _i -> parensSep $
[ "step"
] ++ maybe [] (\entity -> [pretty entity]) mEntity ++
[ pretty exec
]
Step mEntity exec (Just rollback) _i -> parensSep $
[ "step-with-rollback"
] ++ maybe [] (\entity -> [pretty entity]) mEntity ++
[ pretty exec
, pretty rollback
]
instance (SizeOf n) => SizeOf (Step n)
-- -------------------------------------------------------------------------- --
-- ModRef
-- | A reference to a module or interface.
data ModRef = ModRef
{ _modRefName :: !ModuleName
-- ^ Fully-qualified module name.
, _modRefSpec :: !(Maybe [ModuleName])
-- ^ Specification: for modules, 'Just' implemented interfaces;
-- for interfaces, 'Nothing'.
, _modRefInfo :: !Info
} deriving (Eq,Show,Generic)
instance NFData ModRef
instance HasInfo ModRef where getInfo = _modRefInfo
instance Pretty ModRef where
pretty (ModRef mn _sm _i) = pretty mn
instance ToJSON ModRef where toJSON = lensyToJSON 4
instance FromJSON ModRef where parseJSON = lensyParseJSON 4
instance Ord ModRef where
(ModRef a b _) `compare` (ModRef c d _) = (a,b) `compare` (c,d)
instance Arbitrary ModRef where
arbitrary = ModRef <$> arbitrary <*> arbitrary <*> pure def
instance SizeOf ModRef where
sizeOf (ModRef n s _) = constructorCost 1 + sizeOf n + sizeOf s
-- -------------------------------------------------------------------------- --
-- ModuleGuard
data ModuleGuard = ModuleGuard
{ _mgModuleName :: !ModuleName
, _mgName :: !Text
} deriving (Eq,Generic,Show,Ord)
instance Arbitrary ModuleGuard where
arbitrary = ModuleGuard <$> arbitrary <*> genBareText
instance NFData ModuleGuard
instance Pretty ModuleGuard where
pretty ModuleGuard{..} = "ModuleGuard" <+> commaBraces
[ "module: " <> pretty _mgModuleName
, "name: " <> pretty _mgName
]
instance SizeOf ModuleGuard where
sizeOf (ModuleGuard md n) =
(constructorCost 2) + (sizeOf md) + (sizeOf n)
instance ToJSON ModuleGuard where toJSON = lensyToJSON 3
instance FromJSON ModuleGuard where parseJSON = lensyParseJSON 3
-- -------------------------------------------------------------------------- --
-- PactGuard
data PactGuard = PactGuard
{ _pgPactId :: !PactId
, _pgName :: !Text
} deriving (Eq,Generic,Show,Ord)
instance Arbitrary PactGuard where
arbitrary = PactGuard <$> arbitrary <*> genBareText
instance NFData PactGuard
instance Pretty PactGuard where
pretty PactGuard{..} = "PactGuard" <+> commaBraces
[ "pactId: " <> pretty _pgPactId
, "name: " <> pretty _pgName
]
instance SizeOf PactGuard where
sizeOf (PactGuard pid pn) =
(constructorCost 2) + (sizeOf pid) + (sizeOf pn)
instance ToJSON PactGuard where toJSON = lensyToJSON 3
instance FromJSON PactGuard where parseJSON = lensyParseJSON 3
-- -------------------------------------------------------------------------- --
-- ObjectMap
-- | Simple dictionary for object values.
newtype ObjectMap v = ObjectMap { _objectMap :: (M.Map FieldKey v) }
deriving (Eq,Ord,Show,Functor,Foldable,Traversable,Generic,SizeOf)
instance NFData v => NFData (ObjectMap v)
-- potentially long output due to constrained recursion of PactValue
instance (Eq v, FromJSON v, ToJSON v, Arbitrary v) => Arbitrary (ObjectMap v) where
arbitrary = ObjectMap <$> M.fromList <$> listOf1 arbitrary
-- | O(n) conversion to list. Adapted from 'M.toAscList'
objectMapToListWith :: (FieldKey -> v -> r) -> ObjectMap v -> [r]
objectMapToListWith f (ObjectMap m) = M.foldrWithKey (\k x xs -> (f k x):xs) [] m
instance Pretty v => Pretty (ObjectMap v) where
pretty om = annotate Val $ commaBraces $
objectMapToListWith (\k v -> pretty k <> ": " <> pretty v) om
instance ToJSON v => ToJSON (ObjectMap v)
where toJSON om =
object $ objectMapToListWith (\k v -> (asString k,toJSON v)) om
instance FromJSON v => FromJSON (ObjectMap v)
where parseJSON = withObject "ObjectMap" $ \o ->
ObjectMap . M.fromList <$>
traverse (\(k,v) -> (FieldKey k,) <$> parseJSON v) (HM.toList o)
instance Default (ObjectMap v) where
def = ObjectMap M.empty
-- -------------------------------------------------------------------------- --
-- Use
data Use = Use
{ _uModuleName :: !ModuleName
, _uModuleHash :: !(Maybe ModuleHash)
, _uImports :: !(Maybe (Vector Text))
, _uInfo :: !Info
} deriving (Show, Eq, Generic)
instance HasInfo Use where getInfo = _uInfo
instance Pretty Use where
pretty Use{..} =
let args = pretty _uModuleName : maybe [] (\mh -> [pretty mh]) _uModuleHash
in parensSep $ "use" : args
instance ToJSON Use where
toJSON Use{..} = object
[ "module" .= _uModuleName
, "hash" .= _uModuleHash
, "imports" .= _uImports
, "i" .= _uInfo
]
instance FromJSON Use where
parseJSON = withObject "Use" $ \o ->
Use <$> o .: "module"
<*> o .:? "hash"
<*> o .:? "imports"
<*> o .: "i"
instance NFData Use
instance SizeOf Use
-- -------------------------------------------------------------------------- --
-- Guard
data Guard a
= GPact !PactGuard
| GKeySet !KeySet
| GKeySetRef !KeySetName
| GModule !ModuleGuard
| GUser !(UserGuard a)
deriving (Eq,Show,Generic,Functor,Foldable,Traversable,Ord)
-- potentially long output due to constrained recursion of PactValue
instance (Arbitrary a) => Arbitrary (Guard a) where
arbitrary = oneof
[ GPact <$> arbitrary
, GKeySet <$> arbitrary
, GKeySetRef <$> arbitrary
, GModule <$> arbitrary
, GUser <$> arbitrary ]
instance NFData a => NFData (Guard a)
instance Pretty a => Pretty (Guard a) where
pretty (GPact g) = pretty g
pretty (GKeySet g) = pretty g
pretty (GKeySetRef g) = pretty g
pretty (GUser g) = pretty g
pretty (GModule g) = pretty g
instance (SizeOf p) => SizeOf (Guard p) where
sizeOf (GPact pg) = (constructorCost 1) + (sizeOf pg)
sizeOf (GKeySet ks) = (constructorCost 1) + (sizeOf ks)
sizeOf (GKeySetRef ksr) = (constructorCost 1) + (sizeOf ksr)
sizeOf (GModule mg) = (constructorCost 1) + (sizeOf mg)
sizeOf (GUser ug) = (constructorCost 1) + (sizeOf ug)
guardCodec :: (ToJSON a, FromJSON a) => Codec (Guard a)
guardCodec = Codec enc dec
where
enc (GKeySet k) = toJSON k
enc (GKeySetRef n) = object [ keyNamef .= n ]
enc (GPact g) = toJSON g
enc (GModule g) = toJSON g
enc (GUser g) = toJSON g
{-# INLINE enc #-}
dec v =
(GKeySet <$> parseJSON v) <|>
(withObject "KeySetRef" $ \o ->
GKeySetRef . KeySetName <$> o .: keyNamef) v <|>
(GPact <$> parseJSON v) <|>
(GModule <$> parseJSON v) <|>
(GUser <$> parseJSON v)
{-# INLINE dec #-}
keyNamef = "keysetref"
instance (FromJSON a,ToJSON a) => ToJSON (Guard a) where toJSON = encoder guardCodec
instance (FromJSON a,ToJSON a) => FromJSON (Guard a) where parseJSON = decoder guardCodec
-- -------------------------------------------------------------------------- --
-- Module
data Module g = Module
{ _mName :: !ModuleName
, _mGovernance :: !(Governance g)
, _mMeta :: !Meta
, _mCode :: !Code
, _mHash :: !ModuleHash
, _mBlessed :: !(HS.HashSet ModuleHash)
, _mInterfaces :: ![ModuleName]
, _mImports :: ![Use]
} deriving (Eq,Functor,Foldable,Traversable,Show,Generic)
instance NFData g => NFData (Module g)
instance Pretty g => Pretty (Module g) where
pretty Module{..} = parensSep
[ "module" , pretty _mName , pretty _mGovernance , pretty _mHash ]
instance ToJSON g => ToJSON (Module g) where toJSON = lensyToJSON 2
instance FromJSON g => FromJSON (Module g) where parseJSON = lensyParseJSON 2
instance (SizeOf g) => SizeOf (Module g)
-- -------------------------------------------------------------------------- --
-- Interface
data Interface = Interface
{ _interfaceName :: !ModuleName
, _interfaceCode :: !Code
, _interfaceMeta :: !Meta
, _interfaceImports :: ![Use]
} deriving (Eq,Show,Generic)
instance Pretty Interface where
pretty Interface{..} = parensSep [ "interface", pretty _interfaceName ]
instance ToJSON Interface where toJSON = lensyToJSON 10
instance FromJSON Interface where parseJSON = lensyParseJSON 10
instance NFData Interface
instance SizeOf Interface
-- -------------------------------------------------------------------------- --
-- Namespace
data Namespace a = Namespace
{ _nsName :: !NamespaceName
, _nsUser :: !(Guard a)
, _nsAdmin :: !(Guard a)
} deriving (Eq, Show, Generic)
instance (Arbitrary a) => Arbitrary (Namespace a) where
arbitrary = Namespace <$> arbitrary <*> arbitrary <*> arbitrary
instance Pretty (Namespace a) where
pretty Namespace{..} = "(namespace " <> prettyString (asString' _nsName) <> ")"
instance (SizeOf n) => SizeOf (Namespace n) where
sizeOf (Namespace name ug ag) =
(constructorCost 3) + (sizeOf name) + (sizeOf ug) + (sizeOf ag)
instance (ToJSON a, FromJSON a) => ToJSON (Namespace a) where toJSON = lensyToJSON 3
instance (FromJSON a, ToJSON a) => FromJSON (Namespace a) where parseJSON = lensyParseJSON 3
instance (NFData a) => NFData (Namespace a)
-- -------------------------------------------------------------------------- --
-- ModuleDef
data ModuleDef g
= MDModule !(Module g)
| MDInterface !Interface
deriving (Eq,Functor,Foldable,Traversable,Show,Generic)
instance NFData g => NFData (ModuleDef g)
instance Pretty g => Pretty (ModuleDef g) where
pretty = \case
MDModule m -> pretty m
MDInterface i -> pretty i
instance ToJSON g => ToJSON (ModuleDef g) where
toJSON (MDModule m) = toJSON m
toJSON (MDInterface i) = toJSON i
instance FromJSON g => FromJSON (ModuleDef g) where
parseJSON v = MDModule <$> parseJSON v <|> MDInterface <$> parseJSON v
instance (SizeOf g) => SizeOf (ModuleDef g)
moduleDefName :: ModuleDef g -> ModuleName
moduleDefName (MDModule m) = _mName m
moduleDefName (MDInterface m) = _interfaceName m
moduleDefCode :: ModuleDef g -> Code
moduleDefCode (MDModule m) = _mCode m
moduleDefCode (MDInterface m) = _interfaceCode m
moduleDefMeta :: ModuleDef g -> Meta
moduleDefMeta (MDModule m) = _mMeta m
moduleDefMeta (MDInterface m) = _interfaceMeta m
-- -------------------------------------------------------------------------- --
-- The following types have cyclic dependencies. There must be no TH splice
-- in between the definitions of these types.
--
-- * FunApp
-- * Ref' d (and Ref)
-- * NativeDFun
-- * Def n
-- * Object n
-- * Term n
-- -------------------------------------------------------------------------- --
-- FunApp
-- | Capture function application metadata
data FunApp = FunApp {
_faInfo :: !Info
, _faName :: !Text
, _faModule :: !(Maybe ModuleName)
, _faDefType :: !DefType
, _faTypes :: !(FunTypes (Term Name))
, _faDocs :: !(Maybe Text)
} deriving (Generic)
deriving instance (Show1 Term) => Show FunApp
deriving instance (Eq1 Term) => Eq FunApp
instance NFData FunApp
instance ToJSON FunApp where toJSON = lensyToJSON 3
instance FromJSON FunApp where parseJSON = lensyParseJSON 3
instance HasInfo FunApp where getInfo = _faInfo
-- -------------------------------------------------------------------------- --
-- Ref'
type Ref = Ref' (Term Name)
-- | Variable type for an evaluable 'Term'.
data Ref' d =
-- | "Reduced" (evaluated) or native (irreducible) term.
Direct !d |
-- | Unevaulated/un-reduced term, never a native.
Ref !(Term (Ref' d))
deriving (Functor,Foldable,Traversable,Generic)
deriving instance (Eq1 Term, Eq d) => Eq (Ref' d)
deriving instance (Show1 Term, Show d) => Show (Ref' d)
instance NFData d => NFData (Ref' d)
instance Pretty d => Pretty (Ref' d) where
pretty (Direct tm) = pretty tm
pretty (Ref tm) = pretty tm
instance HasInfo n => HasInfo (Ref' n) where
getInfo (Direct d) = getInfo d
getInfo (Ref r) = getInfo r
instance (SizeOf d) => SizeOf (Ref' d)
-- -------------------------------------------------------------------------- --
-- NativeDFun
data NativeDFun = NativeDFun
{ _nativeName :: !NativeDefName
, _nativeFun :: !(forall m . Monad m => FunApp -> [Term Ref] -> m (Gas,Term Name))
}
instance Eq NativeDFun where a == b = _nativeName a == _nativeName b
instance Show NativeDFun where
showsPrec p (NativeDFun name _) = showParen (p > 10) $
showString "NativeDFun " . showsPrec 11 name . showString " _"
instance NFData NativeDFun where
rnf (NativeDFun n _f) = seq n ()
-- -------------------------------------------------------------------------- --
-- Def
data Def n = Def
{ _dDefName :: !DefName
, _dModule :: !ModuleName
, _dDefType :: !DefType
, _dFunType :: !(FunType (Term n))
, _dDefBody :: !(Scope Int Term n)
, _dMeta :: !Meta
, _dDefMeta :: !(Maybe (DefMeta (Term n)))
, _dInfo :: !Info
} deriving (Functor,Foldable,Traversable,Generic)
deriving instance (Show1 Term, Show n) => Show (Def n)
deriving instance (Eq1 Term, Eq n) => Eq (Def n)
instance NFData (Term n) => NFData (Def n)
instance (Eq1 Term, Eq n) => Ord (Def n) where
a `compare` b = nm a `compare` nm b
where nm d = (_dModule d, _dDefName d)
instance HasInfo (Def n) where getInfo = _dInfo
instance Pretty (Term n) => Pretty (Def n) where
pretty Def{..} = parensSep $
[ prettyString (defTypeRep _dDefType)
, pretty _dModule <> "." <> pretty _dDefName <> ":" <> pretty (_ftReturn _dFunType)
, parensSep $ pretty <$> _ftArgs _dFunType
] ++ maybe [] (\docs -> [pretty docs]) (_mDocs _dMeta)
++ maybe [] (pure . pretty) _dDefMeta
instance (ToJSON (Term n), FromJSON (Term n)) => ToJSON (Def n) where toJSON = lensyToJSON 2
instance (ToJSON (Term n), FromJSON (Term n)) => FromJSON (Def n) where parseJSON = lensyParseJSON 2
derefDef :: Def n -> Name
derefDef Def{..} = QName $ QualifiedName _dModule (asString _dDefName) _dInfo
instance (SizeOf n) => SizeOf (Def n)
-- -------------------------------------------------------------------------- --
-- Lam
data Lam n
= Lam
{ _lamArg :: !Text
, _lamTy :: !(FunType (Term n))
, _lamBindBody :: !(Scope Int Term n)
, _lamInfo :: !Info
} deriving (Functor,Foldable,Traversable,Generic)
deriving instance (Show1 Term, Show n) => Show (Lam n)
deriving instance (Eq1 Term, Eq n) => Eq (Lam n)
instance HasInfo (Lam n) where getInfo = _lamInfo
instance Pretty n => Pretty (Lam n) where
pretty (Lam arg ty _ _) =
pretty arg <> ":" <> pretty (_ftReturn ty) <+> "lambda" <> (parensSep $ pretty <$> _ftArgs ty) <+> "..."
instance NFData n => NFData (Lam n)
instance (ToJSON (Term n), FromJSON (Term n)) => ToJSON (Lam n) where toJSON = lensyToJSON 2
instance (ToJSON (Term n), FromJSON (Term n)) => FromJSON (Lam n) where parseJSON = lensyParseJSON 2
instance (SizeOf n) => SizeOf (Lam n)
-- -------------------------------------------------------------------------- --
-- Object
-- | Full Term object.
data Object n = Object
{ _oObject :: !(ObjectMap (Term n))
, _oObjectType :: !(Type (Term n))
, _oKeyOrder :: !(Maybe [FieldKey])
, _oInfo :: !Info
} deriving (Functor,Foldable,Traversable,Generic)
deriving instance (Show1 Term, Show n) => Show (Object n)
deriving instance (Eq1 Term, Eq n) => Eq (Object n)
instance HasInfo (Object n) where getInfo = _oInfo
instance Pretty n => Pretty (Object n) where
pretty (Object bs _ Nothing _) = pretty bs
pretty (Object (ObjectMap om) _ (Just ko) _) =
annotate Val $ commaBraces $
map (\(k,v) -> pretty k <> ": " <> pretty v) $
sortBy (compare `on` (keyOrder . fst)) $
M.toList om
where keyOrder f = elemIndex f ko
instance NFData n => NFData (Object n)
instance (ToJSON n, FromJSON n) => ToJSON (Object n) where
toJSON Object{..} = object $
[ "obj" .= _oObject
, "type" .= _oObjectType
, "i" .= _oInfo ] ++
maybe [] (pure . ("keyorder" .=)) _oKeyOrder
instance (ToJSON n, FromJSON n) => FromJSON (Object n) where
parseJSON = withObject "Object" $ \o ->
Object <$> o .: "obj" <*> o .: "type" <*> o .:? "keyorder" <*> o .: "i"
instance (SizeOf n) => SizeOf (Object n)
-- -------------------------------------------------------------------------- --
-- Term
-- | Pact evaluable term.
data Term n =
TModule {
_tModuleDef :: !(ModuleDef (Term n))
, _tModuleBody :: !(Scope () Term n)
, _tInfo :: !Info
} |
TList {
_tList :: !(Vector (Term n))
, _tListType :: !(Type (Term n))
, _tInfo :: !Info
} |
TDef {
_tDef :: Def n
, _tInfo :: !Info
} |
TNative {
_tNativeName :: !NativeDefName
, _tNativeFun :: !NativeDFun
, _tFunTypes :: !(FunTypes (Term n))
, _tNativeExamples :: ![Example]
, _tNativeDocs :: !Text
, _tNativeTopLevelOnly :: !Bool
, _tInfo :: !Info
} |
TConst {
_tConstArg :: !(Arg (Term n))
, _tModule :: !(Maybe ModuleName)
, _tConstVal :: !(ConstVal (Term n))
, _tMeta :: !Meta
, _tInfo :: !Info
} |
TApp {
_tApp :: !(App (Term n))
, _tInfo :: !Info
} |
TVar {
_tVar :: !n
, _tInfo :: !Info
} |
TBinding {
_tBindPairs :: ![BindPair (Term n)]
, _tBindBody :: !(Scope Int Term n)
, _tBindType :: !(BindType (Type (Term n)))
, _tInfo :: !Info
} |
TLam {
_tLam :: Lam n
, _tInfo :: !Info
} |
TObject {
_tObject :: !(Object n)
, _tInfo :: !Info
} |
TSchema {
_tSchemaName :: !TypeName
, _tModule :: !(Maybe ModuleName)
, _tMeta :: !Meta
, _tFields :: ![Arg (Term n)]
, _tInfo :: !Info
} |
TLiteral {
_tLiteral :: !Literal
, _tInfo :: !Info
} |
TGuard {
_tGuard :: !(Guard (Term n))
, _tInfo :: !Info
} |
TUse {
_tUse :: !Use
, _tInfo :: !Info
} |
TStep {
_tStep :: !(Step (Term n))
, _tMeta :: !Meta
, _tInfo :: !Info
} |
TModRef {
_tModRef :: !ModRef
, _tInfo :: !Info
} |
TTable {
_tTableName :: !TableName
, _tModuleName :: !ModuleName
, _tHash :: !ModuleHash
, _tTableType :: !(Type (Term n))
, _tMeta :: !Meta
, _tInfo :: !Info
} |
TDynamic {
_tDynModRef :: !(Term n)
, _tDynMember :: !(Term n)
, _tInfo :: !Info
}
deriving (Functor,Foldable,Traversable,Generic)
deriving instance (Show1 Term, Show n) => Show (Term n)
deriving instance (Eq1 Term, Eq n) => Eq (Term n)
instance NFData n => NFData (Term n)
instance HasInfo (Term n) where
getInfo t = case t of
TApp{..} -> getInfo _tApp
TBinding{..} -> _tInfo
TConst{..} -> _tInfo
TDef{..} -> getInfo _tDef
TGuard{..} -> _tInfo
TList{..} -> _tInfo
TLiteral{..} -> _tInfo
TModule{..} -> _tInfo
TNative{..} -> _tInfo
TObject{..} -> getInfo _tObject
TSchema{..} -> _tInfo
TLam{..} -> _tInfo
TStep{..} -> _tInfo
TTable{..} -> _tInfo
TUse{..} -> getInfo _tUse
TVar{..} -> _tInfo
TDynamic{..} -> _tInfo
TModRef{..} -> _tInfo
instance Pretty n => Pretty (Term n) where
pretty = \case
TModule{..} -> pretty _tModuleDef
TList{..} -> bracketsSep $ pretty <$> V.toList _tList
TDef{..} -> pretty _tDef
TNative{..} -> annotate Header ("native `" <> pretty _tNativeName <> "`")
<> nest 2 (
line
<> line <> fillSep (pretty <$> T.words _tNativeDocs)
<> line
<> line <> annotate Header "Type:"
<> line <> align (vsep (prettyFunType <$> toList _tFunTypes))
<> examples
) where examples = case _tNativeExamples of
[] -> mempty
exs ->
line <> line <> annotate Header "Examples:"
<> line <> align (vsep (pretty <$> exs))
TConst{..} -> "constant "
<> maybe "" ((<>) "." . pretty) _tModule
<> pretty _tConstArg
<> " " <> pretty _tMeta
TApp a _ -> pretty a
TVar n _ -> pretty n
TBinding pairs body BindLet _i -> parensSep
[ "let"
, parensSep $ fmap pretty pairs
, pretty $ unscope body
]
TBinding pairs body (BindSchema _) _i -> parensSep
[ commaBraces $ fmap pretty pairs
, pretty $ unscope body
]
TLam lam _ -> pretty lam
TObject o _ -> pretty o
TLiteral l _ -> annotate Val $ pretty l
TGuard k _ -> pretty k
TUse u _ -> pretty u
TStep s _meta _i -> pretty s
TSchema{..} -> parensSep
[ "defschema"
, pretty _tSchemaName
, pretty _tMeta
, prettyList _tFields
]
TTable{..} -> parensSep
[ "deftable"
, pretty _tTableName <> ":" <> pretty (fmap prettyTypeTerm _tTableType)
, pretty _tMeta
]
TDynamic ref var _i -> pretty ref <> "::" <> pretty var
TModRef mr _ -> pretty mr
where
prettyFunType (FunType as r) = pretty (FunType (map (fmap prettyTypeTerm) as) (prettyTypeTerm <$> r))
prettyTypeTerm :: Term n -> SpecialPretty (Term n)
prettyTypeTerm TSchema{..} = SPSpecial ("{" <> asString _tSchemaName <> "}")
prettyTypeTerm t = SPNormal t
instance SizeOf1 Term where
sizeOf1 = \case
TModule defn body info ->
constructorCost 3 + sizeOf defn + sizeOf body + sizeOf info
TList li typ info ->
constructorCost 3 + sizeOf li + sizeOf typ + sizeOf info
TDef defn info ->
constructorCost 2 + sizeOf defn + sizeOf info
-- note: we actually strip docs and examples
-- post fork
TNative name _defun ftyps examples docs tlo info ->
constructorCost 7 + sizeOf name + sizeOf ftyps + sizeOf examples +
sizeOf docs + sizeOf tlo + sizeOf info
TConst arg mname cval meta info ->
constructorCost 5 + sizeOf arg + sizeOf mname + sizeOf cval + sizeOf meta + sizeOf info
TApp app info ->
constructorCost 2 + sizeOf app + sizeOf info
TVar v info ->
constructorCost 2 + sizeOf v + sizeOf info
TBinding bps body btyp info ->
constructorCost 4 + sizeOf bps + sizeOf body + sizeOf btyp + sizeOf info
TLam lam info ->
constructorCost 2 + sizeOf lam + sizeOf info
TObject obj info ->
constructorCost 2 + sizeOf obj + sizeOf info
TSchema tn mn meta args info ->
constructorCost 5 + sizeOf tn + sizeOf mn + sizeOf meta + sizeOf args + sizeOf info
TLiteral lit info ->
constructorCost 2 + sizeOf lit + sizeOf info
TGuard g info ->
constructorCost 2 + sizeOf g + sizeOf info
TUse u info->
constructorCost 2 + sizeOf u + sizeOf info
TStep step meta info ->
constructorCost 3 + sizeOf step + sizeOf meta + sizeOf info
TModRef mr info ->
constructorCost 2 + sizeOf mr + sizeOf info
TTable tn mn hs typ meta info ->
constructorCost 6 + sizeOf tn + sizeOf mn + sizeOf hs + sizeOf typ
+ sizeOf meta + sizeOf info
TDynamic e1 e2 info ->
constructorCost 3 + sizeOf e1 + sizeOf e2 + sizeOf info
instance (SizeOf a) => SizeOf (Term a) where
sizeOf t = sizeOf1 t
instance Applicative Term where
pure = return
(<*>) = ap
instance Monad Term where
return a = TVar a def
TModule m b i >>= f = TModule (fmap (>>= f) m) (b >>>= f) i
TList bs t i >>= f = TList (V.map (>>= f) bs) (fmap (>>= f) t) i
TDef (Def n m dt ft b d dm i) i' >>= f =
TDef (Def n m dt (fmap (>>= f) ft) (b >>>= f) d (fmap (fmap (>>= f)) dm) i) i'
TNative n fn t exs d tl i >>= f = TNative n fn (fmap (fmap (>>= f)) t) exs d tl i
TConst d m c t i >>= f = TConst (fmap (>>= f) d) m (fmap (>>= f) c) t i
TApp a i >>= f = TApp (fmap (>>= f) a) i
TVar n i >>= f = (f n) { _tInfo = i }
TBinding bs b c i >>= f =
TBinding (map (fmap (>>= f)) bs) (b >>>= f) (fmap (fmap (>>= f)) c) i
TLam (Lam arg ty b i) i' >>= f =
TLam (Lam arg (fmap (>>= f) ty) (b >>>= f) i) i'
TObject (Object bs t kf oi) i >>= f =
TObject (Object (fmap (>>= f) bs) (fmap (>>= f) t) kf oi) i
TLiteral l i >>= _ = TLiteral l i
TGuard g i >>= f = TGuard (fmap (>>= f) g) i
TUse u i >>= _ = TUse u i
TStep (Step ent e r si) meta i >>= f =
TStep (Step (fmap (>>= f) ent) (e >>= f) (fmap (>>= f) r) si) meta i
TSchema {..} >>= f =
TSchema _tSchemaName _tModule _tMeta (fmap (fmap (>>= f)) _tFields) _tInfo
TTable {..} >>= f =
TTable _tTableName _tModuleName _tHash (fmap (>>= f) _tTableType) _tMeta _tInfo
TDynamic r m i >>= f = TDynamic (r >>= f) (m >>= f) i
TModRef mr i >>= _ = TModRef mr i
termCodec :: (ToJSON n, FromJSON n) => Codec (Term n)
termCodec = Codec enc dec
where
enc t = case t of
TModule d b i -> ob [ moduleDef .= d, body .= b, inf i ]
TList ts ty i -> ob [ list' .= ts, type' .= ty, inf i ]
TDef d _i -> toJSON d
-- TNative intentionally not marshallable
TNative n _fn tys _exs d tl i ->
ob [ natName .= n, natFun .= Null {- TODO fn -}
, natFunTypes .= tys, natExamples .= Null {- TODO exs -},
natDocs .= d, natTopLevel .= tl, inf i ]
TConst d m c met i ->
ob [ constArg .= d, modName .= m, constVal .= c, meta .= met, inf i ]
TApp a _i -> toJSON a
TVar n i -> ob [ var .= n, inf i ]
TBinding bs b c i -> ob [pairs .= bs, body .= b, type' .= c, inf i]
TObject o _i -> toJSON o
TLiteral l i -> ob [literal .= l, inf i]
TLam tlam _i -> toJSON tlam
TGuard k i -> ob [guard' .= k, inf i]
TUse u _i -> toJSON u
TStep s tmeta i -> ob [body .= s, meta .= tmeta, inf i]
TSchema sn smod smeta sfs i ->
ob [ schemaName .= sn, modName .= smod, meta .= smeta
, fields .= sfs, inf i ]
TTable tn tmod th tty tmeta i ->
ob [ tblName .= tn, modName .= tmod, hash' .= th, type' .= tty
, meta .= tmeta, inf i ]
TDynamic r m i ->
ob [ dynRef .= r, dynMem .= m, inf i ]
TModRef mr _i -> toJSON mr
dec decval =
let wo n f = withObject n f decval
parseWithInfo f = uncurry f . (id &&& getInfo) <$> parseJSON decval
in
wo "Module" (\o -> TModule <$> o .: moduleDef <*> o .: body <*> inf' o)
<|> wo "List"
(\o -> TList <$> o .: list' <*> o .: type' <*> inf' o)
<|> parseWithInfo TDef
-- TNative intentionally not marshallable
<|> wo "Const"
(\o -> TConst <$> o .: constArg <*> o .: modName
<*> o .: constVal <*> o .: meta <*> inf' o )
<|> parseWithInfo TApp
<|> wo "Var" (\o -> TVar <$> o .: var <*> inf' o )
<|> wo "Binding"
(\o -> TBinding <$> o .: pairs <*> o .: body
<*> o .: type' <*> inf' o)
<|> parseWithInfo TObject
<|> wo "Literal" (\o -> TLiteral <$> o .: literal <*> inf' o)
<|> wo "Guard" (\o -> TGuard <$> o .: guard' <*> inf' o)
<|> parseWithInfo TUse
<|> parseWithInfo TLam
<|> wo "Step"
(\o -> TStep <$> o .: body <*> o .: meta <*> inf' o)
-- parseWithInfo TStep
<|> wo "Schema"
(\o -> TSchema <$> o .: schemaName <*> o .: modName
<*> o .: meta <*> o .: fields <*> inf' o )
<|> wo "Table"
(\o -> TTable <$> o .: tblName <*> o .: modName
<*> o .: hash' <*> o .: type'
<*> o .: meta <*> inf' o )
<|> wo "Dynamic"
(\o -> TDynamic <$> o .: dynRef <*> o .: dynMem <*> inf' o)
<|> parseWithInfo TModRef
ob = object
moduleDef = "module"
body = "body"
meta = "meta"
inf i = "i" .= i
inf' o = o .: "i"
list' = "list"
type' = "type"
natName = "name"
natFun = "fun"
natFunTypes = "types"
natExamples = "examples"
natDocs = "docs"
natTopLevel = "tl"
constArg = "arg"
modName = "modname"
constVal = "val"
var = "var"
pairs = "pairs"
literal = "lit"
guard' = "guard"
schemaName = "name"
fields = "fields"
tblName = "name"
hash' = "hash"
dynRef = "dref"
dynMem = "dmem"
instance (ToJSON n, FromJSON n) => FromJSON (Term n) where
parseJSON = decoder termCodec
instance (ToJSON n, FromJSON n) => ToJSON (Term n) where
toJSON = encoder termCodec
-- -------------------------------------------------------------------------- --
-- ToTerm
class ToTerm a where
toTerm :: a -> Term m
instance ToTerm Bool where toTerm = tLit . LBool
instance ToTerm Integer where toTerm = tLit . LInteger
instance ToTerm Int where toTerm = tLit . LInteger . fromIntegral
instance ToTerm Decimal where toTerm = tLit . LDecimal
instance ToTerm Text where toTerm = tLit . LString
instance ToTerm KeySet where toTerm k = TGuard (GKeySet k) def
instance ToTerm Literal where toTerm = tLit
instance ToTerm UTCTime where toTerm = tLit . LTime
instance ToTerm Word32 where toTerm = tLit . LInteger . fromIntegral
instance ToTerm Word64 where toTerm = tLit . LInteger . fromIntegral
instance ToTerm Int64 where toTerm = tLit . LInteger . fromIntegral
instance ToTerm TableName where toTerm = tLit . LString . asString
instance ToTerm PactId where toTerm (PactId t) = toTerm t
toTermList :: (ToTerm a,Foldable f) => Type (Term b) -> f a -> Term b
toTermList ty l = TList (V.map toTerm (V.fromList (toList l))) ty def
-- | Convenience for OverloadedStrings annoyances
tStr :: Text -> Term n
tStr = toTerm
-- -------------------------------------------------------------------------- --
-- Miscelaneous Functions
tLit :: Literal -> Term n
tLit = (`TLiteral` def)
{-# INLINE tLit #-}
-- Support 'termEq' in Ref'
refEq :: Eq1 Guard => Eq n => Ref' (Term n) -> Ref' (Term n) -> Bool
refEq a b = case (a,b) of
(Direct x,Direct y) -> termEq x y
(Ref x,Ref y) -> termEq1 refEq x y
_ -> False
toTObject :: Type (Term n) -> Info -> [(FieldKey,Term n)] -> Term n
toTObject ty i = toTObjectMap ty i . ObjectMap . M.fromList
toTObjectMap :: Type (Term n) -> Info -> ObjectMap (Term n) -> Term n
toTObjectMap ty i m = TObject (Object m ty def i) i
toTList :: Type (Term n) -> Info -> [Term n] -> Term n
toTList ty i = toTListV ty i . V.fromList
toTListV :: Type (Term n) -> Info -> V.Vector (Term n) -> Term n
toTListV ty i vs = TList vs ty i
guardTypeOf :: Guard a -> GuardType
guardTypeOf g = case g of
GKeySet{} -> GTyKeySet
GKeySetRef{} -> GTyKeySetName
GPact {} -> GTyPact
GUser {} -> GTyUser
GModule {} -> GTyModule
-- | Return a Pact type, or a String description of non-value Terms.
-- Does not handle partial schema types.
typeof :: Term a -> Either Text (Type (Term a))
typeof t = case t of
TLiteral l _ -> Right $ TyPrim $ litToPrim l
TModule{}-> Left "module"
TList {..} -> Right $ TyList _tListType
TDef{..} -> Right $ TyFun (_dFunType _tDef)
TNative {} -> Left "defun"
TConst {..} -> Left $ "const:" <> _aName _tConstArg
TApp {} -> Left "app"
TVar {} -> Left "var"
TBinding {..} -> case _tBindType of
BindLet -> Left "let"
BindSchema bt -> Right $ TySchema TyBinding bt def
-- This will likely change later on.
TLam{..} -> Right $ TyFun (_lamTy _tLam)
TObject (Object {..}) _ -> Right $ TySchema TyObject _oObjectType def
TGuard {..} -> Right $ TyPrim $ TyGuard $ Just $ guardTypeOf _tGuard
TUse {} -> Left "use"
TStep {} -> Left "step"
TSchema {..} -> Left $ "defobject:" <> asString _tSchemaName
TTable {..} -> Right $ TySchema TyTable _tTableType def
TDynamic {} -> Left "dynamic"
TModRef m _ -> Right $ modRefTy m
{-# INLINE typeof #-}
-- | Populate 'TyModule' using a 'ModRef'
modRefTy :: ModRef -> Type (Term a)
modRefTy (ModRef _mn is _) = TyModule $ fmap (map (\i -> TModRef (ModRef i Nothing def) def)) is
-- | Return string type description.
typeof' :: Pretty a => Term a -> Text
typeof' = either id renderCompactText . typeof
pattern TLitString :: Text -> Term t
pattern TLitString s <- TLiteral (LString s) _
pattern TLitInteger :: Integer -> Term t
pattern TLitInteger i <- TLiteral (LInteger i) _
pattern TLitBool :: Bool -> Term t
pattern TLitBool b <- TLiteral (LBool b) _
-- | Equality dictionary for term-level equality
--
canEq :: Term n -> Term n -> Bool
canEq TList{} TList{} = True
canEq TObject{} TObject{} = True
canEq TLiteral{} TLiteral{} = True
canEq TTable{} TTable{} = True
canEq TSchema{} TSchema{} = True
canEq TGuard{} TGuard{} = True
canEq TModRef{} TModRef{} = True
canEq _ _ = False
-- | Support pact `=` for value-level terms
-- and TVar for types.
termEq :: Eq1 Guard => Eq n => Term n -> Term n -> Bool
termEq a b = termEq1 (==) a b
-- | Support 'termEq' for 'Term Ref'
termRefEq :: Eq1 Guard => Term Ref -> Term Ref -> Bool
termRefEq = termEq1 refEq
-- | Lifted version; support pact `=` for value-level terms
-- and TVar for types.
termEq1 :: Eq1 Guard => (n -> n -> Bool) -> Term n -> Term n -> Bool
termEq1 eq (TList a _ _) (TList b _ _) = length a == length b && and (V.zipWith (termEq1 eq) a b)
termEq1 eq (TObject (Object (ObjectMap a) _ _ _) _) (TObject (Object (ObjectMap b) _ _ _) _) =
-- O(3n), 2x M.toList + short circuiting walk
M.size a == M.size b && go (M.toList a) (M.toList b) True
where go _ _ False = False
go ((k1,v1):r1) ((k2,v2):r2) _ = go r1 r2 $ k1 == k2 && (termEq1 eq v1 v2)
go [] [] _ = True
go _ _ _ = False
termEq1 _ (TLiteral a _) (TLiteral b _) = a == b
termEq1 eq (TGuard a _) (TGuard b _) = liftEq (termEq1 eq) a b
termEq1 eq (TTable a b c d x _) (TTable e f g h y _) = a == e && b == f && c == g && liftEq (termEq1 eq) d h && x == y
termEq1 eq (TSchema a b c d _) (TSchema e f g h _) = a == e && b == f && c == g && length d == length h && and (zipWith (argEq1 (termEq1 eq)) d h)
termEq1 eq (TVar a _) (TVar b _) = eq a b
termEq1 _ (TModRef (ModRef am as _) _) (TModRef (ModRef bm bs _) _) = am == bm && as == bs
termEq1 _ _ _ = False
-- | Workhorse runtime typechecker on `Type (Term n)` to specialize
-- 'unifiesWith' on Term/'termEq'.
-- First argument is spec, second is value.
canUnifyWith :: Eq1 Guard => Eq n => Type (Term n) -> Type (Term n) -> Bool
canUnifyWith = unifiesWith termEq
-- -------------------------------------------------------------------------- --
-- Lenses
makeLenses ''Namespace
makeLenses ''Meta
makeLenses ''Module
makeLenses ''Interface
makePrisms ''ModuleDef
makeLenses ''App
makePrisms ''DefType
makeLenses ''BindPair
makeLenses ''Step
makeLenses ''ModuleHash
makeLenses ''ModRef
makePrisms ''Guard
makeLenses ''FunApp
makePrisms ''Ref'
makeLenses ''Def
makeLenses ''Lam
makeLenses ''Object
makeLenses ''Term
makePrisms ''Term
-- This noop TH splice is required to ensure that all types that are defined
-- above in this module are available in the type environment of the following
-- TH splices.
--
return []
-- -------------------------------------------------------------------------- --
-- Eq1 Instances
instance Eq1 Guard where
liftEq = $(makeLiftEq ''Guard)
instance Eq1 UserGuard where
liftEq = $(makeLiftEq ''UserGuard)
instance Eq1 BindPair where
liftEq = $(makeLiftEq ''BindPair)
instance Eq1 App where
liftEq = $(makeLiftEq ''App)
instance Eq1 BindType where
liftEq = $(makeLiftEq ''BindType)
instance Eq1 ConstVal where
liftEq = $(makeLiftEq ''ConstVal)
instance Eq1 DefcapMeta where
liftEq = $(makeLiftEq ''DefcapMeta)
instance Eq1 DefMeta where
liftEq = $(makeLiftEq ''DefMeta)
instance Eq1 ModuleDef where
liftEq = $(makeLiftEq ''ModuleDef)
instance Eq1 Module where
liftEq = $(makeLiftEq ''Module)
instance Eq1 Governance where
liftEq = $(makeLiftEq ''Governance)
instance Eq1 ObjectMap where
liftEq = $(makeLiftEq ''ObjectMap)
instance Eq1 Step where
liftEq = $(makeLiftEq ''Step)
instance Eq1 Def where
liftEq = $(makeLiftEq ''Def)
instance Eq1 Lam where
liftEq = $(makeLiftEq ''Lam)
instance Eq1 Object where
liftEq = $(makeLiftEq ''Object)
instance Eq1 Term where
liftEq = $(makeLiftEq ''Term)
-- -------------------------------------------------------------------------- --
-- Show1 Instances
instance Show1 Guard where
liftShowsPrec = $(makeLiftShowsPrec ''Guard)
instance Show1 UserGuard where
liftShowsPrec = $(makeLiftShowsPrec ''UserGuard)
instance Show1 BindPair where
liftShowsPrec = $(makeLiftShowsPrec ''BindPair)
instance Show1 App where
liftShowsPrec = $(makeLiftShowsPrec ''App)
instance Show1 ObjectMap where
liftShowsPrec = $(makeLiftShowsPrec ''ObjectMap)
instance Show1 BindType where
liftShowsPrec = $(makeLiftShowsPrec ''BindType)
instance Show1 ConstVal where
liftShowsPrec = $(makeLiftShowsPrec ''ConstVal)
instance Show1 DefcapMeta where
liftShowsPrec = $(makeLiftShowsPrec ''DefcapMeta)
instance Show1 DefMeta where
liftShowsPrec = $(makeLiftShowsPrec ''DefMeta)
instance Show1 ModuleDef where
liftShowsPrec = $(makeLiftShowsPrec ''ModuleDef)
instance Show1 Module where
liftShowsPrec = $(makeLiftShowsPrec ''Module)
instance Show1 Governance where
liftShowsPrec = $(makeLiftShowsPrec ''Governance)
instance Show1 Step where
liftShowsPrec = $(makeLiftShowsPrec ''Step)
instance Show1 Def where
liftShowsPrec = $(makeLiftShowsPrec ''Def)
instance Show1 Lam where
liftShowsPrec = $(makeLiftShowsPrec ''Lam)
instance Show1 Object where
liftShowsPrec = $(makeLiftShowsPrec ''Object)
instance Show1 Term where
liftShowsPrec = $(makeLiftShowsPrec ''Term)
| kadena-io/pact | src/Pact/Types/Term.hs | bsd-3-clause | 52,383 | 0 | 34 | 11,356 | 18,703 | 9,627 | 9,076 | 1,451 | 19 |
-- | The Github Search API, as described at
-- <http://developer.github.com/v3/search/>.
module Github.Search(
searchRepos'
,searchRepos
,module Github.Data
) where
import Github.Data
import Github.Private
-- | Perform a repository search.
-- | With authentication.
--
-- > searchRepos' (Just $ GithubBasicAuth "github-username" "github-password') "q=a in%3Aname language%3Ahaskell created%3A>2013-10-01&per_page=100"
searchRepos' :: Maybe GithubAuth -> String -> IO (Either Error SearchReposResult)
searchRepos' auth queryString = githubGetWithQueryString' auth ["search/repositories"] queryString
-- | Perform a repository search.
-- | Without authentication.
--
-- > searchRepos "q=a in%3Aname language%3Ahaskell created%3A>2013-10-01&per_page=100"
searchRepos :: String -> IO (Either Error SearchReposResult)
searchRepos = searchRepos' Nothing
| mavenraven/github | Github/Search.hs | bsd-3-clause | 854 | 0 | 9 | 101 | 115 | 66 | 49 | 10 | 1 |
{-# LANGUAGE TemplateHaskell, ViewPatterns, FlexibleInstances #-}
module Math.CurveGenerator
(CurveInput(..)
, CurveOptions(..)
, GridOptions(..)
, AxisOptions(..)
, TangentsOptions(..)
, CGConfig(..)
, PointInfo(..)
, Curve(..)
, saveConfig
, loadConfig
, drawingTangent
, createCurve) where
import Diagrams.Prelude
import Diagrams.Coordinates
import Data.Maybe
import Data.SafeCopy
import Data.Default
import Data.ByteString (ByteString)
import Data.Serialize
-- All major input types and the configuration that holds them all
data CurveInput = CurvePointsAndT { looseness :: Double, pointsWithT :: [(P2, Maybe Double, Bool)] }
| CurveFunction { func :: String, wantTangents :: [Double] }
instance Default CurveInput where
def = CurvePointsAndT { looseness=0.4, pointsWithT=[] }
instance SafeCopy (Point R2) where
putCopy (coords -> x :& y) = contain $ safePut x >> safePut y
getCopy = contain $ curry p2 <$> safeGet <*> safeGet
deriveSafeCopy 1 'base ''CurveInput
data CurveOptions = CurveOpts { curveColor :: String, curveStyle :: String }
instance Default CurveOptions where
def = CurveOpts { curveColor="black", curveStyle="solid" } -- Allowed curveStyle : solid, dashed, dotted
deriveSafeCopy 1 'base ''CurveOptions
data GridOptions = GridOpts { dxMajor, dyMajor, dxMinor, dyMinor :: Double, majorGrid, minorGrid :: Bool }
instance Default GridOptions where
def = GridOpts 1 1 0.2 0.2 True False
deriveSafeCopy 1 'base ''GridOptions
data AxisOptions = AxisOpts { xMin, xMax, yMin, yMax, xOrig, yOrig, xTicks, yTicks :: Double }
instance Default AxisOptions where
def = AxisOpts { xMin=(-8), xMax=8, yMin=(-6), yMax=6, xTicks=1, yTicks=1, xOrig=0, yOrig=0 }
deriveSafeCopy 1 'base ''AxisOptions
data TangentsOptions = TanOpts { tangentLen :: Double, tangentColor :: String, tangentStyle :: String }
instance Default TangentsOptions where
def = TanOpts { tangentLen = 2, tangentColor = "black", tangentStyle = "solid" }
deriveSafeCopy 1 'base ''TangentsOptions
data CGConfig = CGConfig { curveInputs :: [(CurveInput, CurveOptions)]
, gridOptions :: GridOptions
, axisOptions :: AxisOptions
, tangentsOptions :: TangentsOptions
, comments :: Bool
}
instance Default CGConfig where
def = CGConfig (replicate 10 (def,def)) def def def False
deriveSafeCopy 1 'base ''CGConfig
saveConfig :: CGConfig -> ByteString
saveConfig = runPut . safePut
loadConfig :: ByteString -> Either String CGConfig
loadConfig = runGet safeGet
data PointInfo = Through { piPoint :: P2, tangent :: R2, drawTangent :: Bool } | Control { piPoint :: P2 }
data Curve = BezierJoints [PointInfo]
drawingTangent :: PointInfo -> Bool
drawingTangent (Through _ _ True) = True
drawingTangent _ = False
createCurve :: CurveInput -> Curve
createCurve (CurvePointsAndT e params@((lextr,t, b):(p2,_,_):ps)) = BezierJoints $ Through lextr dv b : Control clextr : go params
where
dv = computeDVector (centralSymAbout lextr p2) lextr p2 t
clextr = lextr .+^ (e *^ dv)
go [(pbl,_,_),(rextr,t, b)] = [Control crextr, Through rextr dv b]
where
dv = computeDVector pbl rextr (centralSymAbout rextr pbl) t
crextr = rextr .-^ (e *^ dv)
go ((p1,_,_):ps@((p2,t,b):(p3,_,_):_)) = Control lcp : Through p2 dv b : Control rcp : go ps
where
dv = computeDVector p1 p2 p3 t
lcp = p2 .-^ (e *^ dv)
rcp = p2 .+^ (e *^ dv)
createCurve _ = BezierJoints []
computeDVector :: P2 -> P2 -> P2 -> Maybe Double -> R2
computeDVector (coords -> lx :& ly) (coords -> mx :& my) (coords -> rx :& ry) givenT
| (ly - my)*(ry - my) > 0 && isNothing givenT = x ^& 0
| otherwise = x ^& y
where
t = fromMaybe ((ly-ry)/(lx-rx)) givenT
x = min (mx - lx) (rx - mx)
y = t*x
centralSymAbout c = rotateAbout c (1/2 @@ turn)
| ocramz/CurveProject | src/Math/CurveGenerator.hs | bsd-3-clause | 4,007 | 0 | 14 | 926 | 1,393 | 793 | 600 | 82 | 2 |
{-# LANGUAGE TypeApplications, ScopedTypeVariables #-}
module Lamdu.Eval.Results.Process
( addTypes
) where
import qualified Control.Lens as Lens
import qualified Data.Map as Map
import qualified Data.Text as Text
import Hyper
import Hyper.Class.Optic (HNodeLens(..))
import qualified Hyper.Syntax.Nominal as N
import Hyper.Syntax.Row (RowExtend(..))
import qualified Hyper.Syntax.Row as Row
import Hyper.Syntax.Scheme (sTyp, _QVarInstances, QVarInstances, Scheme)
import Hyper.Unify.QuantifiedVar (HasQuantifiedVar(..))
import qualified Lamdu.Builtins.Anchors as Builtins
import qualified Lamdu.Calc.Type as T
import Lamdu.Eval.Results (Val, Body(..))
import qualified Lamdu.Eval.Results as ER
import Lamdu.Prelude
extractRecordTypeField :: T.Tag -> Pure # T.Type -> Maybe (Pure # T.Type, Pure # T.Type)
extractRecordTypeField tag typ =
do
flat <- typ ^? _Pure . T._TRecord . T.flatRow
fieldType <- flat ^. Row.freExtends . Lens.at tag
Just
( fieldType
, _Pure . T._TRecord . T.flatRow # (flat & Row.freExtends . Lens.at tag .~ Nothing)
)
extractVariantTypeField :: T.Tag -> Pure # T.Type -> Maybe (Pure # T.Type)
extractVariantTypeField tag typ =
typ ^? _Pure . T._TVariant . T.flatRow
>>= (^. Row.freExtends . Lens.at tag)
type AddTypes val f = (Pure # T.Type -> val -> f :# Body) -> Pure # T.Type -> Body f
typeError :: String -> Body val
typeError = RError . ER.EvalTypeError . Text.pack
addTypesRecExtend ::
RowExtend T.Tag val val # k ->
(Pure # T.Type -> k # val -> f # Body) ->
Pure # T.Type ->
Body # f
addTypesRecExtend (RowExtend tag val rest) go typ =
case extractRecordTypeField tag typ of
Nothing ->
-- TODO: this is a work-around for a bug. HACK
-- we currently don't know types for eval results of polymorphic values
case typ ^. _Pure of
T.TVar{} ->
RowExtend tag
(go typ val)
(go typ rest)
& RRecExtend
T.TInst{} ->
-- Work around for MutRefs: todo better presentation which shows their current value?
RRecEmpty
_ -> "addTypesRecExtend got " ++ show typ & typeError
Just (valType, restType) ->
RowExtend tag
(go valType val)
(go restType rest)
& RRecExtend
addTypesInject :: ER.Inject # Ann a -> AddTypes (Ann a # Body) f
addTypesInject (ER.Inject tag val) go typ =
case extractVariantTypeField tag typ of
Nothing ->
-- TODO: this is a work-around for a bug. HACK
-- we currently don't know types for eval results of polymorphic values
case typ ^. _Pure of
T.TVar{} -> go typ val & ER.Inject tag & RInject
_ -> "addTypesInject got " ++ show typ & typeError
Just valType -> go valType val & ER.Inject tag & RInject
addTypesArray :: [val] -> AddTypes val f
addTypesArray items go typ =
case typ ^? _Pure . T._TInst . N.nArgs . hNodeLens . _QVarInstances . Lens.ix Builtins.valTypeParamId of
Nothing ->
-- TODO: this is a work-around for a bug. HACK
-- we currently don't know types for eval results of polymorphic values
case typ ^. _Pure of
T.TVar{} -> items <&> go typ & RArray
_ -> "addTypesArray got " ++ show typ & typeError
Just paramType -> items <&> go paramType & RArray
addTypes :: Map T.NominalId (Pure # N.NominalDecl T.Type) -> Pure # T.Type -> Val () -> Val (Pure # T.Type)
addTypes nomsMap typ (Ann (Const ()) b) =
case b of
RRecExtend recExtend -> r (addTypesRecExtend recExtend)
RInject inject -> r (addTypesInject inject)
RArray items -> r (addTypesArray items)
RFunc x -> RFunc x
RRecEmpty -> RRecEmpty
RPrimVal l -> RPrimVal l
RError e -> RError e
& Ann (Const typ)
where
r f = f (addTypes nomsMap) (unwrapTInsts nomsMap typ)
class
(HFunctor k, HasQuantifiedVar k, Ord (QVar k), HNodeLens T.Types k) =>
ApplyNominal k where
applyNominalRecursive :: Proxy k -> Dict (HNodesConstraint k ApplyNominal)
instance ApplyNominal T.Type where applyNominalRecursive _ = Dict
instance ApplyNominal T.Row where applyNominalRecursive _ = Dict
applyNominal ::
Pure # N.NominalDecl T.Type ->
T.Types # QVarInstances Pure ->
Pure # Scheme T.Types T.Type
applyNominal nom params =
_Pure # (nom ^. _Pure . N.nScheme & sTyp %~ subst params)
subst ::
forall t.
ApplyNominal t =>
T.Types # QVarInstances Pure ->
Pure # t ->
Pure # t
subst params (Pure x) =
withDict (applyNominalRecursive (Proxy @t)) $
_Pure #
case x ^? quantifiedVar of
Nothing -> hmap (Proxy @ApplyNominal #> subst params) x
Just q ->
params ^?
hNodeLens . _QVarInstances . Lens.ix q . _Pure
& fromMaybe (quantifiedVar # q)
-- Will loop forever for bottoms like: newtype Void = Void Void
unwrapTInsts :: Map T.NominalId (Pure # N.NominalDecl T.Type) -> Pure # T.Type -> Pure # T.Type
unwrapTInsts nomsMap typ =
case typ ^. _Pure of
T.TInst (N.NominalInst tid params) ->
Map.lookup tid nomsMap
<&> (\nominalInst -> applyNominal nominalInst params ^. _Pure . sTyp)
<&> unwrapTInsts nomsMap
& fromMaybe typ
_ -> typ
| lamdu/lamdu | src/Lamdu/Eval/Results/Process.hs | gpl-3.0 | 5,329 | 0 | 15 | 1,397 | 1,714 | 880 | 834 | -1 | -1 |
-----------------------------------------------------------------------------
-- |
-- Copyright : (C) 2013-15 Edward Kmett
-- License : BSD-style (see the file LICENSE)
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : experimental
-- Portability : non-portable
--
-- Utility functions for the RRR class and offset representation
-----------------------------------------------------------------------------
module Succinct.Internal.Binomial
( binomial
, logBinomial
, bitmap
, offset
) where
import Control.Monad.ST
import Data.Bits
import Data.Foldable as F
import Data.Function
import Data.List as List (sortBy, scanl)
import Data.Vector as V
import Data.Vector.Primitive as P
import Data.Vector.Primitive.Mutable as PM
import Data.Word
-- maximum binomial term
_N :: Int
_N = 15
bits :: Word16 -> Word8
bits = go 0 where
go i 0 = i
go i n = go (i + 1) (unsafeShiftR n 1)
{-# INLINE bits #-}
-- build a fixed sized table of binomial coeffients
-- bins :: (V.Vector (P.Vector Word16), V.Vector (P.Vector Word8))
bin :: V.Vector (P.Vector Word16)
lbin :: V.Vector (P.Vector Word8)
(bin, lbin) = runST $ do
mbin <- V.replicateM (_N+2) $ PM.replicate (_N+2) 0
mlbin <- V.replicateM (_N+2) $ PM.replicate (_N+2) 0
F.forM_ [0.._N] $ \i -> do
mbini <- V.unsafeIndexM mbin i
PM.unsafeWrite mbini 0 1
PM.unsafeWrite mbini 1 1
PM.unsafeWrite mbini i 1
mlbini <- V.unsafeIndexM mlbin i
PM.unsafeWrite mlbini 0 0
PM.unsafeWrite mlbini 1 0
PM.unsafeWrite mlbini i 0
F.forM_ [1.._N+1] $ \j ->
F.forM_ [j+1.._N+1] $ \i -> do
mbinim1 <- V.unsafeIndexM mbin (i - 1)
mbini <- V.unsafeIndexM mbin i
bx <- PM.unsafeRead mbinim1 (j-1)
by <- PM.unsafeRead mbinim1 j
let bz = bx + by
PM.unsafeWrite mbini j bz
mlbini <- V.unsafeIndexM mlbin i
PM.unsafeWrite mlbini j (bits bz)
xs <- V.forM mbin P.unsafeFreeze
ys <- V.forM mlbin P.unsafeFreeze
return (xs,ys)
-- | The sortBy below could be replaced with judicious use of <http://alexbowe.com/popcount-permutations/>
-- to reduce startup times.
bitmaps :: P.Vector Word16
bitmaps = P.fromListN 32768 $ sortBy (compare `on` popCount) [0..0x7fff]
classOffsets :: P.Vector Word16
classOffsets = P.fromListN (_N+1) $ List.scanl (\a k -> a + fromIntegral (binomial _N k)) 0 [0.._N]
offsets :: P.Vector Word16
offsets
= P.fromListN (P.length bitmaps)
$ fmap (\(w,o) -> o - (classOffsets P.! popCount w))
$ sortBy (on compare fst)
$ Prelude.zip (P.toList bitmaps) [0..]
-- @'binomial' n k@ returns @n `choose` k@ for @n, k <= 15@
binomial :: Int -> Int -> Int
binomial n k
| 0 <= n, n <= _N, 0 <= k, k <= _N = fromIntegral $ P.unsafeIndex (V.unsafeIndex bin n) k
| otherwise = error "binomial: out of range"
{-# INLINE binomial #-}
logBinomial :: Int -> Int -> Int
logBinomial n k
| 0 <= n, n <= _N, 0 <= k, k <= _N = fromIntegral $ P.unsafeIndex (V.unsafeIndex lbin n) k
| otherwise = error "logBinomial: out of range"
{-# INLINE logBinomial #-}
-- | bitmap by class and offset
--
-- There are 16 classes @k@ (based on popCount) each with @binomial 15 k@ possible offsets in a 'Word16' with the msb unset
bitmap :: Int -> Word16 -> Word16
bitmap k o = bitmaps P.! (fromIntegral (classOffsets P.! fromIntegral k) + fromIntegral o)
{-# INLINE bitmap #-}
-- | Calculate the offset of a Word16 into its class.
--
-- You can use @popCount@ to calculate the class, given @w <= 0x7fff@
--
-- @
-- 'bitmap' ('popCount' w) ('offset' w) = w
-- @
offset :: Word16 -> Word16
offset w = fromIntegral (offsets P.! fromIntegral w)
{-# INLINE offset #-}
| Gabriel439/succinct | src/Succinct/Internal/Binomial.hs | bsd-2-clause | 3,631 | 0 | 17 | 730 | 1,141 | 587 | 554 | 74 | 2 |
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-incomplete-patterns #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.TypeLevel.Num.Aliases
-- Copyright : (c) 2008 Alfonso Acosta, Oleg Kiselyov, Wolfgang Jeltsch
-- and KTH's SAM group
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : non-portable (Template Haskell)
--
-- Internal template haskell functions to generate type-level numeral aliases
--
----------------------------------------------------------------------------
module Data.TypeLevel.Num.Aliases.TH (genAliases, dec2TypeLevel) where
import Language.Haskell.TH
import Data.TypeLevel.Num.Reps
data Base = Bin | Oct | Dec | Hex
base2Int :: Base -> Int
base2Int Bin = 2
base2Int Oct = 8
base2Int Dec = 10
base2Int Hex = 16
-- This module needs to be separated from Data.TypeLevel.Num.Aliases due to
-- a limitation in Template Haskell implementation:
-- "You can only run a function at compile time if it is imported from another
-- module."
genAliases :: Int -- how many binary aliases
-> Int -- how many octal aliases
-> Int -- how many dec aliases
-> Int -- how many hex aliases
-> Q [Dec]
genAliases nb no nd nh = genAliases' nb no nd nh (maximum [nb,no,nd,nh])
genAliases' :: Int -- how many binary aliases
-> Int -- how many octal aliases
-> Int -- how many dec aliases
-> Int -- how many hex aliases
-> Int -- maximum alias
-> Q [Dec]
-- FIXME: genAliases' is ugly!
genAliases' nb no nd nh curr
| curr < 0 = return []
| otherwise =
do rest <- genAliases' nb no nd nh (curr-1)
-- binaries
restb <- addAliasBase (curr > nb) ('b' : bStr) ('B' : bStr) rest
-- octals
resto <- addAliasBase (curr > no) ('o' : oStr) ('O' : oStr) restb
-- decimals, we don't aliases of the decimal digits
-- (they are alredy defined in the representation module)
restd <- if curr > nd then return resto
else do val <- genValAlias ('d' : dStr) decRep
typ <- genTypeAlias ('D' : dStr) decRep
if (curr < 10) then return $ val : resto
else return $ val : typ : resto
-- hexadicimals
addAliasBase (curr > no) ('h' : hStr) ('H' : hStr) restd
where -- Add aliases of certain base to the rest of aliases
addAliasBase cond vStr tStr rest =
if cond then return rest
else do val <- genValAlias vStr decRep
typ <- genTypeAlias tStr decRep
return $ val : typ : rest
decRep = dec2TypeLevel curr
bStr = toBase Bin curr
oStr = toBase Oct curr
dStr = toBase Dec curr
hStr = toBase Hex curr
-- | Generate the type-level decimal representation for a value-level
-- natural number.
-- NOTE: This function could be useful by itself avoiding to generate
-- aliases. However, type-splicing is not yet supported by template haskell.
dec2TypeLevel :: Int -> Q Type
dec2TypeLevel n
| n < 0 = error "natural number expected"
| n < 10 = let name = case n of
0 -> ''D0; 1 -> ''D1; 2 -> ''D2; 3 -> ''D3; 4 -> ''D4
5 -> ''D5; 6 -> ''D6; 7 -> ''D7; 8 -> ''D8; 9 -> ''D9
in conT name
| otherwise = let (quotient, reminder) = n `quotRem` 10
remType = dec2TypeLevel reminder
quotType = dec2TypeLevel quotient
in (conT ''(:*)) `appT` quotType `appT` remType
-- | Generate a decimal type synonym alias
genTypeAlias :: String -> Q Type -> Q Dec
genTypeAlias str t = tySynD name [] t
where name = mkName $ str
-- | Generate a decimal value-level reflected alias
genValAlias :: String -> Q Type -> Q Dec
genValAlias str t = body
where name = mkName $ str
body = valD (varP name)
(normalB (sigE [| undefined |] t)) []
-- | Print an integer in certain base
toBase :: Base -- base
-> Int -- Number to print
-> String
toBase Dec n = show n
toBase b n
| n < 0 = '-' : toBase b (- n)
| n < bi = [int2Char n]
| otherwise = (toBase b rest) ++ [int2Char currDigit]
where bi = base2Int b
(rest, currDigit) = n `quotRem` bi
-- | print the corresponding character of a digit
int2Char :: Int -- Number to print
-> Char
int2Char i
| i' < 10 = toEnum (i'+ 48)
| otherwise = toEnum (i' + 55)
where i' = abs i
| coreyoconnor/type-level-tf | src/Data/TypeLevel/Num/Aliases/TH.hs | bsd-3-clause | 4,660 | 0 | 15 | 1,388 | 1,168 | 620 | 548 | 80 | 10 |
module DPH.Pass.Dump
(passDump)
where
import DPH.Core.Pretty
import HscTypes
import CoreMonad
import System.IO.Unsafe
-- | Dump a module.
passDump :: String -> ModGuts -> CoreM ModGuts
passDump name guts
= unsafePerformIO
$ do
writeFile ("dump." ++ name ++ ".hs")
$ render RenderIndent (pprModGuts guts)
return (return guts)
| mainland/dph | dph-plugin/DPH/Pass/Dump.hs | bsd-3-clause | 363 | 0 | 12 | 84 | 105 | 56 | 49 | 13 | 1 |
{-# LANGUAGE TypeOperators #-}
module Data.Comp.Examples.Multi where
import Examples.Multi.Common
import Examples.Multi.Eval as Eval
import Examples.Multi.EvalI as EvalI
import Examples.Multi.EvalM as EvalM
import Examples.Multi.Desugar as Desugar
import Data.Comp.Multi
import Test.Framework
import Test.Framework.Providers.HUnit
import Test.HUnit
import Test.Utils hiding (iPair)
--------------------------------------------------------------------------------
-- Test Suits
--------------------------------------------------------------------------------
tests = testGroup "Generalised Compositional Data Types" [
testCase "eval" evalTest,
testCase "evalI" evalITest,
testCase "evalM" evalMTest,
testCase "desugarEval" desugarEvalTest,
testCase "desugarPos" desugarPosTest
]
--------------------------------------------------------------------------------
-- Properties
--------------------------------------------------------------------------------
instance (EqHF f, Eq p) => EqHF (f :&: p) where
eqHF (v1 :&: p1) (v2 :&: p2) = p1 == p2 && v1 `eqHF` v2
evalTest = Eval.evalEx @=? iConst 2
evalITest = evalIEx @=? 2
evalMTest = evalMEx @=? Just (iConst 5)
desugarEvalTest = Desugar.evalEx @=? iPair (iConst 2) (iConst 1)
desugarPosTest = desugPEx @=? iAPair (Pos 1 0)
(iASnd (Pos 1 0)
(iAPair (Pos 1 1)
(iAConst (Pos 1 2) 1)
(iAConst (Pos 1 3) 2)))
(iAFst (Pos 1 0)
(iAPair (Pos 1 1)
(iAConst (Pos 1 2) 1)
(iAConst (Pos 1 3) 2))) | spacekitteh/compdata | testsuite/tests/Data/Comp/Examples/Multi.hs | bsd-3-clause | 1,840 | 0 | 14 | 573 | 430 | 238 | 192 | 33 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Diagrams.TwoD.Path.Turtle
-- Copyright : (c) 2011 Michael Sloan
-- License : BSD-style (see LICENSE)
-- Maintainer : Michael Sloan <mgsloan at gmail>, Deepak Jois <[email protected]>
-- Authors : Michael Sloan <mgsloan at gmail>, Deepak Jois <[email protected]>
--
-- A module consisting of core types and functions to represent and operate on
-- a \"turtle\".
--
-- More info about turtle graphics:
-- <http://en.wikipedia.org/wiki/Turtle_graphics>
--
-----------------------------------------------------------------------------
module Diagrams.TwoD.Path.Turtle.Internal
(
-- * Turtle data types and accessors
TurtleState(..), TurtlePath(..), PenStyle(..)
-- * Motion commands
, forward, backward, left, right
-- * Pen style commands
, setPenColor, setPenColour, setPenWidth
-- * State setters
, startTurtle, setHeading, towards
, setPenPos
-- * Drawing control
, penUp, penDown, penHop, closeCurrent
-- * Diagram related
, getTurtleDiagram
, getTurtlePath
) where
import Diagrams.Prelude
-- | Style attributes associated with the turtle pen
data PenStyle n = PenStyle
{ penWidth :: Measure n -- ^ Width of pen. Default is 1.0
, penColor :: Colour Double -- ^ Color of pen. Default is @black@
}
-- | Turtle path type that captures a list of paths and the style attributes
-- associated with them
data TurtlePath n = TurtlePath
{ penStyle :: PenStyle n -- ^ Style
, turtleTrail :: Located (Trail V2 n) -- ^ Path
}
-- | Core turtle data type. A turtle needs to keep track of its current
-- position, like its position, heading etc., and all the paths that it has
-- traversed so far.
--
-- We need to record a new path, everytime an attribute like style, pen position
-- etc changes, so that we can separately track styles for each portion of the
-- eventual path that the turtle took.
data TurtleState n = TurtleState
{ -- | State of the pen. @False@ means that turtle movements will not draw
-- anything
isPenDown :: Bool
-- | Current position. This is updated everytime the turtle moves
, penPos :: P2 n
-- | Orientation of the turtle in 2D space, given in degrees
, heading :: Angle n
-- | Path traversed by the turtle so far, without any style or pen
-- attributes changing
, currTrail :: Located (Trail' Line V2 n)
-- | Current style of the pen
, currPenStyle :: PenStyle n
-- | List of paths along with style information, traversed by the turtle
-- previously
, paths :: [TurtlePath n]
}
-- | Default pen style, with @penWidth@ set to 1.0 and @penColor@ set to black
defaultPenStyle :: (Floating n, Ord n) => PenStyle n
defaultPenStyle = PenStyle (normalized 0.004 `atLeast` output 0.5) black
-- | The initial state of turtle. The turtle is located at the origin, at an
-- orientation of 0 degrees with its pen position down. The pen style is
-- @defaultPenStyle@.
startTurtle :: (Floating n, Ord n) => TurtleState n
startTurtle = TurtleState True origin zero (mempty `at` origin) defaultPenStyle []
-- | Draw a segment along the turtleβs path and update its position. If the pen
-- is up, only the position is updated.
moveTurtle :: (Floating n, Ord n) => Segment Closed V2 n -- ^ Segment representing the path to travel
-> TurtleState n -- ^ Turtle to move
-> TurtleState n -- ^ Resulting turtle
moveTurtle s t@(TurtleState pd pos h tr _ _) =
if pd
-- Add segment to current trail and update position
then t { currTrail = newTrail
, penPos = newPenPos
}
-- Update position only
else t { penPos = newPenPos }
where
-- Rotate segment by orientation before adding to trail
rotatedSeg = rotate h s
newTrail = mapLoc (<> fromSegments [rotatedSeg]) tr
-- Calculate the new position along the segment
newPenPos = pos .+^ segOffset rotatedSeg
-- | Move the turtle forward by @x@ units
forward :: (Floating n, Ord n) => n -- ^ Distance to move
-> TurtleState n -- ^ Turtle to move
-> TurtleState n -- ^ Resulting turtle
forward x = moveTurtle (straight $ r2 (x,0))
-- | Move the turtle backward by @x@ units
backward :: (Floating n, Ord n) => n -- ^ Distance to move
-> TurtleState n -- ^ Turtle to move
-> TurtleState n -- ^ Resulting turtle
backward x = moveTurtle (straight $ r2 (negate x, 0))
-- | Turn the turtle by applying the given function to its current orientation
-- (in degrees)
turnTurtle :: (Angle n -> Angle n) -- ^ Transformation to apply on current orientation
-> TurtleState n -- ^ Turtle to turn
-> TurtleState n -- ^ Resulting turtle
turnTurtle f t@(TurtleState _ _ h _ _ _) = t { heading = f h }
-- | Turn the turtle anti-clockwise (left)
left :: Floating n
=> n -- ^ Degree of turn
-> TurtleState n -- ^ Turtle to turn
-> TurtleState n -- ^ Resulting turtle
left d = turnTurtle (^+^ (d @@ deg))
-- | Turn the turtle clockwise (right)
right :: Floating n
=> n -- ^ Degree of turn
-> TurtleState n -- ^ Turtle to turn
-> TurtleState n -- ^ Resulting turtle
right d = turnTurtle (^-^ (d @@ deg))
-- | Turn the turtle to the given orientation, in degrees
setHeading :: Floating n
=> n -- ^ Degree of orientation
-> TurtleState n -- ^ Turtle to orient
-> TurtleState n -- ^ Resulting turtle
setHeading d = turnTurtle (const $ d @@ deg)
-- | Sets the turtle orientation towards a given location.
towards :: RealFloat n =>
P2 n -- ^ Point to orient turtle towards
-> TurtleState n -- ^ Turtle to orient
-> TurtleState n -- ^ Resulting turtle
towards p = setHeading =<< (360 *) . (/ tau) . uncurry atan2 . unr2 . (p .-.) . penPos
-- | Puts the turtle pen in βUpβ mode. Turtle movements will not draw anything
--
-- Does nothing if the pen was already up. Otherwise, it creates a turtle with
-- the current trail added to @paths@.
penUp :: (Ord n, Floating n) => TurtleState n -- ^ Turtle to modify
-> TurtleState n -- ^ Resulting turtle
penUp t
| isPenDown t = t # makeNewTrail # \t' -> t' { isPenDown = False }
| otherwise = t
-- | Puts the turtle pen in βDownβ mode. Turtle movements will cause drawing to
-- happen
--
-- Does nothing if the pen was already down. Otherwise, starts a new trail
-- starting at the current position.
penDown :: (Ord n, Floating n) => TurtleState n -- ^ Turtle to modify
-> TurtleState n -- ^ Resulting turtle
penDown t
| isPenDown t = t
| otherwise = t # makeNewTrail # \t' -> t' { isPenDown = True }
-- Start a new trail at current position
penHop :: (Ord n, Floating n) => TurtleState n
-> TurtleState n
penHop t = t # makeNewTrail
-- Closes the current path, to the starting position of the current
-- trail. Has no effect when the pen is up.
closeCurrent :: (Floating n, Ord n) => TurtleState n
-> TurtleState n
closeCurrent t
| isPenDown t = t # closeTTrail
| otherwise = t
where startPos = loc . currTrail $ t
closeTTrail t' = t' { penPos = startPos
, currTrail = mempty `at` startPos
, paths = addTrailToPath t'
(mapLoc (wrapTrail . closeLine) $ currTrail t)
}
-- | Set the turtle X/Y position.
--
-- If pen is down and the current trail is non-empty, this will also add the
-- current trail to the @paths@ field.
setPenPos :: (Ord n, Floating n) => P2 n -- ^ Position to place true
-> TurtleState n -- ^ Turtle to position
-> TurtleState n -- ^ Resulting turtle
setPenPos newPos t = t {penPos = newPos } # makeNewTrail
-- | Set a new pen width for turtle.
--
-- If pen is down, this adds the current trail to @paths@ and starts a new empty
-- trail.
setPenWidth :: (Ord n, Floating n) => Measure n -- ^ Width of Pen
-> TurtleState n -- ^ Turtle to change
-> TurtleState n -- ^ Resulting Turtle
setPenWidth w = modifyCurrStyle (\s -> s { penWidth = w })
-- | Set a new pen color for turtle.
--
-- If pen is down, this adds the current trail to @paths@ and starts a new empty
-- trail.
setPenColour :: (Ord n, Floating n) => Colour Double -- ^ Width of Pen
-> TurtleState n -- ^ Turtle to change
-> TurtleState n -- ^ Resulting Turtle
setPenColour c = modifyCurrStyle (\s -> s { penColor = c })
-- | alias of @setPenColour@
setPenColor :: (Ord n, Floating n) => Colour Double -- ^ Width of Pen
-> TurtleState n -- ^ Turtle to change
-> TurtleState n -- ^ Resulting Turtle
setPenColor = setPenColour
-- | Creates a diagram from a turtle
--
-- Applies the styles to each trails in @paths@ separately and combines them
-- into a single diagram
getTurtleDiagram :: (Renderable (Path V2 n) b, TypeableFloat n)
=> TurtleState n
-> QDiagram b V2 n Any
getTurtleDiagram t =
mconcat .
map turtlePathToStroke .
paths $ t # penUp -- Do a penUp to add @currTrail@ to @paths@
-- | Creates a path from a turtle, ignoring the styles.
getTurtlePath :: (Floating n, Ord n) => TurtleState n -> Path V2 n
getTurtlePath = mconcat . map turtlePathToTrailLike . paths . penUp
-- * Helper functions
-- Makes a "TurtlePath" from a "Turtle"βs @currTrail@ field
makeTurtlePath :: TurtleState n
-> Located (Trail V2 n)
-> TurtlePath n
makeTurtlePath t tr = TurtlePath (currPenStyle t) tr
-- Returns a list of paths, with current trail added to a "Turtle"βs @paths@ field
addTrailToPath :: (Ord n, Floating n) => TurtleState n
-> Located (Trail V2 n)
-> [TurtlePath n]
addTrailToPath t tr
| isTrailEmpty (unLoc tr) = paths t
| otherwise = makeTurtlePath t tr : paths t
-- Starts a new trail and adds current trail to path
makeNewTrail :: (Ord n, Floating n) => TurtleState n
-> TurtleState n
makeNewTrail t = t { currTrail = mempty `at` penPos t
, paths = addTrailToPath t (mapLoc wrapTrail (currTrail t))
}
-- Modifies the current style after starting a new trail
modifyCurrStyle :: (Floating n, Ord n) =>
(PenStyle n -> PenStyle n)
-> TurtleState n
-> TurtleState n
modifyCurrStyle f t = t # makeNewTrail # \t' -> t' { currPenStyle = (f . currPenStyle) t' }
-- Creates any TrailLike from a TurtlePath.
turtlePathToTrailLike :: (V t ~ V2, N t ~ n, TrailLike t) => TurtlePath n -> t
turtlePathToTrailLike (TurtlePath _ t) = trailLike t
-- Creates a diagram from a TurtlePath using the provided styles
turtlePathToStroke :: (Renderable (Path V2 n) b, TypeableFloat n) =>
TurtlePath n
-> QDiagram b V2 n Any
turtlePathToStroke t@(TurtlePath (PenStyle lineWidth_ lineColor_) _) = d
where d = lc lineColor_ .
lw lineWidth_ .
strokeLocTrail $ turtlePathToTrailLike t
| diagrams/diagrams-contrib | src/Diagrams/TwoD/Path/Turtle/Internal.hs | bsd-3-clause | 11,441 | 0 | 14 | 3,025 | 2,195 | 1,203 | 992 | 152 | 2 |
{-# LANGUAGE CPP #-}
-----------------------------------------------------------------------------
-- |
-- Module : Main
-- Copyright : (c) David Himmelstrup 2005
-- License : BSD-like
--
-- Maintainer : [email protected]
-- Stability : provisional
-- Portability : portable
--
-- Entry point to the default cabal-install front-end.
-----------------------------------------------------------------------------
module Main (main) where
import Distribution.Client.Setup
( GlobalFlags(..), globalCommand, globalRepos
, ConfigFlags(..)
, ConfigExFlags(..), defaultConfigExFlags, configureExCommand
, BuildFlags(..), BuildExFlags(..), SkipAddSourceDepsCheck(..)
, buildCommand, replCommand, testCommand, benchmarkCommand
, InstallFlags(..), defaultInstallFlags
, installCommand, upgradeCommand, uninstallCommand
, FetchFlags(..), fetchCommand
, FreezeFlags(..), freezeCommand
, GetFlags(..), getCommand, unpackCommand
, checkCommand
, formatCommand
, updateCommand
, ListFlags(..), listCommand
, InfoFlags(..), infoCommand
, UploadFlags(..), uploadCommand
, ReportFlags(..), reportCommand
, runCommand
, InitFlags(initVerbosity), initCommand
, SDistFlags(..), SDistExFlags(..), sdistCommand
, Win32SelfUpgradeFlags(..), win32SelfUpgradeCommand
, SandboxFlags(..), sandboxCommand
, ExecFlags(..), execCommand
, UserConfigFlags(..), userConfigCommand
, reportCommand
)
import Distribution.Simple.Setup
( HaddockFlags(..), haddockCommand, defaultHaddockFlags
, HscolourFlags(..), hscolourCommand
, ReplFlags(..)
, CopyFlags(..), copyCommand
, RegisterFlags(..), registerCommand
, CleanFlags(..), cleanCommand
, TestFlags(..), BenchmarkFlags(..)
, Flag(..), fromFlag, fromFlagOrDefault, flagToMaybe, toFlag
, configAbsolutePaths
)
import Distribution.Client.SetupWrapper
( setupWrapper, SetupScriptOptions(..), defaultSetupScriptOptions )
import Distribution.Client.Config
( SavedConfig(..), loadConfig, defaultConfigFile, userConfigDiff
, userConfigUpdate )
import Distribution.Client.Targets
( readUserTargets )
import qualified Distribution.Client.List as List
( list, info )
import Distribution.Client.Install (install)
import Distribution.Client.Configure (configure)
import Distribution.Client.Update (update)
import Distribution.Client.Exec (exec)
import Distribution.Client.Fetch (fetch)
import Distribution.Client.Freeze (freeze)
import Distribution.Client.Check as Check (check)
--import Distribution.Client.Clean (clean)
import Distribution.Client.Upload as Upload (upload, check, report)
import Distribution.Client.Run (run, splitRunArgs)
import Distribution.Client.SrcDist (sdist)
import Distribution.Client.Get (get)
import Distribution.Client.Sandbox (sandboxInit
,sandboxAddSource
,sandboxDelete
,sandboxDeleteSource
,sandboxListSources
,sandboxHcPkg
,dumpPackageEnvironment
,getSandboxConfigFilePath
,loadConfigOrSandboxConfig
,initPackageDBIfNeeded
,maybeWithSandboxDirOnSearchPath
,maybeWithSandboxPackageInfo
,WereDepsReinstalled(..)
,maybeReinstallAddSourceDeps
,tryGetIndexFilePath
,sandboxBuildDir
,updateSandboxConfigFileFlag
,configCompilerAux'
,configPackageDB')
import Distribution.Client.Sandbox.PackageEnvironment
(setPackageDB
,userPackageEnvironmentFile)
import Distribution.Client.Sandbox.Timestamp (maybeAddCompilerTimestampRecord)
import Distribution.Client.Sandbox.Types (UseSandbox(..), whenUsingSandbox)
import Distribution.Client.Types (Password (..))
import Distribution.Client.Init (initCabal)
import qualified Distribution.Client.Win32SelfUpgrade as Win32SelfUpgrade
import Distribution.Client.Utils (determineNumJobs
#if defined(mingw32_HOST_OS)
,relaxEncodingErrors
#endif
,existsAndIsMoreRecentThan)
import Distribution.PackageDescription
( Executable(..), benchmarkName, benchmarkBuildInfo, testName
, testBuildInfo, buildable )
import Distribution.PackageDescription.Parse
( readPackageDescription )
import Distribution.PackageDescription.PrettyPrint
( writeGenericPackageDescription )
import Distribution.Simple.Build
( startInterpreter )
import Distribution.Simple.Command
( CommandParse(..), CommandUI(..), Command
, commandsRun, commandAddAction, hiddenCommand )
import Distribution.Simple.Compiler
( Compiler(..) )
import Distribution.Simple.Configure
( checkPersistBuildConfigOutdated, configCompilerAuxEx
, ConfigStateFileError(..), localBuildInfoFile
, getPersistBuildConfig, tryGetPersistBuildConfig )
import qualified Distribution.Simple.LocalBuildInfo as LBI
import Distribution.Simple.Program (defaultProgramConfiguration
,configureAllKnownPrograms
,simpleProgramInvocation
,getProgramInvocationOutput)
import Distribution.Simple.Program.Db (reconfigurePrograms)
import qualified Distribution.Simple.Setup as Cabal
import Distribution.Simple.Utils
( cabalVersion, die, notice, info, topHandler
, findPackageDesc, tryFindPackageDesc )
import Distribution.Text
( display )
import Distribution.Verbosity as Verbosity
( Verbosity, normal )
import Distribution.Version
( Version(..), orLaterVersion )
import qualified Paths_cabal_install (version)
import System.Environment (getArgs, getProgName)
import System.Exit (exitFailure)
import System.FilePath (splitExtension, takeExtension)
import System.IO ( BufferMode(LineBuffering), hSetBuffering
#ifdef mingw32_HOST_OS
, stderr
#endif
, stdout )
import System.Directory (doesFileExist, getCurrentDirectory)
import Data.List (intercalate)
import Data.Maybe (mapMaybe)
#if !MIN_VERSION_base(4,8,0)
import Data.Monoid (Monoid(..))
import Control.Applicative (pure, (<$>))
#endif
import Control.Monad (when, unless)
-- | Entry point
--
main :: IO ()
main = do
-- Enable line buffering so that we can get fast feedback even when piped.
-- This is especially important for CI and build systems.
hSetBuffering stdout LineBuffering
-- The default locale encoding for Windows CLI is not UTF-8 and printing
-- Unicode characters to it will fail unless we relax the handling of encoding
-- errors when writing to stderr and stdout.
#ifdef mingw32_HOST_OS
relaxEncodingErrors stdout
relaxEncodingErrors stderr
#endif
getArgs >>= mainWorker
mainWorker :: [String] -> IO ()
mainWorker args = topHandler $
case commandsRun (globalCommand commands) commands args of
CommandHelp help -> printGlobalHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo (globalFlags, commandParse) ->
case commandParse of
_ | fromFlagOrDefault False (globalVersion globalFlags)
-> printVersion
| fromFlagOrDefault False (globalNumericVersion globalFlags)
-> printNumericVersion
CommandHelp help -> printCommandHelp help
CommandList opts -> printOptionsList opts
CommandErrors errs -> printErrors errs
CommandReadyToGo action -> do
globalFlags' <- updateSandboxConfigFileFlag globalFlags
action globalFlags'
where
printCommandHelp help = do
pname <- getProgName
putStr (help pname)
printGlobalHelp help = do
pname <- getProgName
configFile <- defaultConfigFile
putStr (help pname)
putStr $ "\nYou can edit the cabal configuration file to set defaults:\n"
++ " " ++ configFile ++ "\n"
exists <- doesFileExist configFile
when (not exists) $
putStrLn $ "This file will be generated with sensible "
++ "defaults if you run 'cabal update'."
printOptionsList = putStr . unlines
printErrors errs = die $ intercalate "\n" errs
printNumericVersion = putStrLn $ display Paths_cabal_install.version
printVersion = putStrLn $ "cabal-install version "
++ display Paths_cabal_install.version
++ "\nusing version "
++ display cabalVersion
++ " of the Cabal library "
commands =
[installCommand `commandAddAction` installAction
,updateCommand `commandAddAction` updateAction
,listCommand `commandAddAction` listAction
,infoCommand `commandAddAction` infoAction
,fetchCommand `commandAddAction` fetchAction
,freezeCommand `commandAddAction` freezeAction
,getCommand `commandAddAction` getAction
,hiddenCommand $
unpackCommand `commandAddAction` unpackAction
,checkCommand `commandAddAction` checkAction
,sdistCommand `commandAddAction` sdistAction
,uploadCommand `commandAddAction` uploadAction
,reportCommand `commandAddAction` reportAction
,runCommand `commandAddAction` runAction
,initCommand `commandAddAction` initAction
,configureExCommand `commandAddAction` configureAction
,buildCommand `commandAddAction` buildAction
,replCommand `commandAddAction` replAction
,sandboxCommand `commandAddAction` sandboxAction
,haddockCommand `commandAddAction` haddockAction
,execCommand `commandAddAction` execAction
,userConfigCommand `commandAddAction` userConfigAction
,cleanCommand `commandAddAction` cleanAction
,wrapperAction copyCommand
copyVerbosity copyDistPref
,wrapperAction hscolourCommand
hscolourVerbosity hscolourDistPref
,wrapperAction registerCommand
regVerbosity regDistPref
,testCommand `commandAddAction` testAction
,benchmarkCommand `commandAddAction` benchmarkAction
,hiddenCommand $
uninstallCommand `commandAddAction` uninstallAction
,hiddenCommand $
formatCommand `commandAddAction` formatAction
,hiddenCommand $
upgradeCommand `commandAddAction` upgradeAction
,hiddenCommand $
win32SelfUpgradeCommand`commandAddAction` win32SelfUpgradeAction
]
wrapperAction :: Monoid flags
=> CommandUI flags
-> (flags -> Flag Verbosity)
-> (flags -> Flag String)
-> Command (GlobalFlags -> IO ())
wrapperAction command verbosityFlag distPrefFlag =
commandAddAction command
{ commandDefaultFlags = mempty } $ \flags extraArgs _globalFlags -> do
let verbosity = fromFlagOrDefault normal (verbosityFlag flags)
setupScriptOptions = defaultSetupScriptOptions {
useDistPref = fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(distPrefFlag flags)
}
setupWrapper verbosity setupScriptOptions Nothing
command (const flags) extraArgs
configureAction :: (ConfigFlags, ConfigExFlags)
-> [String] -> GlobalFlags -> IO ()
configureAction (configFlags, configExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity
globalFlags (configUserInstall configFlags)
let configFlags' = savedConfigureFlags config `mappend` configFlags
configExFlags' = savedConfigureExFlags config `mappend` configExFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAuxEx configFlags'
-- If we're working inside a sandbox and the user has set the -w option, we
-- may need to create a sandbox-local package DB for this compiler and add a
-- timestamp record for this compiler to the timestamp file.
let configFlags'' = case useSandbox of
NoSandbox -> configFlags'
(UseSandbox sandboxDir) -> setPackageDB sandboxDir
comp platform configFlags'
whenUsingSandbox useSandbox $ \sandboxDir -> do
initPackageDBIfNeeded verbosity configFlags'' comp conf
-- NOTE: We do not write the new sandbox package DB location to
-- 'cabal.sandbox.config' here because 'configure -w' must not affect
-- subsequent 'install' (for UI compatibility with non-sandboxed mode).
indexFile <- tryGetIndexFilePath config
maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile
(compilerId comp) platform
maybeWithSandboxDirOnSearchPath useSandbox $
configure verbosity
(configPackageDB' configFlags'')
(globalRepos globalFlags')
comp platform conf configFlags'' configExFlags' extraArgs
buildAction :: (BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO ()
buildAction (buildFlags, buildExFlags) extraArgs globalFlags = do
let distPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions)
(buildDistPref buildFlags)
verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags)
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- Calls 'configureAction' to do the real work, so nothing special has to be
-- done to support sandboxes.
(useSandbox, config) <- reconfigure verbosity distPref
mempty [] globalFlags noAddSource
(buildNumJobs buildFlags) (const Nothing)
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags extraArgs
-- | Actually do the work of building the package. This is separate from
-- 'buildAction' so that 'testAction' and 'benchmarkAction' do not invoke
-- 'reconfigure' twice.
build :: Verbosity -> SavedConfig -> FilePath -> BuildFlags -> [String] -> IO ()
build verbosity config distPref buildFlags extraArgs =
setupWrapper verbosity setupOptions Nothing
(Cabal.buildCommand progConf) mkBuildFlags extraArgs
where
progConf = defaultProgramConfiguration
setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
mkBuildFlags version = filterBuildFlags version config buildFlags'
buildFlags' = buildFlags
{ buildVerbosity = toFlag verbosity
, buildDistPref = toFlag distPref
}
-- | Make sure that we don't pass new flags to setup scripts compiled against
-- old versions of Cabal.
filterBuildFlags :: Version -> SavedConfig -> BuildFlags -> BuildFlags
filterBuildFlags version config buildFlags
| version >= Version [1,19,1] [] = buildFlags_latest
-- Cabal < 1.19.1 doesn't support 'build -j'.
| otherwise = buildFlags_pre_1_19_1
where
buildFlags_pre_1_19_1 = buildFlags {
buildNumJobs = NoFlag
}
buildFlags_latest = buildFlags {
-- Take the 'jobs' setting '~/.cabal/config' into account.
buildNumJobs = Flag . Just . determineNumJobs $
(numJobsConfigFlag `mappend` numJobsCmdLineFlag)
}
numJobsConfigFlag = installNumJobs . savedInstallFlags $ config
numJobsCmdLineFlag = buildNumJobs buildFlags
replAction :: (ReplFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO ()
replAction (replFlags, buildExFlags) extraArgs globalFlags = do
cwd <- getCurrentDirectory
pkgDesc <- findPackageDesc cwd
either (const onNoPkgDesc) (const onPkgDesc) pkgDesc
where
verbosity = fromFlagOrDefault normal (replVerbosity replFlags)
-- There is a .cabal file in the current directory: start a REPL and load
-- the project's modules.
onPkgDesc = do
let distPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions)
(replDistPref replFlags)
noAddSource = case replReload replFlags of
Flag True -> SkipAddSourceDepsCheck
_ -> fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
progConf = defaultProgramConfiguration
setupOptions = defaultSetupScriptOptions
{ useCabalVersion = orLaterVersion $ Version [1,18,0] []
, useDistPref = distPref
}
replFlags' = replFlags
{ replVerbosity = toFlag verbosity
, replDistPref = toFlag distPref
}
-- Calls 'configureAction' to do the real work, so nothing special has to
-- be done to support sandboxes.
(useSandbox, _config) <- reconfigure verbosity distPref
mempty [] globalFlags noAddSource NoFlag
(const Nothing)
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
(Cabal.replCommand progConf) (const replFlags') extraArgs
-- No .cabal file in the current directory: just start the REPL (possibly
-- using the sandbox package DB).
onNoPkgDesc = do
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
mempty
let configFlags = savedConfigureFlags config
(comp, _platform, programDb) <- configCompilerAux' configFlags
programDb' <- reconfigurePrograms verbosity
(replProgramPaths replFlags)
(replProgramArgs replFlags)
programDb
startInterpreter verbosity programDb' comp (configPackageDB' configFlags)
-- | Re-configure the package in the current directory if needed. Deciding
-- when to reconfigure and with which options is convoluted:
--
-- If we are reconfiguring, we must always run @configure@ with the
-- verbosity option we are given; however, that a previous configuration
-- uses a different verbosity setting is not reason enough to reconfigure.
--
-- The package should be configured to use the same \"dist\" prefix as
-- given to the @build@ command, otherwise the build will probably
-- fail. Not only does this determine the \"dist\" prefix setting if we
-- need to reconfigure anyway, but an existing configuration should be
-- invalidated if its \"dist\" prefix differs.
--
-- If the package has never been configured (i.e., there is no
-- LocalBuildInfo), we must configure first, using the default options.
--
-- If the package has been configured, there will be a 'LocalBuildInfo'.
-- If there no package description file, we assume that the
-- 'PackageDescription' is up to date, though the configuration may need
-- to be updated for other reasons (see above). If there is a package
-- description file, and it has been modified since the 'LocalBuildInfo'
-- was generated, then we need to reconfigure.
--
-- The caller of this function may also have specific requirements
-- regarding the flags the last configuration used. For example,
-- 'testAction' requires that the package be configured with test suites
-- enabled. The caller may pass the required settings to this function
-- along with a function to check the validity of the saved 'ConfigFlags';
-- these required settings will be checked first upon determining that
-- a previous configuration exists.
reconfigure :: Verbosity -- ^ Verbosity setting
-> FilePath -- ^ \"dist\" prefix
-> ConfigFlags -- ^ Additional config flags to set. These flags
-- will be 'mappend'ed to the last used or
-- default 'ConfigFlags' as appropriate, so
-- this value should be 'mempty' with only the
-- required flags set. The required verbosity
-- and \"dist\" prefix flags will be set
-- automatically because they are always
-- required; therefore, it is not necessary to
-- set them here.
-> [String] -- ^ Extra arguments
-> GlobalFlags -- ^ Global flags
-> SkipAddSourceDepsCheck
-- ^ Should we skip the timestamp check for modified
-- add-source dependencies?
-> Flag (Maybe Int)
-- ^ -j flag for reinstalling add-source deps.
-> (ConfigFlags -> Maybe String)
-- ^ Check that the required flags are set in
-- the last used 'ConfigFlags'. If the required
-- flags are not set, provide a message to the
-- user explaining the reason for
-- reconfiguration. Because the correct \"dist\"
-- prefix setting is always required, it is checked
-- automatically; this function need not check
-- for it.
-> IO (UseSandbox, SavedConfig)
reconfigure verbosity distPref addConfigFlags extraArgs globalFlags
skipAddSourceDepsCheck numJobsFlag checkFlags = do
eLbi <- tryGetPersistBuildConfig distPref
case eLbi of
Left err -> onNoBuildConfig err
Right lbi -> onBuildConfig lbi
where
-- We couldn't load the saved package config file.
--
-- If we're in a sandbox: add-source deps don't have to be reinstalled
-- (since we don't know the compiler & platform).
onNoBuildConfig :: ConfigStateFileError -> IO (UseSandbox, SavedConfig)
onNoBuildConfig err = do
let msg = case err of
ConfigStateFileMissing -> "Package has never been configured."
ConfigStateFileNoParse -> "Saved package config file seems "
++ "to be corrupt."
_ -> show err
case err of
ConfigStateFileBadVersion _ _ _ -> info verbosity msg
_ -> do
notice verbosity
$ msg ++ " Configuring with default flags." ++ configureManually
configureAction (defaultFlags, defaultConfigExFlags)
extraArgs globalFlags
loadConfigOrSandboxConfig verbosity globalFlags mempty
-- Package has been configured, but the configuration may be out of
-- date or required flags may not be set.
--
-- If we're in a sandbox: reinstall the modified add-source deps and
-- force reconfigure if we did.
onBuildConfig :: LBI.LocalBuildInfo -> IO (UseSandbox, SavedConfig)
onBuildConfig lbi = do
let configFlags = LBI.configFlags lbi
flags = mconcat [configFlags, addConfigFlags, distVerbFlags]
-- Was the sandbox created after the package was already configured? We
-- may need to skip reinstallation of add-source deps and force
-- reconfigure.
let buildConfig = localBuildInfoFile distPref
sandboxConfig <- getSandboxConfigFilePath globalFlags
isSandboxConfigNewer <-
sandboxConfig `existsAndIsMoreRecentThan` buildConfig
let skipAddSourceDepsCheck'
| isSandboxConfigNewer = SkipAddSourceDepsCheck
| otherwise = skipAddSourceDepsCheck
when (skipAddSourceDepsCheck' == SkipAddSourceDepsCheck) $
info verbosity "Skipping add-source deps check..."
(useSandbox, config, depsReinstalled) <-
case skipAddSourceDepsCheck' of
DontSkipAddSourceDepsCheck ->
maybeReinstallAddSourceDeps verbosity numJobsFlag flags globalFlags
SkipAddSourceDepsCheck -> do
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity
globalFlags (configUserInstall flags)
return (useSandbox, config, NoDepsReinstalled)
-- Is the @cabal.config@ file newer than @dist/setup.config@? Then we need
-- to force reconfigure. Note that it's possible to use @cabal.config@
-- even without sandboxes.
isUserPackageEnvironmentFileNewer <-
userPackageEnvironmentFile `existsAndIsMoreRecentThan` buildConfig
-- Determine whether we need to reconfigure and which message to show to
-- the user if that is the case.
mMsg <- determineMessageToShow lbi configFlags depsReinstalled
isSandboxConfigNewer
isUserPackageEnvironmentFileNewer
case mMsg of
-- No message for the user indicates that reconfiguration
-- is not required.
Nothing -> return (useSandbox, config)
-- Show the message and reconfigure.
Just msg -> do
notice verbosity msg
configureAction (flags, defaultConfigExFlags)
extraArgs globalFlags
return (useSandbox, config)
-- Determine what message, if any, to display to the user if reconfiguration
-- is required.
determineMessageToShow :: LBI.LocalBuildInfo -> ConfigFlags
-> WereDepsReinstalled -> Bool -> Bool
-> IO (Maybe String)
determineMessageToShow _ _ _ True _ =
-- The sandbox was created after the package was already configured.
return $! Just $! sandboxConfigNewerMessage
determineMessageToShow _ _ _ False True =
-- The user package environment file was modified.
return $! Just $! userPackageEnvironmentFileModifiedMessage
determineMessageToShow lbi configFlags depsReinstalled False False = do
let savedDistPref = fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(configDistPref configFlags)
case depsReinstalled of
ReinstalledSomeDeps ->
-- Some add-source deps were reinstalled.
return $! Just $! reinstalledDepsMessage
NoDepsReinstalled ->
case checkFlags configFlags of
-- Flag required by the caller is not set.
Just msg -> return $! Just $! msg ++ configureManually
Nothing
-- Required "dist" prefix is not set.
| savedDistPref /= distPref ->
return $! Just distPrefMessage
-- All required flags are set, but the configuration
-- may be outdated.
| otherwise -> case LBI.pkgDescrFile lbi of
Nothing -> return Nothing
Just pdFile -> do
outdated <- checkPersistBuildConfigOutdated
distPref pdFile
return $! if outdated
then Just $! outdatedMessage pdFile
else Nothing
defaultFlags = mappend addConfigFlags distVerbFlags
distVerbFlags = mempty
{ configVerbosity = toFlag verbosity
, configDistPref = toFlag distPref
}
reconfiguringMostRecent = " Re-configuring with most recently used options."
configureManually = " If this fails, please run configure manually."
sandboxConfigNewerMessage =
"The sandbox was created after the package was already configured."
++ reconfiguringMostRecent
++ configureManually
userPackageEnvironmentFileModifiedMessage =
"The user package environment file ('"
++ userPackageEnvironmentFile ++ "') was modified."
++ reconfiguringMostRecent
++ configureManually
distPrefMessage =
"Package previously configured with different \"dist\" prefix."
++ reconfiguringMostRecent
++ configureManually
outdatedMessage pdFile =
pdFile ++ " has been changed."
++ reconfiguringMostRecent
++ configureManually
reinstalledDepsMessage =
"Some add-source dependencies have been reinstalled."
++ reconfiguringMostRecent
++ configureManually
installAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
installAction (configFlags, _, installFlags, _) _ _globalFlags
| fromFlagOrDefault False (installOnly installFlags)
= let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
in setupWrapper verbosity defaultSetupScriptOptions Nothing
installCommand (const mempty) []
installAction (configFlags, configExFlags, installFlags, haddockFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (configVerbosity configFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity
globalFlags (configUserInstall configFlags)
targets <- readUserTargets verbosity extraArgs
-- TODO: It'd be nice if 'cabal install' picked up the '-w' flag passed to
-- 'configure' when run inside a sandbox. Right now, running
--
-- $ cabal sandbox init && cabal configure -w /path/to/ghc
-- && cabal build && cabal install
--
-- performs the compilation twice unless you also pass -w to 'install'.
-- However, this is the same behaviour that 'cabal install' has in the normal
-- mode of operation, so we stick to it for consistency.
let sandboxDistPref = case useSandbox of
NoSandbox -> NoFlag
UseSandbox sandboxDir -> Flag $ sandboxBuildDir sandboxDir
configFlags' = maybeForceTests installFlags' $
savedConfigureFlags config `mappend` configFlags
configExFlags' = defaultConfigExFlags `mappend`
savedConfigureExFlags config `mappend` configExFlags
installFlags' = defaultInstallFlags `mappend`
savedInstallFlags config `mappend` installFlags
haddockFlags' = defaultHaddockFlags `mappend`
savedHaddockFlags config `mappend` haddockFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAux' configFlags'
-- TODO: Redesign ProgramDB API to prevent such problems as #2241 in the future.
conf' <- configureAllKnownPrograms verbosity conf
-- If we're working inside a sandbox and the user has set the -w option, we
-- may need to create a sandbox-local package DB for this compiler and add a
-- timestamp record for this compiler to the timestamp file.
configFlags'' <- case useSandbox of
NoSandbox -> configAbsolutePaths $ configFlags'
(UseSandbox sandboxDir) ->
return $ (setPackageDB sandboxDir comp platform configFlags') {
configDistPref = sandboxDistPref
}
whenUsingSandbox useSandbox $ \sandboxDir -> do
initPackageDBIfNeeded verbosity configFlags'' comp conf'
indexFile <- tryGetIndexFilePath config
maybeAddCompilerTimestampRecord verbosity sandboxDir indexFile
(compilerId comp) platform
-- FIXME: Passing 'SandboxPackageInfo' to install unconditionally here means
-- that 'cabal install some-package' inside a sandbox will sometimes reinstall
-- modified add-source deps, even if they are not among the dependencies of
-- 'some-package'. This can also prevent packages that depend on older
-- versions of add-source'd packages from building (see #1362).
maybeWithSandboxPackageInfo verbosity configFlags'' globalFlags'
comp platform conf useSandbox $ \mSandboxPkgInfo ->
maybeWithSandboxDirOnSearchPath useSandbox $
install verbosity
(configPackageDB' configFlags'')
(globalRepos globalFlags')
comp platform conf'
useSandbox mSandboxPkgInfo
globalFlags' configFlags'' configExFlags'
installFlags' haddockFlags'
targets
where
-- '--run-tests' implies '--enable-tests'.
maybeForceTests installFlags' configFlags' =
if fromFlagOrDefault False (installRunTests installFlags')
then configFlags' { configTests = toFlag True }
else configFlags'
testAction :: (TestFlags, BuildFlags, BuildExFlags) -> [String] -> GlobalFlags
-> IO ()
testAction (testFlags, buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (testVerbosity testFlags)
distPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions)
(testDistPref testFlags)
setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
buildFlags' = buildFlags { buildVerbosity = testVerbosity testFlags
, buildDistPref = testDistPref testFlags }
addConfigFlags = mempty { configTests = toFlag True }
checkFlags flags
| fromFlagOrDefault False (configTests flags) = Nothing
| otherwise = Just "Re-configuring with test suites enabled."
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
(useSandbox, config) <- reconfigure verbosity distPref addConfigFlags []
globalFlags noAddSource
(buildNumJobs buildFlags') checkFlags
-- the package was just configured, so the LBI must be available
lbi <- getPersistBuildConfig distPref
let pkgDescr = LBI.localPkgDescr lbi
nameTestsOnly =
LBI.foldComponent
(const Nothing)
(const Nothing)
(\t ->
if buildable (testBuildInfo t)
then Just (testName t)
else Nothing)
(const Nothing)
tests = mapMaybe nameTestsOnly $ LBI.pkgComponents pkgDescr
extraArgs'
| null extraArgs = tests
| otherwise = extraArgs
if null tests
then notice verbosity "Package has no buildable test suites."
else do
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags' extraArgs'
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
Cabal.testCommand (const testFlags) extraArgs'
benchmarkAction :: (BenchmarkFlags, BuildFlags, BuildExFlags)
-> [String] -> GlobalFlags
-> IO ()
benchmarkAction (benchmarkFlags, buildFlags, buildExFlags)
extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal
(benchmarkVerbosity benchmarkFlags)
distPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions)
(benchmarkDistPref benchmarkFlags)
setupOptions = defaultSetupScriptOptions { useDistPref = distPref }
buildFlags' = buildFlags
{ buildVerbosity = benchmarkVerbosity benchmarkFlags
, buildDistPref = benchmarkDistPref benchmarkFlags }
addConfigFlags = mempty { configBenchmarks = toFlag True }
checkFlags flags
| fromFlagOrDefault False (configBenchmarks flags) = Nothing
| otherwise = Just "Re-configuring with benchmarks enabled."
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
(useSandbox, config) <- reconfigure verbosity distPref addConfigFlags []
globalFlags noAddSource (buildNumJobs buildFlags')
checkFlags
-- the package was just configured, so the LBI must be available
lbi <- getPersistBuildConfig distPref
let pkgDescr = LBI.localPkgDescr lbi
nameBenchsOnly =
LBI.foldComponent
(const Nothing)
(const Nothing)
(const Nothing)
(\b ->
if buildable (benchmarkBuildInfo b)
then Just (benchmarkName b)
else Nothing)
benchs = mapMaybe nameBenchsOnly $ LBI.pkgComponents pkgDescr
extraArgs'
| null extraArgs = benchs
| otherwise = extraArgs
if null benchs
then notice verbosity "Package has no buildable benchmarks."
else do
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags' extraArgs'
maybeWithSandboxDirOnSearchPath useSandbox $
setupWrapper verbosity setupOptions Nothing
Cabal.benchmarkCommand (const benchmarkFlags) extraArgs'
haddockAction :: HaddockFlags -> [String] -> GlobalFlags -> IO ()
haddockAction haddockFlags extraArgs globalFlags = do
let verbosity = fromFlag (haddockVerbosity haddockFlags)
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags mempty
let haddockFlags' = defaultHaddockFlags `mappend`
savedHaddockFlags config `mappend` haddockFlags
setupScriptOptions = defaultSetupScriptOptions {
useDistPref = fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(haddockDistPref haddockFlags')
}
setupWrapper verbosity setupScriptOptions Nothing
haddockCommand (const haddockFlags') extraArgs
cleanAction :: CleanFlags -> [String] -> GlobalFlags -> IO ()
cleanAction cleanFlags extraArgs _globalFlags =
setupWrapper verbosity setupScriptOptions Nothing
cleanCommand (const cleanFlags) extraArgs
where
verbosity = fromFlagOrDefault normal (cleanVerbosity cleanFlags)
setupScriptOptions = defaultSetupScriptOptions {
useDistPref = fromFlagOrDefault
(useDistPref defaultSetupScriptOptions)
(cleanDistPref cleanFlags),
useWin32CleanHack = True
}
listAction :: ListFlags -> [String] -> GlobalFlags -> IO ()
listAction listFlags extraArgs globalFlags = do
let verbosity = fromFlag (listVerbosity listFlags)
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
mempty
let configFlags' = savedConfigureFlags config
configFlags = configFlags' {
configPackageDBs = configPackageDBs configFlags'
`mappend` listPackageDBs listFlags
}
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, conf) <- configCompilerAux' configFlags
List.list verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
listFlags
extraArgs
infoAction :: InfoFlags -> [String] -> GlobalFlags -> IO ()
infoAction infoFlags extraArgs globalFlags = do
let verbosity = fromFlag (infoVerbosity infoFlags)
targets <- readUserTargets verbosity extraArgs
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
mempty
let configFlags' = savedConfigureFlags config
configFlags = configFlags' {
configPackageDBs = configPackageDBs configFlags'
`mappend` infoPackageDBs infoFlags
}
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, conf) <- configCompilerAuxEx configFlags
List.info verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
globalFlags'
infoFlags
targets
updateAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
updateAction verbosityFlag extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'update' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag verbosityFlag
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
NoFlag
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
update verbosity (globalRepos globalFlags')
upgradeAction :: (ConfigFlags, ConfigExFlags, InstallFlags, HaddockFlags)
-> [String] -> GlobalFlags -> IO ()
upgradeAction _ _ _ = die $
"Use the 'cabal install' command instead of 'cabal upgrade'.\n"
++ "You can install the latest version of a package using 'cabal install'. "
++ "The 'cabal upgrade' command has been removed because people found it "
++ "confusing and it often led to broken packages.\n"
++ "If you want the old upgrade behaviour then use the install command "
++ "with the --upgrade-dependencies flag (but check first with --dry-run "
++ "to see what would happen). This will try to pick the latest versions "
++ "of all dependencies, rather than the usual behaviour of trying to pick "
++ "installed versions of all dependencies. If you do use "
++ "--upgrade-dependencies, it is recommended that you do not upgrade core "
++ "packages (e.g. by using appropriate --constraint= flags)."
fetchAction :: FetchFlags -> [String] -> GlobalFlags -> IO ()
fetchAction fetchFlags extraArgs globalFlags = do
let verbosity = fromFlag (fetchVerbosity fetchFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAux' configFlags
fetch verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp platform conf globalFlags' fetchFlags
targets
freezeAction :: FreezeFlags -> [String] -> GlobalFlags -> IO ()
freezeAction freezeFlags _extraArgs globalFlags = do
let verbosity = fromFlag (freezeVerbosity freezeFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags mempty
let configFlags = savedConfigureFlags config
globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, platform, conf) <- configCompilerAux' configFlags
maybeWithSandboxPackageInfo verbosity configFlags globalFlags'
comp platform conf useSandbox $ \mSandboxPkgInfo ->
maybeWithSandboxDirOnSearchPath useSandbox $
freeze verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp platform conf
mSandboxPkgInfo
globalFlags' freezeFlags
uploadAction :: UploadFlags -> [String] -> GlobalFlags -> IO ()
uploadAction uploadFlags extraArgs globalFlags = do
let verbosity = fromFlag (uploadVerbosity uploadFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let uploadFlags' = savedUploadFlags config `mappend` uploadFlags
globalFlags' = savedGlobalFlags config `mappend` globalFlags
tarfiles = extraArgs
checkTarFiles extraArgs
maybe_password <-
case uploadPasswordCmd uploadFlags'
of Flag (xs:xss) -> Just . Password <$>
getProgramInvocationOutput verbosity
(simpleProgramInvocation xs xss)
_ -> pure $ flagToMaybe $ uploadPassword uploadFlags'
if fromFlag (uploadCheck uploadFlags')
then Upload.check verbosity tarfiles
else upload verbosity
(globalRepos globalFlags')
(flagToMaybe $ uploadUsername uploadFlags')
maybe_password
tarfiles
where
checkTarFiles tarfiles
| null tarfiles
= die "the 'upload' command expects one or more .tar.gz packages."
| not (null otherFiles)
= die $ "the 'upload' command expects only .tar.gz packages: "
++ intercalate ", " otherFiles
| otherwise = sequence_
[ do exists <- doesFileExist tarfile
unless exists $ die $ "file not found: " ++ tarfile
| tarfile <- tarfiles ]
where otherFiles = filter (not . isTarGzFile) tarfiles
isTarGzFile file = case splitExtension file of
(file', ".gz") -> takeExtension file' == ".tar"
_ -> False
checkAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
checkAction verbosityFlag extraArgs _globalFlags = do
unless (null extraArgs) $
die $ "'check' doesn't take any extra arguments: " ++ unwords extraArgs
allOk <- Check.check (fromFlag verbosityFlag)
unless allOk exitFailure
formatAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
formatAction verbosityFlag extraArgs _globalFlags = do
let verbosity = fromFlag verbosityFlag
path <- case extraArgs of
[] -> do cwd <- getCurrentDirectory
tryFindPackageDesc cwd
(p:_) -> return p
pkgDesc <- readPackageDescription verbosity path
-- Uses 'writeFileAtomic' under the hood.
writeGenericPackageDescription path pkgDesc
uninstallAction :: Flag Verbosity -> [String] -> GlobalFlags -> IO ()
uninstallAction _verbosityFlag extraArgs _globalFlags = do
let package = case extraArgs of
p:_ -> p
_ -> "PACKAGE_NAME"
die $ "This version of 'cabal-install' does not support the 'uninstall' operation. "
++ "It will likely be implemented at some point in the future; in the meantime "
++ "you're advised to use either 'ghc-pkg unregister " ++ package ++ "' or "
++ "'cabal sandbox hc-pkg -- unregister " ++ package ++ "'."
sdistAction :: (SDistFlags, SDistExFlags) -> [String] -> GlobalFlags -> IO ()
sdistAction (sdistFlags, sdistExFlags) extraArgs _globalFlags = do
unless (null extraArgs) $
die $ "'sdist' doesn't take any extra arguments: " ++ unwords extraArgs
sdist sdistFlags sdistExFlags
reportAction :: ReportFlags -> [String] -> GlobalFlags -> IO ()
reportAction reportFlags extraArgs globalFlags = do
unless (null extraArgs) $
die $ "'report' doesn't take any extra arguments: " ++ unwords extraArgs
let verbosity = fromFlag (reportVerbosity reportFlags)
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
reportFlags' = savedReportFlags config `mappend` reportFlags
Upload.report verbosity (globalRepos globalFlags')
(flagToMaybe $ reportUsername reportFlags')
(flagToMaybe $ reportPassword reportFlags')
runAction :: (BuildFlags, BuildExFlags) -> [String] -> GlobalFlags -> IO ()
runAction (buildFlags, buildExFlags) extraArgs globalFlags = do
let verbosity = fromFlagOrDefault normal (buildVerbosity buildFlags)
distPref = fromFlagOrDefault (useDistPref defaultSetupScriptOptions)
(buildDistPref buildFlags)
noAddSource = fromFlagOrDefault DontSkipAddSourceDepsCheck
(buildOnly buildExFlags)
-- reconfigure also checks if we're in a sandbox and reinstalls add-source
-- deps if needed.
(useSandbox, config) <- reconfigure verbosity distPref mempty []
globalFlags noAddSource (buildNumJobs buildFlags)
(const Nothing)
lbi <- getPersistBuildConfig distPref
(exe, exeArgs) <- splitRunArgs verbosity lbi extraArgs
maybeWithSandboxDirOnSearchPath useSandbox $
build verbosity config distPref buildFlags ["exe:" ++ exeName exe]
maybeWithSandboxDirOnSearchPath useSandbox $
run verbosity lbi exe exeArgs
getAction :: GetFlags -> [String] -> GlobalFlags -> IO ()
getAction getFlags extraArgs globalFlags = do
let verbosity = fromFlag (getVerbosity getFlags)
targets <- readUserTargets verbosity extraArgs
config <- loadConfig verbosity (globalConfigFile globalFlags) mempty
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
get verbosity
(globalRepos (savedGlobalFlags config))
globalFlags'
getFlags
targets
unpackAction :: GetFlags -> [String] -> GlobalFlags -> IO ()
unpackAction getFlags extraArgs globalFlags = do
getAction getFlags extraArgs globalFlags
initAction :: InitFlags -> [String] -> GlobalFlags -> IO ()
initAction initFlags _extraArgs globalFlags = do
let verbosity = fromFlag (initVerbosity initFlags)
(_useSandbox, config) <- loadConfigOrSandboxConfig verbosity
(globalFlags { globalRequireSandbox = Flag False })
mempty
let configFlags = savedConfigureFlags config
let globalFlags' = savedGlobalFlags config `mappend` globalFlags
(comp, _, conf) <- configCompilerAux' configFlags
initCabal verbosity
(configPackageDB' configFlags)
(globalRepos globalFlags')
comp
conf
initFlags
sandboxAction :: SandboxFlags -> [String] -> GlobalFlags -> IO ()
sandboxAction sandboxFlags extraArgs globalFlags = do
let verbosity = fromFlag (sandboxVerbosity sandboxFlags)
case extraArgs of
-- Basic sandbox commands.
["init"] -> sandboxInit verbosity sandboxFlags globalFlags
["delete"] -> sandboxDelete verbosity sandboxFlags globalFlags
("add-source":extra) -> do
when (noExtraArgs extra) $
die "The 'sandbox add-source' command expects at least one argument"
sandboxAddSource verbosity extra sandboxFlags globalFlags
("delete-source":extra) -> do
when (noExtraArgs extra) $
die "The 'sandbox delete-source' command expects \
\at least one argument"
sandboxDeleteSource verbosity extra sandboxFlags globalFlags
["list-sources"] -> sandboxListSources verbosity sandboxFlags globalFlags
-- More advanced commands.
("hc-pkg":extra) -> do
when (noExtraArgs extra) $
die $ "The 'sandbox hc-pkg' command expects at least one argument"
sandboxHcPkg verbosity sandboxFlags globalFlags extra
["buildopts"] -> die "Not implemented!"
-- Hidden commands.
["dump-pkgenv"] -> dumpPackageEnvironment verbosity sandboxFlags globalFlags
-- Error handling.
[] -> die $ "Please specify a subcommand (see 'help sandbox')"
_ -> die $ "Unknown 'sandbox' subcommand: " ++ unwords extraArgs
where
noExtraArgs = (<1) . length
execAction :: ExecFlags -> [String] -> GlobalFlags -> IO ()
execAction execFlags extraArgs globalFlags = do
let verbosity = fromFlag (execVerbosity execFlags)
(useSandbox, config) <- loadConfigOrSandboxConfig verbosity globalFlags
mempty
let configFlags = savedConfigureFlags config
(comp, platform, conf) <- configCompilerAux' configFlags
exec verbosity useSandbox comp platform conf extraArgs
userConfigAction :: UserConfigFlags -> [String] -> GlobalFlags -> IO ()
userConfigAction ucflags extraArgs globalFlags = do
let verbosity = fromFlag (userConfigVerbosity ucflags)
case extraArgs of
("diff":_) -> mapM_ putStrLn =<< userConfigDiff globalFlags
("update":_) -> userConfigUpdate verbosity globalFlags
-- Error handling.
[] -> die $ "Please specify a subcommand (see 'help user-config')"
_ -> die $ "Unknown 'user-config' subcommand: " ++ unwords extraArgs
-- | See 'Distribution.Client.Install.withWin32SelfUpgrade' for details.
--
win32SelfUpgradeAction :: Win32SelfUpgradeFlags -> [String] -> GlobalFlags
-> IO ()
win32SelfUpgradeAction selfUpgradeFlags (pid:path:_extraArgs) _globalFlags = do
let verbosity = fromFlag (win32SelfUpgradeVerbosity selfUpgradeFlags)
Win32SelfUpgrade.deleteOldExeFile verbosity (read pid) path
win32SelfUpgradeAction _ _ _ = return ()
| kosmikus/cabal | cabal-install/Main.hs | bsd-3-clause | 53,349 | 0 | 24 | 14,955 | 9,324 | 4,912 | 4,412 | 861 | 13 |
-- | Internal constructors and helper functions. Note that no guarantees are given for stability of these interfaces.
module Network.Wai.Middleware.RequestSizeLimit.Internal
( RequestSizeLimitSettings(..)
, setMaxLengthForRequest
, setOnLengthExceeded
) where
import Network.Wai
import Data.Word (Word64)
-- | Settings to configure 'requestSizeLimitMiddleware'.
--
-- This type (but not the constructor, or record fields) is exported from "Network.Wai.Middleware.RequestSizeLimit".
-- Since the constructor isn't exported, create a default value with 'defaultRequestSizeLimitSettings' first,
-- then set the values using 'setMaxLengthForRequest' and 'setOnLengthExceeded' (See the examples below).
--
-- If you need to access the constructor directly, it's exported from "Network.Wai.Middleware.RequestSizeLimit.Internal".
--
-- ==== __Examples__
--
-- ===== Conditionally setting the limit based on the request
-- > {-# LANGUAGE OverloadedStrings #-}
-- > import Network.Wai
-- > import Network.Wai.Middleware.RequestSizeLimit
-- >
-- > let megabyte = 1024 * 1024
-- > let sizeForReq req = if pathInfo req == ["upload", "image"] then pure $ Just $ megabyte * 20 else pure $ Just $ megabyte * 2
-- > let finalSettings = setMaxLengthForRequest sizeForReq defaultRequestSizeLimitSettings
--
-- ===== JSON response
-- > {-# LANGUAGE OverloadedStrings #-}
-- > import Network.Wai
-- > import Network.Wai.Middleware.RequestSizeLimit
-- > import Network.HTTP.Types.Status (requestEntityTooLarge413)
-- > import Data.Aeson
-- > import Data.Text (Text)
-- >
-- > let jsonResponse = \_maxLen _app _req sendResponse -> sendResponse $ responseLBS requestEntityTooLarge413 [("Content-Type", "application/json")] (encode $ object ["error" .= ("request size too large" :: Text)])
-- > let finalSettings = setOnLengthExceeded jsonResponse defaultRequestSizeLimitSettings
--
-- @since 3.1.1
data RequestSizeLimitSettings = RequestSizeLimitSettings
{ maxLengthForRequest :: Request -> IO (Maybe Word64) -- ^ Function to determine the maximum request size in bytes for the request. Return 'Nothing' for no limit. Since 3.1.1
, onLengthExceeded :: Word64 -> Middleware -- ^ Callback function when maximum length is exceeded. The 'Word64' argument is the limit computed by 'maxLengthForRequest'. Since 3.1.1
}
-- | Function to determine the maximum request size in bytes for the request. Return 'Nothing' for no limit.
--
-- @since 3.1.1
setMaxLengthForRequest :: (Request -> IO (Maybe Word64)) -> RequestSizeLimitSettings -> RequestSizeLimitSettings
setMaxLengthForRequest fn settings = settings { maxLengthForRequest = fn }
-- | Callback function when maximum length is exceeded. The 'Word64' argument is the limit computed by 'setMaxLengthForRequest'.
--
-- @since 3.1.1
setOnLengthExceeded :: (Word64 -> Middleware) -> RequestSizeLimitSettings -> RequestSizeLimitSettings
setOnLengthExceeded fn settings = settings { onLengthExceeded = fn }
| kazu-yamamoto/wai | wai-extra/Network/Wai/Middleware/RequestSizeLimit/Internal.hs | mit | 2,957 | 0 | 12 | 420 | 202 | 133 | 69 | 13 | 1 |
module D1 where
{-add parameter 'f' to function 'sq' . This refactoring
affects module 'D1', 'C1' and 'A1'-}
sumSquares (x:xs) = sq x + sumSquares xs
sumSquares [] = 0
sq x = x ^ pow
pow =2
| kmate/HaRe | old/testing/addOneParameter/D1.hs | bsd-3-clause | 201 | 0 | 7 | 49 | 57 | 30 | 27 | 5 | 1 |
{-# language KindSignatures #-}
{-# language PolyKinds #-}
{-# language DataKinds #-}
{-# language TypeFamilies #-}
{-# language RankNTypes #-}
{-# language NoImplicitPrelude #-}
{-# language FlexibleContexts #-}
{-# language MultiParamTypeClasses #-}
{-# language GADTs #-}
{-# language ConstraintKinds #-}
{-# language FlexibleInstances #-}
{-# language TypeOperators #-}
{-# language ScopedTypeVariables #-}
{-# language DefaultSignatures #-}
{-# language FunctionalDependencies #-}
{-# language UndecidableSuperClasses #-}
{-# language UndecidableInstances #-}
module T11523 where
import GHC.Types (Constraint, Type)
import qualified Prelude
type Cat i = i -> i -> Type
newtype Y (p :: i -> j -> Type) (a :: j) (b :: i) = Y { getY :: p b a }
class Vacuous (a :: i)
instance Vacuous a
class (Functor p, Dom p ~ Op p, Cod p ~ Nat p (->)) => Category (p :: Cat i) where
type Op p :: Cat i
type Op p = Y p
type Ob p :: i -> Constraint
type Ob p = Vacuous
class (Category (Dom f), Category (Cod f)) => Functor (f :: i -> j) where
type Dom f :: Cat i
type Cod f :: Cat j
class (Functor f, Dom f ~ p, Cod f ~ q) => Fun (p :: Cat i) (q :: Cat j) (f :: i -> j) | f -> p q
instance (Functor f, Dom f ~ p, Cod f ~ q) => Fun (p :: Cat i) (q :: Cat j) (f :: i -> j)
data Nat (p :: Cat i) (q :: Cat j) (f :: i -> j) (g :: i -> j)
instance (Category p, Category q) => Category (Nat p q) where
type Ob (Nat p q) = Fun p q
instance (Category p, Category q) => Functor (Nat p q) where
type Dom (Nat p q) = Y (Nat p q)
type Cod (Nat p q) = Nat (Nat p q) (->)
instance (Category p, Category q) => Functor (Nat p q f) where
type Dom (Nat p q f) = Nat p q
type Cod (Nat p q f) = (->)
instance Category (->)
instance Functor ((->) e) where
type Dom ((->) e) = (->)
type Cod ((->) e) = (->)
instance Functor (->) where
type Dom (->) = Y (->)
type Cod (->) = Nat (->) (->)
instance (Category p, Op p ~ Y p) => Category (Y p) where
type Op (Y p) = p
instance (Category p, Op p ~ Y p) => Functor (Y p a) where
type Dom (Y p a) = Y p
type Cod (Y p a) = (->)
instance (Category p, Op p ~ Y p) => Functor (Y p) where
type Dom (Y p) = p
type Cod (Y p) = Nat (Y p) (->)
{-
Given: Category p, Op p ~ Y p
--> Category p, Op p ~ Y p
Functor p, Dom p ~ Op p, Cod p ~ Nat p (->)
--> Category p, Op p ~ Y p
Functor p, Dom p ~ Op p, Cod p ~ Nat p (->)
Category (Dom p), Category (Cod p)
-}
| sdiehl/ghc | testsuite/tests/polykinds/T11523.hs | bsd-3-clause | 2,453 | 0 | 9 | 619 | 1,038 | 564 | 474 | -1 | -1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PartialTypeSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module T12845 where
import Data.Proxy
data Foo (m :: Bool)
type family Head (xs :: [(Bool, Bool)]) where Head (x ': xs) = x
type family Bar (x :: Bool) (y :: Bool) :: Bool
-- to trigger the bug, r and r' cannot *both* appear on the RHS
broken :: forall r r' rngs . ('(r,r') ~ Head rngs, Bar r r' ~ 'True, _)
=> Foo r -> Proxy rngs -> ()
broken x _ = let y = requireBar x :: Foo r' in ()
requireBar :: (Bar m m' ~ 'True) => Foo m -> Foo m'
requireBar = undefined
| ezyang/ghc | testsuite/tests/partial-sigs/should_compile/T12845.hs | bsd-3-clause | 666 | 0 | 10 | 164 | 225 | 128 | 97 | -1 | -1 |
{-|
Module: Math.Ftensor.SizedList
Copyright: (c) 2015 Michael Benfield
License: ISC
Lists carrying their size in their type. These are used for runtime indexing
into tensors. Many of the functions duplicate functionality for lists from
Haskell's @Prelude@.
-}
{-# OPTIONS_GHC -fplugin GHC.TypeLits.Normalise #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE DeriveFoldable #-}
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE StandaloneDeriving #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-} -- for Flattenable
module Math.Ftensor.SizedList (
SizedList(..),
(++),
concat,
length,
head,
tail,
reverse,
replicate,
take,
drop,
splitAt,
sDot,
toList',
) where
import Prelude hiding ((++), head, tail, reverse, length,
take, drop, replicate, splitAt, concat)
import qualified Prelude
import Data.Proxy
import Unsafe.Coerce
import GHC.Exts (IsList(..))
import GHC.TypeLits
import Control.DeepSeq
data SizedList (n::Nat) a where
N :: SizedList 0 a
(:-) :: a -> SizedList n a -> SizedList (n+1) a
infixr 5 :-
deriving instance Show a => Show (SizedList n a)
deriving instance Eq a => Eq (SizedList n a)
deriving instance Functor (SizedList n)
deriving instance Foldable (SizedList n)
deriving instance Traversable (SizedList n)
instance NFData a => NFData (SizedList n a) where
rnf N = ()
rnf (x:-xs) = rnf (x, xs)
(++) :: SizedList n a -> SizedList m a -> SizedList (n+m) a
(++) N r = r
(++) (x:-xs) r = x :- (++) xs r
infixr 5 ++
concat :: SizedList n (SizedList m a) -> SizedList (m*n) a
concat N = N
concat (x:-xs) = x ++ concat xs
length :: SizedList n a -> Int
length N = 0
length (_:-xs) = 1 + length xs
head :: SizedList (n+1) a -> a
head (x:-_) = x
head _ = error "head"
tail :: SizedList (n+1) a -> SizedList n a
tail (_:-xs) = xs
tail _ = error "tail"
reverse :: SizedList n a -> SizedList n a
reverse list = rev list N
where
rev :: SizedList p a -> SizedList m a -> SizedList (m+p) a
rev N ys = ys
rev (x:-xs) ys = rev xs (x:-ys)
replicate :: forall a n. KnownNat n => a -> SizedList n a
replicate val = unsafeRep (fromInteger $ natVal (Proxy :: Proxy n)) N
where
unsafeRep :: Int -> SizedList m a -> SizedList p a
unsafeRep 0 sl = unsafeCoerce sl
unsafeRep i sl = unsafeRep (i-1) (val:-sl)
take
:: KnownNat n
=> Proxy (n::Nat)
-> SizedList (m+n) a
-> SizedList n a
take p = fst . splitAt p
drop
:: KnownNat n
=> Proxy (n::Nat)
-> SizedList (m+n) a
-> SizedList m a
drop p = snd . splitAt p
splitAt
:: KnownNat n
=> Proxy (n::Nat)
-> SizedList (m+n) a
-> (SizedList n a, SizedList m a)
splitAt nP list = unsafeSplitAt (fromIntegral $ natVal nP) list
where
unsafeSplitAt :: Int -> SizedList p a -> (SizedList q a, SizedList r a)
unsafeSplitAt 0 list = unsafeCoerce (N, list)
unsafeSplitAt i list =
let (first, second) = unsafeSplitAt (i-1) (tail $ unsafeCoerce list)
in
unsafeCoerce (head (unsafeCoerce list) :- first, second)
-- | Dot product.
sDot :: Num a => SizedList n a -> SizedList n a -> a
sDot N N = 0
sDot (x:-xs) (y:-ys) = x*y + sDot xs ys
sDot _ _ = error "sDot: can't happen"
fromList_ :: [a] -> (Int, SizedList n a)
fromList_ = f 0
where
f i [] = (i, unsafeCoerce N)
f i (x:xs) =
let (sum, lst) = f (i+1) xs
in
unsafeCoerce (sum, x :- unsafeCoerce lst)
fromList__ :: [a] -> SizedList n a
fromList__ [] = unsafeCoerce N
fromList__ (x:xs) = unsafeCoerce $ x :- fromList__ xs
instance KnownNat n => IsList (SizedList n a) where
type Item (SizedList n a) = a
fromList lst
| len' == len = result
| otherwise = error $
"fromList (SizedList): list wrong size" Prelude.++ show (len, len')
where
len' = fromInteger . natVal $ (Proxy::Proxy n)
(len, result) = fromList_ lst
fromListN len lst
| len' == len = result
| otherwise = error $
"fromListN (SizedList): list wrong size" Prelude.++ show (len, len')
where
len' = fromInteger . natVal $ (Proxy::Proxy n)
result = fromList__ lst
toList = toList'
-- | Since this function can be called without requiring @KnownNat n@,
-- an implementation separate from the @IsList@ class is provided.
toList' :: SizedList n a -> [a]
toList' N = []
toList' (x:-xs) = x : toList' xs
| mikebenfield/ftensor | src/Math/Ftensor/SizedList.hs | isc | 4,543 | 0 | 14 | 1,122 | 1,729 | 905 | 824 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module Ebay.Details
( getReturnPolicyDetails
, module Ebay.Types.Details
) where
import Control.Monad.Reader
import Data.Text (Text)
import Data.XML.Pickle
import Data.XML.Types
import Ebay
import Ebay.Types.Authentication
import Ebay.Types.Details
type DetailName = Text
getDetails :: AuthToken -> DetailName -> PU [Node] a -> EbayT (StandardOutput, a)
getDetails tok dname xpOutput = do
(EbayConf{..}) <- ask
let input = (fromAuthToken tok, dname)
ebayPost "GeteBayDetails" xpInput xpOutput input
where xpInput = xp2Tuple xpWithAuth (xpElemText "{urn:ebay:apis:eBLBaseComponents}DetailName")
getReturnPolicyDetails :: AuthToken -> EbayT (StandardOutput, ReturnPolicyDetails)
getReturnPolicyDetails tok = getDetails tok "ReturnPolicyDetails"
(xpElemNodes "{urn:ebay:apis:eBLBaseComponents}ReturnPolicyDetails" xpReturnPolicyDetails)
| AndrewRademacher/hs-ebay-trading | src/Ebay/Details.hs | mit | 1,045 | 0 | 11 | 235 | 220 | 122 | 98 | 22 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.FileError
(pattern NOT_FOUND_ERR, pattern SECURITY_ERR, pattern ABORT_ERR,
pattern NOT_READABLE_ERR, pattern ENCODING_ERR,
pattern NO_MODIFICATION_ALLOWED_ERR, pattern INVALID_STATE_ERR,
pattern SYNTAX_ERR, pattern INVALID_MODIFICATION_ERR,
pattern QUOTA_EXCEEDED_ERR, pattern TYPE_MISMATCH_ERR,
pattern PATH_EXISTS_ERR, js_getCode, getCode, FileError,
castToFileError, gTypeFileError)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
pattern NOT_FOUND_ERR = 1
pattern SECURITY_ERR = 2
pattern ABORT_ERR = 3
pattern NOT_READABLE_ERR = 4
pattern ENCODING_ERR = 5
pattern NO_MODIFICATION_ALLOWED_ERR = 6
pattern INVALID_STATE_ERR = 7
pattern SYNTAX_ERR = 8
pattern INVALID_MODIFICATION_ERR = 9
pattern QUOTA_EXCEEDED_ERR = 10
pattern TYPE_MISMATCH_ERR = 11
pattern PATH_EXISTS_ERR = 12
foreign import javascript unsafe "$1[\"code\"]" js_getCode ::
JSRef FileError -> IO Word
-- | <https://developer.mozilla.org/en-US/docs/Web/API/FileError.code Mozilla FileError.code documentation>
getCode :: (MonadIO m) => FileError -> m Word
getCode self = liftIO (js_getCode (unFileError self)) | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/FileError.hs | mit | 1,959 | 6 | 9 | 262 | 514 | 312 | 202 | 39 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
-- | GitHub event predicates.
-- Mostly for filtering events.
module Github.Event.Predicate
( isInterestingEvent
, isClosingIssueComment
) where
import Github.Api
-- ----------------------------------------------
-- | If an 'Event' is interesting enough to be considered for publication.
isInterestingEvent :: Event -> Bool
isInterestingEvent e
= isInterestingPush p
|| isInterestingPR p
|| isInterestingIssue p
|| isInterestingIssueComment p
|| isInterestingReview p
|| isInterestingReviewComment p
|| isInterestingStatus p
|| isPingEvent p
where p = evtPayload e
isInterestingPush :: EventPayload -> Bool
-- ignore pushes that are the result of a GitHub PR merge using the web interface
isInterestingPush (PushEvent _ _ (Just (PushCommit _ _ (Committer email username _))) _ _)
= not (email == "[email protected]" && username == "web-flow")
isInterestingPush PushEvent{} = True
isInterestingPush _ = False
isInterestingPR :: EventPayload -> Bool
isInterestingPR PullRequestEvent{..}
= eprAction == "opened"
|| eprAction == "synchronize"
|| eprAction == "closed"
|| eprAction == "reopened"
isInterestingPR _ = False
isInterestingIssue :: EventPayload -> Bool
isInterestingIssue IssuesEvent{..}
= eisAction == "opened"
|| eisAction == "closed"
|| eisAction == "reopened"
isInterestingIssue _ = False
isInterestingIssueComment :: EventPayload -> Bool
isInterestingIssueComment IssueCommentEvent{..}
= ecoAction == "created"
isInterestingIssueComment _ = False
isInterestingReview :: EventPayload -> Bool
isInterestingReview PullRequestReviewEvent{..}
= True
isInterestingReview _ = False
isInterestingReviewComment :: EventPayload -> Bool
isInterestingReviewComment PullRequestReviewCommentEvent{..}
= ercAction == "created"
isInterestingReviewComment _ = False
isInterestingStatus :: EventPayload -> Bool
isInterestingStatus StatusEvent{..}
= estState /= "pending"
isInterestingStatus _ = False
-- | If an event is the accompanying comment to the closing of an issue.
isClosingIssueComment :: EventPayload -> Bool
isClosingIssueComment IssueCommentEvent{..}
= issClosed_at ecoIssue == Just (comCreated_at ecoComment)
isClosingIssueComment _ = False
| UlfS/ghmm | src/Github/Event/Predicate.hs | mit | 2,310 | 0 | 13 | 364 | 495 | 254 | 241 | 55 | 1 |
module Excersises_02 where
import qualified Data.Time as Time
import qualified Data.Map as Map
import Data.Maybe
--datatype in record syntax
data Person = Male { firstName :: String, lastName :: String } | Female { firstName :: String, lastName :: String } | Asexual { designation :: String } deriving (Show)
--function that takes in a female, uses person@ for the entire pattern (Female _ _ )
--function that takes in a male uses standard datatype sytnax, also works as it should
greet :: Person -> String
greet person@(Female _ _) = "Hello, Miss " ++ (firstName person) ++ " " ++ (lastName person)
greet (Male firstName lastName) = "Hello, Mister " ++ firstName ++ " " ++ lastName
main_10 = do
--equivalent invocations
print $ greet $ Male { lastName="Doe", firstName="John" }
print $ greet $ Male "John" "Doe"
print $ greet $ Female "Jane" "Doe"
return ()
--generic type, 'a' can be of any type
data Nullable a = Null | Value a
printn :: (Show a) => Nullable a -> IO ()
printn (Value a) = print a
printn Null = print "NULL"
getnull :: Nullable a
getnull = Null
--construction of a custom Vector datatype
--functions are defined with infix notation `nameOfFunction`
data Vector a = Vector a a a deriving (Show)
vplus :: (Num t) => Vector t -> Vector t -> Vector t
(Vector i j k) `vplus` (Vector l m n) = Vector (i+l) (j+m) (k+n)
vectMult :: (Num t) => Vector t -> t -> Vector t
(Vector i j k) `vectMult` m = Vector (i*m) (j*m) (k*m)
scalarMult :: (Num t) => Vector t -> Vector t -> t
(Vector i j k) `scalarMult` (Vector l m n) = i*l + j*m + k*n
--making our custom type implement a typeclass
data Person2 = Person2 { name :: String, age :: Int, dateOfBirth :: Time.Day } deriving (Eq, Show, Read)
--enum type
data Day = Monday | Tuesday | Wednesday | Thursday | Friday | Saturday | Sunday deriving (Eq, Show, Read, Bounded, Enum, Ord)
main_20 :: IO ()
main_20 = do
printn $ Value 5
printn $ Value "thing"
printn $ (Null :: Nullable Int)
--Maybe is Prelude's nullable
print $ Just 5
print $ (Nothing :: Maybe Int)
--default behavior for Show is generated by compiler
print $ Person2 "Tino" 30 (Time.fromGregorian 1983 12 22)
--parsing from String (specify reads return type)
let thing = read "Wednesday" :: Day
print thing
--minBound and maxBound return biggest and smallest value for Day datatype
print (minBound :: Day)
print (maxBound :: Day)
--since we are part of Enum we can do this
print $ succ Monday
print $ pred Wednesday
print $ [Monday .. Sunday]
return ()
--aliasing typenames
type Pair a = (a,a)
type PairInt = Pair Int
--we can use type alias, also demonstrate function that does IO
printPair :: PairInt -> IO()
printPair (a,b) = do
print "PAIR"
print $ " " ++ (show a) ++ ":" ++ (show b)
--doing lookups in a map, using case
findAndPrintValue :: (Ord a, Show b) => a -> Map.Map a b -> IO()
findAndPrintValue key map = let res = Map.lookup key map in
case res of
Nothing -> print "Nothing found!!!"
Just b -> print b
main_30 :: IO()
main_30 = do
let b = (3,4)
printPair b
--maps and lookups
let mapping = Map.fromList [(0,"a"),(1,"b"),(2,"c")]
findAndPrintValue 0 mapping
findAndPrintValue 1 mapping
findAndPrintValue 5 mapping
return ()
--definition of our own typeclass
class XMLSerializable arg where
serializeToXML :: arg -> String
deserializeFromXML :: String -> arg
--implement Person type as instance of XMLSerializable typeclass
instance XMLSerializable Person where
serializeToXML a = let name = "<name>" ++ (firstName a) ++ " " ++ (lastName a) ++ "</name>"
persontype = case a of
Male _ _ -> "<type>Male</type>"
Female _ _ -> "<type>Female</type>"
in "<person>" ++ name ++ persontype ++ "</person>"
deserializeFromXML xml = Male "fake" "fake"
--implement serialization for a pair of values, each of which must be itself serializable
--we use typeclass constraint (XML.. a, XML.. b) =>
instance (XMLSerializable a, XMLSerializable b) => XMLSerializable (a,b) where
serializeToXML (arg1,arg2) = (serializeToXML arg1) ++ (serializeToXML arg2)
deserializeFromXML xml = ((deserializeFromXML xml) , (deserializeFromXML xml))
--implementing YesNo behavior for various types
class YesNo a where
is :: a -> Bool
--basic stuff
instance YesNo Int where
is 0 = False
is _ = True
instance YesNo [a] where
is [] = False
is _ = True
--id is a standard identity function (id a = a)
instance YesNo Bool where
is = id
--when implementing YesNo for Maybe, use False when Nothing, otherwise use value contained in Just
instance (YesNo a) => YesNo (Maybe a) where
is Nothing = False
is (Just arg) = is arg
--if a type T is instance of Functor typeclass, it has to implement fmap function that takes in (a -> b) and translates T a to T b
--these are test function to show how it does that
addOne :: Int -> Int
addOne = (+ 1)
addOneAndShow :: Int -> String
addOneAndShow = show . addOne
--we can use p { arg = ((arg p) + 1) } to copy the object with changes to it
--when using flipNames with incompatible form, we won't get compile time error, but we WILL get runtime error
--so we have to override the behaviour in case of constructor with different signature
flipNames :: Person -> Person
flipNames p@(Asexual {}) = p
flipNames p = p { firstName = lastName p, lastName = firstName p }
main :: IO()
main = do
print $ serializeToXML $ Male "tino" "juricic"
print $ serializeToXML ((deserializeFromXML "lalalal") :: Person)
print $ is (0 :: Int)
print $ is [1]
print $ is (Nothing :: Maybe Int)
--use fmap (map that can work on types implementing Functor typeclass)
--Functor typeclass defines a function in which Type a goes into Type b when we have function (a -> b), or to put it like this: given contructor f, fmap is (a -> b) -> f a -> f b
--list implements a functor
print $ [1,2,3]
print $ fmap addOneAndShow [1,2,3]
print $ flipNames $ Male "john" "smith"
print $ flipNames $ Female "jane" "watson"
print $ flipNames $ Asexual "amiffskatenwaf"
return () | omittones/haskell-test | src/Excersises_02.hs | mit | 6,401 | 0 | 15 | 1,586 | 1,830 | 955 | 875 | 110 | 2 |
{-# htermination (isNaNFloat :: Float -> MyBool) #-}
import qualified Prelude
data MyInt = Pos Nat | Neg Nat ;
data Nat = Succ Nat | Zero ;
data MyBool = MyTrue | MyFalse
data List a = Cons a (List a) | Nil
data Float = Float MyInt MyInt ;
isNaNFloat :: Float -> MyBool
isNaNFloat vv = MyFalse;
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/basic_haskell/isNaN_1.hs | mit | 307 | 0 | 8 | 72 | 95 | 56 | 39 | 8 | 1 |
{-# OPTIONS -Wall -fwarn-tabs -fno-warn-type-defaults #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
module HeightMap.Mesh
where
import HeightMap.Base (heightMap,heightMap',unitHeightMap,unitHeightMap')
| ftomassetti/haskell-diamond-square | src/HeightMap/Mesh.hs | mit | 270 | 0 | 5 | 26 | 29 | 20 | 9 | 6 | 0 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE QuasiQuotes #-}
-- |
--
-- > {-# LANGUAGE TemplateHaskell #-}
-- >
-- > import Prelude hiding (error)
-- > import ErrorLoc
-- >
-- > main :: IO ()
-- > main = $error "Oh no!"
--
-- > test.hs:7:10: Oh no!
module ErrorLoc (error) where
import Language.Haskell.TH
import Prelude hiding (error)
import qualified Prelude as P
-- | Provides a version of 'Prelude.error' with call-site metadata.
error :: Q Exp
error = do
loc <- location
[e|(.) P.error (concat [$(stringE (loc_filename loc))
, ":"
, $(stringE . show . fst $ loc_start loc)
, ":"
, $(stringE . show . snd $ loc_start loc)
, ": "] ++)|]
| pikajude/error-loc | ErrorLoc.hs | mit | 787 | 0 | 7 | 263 | 71 | 50 | 21 | 15 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module HamiltonGraph where
import Data.Graph
import qualified Data.Set as S
import GaGraph
import Individual
import Control.Monad.State
import Control.Monad.List
import Control.Lens
import Control.Monad
import Control.Monad.List as L
data HamiltonGraph = HamiltonGraph {graph :: Graph, genome :: Int}
data HamiltonEdgesState = HamiltonEdgesState {_outbound :: [Vertex], _inbound :: [Vertex]}
makeLenses ''HamiltonEdgesState
instance Individual HamiltonGraph where
mutate = mutateBitString
crossover = crossoverBitString
maxLocale HamiltonGraph{graph = g} = hamiltonPathDimension g - 1
fitnesse eg@HamiltonGraph{graph = g} = hamiltonFitnesse2 g $ hamiltonPhenotype eg
instance BitStringInd HamiltonGraph where
getGenome ind = genome ind
setGenome ind newG = ind{genome = newG}
hamiltonPathDimension :: Graph -> Int
hamiltonPathDimension g = (vertexDimension g) * (verticesNum g)
hamiltonPhenotype :: HamiltonGraph -> [Vertex]
hamiltonPhenotype HamiltonGraph{graph = g, genome = gen} = mapFromBits gen len cnt
where len = vertexDimension g
cnt = verticesNum g
-- fitnesse is count of unique edges in which vertexes isn't repeated
hamiltonFitnesse1 :: Graph -> [Vertex] -> Int
hamiltonFitnesse1 g = countHamiltonEdges
.(formUniqueEdgesSequence g)
countHamiltonEdges :: [Edge] -> Int
countHamiltonEdges e = evalState (foldM doCountHamiltonEdges 0 e) initState
where initState = HamiltonEdgesState {_outbound = [], _inbound = [startVertex e]}
doCountHamiltonEdges :: Int -> Edge -> State HamiltonEdgesState Int
doCountHamiltonEdges accum (o,i) =
do outbounds <- use outbound
inbounds <- use inbound
if (not (o `elem` outbounds)) && (not (i `elem` inbounds))
then do
outbound .= o:outbounds
inbound .= i:inbounds
return (accum + 1)
else return accum
-- fitnesse is score = m + (max {|Pe|} - 1) * n,
-- where m - count of unique edges in path
-- |Pe| - cardinality of uninterrupted subpath
-- {|Pe|} - set of cardinalities of all uninterrupted subpaths
-- n - count of vertexes
hamiltonFitnesse2 :: Graph -> [Vertex] -> Int
hamiltonFitnesse2 g path = m + (maxP - 1) * n
where m = length $ formUniqueEdgesSequence g path
maxCard = maxCardinality g path
maxP = if(maxCard > 0) then maxCard else 1
n = verticesNum g
maxCardinality :: Graph -> [Vertex] -> Int
maxCardinality g = maxDef0
.(map length)
.(filter (\p -> (length.uniqueEdges) p == length p))
.(subpaths g)
maxDef0 :: [Int] -> Int
maxDef0 [] = 0
maxDef0 v = maximum v
subpaths :: Graph -> [Vertex] -> [[Edge]]
subpaths g [] = []
subpaths g (v:[]) = []
subpaths g vertexes@(v:tail) = (splitToSubPaths $ subpath g vertexes) ++ subpaths g tail
splitToSubPaths :: [Edge] -> [[Edge]]
splitToSubPaths path = evalState (foldM doSplitToSubPaths [] path) []
doSplitToSubPaths :: [[Edge]] -> Edge -> State [Edge] [[Edge]]
doSplitToSubPaths accum e =
do cp <- get
let np = cp ++ [e]
put np
return $ np:accum
subpath :: Graph -> [Vertex] -> [Edge]
subpath g v =
let edges = formEdges v
initState = S.fromList [startVertex edges]
in evalState (doSubpath g edges) initState
doSubpath :: Graph -> [Edge] -> State (S.Set Vertex) [Edge]
doSubpath _ [] = do return []
doSubpath g (e@(_,f):tail) =
do ctx <- get
if((hasEdge e g) && not (f `S.member` ctx))
then do
put $ f `S.insert` ctx
lowerSubPath <- doSubpath g tail
return $ e:lowerSubPath
else return []
| salamansar/GA-cube | src/HamiltonGraph.hs | mit | 3,645 | 4 | 13 | 832 | 1,226 | 651 | 575 | 85 | 2 |
import Control.Monad
import Data.List
import Data.Bits
import Data.Int (Int64)
import Text.Printf
-- q = 0,1,2,3
centerCoord :: Int -> Int
centerCoord x
| abs (x-1) <= 1 = 1
| abs (x-4) <= 1 = 4
| otherwise = error "bad coordinate"
center :: Int -> (Int,Int)
center q
| q == 0 = (1,1)
| q == 1 = (1,4)
| q == 2 = (4,1)
| q == 3 = (4,4)
| otherwise = error "bad quadrant"
rotate_ cw q (x,y)
| (cx,cy) /= (qx,qy) = (x,y)
| otherwise = (cx - s*dy, cy + s*dx)
where
(qx,qy) = center q
cx = centerCoord x
cy = centerCoord y
dx = x-cx
dy = y-cy
s = if cw then 1 else -1
rotateCW q (x,y) = rotate_ True q (x,y)
rotateCCW q (x,y) = rotate_ False q (x,y)
bitIndex (x,y) = x*6+y
showMatrix m m' = unlines [ unwords (compareRow r r') | (r,r') <- zip m m' ]
compareRow xs ys = zipWith go xs ys
where go x y = if x == y then " . " else show y
showRotation q cw = do
let m = [ [ (i,j) | j <- [0..5] ] | i <- [0..5] ]
m' = map (map (rotate_ cw q) ) m
c = if cw then "clockwise" else "counter-clockwise"
putStrLn $ "Rotation of quadrant " ++ show q ++ " " ++ c
putStrLn $ showMatrix m m'
test1 = showRotation 0 True
pairs xs = zip xs (tail $ cycle xs)
genRotation q cw = do
let (qx,qy) = center q
xy1 = (qx-1,qy-1)
xy2 = (qx-1,qy)
chain1 = take 4 $ iterate (rotate_ (not cw) q) xy1
chain2 = take 4 $ iterate (rotate_ (not cw) q) xy2
-- putStrLn $ "cw chain1: " ++ intercalate " - " (map show chain1)
-- putStrLn $ "cw chain2: " ++ intercalate " - " (map show chain2)
let mask1 = foldl' setBit (0::Int64) indx1
mask2 = foldl' setBit (0::Int64) indx2
indx1 = map bitIndex chain1
indx2 = map bitIndex chain2
-- putStrLn $ printf "mask1 = 0x%010x" mask1
-- putStrLn $ printf "mask2 = 0x%010x" mask2
let trans1 = intercalate " . " [ "tb v " ++ show i ++ " " ++ show j | (i,j) <- pairs indx1 ]
trans2 = intercalate " . " [ "tb v " ++ show i ++ " " ++ show j | (i,j) <- pairs indx2 ]
-- putStrLn $ "trans1: " ++ trans1
-- putStrLn $ "trans2: " ++ trans2
let code = [ name ++ " v = maskbits (maskbits v m1 b1) m2 b2"
, " where"
, " m1 = " ++ printf "0x%010x" mask1
, " b1 = " ++ trans1 ++ " $ 0"
, " m2 = " ++ printf "0x%010x" mask2
, " b2 = " ++ trans2 ++ " $ 0"
]
name = "rot" ++ show q ++ (if cw then "cw" else "ccw")
putStrLn $ unlines code
{-# INLINE maskbits #-}
maskbits v m b = (v .&. (complement m) .|. b)
{-# INLINE tb #-}
-- tb v i j m = if testBit i v then setBit j m else m
tb v i j m = m .|. (rotate (v .&. (bit i)) (j-i))
genRotations = do
let defs = [ "{-# INLINE maskbits #-}"
, "maskbits v m b = (v .&. (complement m) .|. b)"
, ""
, "{-# INLINE tb #-}"
, "tb v i j m = m .|. (rotate (v .&. (bit i)) (j-i))"
]
putStrLn $ unlines defs
forM_ [0..3] $ \q ->
forM_ [True,False] $ \cw -> do
genRotation q cw
putStrLn ""
main = genRotations
| erantapaa/haskell-pentago | genRotations.hs | mit | 3,097 | 0 | 15 | 992 | 1,253 | 652 | 601 | 76 | 2 |
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
-- module
module CardMaps ( CardMap
, CardMapW(..)
, QuantityMap
, findByName
, updateQuantity
, dumpQuantity
, missingQuantity
) where
import Control.Monad.Except
import Data.Aeson
import qualified Data.Map as M
import Data.Maybe
import qualified Data.Vector as V
import Card
-- exported types
type IdMap a = M.Map CardId a
type CardMap = IdMap Card
type QuantityMap = IdMap CardQuantity
newtype CardMapW = CardMapW { getCardMap :: CardMap }
-- instances
instance FromJSON CardMapW where
parseJSON = withArray "CardMap" $ return
. CardMapW
. V.foldl' insertIfResult M.empty
. fmap fromJSON
where insertIfResult m (Success c) = insertCard c m
insertIfResult m (Error _) = m
-- exported functions
findByName :: MonadError String m => CardMap -> CardName -> m CardId
findByName cmap cname =
case M.size matches of
1 -> return $ cardId $ head $ M.elems matches
0 -> throwError $ "found no card named " ++ getCardName cname
_ -> throwError $ "found more than one card named " ++ getCardName cname ++ "!!?"
where matches = M.filter (\c -> cardName c == cname) cmap
updateQuantity :: QuantityMap -> CardMap -> CardMap
updateQuantity = flip $ M.foldlWithKey' combine
where combine c i q = M.adjust (setQuantity q) i c
dumpQuantity :: CardMap -> QuantityMap
dumpQuantity = M.mapMaybe cardQuantity
missingQuantity :: CardMap -> CardMap
missingQuantity = M.filter $ isNothing . cardQuantity
-- internal functions
insertCard :: Card -> CardMap -> CardMap
insertCard c cm = M.insert (cardId c) c cm
| nicuveo/HCM | src/CardMaps.hs | mit | 1,951 | 0 | 11 | 607 | 473 | 255 | 218 | 43 | 3 |
hue a b c = if a + b < 10
then "hello"
else if c > 9
then "wow so big"
else "oh that's okay"
asdf = hue 1 2 3
a = (\x -> x + 1) [1, 2, 3]
test f =
let k = f + 1
in case k of
10 -> 9
_ -> 100
| santolucito/ives | Ives/SymbolicExecution/Sample.hs | mit | 234 | 0 | 9 | 104 | 121 | 64 | 57 | 12 | 3 |
module GHCJS.DOM.InspectorFrontendHost (
) where
| manyoo/ghcjs-dom | ghcjs-dom-webkit/src/GHCJS/DOM/InspectorFrontendHost.hs | mit | 51 | 0 | 3 | 7 | 10 | 7 | 3 | 1 | 0 |
{- |
Copyright: (c) 2022 Kowainik
SPDX-License-Identifier: BSD-3-Clause
Maintainer: Kowainik <[email protected]>
Stack-only example with all integrations
-}
module StackFull
( projectName
) where
projectName :: String
projectName = "stack-full"
| vrom911/hs-init | summoner-cli/examples/stack-full/src/StackFull.hs | mit | 259 | 0 | 4 | 41 | 20 | 13 | 7 | 4 | 1 |
{-# LANGUAGE OverloadedStrings #-}
-----------------------------------------------------------------------------
-- |
-- Module : Database.Kdb.Internal.TypesTest
-- Copyright : (c) 2014, Jakub Kozlowski
-- License : MIT
--
-- Maintainer : [email protected]
--
-- Tests for 'Database.Kdb.Internal.IPC'.
-----------------------------------------------------------------------------
module Database.Kdb.Internal.IPCTest (tests) where
import qualified Blaze.ByteString.Builder as Blaze
import Control.Applicative ((<$>), (<*))
import Control.DeepSeq (deepseq)
import qualified Data.Attoparsec as A
import qualified Data.ByteString as B
import Data.ByteString.Base16 (decode, encode)
import Data.ByteString.Char8 (ByteString, unpack)
import Data.Time (Day, NominalDiffTime,
TimeOfDay (..),
UTCTime (..),
diffUTCTime,
fromGregorian,
timeOfDayToTime,
timeOfDayToTime)
import qualified Database.Kdb.Internal.IPC as IPC
import Database.Kdb.Internal.Types.KdbTypes (Value, bool, boolV, byte,
byteV, char, charV, date,
dateTime, dateTimeV,
dateV, dict, float,
floatV, int, intV, list,
long, longV, longVV,
minute, minuteV, month,
monthV, real, realV, s,
second, secondV, short,
shortV, symV, symVV,
table, time, timeV,
timespan, timespanV,
timestamp, timestampV)
import qualified System.Endian as End
import Test.Tasty
import Test.Tasty.HUnit (assertEqual,
assertFailure, testCase)
tests :: TestTree
tests = testGroup "Database.Kdb.Internal.IPC" [ qcProps, unitTests ]
qcProps :: TestTree
qcProps = testGroup "(checked by QuickCheck)"
[
]
unitTests :: TestTree
unitTests = testGroup "Unit tests" [
testGroup "Serialisation" $ testCases serializationTest
, testGroup "Deserialisation" $ testCases deserializationTest
]
type SimpleTestCase = (String, Value, ByteString)
testCases :: (SimpleTestCase -> TestTree) -> [TestTree]
testCases f = f <$> t
serializationTest :: SimpleTestCase -> TestTree
serializationTest (msg, actual, expected) = testCase msg $ do
let actualIPC = Blaze.toByteString $ IPC.asyncIPC actual
msg' = unlines [
msg
, " actual =" ++ (unpack . encode $ actualIPC)
, " expected=" ++ unpack expected
, " expectedValue=" ++ show actual
]
assertEqual msg' (fst . decode $ expected) actualIPC
deserializationTest :: SimpleTestCase -> TestTree
deserializationTest (msg, actual, expected) = testCase msg $ do
let actualDecoded = A.parseOnly (IPC.ipcParser <* A.endOfInput) (fst . decode $ expected)
case actualDecoded of
Left m -> assertFailure m
Right v -> assertEqual msg v actual
-- | Day used for tests.
--
-- Needs to be the first day and month to not upset some tests.
testDay :: Day
testDay = fromGregorian 2014 1 1
-- | UTCTime used for tests.
testUtcTimeToSecond :: UTCTime
testUtcTimeToSecond = UTCTime testDay $ timeOfDayToTime $ TimeOfDay 19 38 38
-- | UTCTime used for tests.
testUtcTimeToNanos :: UTCTime
testUtcTimeToNanos = UTCTime testDay $ timeOfDayToTime $ TimeOfDay 19 38 38.312312323
testNominalDiffTimeToNano :: NominalDiffTime
testNominalDiffTimeToNano =
let midnight = UTCTime testDay 0
theTime = UTCTime testDay $ timeOfDayToTime (TimeOfDay 12 12 12.123456789)
in diffUTCTime theTime midnight
testNominalDiffTimeToMinute :: NominalDiffTime
testNominalDiffTimeToMinute =
let midnight = UTCTime testDay 0
theTime = UTCTime testDay $ timeOfDayToTime (TimeOfDay 12 12 0)
in diffUTCTime theTime midnight
testNominalDiffTimeToSecond :: NominalDiffTime
testNominalDiffTimeToSecond =
let midnight = UTCTime testDay 0
theTime = UTCTime testDay $ timeOfDayToTime (TimeOfDay 12 12 12)
in diffUTCTime theTime midnight
todToMilli :: TimeOfDay
todToMilli = TimeOfDay 12 12 12.123
-- | Test cases for all types.
--
-- System endianess gets prepended.
-- TODO: add tests for empty vectors.
t :: [SimpleTestCase]
t =
let prepare (a, b, c) = (a, deepseq b b, B.append end c)
end = case End.getSystemEndianness of
End.BigEndian -> "00"
End.LittleEndian -> "01"
in prepare <$> [
-- KBool
( "q)-8!\"b\"1"
, bool True
, "0000000A000000FF01"
)
-- KByte
, ( "q)-8!\"x\"$97"
, byte 97
, "0000000A000000FC61"
)
-- KShort
, ( "q)-8!\"h\"$12"
, short 12
, "0000000B000000FB0C00"
)
-- KInt
, ( "q)-8!\"i\"$100000000"
, int 100000000
, "0000000D000000FA00E1F505"
)
-- KLong
, ( "q)-8!\"j\"$123456789012345678"
, long (123456789012345678 :: Int)
, "00000011000000F94EF330A64B9BB601"
)
-- KReal
, ( "q)-8!\"e\"$3.14"
, real 3.14
, "0000000D000000F8C3F54840"
)
-- KFloat
, ( "q)-8!\"f\"$1.6180"
, float 1.6180
, "00000011000000F717D9CEF753E3F93F"
)
-- KChar
, ( "q)-8!\"c\"$30"
, char 'c'
, "0000000A000000F663"
)
-- KSymbol
, ( "q)-8!`helloword"
, s "helloworld"
, "00000014000000F568656C6C6F776F726C6400"
)
, -- KTimestamp
( "q)-8!\"P\"$\"2014-1-1T19:38:38.312312323\""
, timestamp testUtcTimeToNanos
, "00000011000000F4036E082830042206"
)
-- KMonth
, ( "q)-8!\"M\"$\"2014/01\""
, month testDay
, "0000000D000000F3A8000000"
)
, ( "q)-8!\"D\"$\"2014/1/1\""
, date testDay
, "0000000D000000F2FA130000"
)
-- KDateTime
, ( "q)-8!\"Z\"$\"2014-1-1T19:38:38"
, dateTime testUtcTimeToSecond
, "00000011000000F1AB9FE988D1FAB340"
)
-- KTimespan
, ( "q)-8!\"N\"$\"12:12:12.123456789\""
, timespan testNominalDiffTimeToNano
, "00000011000000F015E59CBEF4270000"
)
-- KMinute
, ( "q)-8!\"U\"$\"12:12\""
, minute testNominalDiffTimeToMinute
, "0000000D000000EFDC020000"
)
-- KSecond
, ( "q)-8!\"V\"$\"12:12:12\""
, second testNominalDiffTimeToSecond
, "0000000D000000EE9CAB0000"
)
-- Ktime
, ( "q)-8!\"T\"$\"12:12:12:123\""
, time todToMilli
, "0000000D000000EDDB599E02"
)
-- KBoolV
, ( "q)-8!enlist 0b"
, boolV [False]
, "0000000F00000001000100000000"
)
-- KByteV
, ( "q)-8!`byte$til 5"
, byteV [0..4]
, "000000130000000400050000000001020304"
)
-- KShortV
, ( "q)-8!`short$til 5"
, shortV [0..4]
, "0000001800000005000500000000000100020003000400"
)
-- KIntV
, ( "q)-8!`int$til 5"
, intV [0..4]
, "000000220000000600050000000000000001000000020000000300000004000000"
)
-- KLongV
, ( "q)-8!`long$til 5"
, longV [0..4]
, "0000003600000007000500000000000000000000000100000000000000020000000000000003000000000000000400000000000000"
)
-- KRealV
, ( "q)-8!`real$til 5"
, realV [0..4]
, "00000022000000080005000000000000000000803F000000400000404000008040"
)
-- KFloatV
, ( "q)-8!`float$til 5"
, floatV [0..4]
, "000000360000000900050000000000000000000000000000000000F03F000000000000004000000000000008400000000000001040"
)
-- KCharV
, ( "q)-8!\"Hello\""
, charV "Hello"
, "000000130000000A000500000048656C6C6F"
)
-- KSymV
, ( "q)-8!`Hello`World"
, symV ["Hello", "World"]
, "0000001A0000000B000200000048656C6C6F00576F726C6400"
)
-- KTimestampV
, ( "q)-8!enlist \"P\"$\"2014-1-1T19:38:38.312312323\""
, timestampV [testUtcTimeToNanos]
, "000000160000000C0001000000036E082830042206"
)
-- KMonthV
, ( "q)-8!enlist \"M\"$\"2014/01\""
, monthV [testDay]
, "000000120000000D0001000000A8000000"
)
-- KDateV
, ( "q)-8!enlist \"D\"$\"2014/1/1\""
, dateV [testDay]
, "000000120000000E0001000000FA130000"
)
-- KDateTimeV
, ( "q)-8!enlist \"Z\"$\"2014-1-1T19:38:38"
, dateTimeV [testUtcTimeToSecond]
, "000000160000000F0001000000AB9FE988D1FAB340"
)
-- KTimespanV
, ( "q)-8!enlist \"N\"$\"12:12:12.123456789\""
, timespanV [testNominalDiffTimeToNano]
, "0000001600000010000100000015E59CBEF4270000"
)
-- KMinuteV
, ( "q)-8!enlist \"U\"$\"12:12\""
, minuteV [testNominalDiffTimeToMinute]
, "00000012000000110001000000DC020000"
)
-- KSecondV
, ( "q)-8!enlist \"V\"$\"12:12:12\""
, secondV [testNominalDiffTimeToSecond]
, "000000120000001200010000009CAB0000"
)
-- KTimeV
, ( "q)-8!enlist \"T\"$\"12:12:12:123\""
, timeV [todToMilli]
, "00000012000000130001000000DB599E02"
)
-- KList
, ( "q)-8!enlist each 2 3"
, list [longV [2], longV [3]]
, "0000002A00000000000200000007000100000002000000000000000700010000000300000000000000"
)
-- KDict
, ( "q)-8!`a`b!2 3"
, dict (symVV ["a", "b"]) (longVV [2, 3])
, "00000029000000630B00020000006100620007000200000002000000000000000300000000000000"
)
-- KTable
, ( "q)-8!'(flip`a`b!enlist each 2 3;([]a:enlist 2;b:enlist 3))"
, table [symV ["a", "b"], list [intV [2], intV[3]]]
, "0000002f0000006200630b0002000000610062000000020000000600010000000200000006000100000003000000"
)
]
| jkozlowski/kdb-haskell | tests/Database/Kdb/Internal/IPCTest.hs | mit | 10,778 | 0 | 16 | 3,655 | 1,762 | 1,040 | 722 | 202 | 2 |
{-# LANGUAGE ScopedTypeVariables #-}
module Orville.PostgreSQL.Internal.MigrationLock
( withLockedTransaction,
)
where
import Control.Concurrent (threadDelay)
import Control.Exception (Exception, throwIO)
import qualified Control.Monad as Monad
import qualified Control.Monad.IO.Class as MIO
import Data.Int (Int32)
import qualified Orville.PostgreSQL.Internal.Execute as Execute
import qualified Orville.PostgreSQL.Internal.FieldDefinition as FieldDefinition
import qualified Orville.PostgreSQL.Internal.MonadOrville as MonadOrville
import qualified Orville.PostgreSQL.Internal.RawSql as RawSql
import qualified Orville.PostgreSQL.Internal.SqlMarshaller as SqlMarshaller
import qualified Orville.PostgreSQL.Internal.SqlValue as SqlValue
import qualified Orville.PostgreSQL.Internal.Transaction as Transaction
withLockedTransaction :: forall m a. MonadOrville.MonadOrville m => m a -> m a
withLockedTransaction action = do
go 0
where
go :: Int -> m a
go attempts = do
result <- runWithTransaction
case result of
Just a -> pure a
Nothing -> do
MIO.liftIO $ do
Monad.when (attempts >= 25) $ do
throwIO $
MigrationLockError
"Giving up after 25 attempts to aquire the migration lock."
threadDelay 10000
go $ attempts + 1
runWithTransaction =
Transaction.withTransaction $ do
tryLockResults <-
Execute.executeAndDecode tryLockExpr lockedMarshaller
case tryLockResults of
[True] ->
-- If we were able to acquire the lock then we can go ahead and
-- execute the action.
Just <$> action
[False] -> do
-- If we were not able to acquire the lock, wait for the lock to
-- become available. However, the state of the database schema may
-- have changed while we were waiting (for instance, another
-- Orville process migrating the same schema). We must exit the
-- current transaction and enter a new one, acquiring the lock
-- again in that new transaction.
Execute.executeVoid waitForLockExpr
pure Nothing
rows ->
MIO.liftIO . throwIO . MigrationLockError $
"Expected exactly one row from attempt to acquire migration lock, but got " <> show (length rows)
orvilleLockScope :: Int32
orvilleLockScope = 17772
migrationLockId :: Int32
migrationLockId = 7995632
lockedMarshaller :: SqlMarshaller.AnnotatedSqlMarshaller Bool Bool
lockedMarshaller =
SqlMarshaller.annotateSqlMarshallerEmptyAnnotation $
SqlMarshaller.marshallField id (FieldDefinition.booleanField "locked")
tryLockExpr :: RawSql.RawSql
tryLockExpr =
RawSql.fromString "SELECT pg_try_advisory_xact_lock("
<> RawSql.parameter (SqlValue.fromInt32 orvilleLockScope)
<> RawSql.comma
<> RawSql.parameter (SqlValue.fromInt32 migrationLockId)
<> RawSql.fromString ") as locked"
waitForLockExpr :: RawSql.RawSql
waitForLockExpr =
RawSql.fromString "SELECT pg_advisory_xact_lock("
<> RawSql.parameter (SqlValue.fromInt32 orvilleLockScope)
<> RawSql.comma
<> RawSql.parameter (SqlValue.fromInt32 migrationLockId)
newtype MigrationLockError
= MigrationLockError String
deriving (Show)
instance Exception MigrationLockError
| flipstone/orville | orville-postgresql-libpq/src/Orville/PostgreSQL/Internal/MigrationLock.hs | mit | 3,377 | 0 | 21 | 762 | 601 | 330 | 271 | 69 | 4 |
module Flowskell.State where
import Data.IORef
import Graphics.Rendering.OpenGL hiding (Bool, Float)
import Graphics.Rendering.OpenGL.GLU (perspective)
import Graphics.Rendering.GLU.Raw
import Graphics.Rendering.OpenGL.GL.FramebufferObjects
import Graphics.Rendering.OpenGL.Raw.ARB.Compatibility (glPushMatrix, glPopMatrix)
import Graphics.UI.GLUT hiding (Bool, Float)
import Language.Scheme.Types (Env)
import Data.Time.Clock (getCurrentTime)
import qualified Data.Time.Clock as C
import Flowskell.TextureUtils
import Flowskell.ShaderUtils
import Flowskell.InputLine (InputLine, newInputLine)
-- State data
-- TODO: Try to implement HasGetter/HasSetter for MVar instead IORef (Maybe ...)
data State = State {
rotation :: IORef (Vector3 GLfloat),
environment :: IORef (Maybe Env),
currentResolution :: IORef Size,
forceResolution :: IORef (Maybe Size),
lastEnvironment :: IORef (Maybe Env),
initFunc :: IORef (Maybe (String -> IO Env)),
blurFactor :: IORef GLfloat,
renderTexture :: IORef (Maybe TextureObject),
renderFramebuffer :: IORef (Maybe FramebufferObject),
lastRenderTexture :: IORef (Maybe TextureObject),
lastRenderFramebuffer :: IORef (Maybe FramebufferObject),
depthBuffer :: IORef (Maybe RenderbufferObject),
lastRenderDepthBuffer :: IORef (Maybe RenderbufferObject),
lastPosition :: IORef Position,
blurProgram :: IORef (Maybe Program),
source :: String,
lastReloadCheck :: IORef C.UTCTime,
lastSourceModification :: IORef C.UTCTime,
lastFrameCounterTime :: IORef C.UTCTime,
showFramesPerSecond :: IORef Bool,
frameCounter :: IORef Int,
framesPerSecond :: IORef Float,
showHelp :: IORef Bool,
showREPL :: IORef Bool,
replInputLine :: IORef InputLine,
replLines :: IORef [String]
}
makeState :: String -> IO State
makeState source' = do
environment' <- newIORef Nothing
lastEnvironment' <- newIORef Nothing
rotation' <- newIORef (Vector3 0 0 (0 :: GLfloat))
blurFactor' <- newIORef 0
currentResolution' <- newIORef (Size 0 0)
forceResolution' <- newIORef $ Nothing
renderTexture' <- newIORef Nothing
lastRenderTexture' <- newIORef Nothing
renderFramebuffer' <- newIORef Nothing
lastRenderFramebuffer' <- newIORef Nothing
lastRenderDepthBuffer' <- newIORef Nothing
blurProgram' <- newIORef Nothing
depthBuffer' <- newIORef Nothing
lastPosition' <- newIORef (Position (-1) (-1 :: GLint))
lastReloadCheck' <- getCurrentTime >>= newIORef
lastSourceModification' <- getCurrentTime >>= newIORef
frameCounter' <- newIORef 0
framesPerSecond' <- newIORef 0
showFramesPerSecond' <- newIORef False
lastFrameCounterTime' <- getCurrentTime >>= newIORef
initFunc' <- newIORef Nothing
showHelp' <- newIORef False
showREPL' <- newIORef False
replInputLine' <- newIORef newInputLine
replLines' <- newIORef []
return State {
environment = environment',
lastEnvironment = lastEnvironment',
rotation = rotation',
forceResolution = forceResolution',
currentResolution = currentResolution',
blurFactor = blurFactor',
renderTexture = renderTexture',
lastRenderTexture = lastRenderTexture',
renderFramebuffer = renderFramebuffer',
lastRenderFramebuffer = lastRenderFramebuffer',
lastPosition = lastPosition',
blurProgram = blurProgram',
lastRenderDepthBuffer = lastRenderDepthBuffer',
depthBuffer = depthBuffer',
lastReloadCheck = lastReloadCheck',
lastSourceModification = lastSourceModification',
frameCounter = frameCounter',
framesPerSecond = framesPerSecond',
lastFrameCounterTime = lastFrameCounterTime',
showFramesPerSecond = showFramesPerSecond',
source = source',
initFunc = initFunc',
showHelp = showHelp',
showREPL = showREPL',
replInputLine = replInputLine',
replLines = replLines'
}
| lordi/flowskell | src/Flowskell/State.hs | gpl-2.0 | 4,021 | 0 | 14 | 826 | 957 | 522 | 435 | 95 | 1 |
module DataMining.LargeScaleLearning.Terms where
import Notes
makeDefs [
"convex programming problem"
, "regret"
, "optimal feasable fixed point"
, "average regret"
, "no regret"
, "online convex programming problem"
, "greedy projection"
]
| NorfairKing/the-notes | src/DataMining/LargeScaleLearning/Terms.hs | gpl-2.0 | 287 | 0 | 6 | 78 | 37 | 23 | 14 | -1 | -1 |
module Abstraction.Ast where
data Abs = Join Bool
| Ignore Bool [String]
| Project [Lit]
deriving (Show, Eq, Ord)
data Lit = PosLit {feature :: String} |Β NegLit {feature :: String}
deriving (Show, Eq, Ord)
| ahmadsalim/p3-tool | p3-tool/Abstraction/Ast.hs | gpl-3.0 | 245 | 0 | 8 | 73 | 89 | 52 | 37 | 7 | 0 |
module Mescaline.Synth.Sampler.Params
( Params(..)
, defaultParams
) where
import Mescaline (Duration)
import qualified Mescaline.Database as DB
data Params = Params {
file :: DB.SourceFile
, unit :: DB.Unit
, offset :: Duration
, duration :: Duration
, rate :: Double
, pan :: Double
, attackTime :: Double
, releaseTime :: Double
, sustainLevel :: Double
, gateLevel :: Double
, sendLevel1 :: Double
, sendLevel2 :: Double
, fxParam1 :: Double
, fxParam2 :: Double
} deriving (Eq, Show)
defaultParams :: DB.SourceFile -> DB.Unit -> Params
defaultParams f u =
Params {
file = f
, unit = u
, offset = 0
, duration = DB.unitDuration u
, rate = 1
, pan = 0
, attackTime = 0
, releaseTime = 0
, sustainLevel = 1
, gateLevel = 0
, sendLevel1 = 0
, sendLevel2 = 0
, fxParam1 = 0
, fxParam2 = 0
}
| kaoskorobase/mescaline | lib/mescaline/Mescaline/Synth/Sampler/Params.hs | gpl-3.0 | 1,060 | 0 | 9 | 419 | 262 | 167 | 95 | 38 | 1 |
{- ============================================================================
| Copyright 2010 Matthew D. Steele <[email protected]> |
| |
| This file is part of Pylos. |
| |
| Pylos 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. |
| |
| Pylos 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 Pylos. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Pylos.Data.Point where
-------------------------------------------------------------------------------
class (Real a) => Axis a where
half :: a -> a
toIntegral :: (Integral b) => a -> b
toFloating :: (RealFloat b) => a -> b
instance Axis Int where
half = (`div` 2)
toIntegral = fromIntegral
toFloating = fromIntegral
instance Axis Double where
half = (/ 2)
toIntegral = round
toFloating = realToFrac
-------------------------------------------------------------------------------
type IPoint = Point Int
type DPoint = Point Double
data Point a = Point { pointX :: !a, pointY :: !a }
deriving (Eq, Show)
instance Functor Point where
fmap f (Point x y) = Point (f x) (f y)
pZero :: (Num a) => Point a
pZero = Point 0 0
infixl 6 `pAdd`, `pSub`
pAdd :: (Num a) => Point a -> Point a -> Point a
pAdd (Point x1 y1) (Point x2 y2) = Point (x1 + x2) (y1 + y2)
pSub :: (Num a) => Point a -> Point a -> Point a
pSub (Point x1 y1) (Point x2 y2) = Point (x1 - x2) (y1 - y2)
pNeg :: (Num a) => Point a -> Point a
pNeg (Point x y) = Point (negate x) (negate y)
-------------------------------------------------------------------------------
type IRect = Rect Int
type DRect = Rect Double
data Rect a = Rect { rectX :: !a, rectY :: !a, rectW :: !a, rectH :: !a }
deriving (Eq, Show)
instance Functor Rect where
fmap f (Rect x y w h) = Rect (f x) (f y) (f w) (f h)
-- | Return 'True' if the rectangle contains the given point, 'False'
-- otherwise.
rectContains :: (Real a) => Rect a -> Point a -> Bool
rectContains (Rect x y w h) (Point x' y') =
x' >= x && y' >= y && x' < x + w && y' < y + h
-- | Find the intersection of two rectangles.
rectIntersection :: (Real a) => Rect a -> Rect a -> Rect a
rectIntersection (Rect x1 y1 w1 h1) (Rect x2 y2 w2 h2) =
let x = max x1 x2
y = max y1 y2
w = max 0 (min (x1 + w1) (x2 + w2) - x)
h = max 0 (min (y1 + h1) (y2 + h2) - y)
in Rect x y w h
rectPlus :: (Num a) => Rect a -> Point a -> Rect a
rectPlus (Rect x1 y1 w h) (Point x2 y2) = Rect (x1 + x2) (y1 + y2) w h
rectMinus :: (Num a) => Rect a -> Point a -> Rect a
rectMinus (Rect x1 y1 w h) (Point x2 y2) = Rect (x1 - x2) (y1 - y2) w h
adjustRect :: (Real a) => a -> a -> a -> a -> Rect a -> Rect a
adjustRect x1 y1 x2 y2 (Rect x y w h) =
Rect (x + x1) (y + y1) (max 0 $ w - x2 - x1) (max 0 $ h - y2 - y1)
-- | Return the size of the rectangle as a @(width, height)@ pair.
rectSize :: Rect a -> (a, a)
rectSize (Rect _ _ w h) = (w, h)
-- | Return the point at the top-left corner of the given rectangle.
rectTopleft :: Rect a -> Point a
rectTopleft (Rect x y _ _) = Point x y
-- | Return the point at the top-left corner of the given rectangle.
rectCenter :: (Axis a) => Rect a -> Point a
rectCenter (Rect x y w h) = Point (x + half w) (y + half h)
-------------------------------------------------------------------------------
data LocSpec a = LocTopleft !(Point a)
| LocTopright !(Point a)
| LocMidleft !(Point a)
| LocCenter !(Point a)
| LocMidright !(Point a)
| LocBottomleft !(Point a)
| LocBottomright !(Point a)
locTopleft :: (Axis a) => LocSpec a -> (a, a) -> Point a
locTopleft loc (w, h) =
case loc of
LocTopleft p -> p
LocTopright (Point x y) -> Point (x - w) y
LocMidleft (Point x y) -> Point x (y - half h)
LocCenter (Point x y) -> Point (x - half w) (y - half h)
LocMidright (Point x y) -> Point (x - w) (y - half h)
LocBottomleft (Point x y) -> Point x (y - h)
LocBottomright (Point x y) -> Point (x - w) (y - h)
locRect :: (Axis a) => LocSpec a -> (a, a) -> Rect a
locRect loc (w, h) = Rect x y w h where
Point x y = locTopleft loc (w, h)
-------------------------------------------------------------------------------
| mdsteele/pylos | src/Pylos/Data/Point.hs | gpl-3.0 | 5,267 | 12 | 14 | 1,648 | 1,777 | 910 | 867 | 103 | 7 |
{- ============================================================================
| Copyright 2011 Matthew D. Steele <[email protected]> |
| |
| This file is part of Fallback. |
| |
| Fallback is free software: you can redistribute it and/or modify it under |
| the terms of the GNU General Public License as published by the Free |
| Software Foundation, either version 3 of the License, or (at your option) |
| any later version. |
| |
| Fallback is distributed in the hope that it will be useful, but WITHOUT |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for |
| more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
module Fallback.Mode.Editor
(newEditorMode)
where
import Control.Applicative ((<$>))
import Control.Monad (when)
import Data.Char (isAlphaNum, isDigit)
import Data.List (find, intercalate)
import Data.Maybe (fromMaybe, listToMaybe)
import Data.IORef
import qualified Data.Set as Set
import qualified Text.ParserCombinators.ReadP as Read
import Text.ParserCombinators.ReadPrec (readPrec_to_P)
import Text.Read (readPrec)
import Fallback.Constants (cameraCenterOffset)
import Fallback.Control.Error (runEO, runIOEO)
import Fallback.Data.Clock (initClock)
import Fallback.Data.Point
import Fallback.Draw (handleScreen, paintScreen)
import Fallback.Event
import Fallback.Mode.Base
import Fallback.Mode.Dialog (newTextEntryDialogMode)
import Fallback.Mode.Narrate (newNarrateMode)
import Fallback.State.Minimap
(newMinimapFromTerrainMap, updateMinimapFromTerrainMap)
import Fallback.State.Resources (Resources, rsrcTileset)
import Fallback.State.Terrain
import Fallback.State.Tileset
import Fallback.Utility (maybeM)
import Fallback.View (fromAction, viewHandler, viewPaint)
import Fallback.View.Editor
-------------------------------------------------------------------------------
newEditorMode :: Resources -> IO Mode
newEditorMode resources = do
view <- newEditorView resources
stateRef <- newEditorState resources >>= newIORef
let
mode EvQuit = do
unsaved <- fmap esUnsaved $ readIORef stateRef
if not unsaved then return DoQuit else
return DoQuit -- TODO offer to save terrain
mode (EvKeyDown KeyR [KeyModCmd] _) = do
es <- readIORef stateRef
ChangeMode <$> newTextEntryDialogMode
resources "Enter new map dimensions:"
(let (w, h) = tmapSize (esTerrain es) in show w ++ "x" ++ show h)
(const True) (return mode) doResize view es
mode (EvKeyDown KeyH [KeyModCmd] _) = do
es <- readIORef stateRef
ChangeMode <$> newTextEntryDialogMode resources
"Enter shift delta:" "0,0" (const True) (return mode) doShift view es
mode event = do
when (event == EvTick) $ modifyIORef stateRef tickEditorState
es <- readIORef stateRef
action <- handleScreen $ viewHandler view es event
when (event == EvTick) $ paintScreen (viewPaint view es)
case fromAction action of
Nothing -> return SameMode
Just (JumpMapTo pos) -> alterState $
es { esCameraTopleft =
round <$> (positionCenter pos `pSub` cameraCenterOffset) }
Just (ScrollMap delta) -> alterState $
es { esCameraTopleft = esCameraTopleft es `pAdd` delta }
Just (ScrollPalette top) -> alterState $
es { esPaletteTop = max 0 top }
Just (PickTile tile) -> alterState es { esBrush = tile }
Just (AutoPaintAt pos) -> do
let brush = autoPaintTile (esTileset es) (esTerrain es) pos
when (ttId (tmapGet (esTerrain es) pos) /= ttId brush) $ do
let terrain' = tmapSet [pos] brush (esTerrain es)
updateMinimapFromTerrainMap (esMinimap es) terrain' [pos]
setTerrain es terrain'
return SameMode
Just (PaintAt pos) -> do
when (ttId (tmapGet (esTerrain es) pos) /= ttId (esBrush es)) $ do
let terrain' = tmapSet [pos] (esBrush es) (esTerrain es)
updateMinimapFromTerrainMap (esMinimap es) terrain' [pos]
setTerrain es terrain'
return SameMode
Just (FloodFill pos) -> do
when (ttId (tmapGet (esTerrain es) pos) /= ttId (esBrush es)) $ do
let (terrain', filled) = floodFill pos (esBrush es) (esTerrain es)
updateMinimapFromTerrainMap (esMinimap es) terrain' filled
setTerrain es terrain'
return SameMode
Just (ChangeMarks pos) -> do
ChangeMode <$> newTextEntryDialogMode
resources ("Set marks for " ++ show pos ++ ":")
(intercalate "," $ Set.toList $ tmapGetMarks pos $ esTerrain es)
(const True) (return mode) (doSetMarks pos) view es
Just (ChangeRects pos) -> do
ChangeMode <$> newTextEntryDialogMode
resources ("Set rect:")
(maybe ("R:" ++ show (makeRect pos (1, 1)))
(\(s, r) -> s ++ ":" ++ show r) $
find (flip rectContains pos . snd) $ tmapAllRects $ esTerrain es)
(const True) (return mode) doSetRect view es
Just DoSave -> do
let doSave name = do
eo <- runIOEO $ saveTerrainMap name $ esTerrain es
case runEO eo of
Left errors -> newNarrateMode resources view es
(intercalate "\n\n" errors) (return mode)
Right () -> do
writeIORef stateRef es { esFilename = name,
esUnsaved = False }
return mode
ChangeMode <$> newTextEntryDialogMode resources
"Save terrain file as:" (esFilename es) (const True)
(return mode) doSave view es
Just DoLoad -> do
let doLoad name = do
eoTerrain <- runIOEO (loadTerrainMap resources name)
case runEO eoTerrain of
Left errors -> newNarrateMode resources view es
(intercalate "\n\n" errors) (return mode)
Right terrain -> do
writeIORef stateRef es { esCameraTopleft = pZero,
esFilename = name,
esRedoStack = [],
esTerrain = terrain,
esUndoStack = [],
esUnsaved = False }
recreateMinimap
return mode
ChangeMode <$> newTextEntryDialogMode resources
"Load terrain file named:" (esFilename es) (const True)
(return mode) doLoad view es
Just DoUndo -> do
case esUndoStack es of
(undo : undos) -> do
writeIORef stateRef es
{ esRedoStack = esTerrain es : esRedoStack es,
esTerrain = undo,
esUndoStack = undos,
esUnsaved = True }
recreateMinimap
[] -> return ()
return SameMode
Just DoRedo -> do
case esRedoStack es of
(redo : redos) -> do
writeIORef stateRef es
{ esRedoStack = redos,
esTerrain = redo,
esUndoStack = esTerrain es : esUndoStack es,
esUnsaved = True }
recreateMinimap
[] -> return ()
return SameMode
alterState es' = writeIORef stateRef es' >> return SameMode
setTerrain es terrain' = writeIORef stateRef $
es { esRedoStack = [],
esTerrain = terrain',
esUndoStack = esTerrain es : take 10 (esUndoStack es),
esUnsaved = True }
doSetMarks pos string = do
let mbKeys = fmap fst $ listToMaybe $ flip Read.readP_to_S string $ do
ks <- Read.sepBy (Read.munch1 isAlphaNum) (Read.char ',')
Read.eof
return ks
maybeM mbKeys $ \keys -> do
es <- readIORef stateRef
setTerrain es $ tmapSetMarks pos (Set.fromList keys) (esTerrain es)
return mode
doSetRect string = do
let mbSetting = fmap fst $ listToMaybe $ flip Read.readP_to_S string $ do
key <- Read.munch1 isAlphaNum
mbRect <- Read.option Nothing $ do
Read.char ':' >> fmap Just (readPrec_to_P readPrec 11)
Read.eof
return (key, mbRect)
maybeM mbSetting $ \(key, mbRect) -> do
es <- readIORef stateRef
setTerrain es $ tmapSetRect key mbRect (esTerrain es)
return mode
doResize string = do
let mbPair = fmap fst $ listToMaybe $ flip Read.readP_to_S string $ do
w <- read <$> Read.munch1 isDigit
_ <- Read.char 'x'
h <- read <$> Read.munch1 isDigit
Read.eof
return (w, h)
maybeM mbPair $ \size -> do
es <- readIORef stateRef
setTerrain es $ tmapResize (esNullTile es) size (esTerrain es)
recreateMinimap
return mode
doShift string = do
let mbPair = fmap fst $ listToMaybe $ flip Read.readP_to_S string $ do
let parseInt = do
sign <- Read.option "" (Read.string "-")
digits <- Read.munch1 isDigit
return $ read $ sign ++ digits
dx <- parseInt
_ <- Read.char ','
dy <- parseInt
Read.eof
return (Point dx dy)
maybeM mbPair $ \delta -> do
es <- readIORef stateRef
setTerrain es $ tmapShift (esNullTile es) delta (esTerrain es)
recreateMinimap
return mode
recreateMinimap = do
es <- readIORef stateRef
let tmap = esTerrain es
minimap <- newMinimapFromTerrainMap tmap
writeIORef stateRef es { esMinimap = minimap }
return mode
-------------------------------------------------------------------------------
autoPaintTile :: Tileset -> TerrainMap -> Position -> TerrainTile
autoPaintTile tileset tmap pos = get $
case ttId tile of
c | caveWall c ->
case nearbyTileIds of
(e, s, w, n, se, sw, nw, ne)
| all wall [e, s, w, n, se, sw, nw, ne] -> 1422
| all wall [c, e, w, n] && none wall [s] -> 8648
| all wall [c, w, n] && none wall [e, s] -> 7655
| all wall [c, s, w, n] && none wall [e] -> 7069
| all wall [c, s, w] && none wall [e, n] -> 9022
| all wall [c, e, s, w] && none wall [n] -> 9090
| all wall [c, e, s] && none wall [n, w] -> 2636
| all wall [c, e, s, n] && none wall [w] -> 8111
| all wall [c, e, n] && none wall [s, w] -> 5652
| all wall [c, e, s, w, n, se, nw, ne] && not (wall sw) -> 2680
| all wall [c, e, s, w, n, se, sw, ne] && not (wall nw) -> 9166
| all wall [c, e, s, w, n, se, sw, nw] && not (wall ne) -> 5750
| all wall [c, e, s, w, n, sw, nw, ne] && not (wall se) -> 1212
| otherwise -> ignore
| grassWall c ->
case nearbyTileIds of
(e, s, w, n, se, sw, nw, ne)
| all wall [e, s, w, n, se, sw, nw, ne] -> 2851
| all wall [c, e, w, n] && none wall [s] -> 4461
| all wall [c, w, n] && none wall [e, s] -> 8920
| all wall [c, s, w, n] && none wall [e] -> 5255
| all wall [c, s, w] && none wall [e, n] -> 3054
| all wall [c, e, s, w] && none wall [n] -> 5504
| all wall [c, e, s] && none wall [n, w] -> 1491
| all wall [c, e, s, n] && none wall [w] -> 1825
| all wall [c, e, n] && none wall [s, w] -> 6055
| all wall [c, e, s, w, n, se, nw, ne] && not (wall sw) -> 3302
| all wall [c, e, s, w, n, se, sw, ne] && not (wall nw) -> 3597
| all wall [c, e, s, w, n, se, sw, nw] && not (wall ne) -> 6745
| all wall [c, e, s, w, n, sw, nw, ne] && not (wall se) -> 3394
| otherwise -> ignore
| snowWall c ->
case nearbyTileIds of
(e, s, w, n, se, sw, nw, ne)
| all wall [e, s, w, n, se, sw, nw, ne] -> 5203
| all wall [c, e, w, n] && none wall [s] -> 1455
| all wall [c, w, n] && none wall [e, s] -> 6668
| all wall [c, s, w, n] && none wall [e] -> 6722
| all wall [c, s, w] && none wall [e, n] -> 0245
| all wall [c, e, s, w] && none wall [n] -> 2645
| all wall [c, e, s] && none wall [n, w] -> 0059
| all wall [c, e, s, n] && none wall [w] -> 8854
| all wall [c, e, n] && none wall [s, w] -> 0941
| all wall [c, e, s, w, n, se, nw, ne] && not (wall sw) -> 4238
| all wall [c, e, s, w, n, se, sw, ne] && not (wall nw) -> 1331
| all wall [c, e, s, w, n, se, sw, nw] && not (wall ne) -> 7167
| all wall [c, e, s, w, n, sw, nw, ne] && not (wall se) -> 7043
| otherwise -> ignore
| darkGrass c ->
case nearbyTileIds of
(e, s, w, n, se, sw, nw, ne)
| all darkg [e, s, w, n, se, sw, nw, ne] -> 3404
| all darkg [c, e, w, n] && none darkg [s] -> 1783
| all darkg [c, w, n] && none darkg [e, s] -> 8052
| all darkg [c, s, w, n] && none darkg [e] -> 6875
| all darkg [c, s, w] && none darkg [e, n] -> 2628
| all darkg [c, e, s, w] && none darkg [n] -> 1435
| all darkg [c, e, s] && none darkg [n, w] -> 3002
| all darkg [c, e, s, n] && none darkg [w] -> 7912
| all darkg [c, e, n] && none darkg [s, w] -> 3602
| all darkg [c, e, s, w, n, se, nw, ne] && not (darkg sw) -> 7088
| all darkg [c, e, s, w, n, se, sw, ne] && not (darkg nw) -> 3632
| all darkg [c, e, s, w, n, se, sw, nw] && not (darkg ne) -> 7401
| all darkg [c, e, s, w, n, sw, nw, ne] && not (darkg se) -> 8417
| otherwise -> ignore
| openWater c ->
case nearbyTileIds of
(e, s, w, n, _, _, _, _)
| all water [e, s, w, n] -> 2937
| all water [s, w, n] && caveFloor e -> 0295
| all water [e, w, n] && caveFloor s -> 6760
| all water [e, s, n] && caveFloor w -> 2443
| all water [e, s, w] && caveFloor n -> 6996
| all water [w, n] && all caveFloor [e, s] -> 9878
| all water [e, n] && all caveFloor [s, w] -> 4701
| all water [e, s] && all caveFloor [n, w] -> 6921
| all water [s, w] && all caveFloor [n, e] -> 3235
| all water [s, n] && all caveFloor [e, w] -> 1701
| all water [e, w] && all caveFloor [n, s] -> 5376
| all water [s, w, n] && e `elem` [9022, 9090, 9166] -> 5153
| all water [e, s, n] && w `elem` [9090, 2636, 5750] -> 5183
| all water [s, w, n] && e `elem` [8648, 7655, 2680] -> 5641
| all water [e, s, n] && w `elem` [8648, 5652, 1212] -> 8290
| all water [e, w, n] && s `elem` [7655, 7069, 5750] -> 3530
| all water [e, s, w] && n `elem` [7069, 9022, 1212] -> 4921
| all water [e, w, n] && s `elem` [8111, 5652, 9166] -> 3361
| all water [e, s, w] && n `elem` [2636, 8111, 2680] -> 2212
| all water [s, w, n] && caveWall e -> 2494
| all water [e, w, n] && caveWall s -> 2431
| all water [e, s, n] && caveWall w -> 3058
| all water [e, s, w] && caveWall n -> 0367
| all water [w, n] && all caveWall [e, s] -> 2864
| all water [e, n] && all caveWall [s, w] -> 4648
| all water [e, s] && all caveWall [n, w] -> 9755
| all water [s, w] && all caveWall [n, e] -> 8118
| all water [s, w, n] && snowFloor e -> 2776
| all water [e, w, n] && snowFloor s -> 2885
| all water [e, s, n] && snowFloor w -> 2206
| all water [e, s, w] && snowFloor n -> 8474
| all water [w, n] && all snowFloor [e, s] -> 6450
| all water [e, n] && all snowFloor [s, w] -> 4061
| all water [e, s] && all snowFloor [n, w] -> 3848
| all water [s, w] && all snowFloor [n, e] -> 0073
| otherwise -> ignore
| waterVBridge c ->
case nearbyTileIds of
(_, s, _, n, _, _, _, _)
| water s && water n -> 7629
| caveFloor s && water n -> 7108
| water s && caveFloor n -> 7264
| caveFloor s && caveFloor n -> 7739
| otherwise -> ignore
| waterHBridge c ->
case nearbyTileIds of
(e, _, w, _, _, _, _, _)
| water e && water w -> 1917
| caveFloor e && water w -> 5497
| water e && caveFloor w -> 6446
| caveFloor e && caveFloor w -> 8790
| otherwise -> ignore
| openOcean c ->
case nearbyTileIds of
(e, s, w, n, se, sw, nw, ne)
| all ocean [e, s, w, n, se, sw, nw, ne] -> 4181
| all ocean [e, w, n] && lightg s -> 7279
| all ocean [w, n] && all lightg [e, s] -> 1729
| all ocean [s, w, n] && lightg e -> 3908
| all ocean [s, w] && all lightg [n, e] -> 1479
| all ocean [e, s, w] && lightg n -> 6744
| all ocean [e, s] && all lightg [n, w] -> 8336
| all ocean [e, s, n] && lightg w -> 4855
| all ocean [e, n] && all lightg [s, w] -> 9373
| all ocean [e, s, w, n, se, nw, ne] && lightg sw -> 5854
| all ocean [e, s, w, n, se, sw, ne] && lightg nw -> 1359
| all ocean [e, s, w, n, se, sw, nw] && lightg ne -> 5285
| all ocean [e, s, w, n, sw, nw, ne] && lightg se -> 6087
| all ocean [e, w, n] && darkg s -> 7918
| all ocean [w, n] && all darkg [e, s] -> 2692
| all ocean [s, w, n] && darkg e -> 9192
| all ocean [s, w] && all darkg [n, e] -> 4633
| all ocean [e, s, w] && darkg n -> 0107
| all ocean [e, s] && all darkg [n, w] -> 5792
| all ocean [e, s, n] && darkg w -> 6899
| all ocean [e, n] && all darkg [s, w] -> 9623
| all ocean [e, s, w, n, se, nw, ne] && darkg sw -> 0255
| all ocean [e, s, w, n, se, sw, ne] && darkg nw -> 0773
| all ocean [e, s, w, n, se, sw, nw] && darkg ne -> 8557
| all ocean [e, s, w, n, sw, nw, ne] && darkg se -> 2909
| otherwise -> ignore
| oceanVBridge c ->
case nearbyTileIds of
(_, s, _, n, _, _, _, _)
| ocean s && ocean n -> 0153
| lightg s && ocean n -> 7584
| ocean s && lightg n -> 3226
| darkg s && ocean n -> 4591
| ocean s && darkg n -> 4132
| otherwise -> ignore
| oceanHBridge c ->
case nearbyTileIds of
(e, _, w, _, _, _, _, _)
| ocean e && ocean w -> 7779
| lightg e && ocean w -> 0387
| ocean e && lightg w -> 3320
| darkg e && ocean w -> 5134
| ocean e && darkg w -> 7987
| otherwise -> ignore
| otherwise -> ignore
where
wall tid = caveWall tid || buildingWall tid || grassWall tid ||
snowWall tid
caveWall = (`elem` [1422, 8648, 7655, 7069, 9022, 9090, 2636, 8111, 5652,
2680, 9166, 5750, 1212, 0000])
buildingWall = (`elem` [7292, 3112, 5588, 0983, 2330, 5719, 3254, 6250,
0111, 7883, 9398, 3037, 7791, 1306, 6933, 6383,
0865, 7148, 9011, 6051, 6455, 0170, 1752, 5489,
3891, 2993, 8625, 0605, 0364, 7185, 1814, 3403,
5216])
grassWall = (`elem` [2851, 4461, 8920, 5255, 3054, 5504, 1491, 1825, 6055,
3302, 3597, 6745, 3394])
snowWall = (`elem` [5203, 1455, 6668, 6722, 0245, 2645, 0059, 8854, 0941,
4238, 1331, 7167, 7043])
darkGrass = (`elem` [3404, 1783, 8052, 6875, 2628, 1435, 3002, 7912, 3602,
7088, 3632, 7401, 8417])
darkg tid = darkGrass tid || grassWall tid ||
tid `elem` [2246, 1953, 8040, 2201, 2297, 2868, 0442, 2768,
4029, 2427, 0198, 3181, 7002, 8274, 1673, 6343,
4307, 9527, 6531, 5342, 9524, 8978, 4215, 8515,
1010, 0754, 6984, 9122, 4007, 0541, 8044, 4977]
lightg = (`elem` [8983, 2583, 2938, 8301, 8740, 0678, 8415, 1397, 5398,
7100, 5308, 7966, 0723, 7888, 9930, 8596, 8799])
caveFloor = (`elem` [1171, 6498, 8959, 4581, 9760, 1376, 0772, 0179, 6341,
5892, 6109, 6914, 7234, 5653, 5073, 6814, 3086, 6852,
0545, 5306, 4196, 3431, 4408, 3899, 0486, 2317, 9224,
3915, 8591, 6079, 9108, 3895, 8300, 5199, 3187, 3525])
snowFloor = (`elem` [5709, 3930, 7591, 6995, 2571, 1332, 7122, 0781, 3384,
3236, 2011, 8721, 5390, 9409, 9456, 1287, 4556, 8284,
0563, 5643])
water tid = openWater tid || waterVBridge tid || waterHBridge tid ||
tid `elem` [5658, 4863]
openWater = (`elem` [2937, 5658, 4863, 0295, 6760, 2443, 6996, 9878, 4701,
6921, 3235, 1701, 5376, 2494, 2431, 3058, 0367, 2864,
4648, 9755, 8118, 5153, 5183, 5641, 8290, 3530, 4921,
3361, 2212, 2776, 2885, 2206, 8474, 6450, 4061, 3848,
0073])
waterVBridge = (`elem` [7629, 7108, 7264, 7739])
waterHBridge = (`elem` [1917, 5497, 6446, 8790])
ocean tid = openOcean tid || oceanVBridge tid || oceanHBridge tid ||
tid `elem` [9702, 2467]
openOcean = (`elem` [4181, 7279, 1729, 3908, 1479, 6744, 8336, 4855, 9373,
5854, 1359, 5285, 6087, 4632, 7733, 8007, 1868, 0176,
4465, 1750, 1919, 7918, 2692, 9192, 4633, 0107, 5792,
6899, 9623, 0255, 0773, 8557, 2909])
oceanVBridge = (`elem` [0153, 3226, 7584, 4132, 4591])
oceanHBridge = (`elem` [7779, 3320, 0387, 7987, 5134])
tile = tmapGet tmap pos
get tid = fromMaybe (error $ "no such tile: " ++ show tid) $
tilesetLookup tid tileset
nearbyTileIds =
let dir = ttId . tmapGet tmap . (pos `plusDir`)
in (dir DirE, dir DirS, dir DirW, dir DirN,
dir DirSE, dir DirSW, dir DirNW, dir DirNE)
none = (not .) . any
ignore = ttId tile
floodFill :: Position -> TerrainTile -> TerrainMap -> (TerrainMap, [Position])
floodFill start tile tmap =
let fill [] visited = visited
fill (pos : rest) visited =
if Set.member pos visited || ttId (tmapGet tmap pos) /= startId
then fill rest visited else
fill (map (pos `plusDir`) cardinalDirections ++ rest)
(Set.insert pos visited)
startId = ttId (tmapGet tmap start)
filled = Set.toList $ fill [start] Set.empty
cardinalDirections = filter isCardinal allDirections
in (tmapSet filled tile tmap, filled)
newEditorState :: Resources -> IO EditorState
newEditorState resources = do
let tileset = rsrcTileset resources
let offTile = tilesetGet OffTile tileset
let nullTile = tilesetGet NullTile tileset
let tmap = makeEmptyTerrainMap (55, 44) offTile nullTile
minimap <- newMinimapFromTerrainMap tmap
return EditorState
{ esBrush = nullTile,
esCameraTopleft = pZero,
esClock = initClock,
esFilename = "",
esMinimap = minimap,
esNullTile = nullTile,
esPaletteTop = 0,
esRedoStack = [],
esTerrain = tmap,
esTileArray = tilesetArray tileset, -- TODO remove this field
esTileset = tileset,
esUndoStack = [],
esUnsaved = False }
-------------------------------------------------------------------------------
| mdsteele/fallback | src/Fallback/Mode/Editor.hs | gpl-3.0 | 24,846 | 8 | 30 | 9,136 | 9,664 | 5,111 | 4,553 | 469 | 22 |
module Hadolint.Rule.DL3005 (rule) where
import Hadolint.Rule
import Hadolint.Shell (ParsedShell)
import qualified Hadolint.Shell as Shell
import Language.Docker.Syntax (Instruction (..), RunArgs (..))
rule :: Rule ParsedShell
rule = simpleRule code severity message check
where
code = "DL3005"
severity = DLErrorC
message = "Do not use apt-get dist-upgrade"
check (Run (RunArgs args _)) =
foldArguments (Shell.noCommands (Shell.cmdHasArgs "apt-get" ["dist-upgrade"])) args
check _ = True
{-# INLINEABLE rule #-}
| lukasmartinelli/hadolint | src/Hadolint/Rule/DL3005.hs | gpl-3.0 | 543 | 0 | 12 | 95 | 153 | 88 | 65 | 13 | 2 |
{-# LANGUAGE OverloadedStrings #-}
import Data.ByteString.Base64
main = do
let dat = "abc123!?$*&()'-=@~"
let sEnc = encode dat
print sEnc
let sDec = decode sEnc
print sDec
| daewon/til | haskell/haskell_by_example/base64.hs | mpl-2.0 | 196 | 0 | 10 | 50 | 58 | 26 | 32 | 8 | 1 |
{-# LANGUAGE TemplateHaskell #-}
module Model.Permission.SQL
( accessRow
, accessSets
) where
import Model.SQL.Select
import Model.Permission.Types
accessRow :: String -- ^ Table name
-> Selector -- ^ 'Access'
accessRow table = selectColumns 'Access table ["site", "member"]
accessSets :: String -- ^ @'Access'@
-> [(String, String)]
accessSets a =
[ ("site", "${accessSite " ++ a ++ "}")
, ("member", "${accessMember " ++ a ++ "}")
]
| databrary/databrary | src/Model/Permission/SQL.hs | agpl-3.0 | 454 | 0 | 8 | 84 | 122 | 74 | 48 | 14 | 1 |
{-# LANGUAGE OverloadedStrings #-}
module Hecate.Properties
( doProperties
) where
import qualified Control.Monad as Monad
import Data.List ((\\))
import Data.Monoid (First (..))
import qualified Data.Text as T
import Data.Text.Arbitrary ()
import Database.SQLite.Simple hiding (Error)
import qualified System.Directory as Directory
import qualified System.IO.Temp as Temp
import Test.QuickCheck (Arbitrary (..), Property, Result)
import qualified Test.QuickCheck as QuickCheck
import qualified Test.QuickCheck.Monadic as Monadic
import qualified Text.Printf as Printf
import Hecate.Backend.SQLite (AppContext (..))
import qualified Hecate.Backend.SQLite as SQLite
import qualified Hecate.Configuration as Configuration
import Hecate.Data
import qualified Hecate.Evaluator as Evaluator
import Hecate.Interfaces
import Hecate.Orphans ()
data TestData = TestData
{ _testDescription :: Description
, _testIdentity :: Maybe Identity
, _testPlaintext :: Plaintext
, _testMetadata :: Maybe Metadata
} deriving (Eq, Show)
instance Arbitrary TestData where
arbitrary = TestData <$> arbitrary <*> arbitrary <*> arbitrary <*> arbitrary
shrink (TestData as bs cs ds) = TestData <$> shrink as <*> shrink bs <*> shrink cs <*> shrink ds
createEntryFromTestData
:: (MonadAppError m, MonadInteraction m, MonadEncrypt m, MonadConfigReader m)
=> TestData
-> m Entry
createEntryFromTestData td = do
cfg <- askConfig
timestamp <- now
createEntry encrypt
(configKeyId cfg)
timestamp
(_testDescription td)
(_testIdentity td)
(_testPlaintext td)
(_testMetadata td)
addEntryToDatabase
:: ( MonadAppError m
, MonadInteraction m
, MonadEncrypt m
, MonadStore m
, MonadConfigReader m
)
=> [TestData]
-> m [Entry]
addEntryToDatabase tds = do
es <- mapM createEntryFromTestData tds
mapM_ put es
return es
createFilePath :: AppContext -> Int -> FilePath
createFilePath ctx x
= configDataDirectory (appContextConfig ctx) ++ "/export-" ++ Printf.printf "%05d" x ++ ".csv"
isNotEmpty :: TestData -> Bool
isNotEmpty testData
= _testDescription testData /= Description T.empty &&
_testIdentity testData /= Just (Identity T.empty) &&
_testPlaintext testData /= Plaintext T.empty &&
_testMetadata testData /= Just (Metadata T.empty)
entriesHaveSameContent :: (MonadAppError m, MonadEncrypt m) => Entry -> Entry -> m Bool
entriesHaveSameContent e1 e2 = do
plaintext1 <- decrypt (entryCiphertext e1)
plaintext2 <- decrypt (entryCiphertext e2)
return ((entryDescription e1 == entryDescription e2) &&
(entryIdentity e1 == entryIdentity e2) &&
(entryMeta e1 == entryMeta e2) &&
(plaintext1 == plaintext2))
prop_roundTripEntriesToDatabase :: AppContext -> Property
prop_roundTripEntriesToDatabase ctx = Monadic.monadicIO $ do
tds <- Monadic.pick (QuickCheck.listOf1 arbitrary)
es <- Monadic.run (SQLite.run (addEntryToDatabase tds) ctx)
res <- Monadic.run (SQLite.run selectAll ctx)
Monadic.assert (null (es \\ res))
prop_roundTripEntriesToCSV :: AppContext -> Property
prop_roundTripEntriesToCSV ctx = Monadic.monadicIO $ do
tds <- Monadic.pick (QuickCheck.listOf1 (QuickCheck.suchThat arbitrary isNotEmpty))
x <- Monadic.pick (QuickCheck.suchThat arbitrary (> 0))
let file = createFilePath ctx x
es <- Monadic.run (SQLite.run (mapM createEntryFromTestData tds) ctx)
_ <- Monadic.run (Evaluator.exportCSV file es)
ies <- Monadic.run (SQLite.run (Evaluator.importCSV file) ctx)
bs <- Monadic.run (Monad.zipWithM entriesHaveSameContent es ies)
Monadic.assert (and bs)
tests :: [AppContext -> Property]
tests =
[ prop_roundTripEntriesToDatabase
, prop_roundTripEntriesToCSV
]
doProperties :: IO [Result]
doProperties = do
sysTempDir <- Temp.getCanonicalTemporaryDirectory
dir <- Temp.createTempDirectory sysTempDir "hecate"
_ <- print ("dir: " ++ dir)
let preConfig = PreConfig (First (Just dir)) mempty mempty mempty
_ <- Directory.copyFile "./example/hecate.toml" (dir ++ "/hecate.toml")
ctx <- Configuration.configureWith preConfig >>= SQLite.initialize
_ <- SQLite.run Evaluator.setup ctx
results <- mapM (\ p -> QuickCheck.quickCheckWithResult QuickCheck.stdArgs (p ctx)) tests
_ <- close (appContextConnection ctx)
return results
| henrytill/hecate | tests/Hecate/Properties.hs | apache-2.0 | 4,718 | 0 | 14 | 1,135 | 1,344 | 689 | 655 | 106 | 1 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
module CI.Docker where
import Control.Applicative
import Control.Monad (when)
import Control.Monad.Eff
import Control.Monad.Eff.Exception
import Control.Monad.Eff.Trace
import qualified Data.ByteString as BS
import Data.Char (isSpace)
import Data.Maybe
import Data.Monoid
import Data.Text (Text)
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import System.Exit (ExitCode)
import CI.Filesystem as FS
import CI.Proc as Proc
-- * Types
-- | A Docker image tag.
newtype Tag = Tag { tagRepr :: Text }
deriving (Eq, Ord)
instance Show Tag where
show = show . tagRepr
-- | A Docker image name.
data Image = Image { imageName :: Text, imageTag :: Tag }
deriving (Eq, Ord)
imageRepr :: Image -> Text
imageRepr (Image img tag) = img <> ":" <> tagRepr tag
instance Show Image where
show = show . imageRepr
-- | Exceptions which may be raised by Docker effects.
data DockerEx
= DockerError { errorMessage :: Text } -- ^ Unknown error from Docker.
| MissingRecipe { missingPath :: Path } -- ^ Path does not exist.
| MissingArguments { errorMessage :: Text } -- ^ Report missing mandatory arguments.
| NoSuchImage { missingImage :: Image } -- ^ An operation failed because an image was missing.
deriving (Show)
-- | Docker effects.
data Docker x where
RemoveImage :: Image -> [Image] -> Docker ()
BuildImage :: Path -> Image -> Docker Image
TagImage :: Image -> Tag -> Docker Image
PushImage :: Image -> Docker ()
PullImage :: Image -> Docker ()
-- * Language
-- | Delete a Docker image.
--
-- If the 'Image' does not exist the 'NoSuchImage' exception will be
-- raised.
removeImage :: Member Docker r => Image -> Eff r ()
removeImage img = send (RemoveImage img [])
-- | Delete multiple Docker images.
--
-- If the list is empty a 'DockerError' exception will be raised. If
-- one or more of the 'Image's does not exist the 'NoSuchImage'
-- exception will be raised.
removeImages
:: (Member Docker r, Member (Exception DockerEx) r)
=> [Image]
-> Eff r ()
removeImages [] = throwException (DockerError "Must specify images to remove")
removeImages (i:is) = send (RemoveImage i is)
-- | Build a Docker image based on instructions in a 'Path'.
--
-- When completed the image will be tagged with the 'Tag'.
buildImage
:: Member Docker r
=> Path
-> Image
-> Eff r Image
buildImage path image = do
send (BuildImage path image)
-- | Apply a 'Tag' to a Docker 'Image'.
tagImage :: Member Docker r => Image -> Tag -> Eff r Image
tagImage img tag = send (TagImage img tag)
-- | Push a Docker 'Image' to a registry.
pushImage :: Member Docker r => Image -> Eff r ()
pushImage img = send (PushImage img)
-- | Pull a Docker 'Image' from a registry.
pullImage :: Member Docker r => Image -> Eff r ()
pullImage img = send (PullImage img)
-- * Interpreters
runDocker
:: forall r a.
( Member (Exception DockerEx) r
, Member Filesystem r
, Member (Exception FilesystemEx) r
, Member Proc r)
=> Eff (Docker ': r) a
-> Eff r a
runDocker = handleRelay return handle
where
handle :: Handler Docker r a
handle (RemoveImage img imgs) k = procRemoveImage (img:imgs) >>= k
handle (BuildImage path img) k = procBuildImage path img >>= k
handle (TagImage img tag) k = procTagImage img tag >>= k
handle (PushImage img) k = procPushImage img >>= k
handle (PullImage img) k = procPullImage img >>= k
-- | Push a Docker 'Image' to a remote.
procPushImage
:: ( Member Proc r
, Member (Exception DockerEx) r)
=> Image
-> Eff r ()
procPushImage img = do
(status, _stdout, stderr) <- docker "push" [imageRepr img]
when (isFailure status) $ throwException (parseError stderr)
return ()
-- | Pull a Docker 'Image'.
procPullImage
:: ( Member Proc r
, Member (Exception DockerEx) r)
=> Image
-> Eff r ()
procPullImage img = do
(status, _stdout, stderr) <- docker "pull" [imageRepr img]
when (isFailure status) $ throwException (parseError stderr)
return ()
-- | Build a Docker 'Image' using the @Dockerfile@ in a directory.
procBuildImage
:: ( Member Proc r
, Member Filesystem r
, Member (Exception DockerEx) r)
=> Path -- ^ Directory containing the @Dockerfile@
-> Image
-> Eff r Image
procBuildImage path img = do
exists <- doesDirectoryExist path
when (not exists) $
throwException (MissingRecipe path)
(status, _stdout, stderr) <- docker "build" ["--tag", imageRepr img, pathToText unixSeparator path]
when (isFailure status) $
throwException (parseError stderr)
-- TODO Parse correct output
return img
-- | Tag a Docker 'Image' with a 'Tag'.
--
-- If the 'Image' does not exist a 'NoSuchImage' exception will be
-- raised.
procTagImage
:: (Member Proc r,
Member (Exception DockerEx) r)
=> Image
-> Tag
-> Eff r Image
procTagImage img@(Image name _tag) tag' = do
(status, _stdout, stderr) <- docker "tag" [imageRepr img, name <> ":" <> tagRepr tag']
when (isFailure status) $
-- TODO Parse the error and throw correct exception
when (isFailure status) $ throwException (parseError stderr)
return (Image name tag')
procRemoveImage
:: ( Member Proc r
, Member (Exception DockerEx) r)
=> [Image]
-> Eff r ()
procRemoveImage imgs = do
(status, _stdout, stderr) <- docker "rmi" (imageRepr <$> imgs)
-- TODO: Parse actual response.
when (isFailure status) $ throwException (parseError stderr)
return ()
parseError
:: Stderr
-> DockerEx
parseError (Stderr stderr) =
let err = T.dropAround isSpace . T.decodeUtf8 $ stderr
in fromMaybe (error $ "Failed to parse a docker error: " <> T.unpack err) (isNoSuchImage err <|> isUnknownError err)
where
isUnknownError err = Just (DockerError err)
isNoSuchImage err =
if T.isInfixOf "No such image:" err
then case T.splitOn ":" (T.takeWhileEnd (/= ' ') err) of
[name, tag] -> Just $ NoSuchImage (Image name (Tag tag))
_ -> Nothing
else Nothing
-- | Invoke the docker command line application.
docker
:: (Member Proc r)
=> Text -- ^ Subcommand
-> [Text] -- ^ Arguments.
-> Eff r (ExitCode, Stdout, Stderr)
docker cmd args = proc "docker" (cmd:args) (Stdin BS.empty)
runDockerTrace
:: forall r a.
(Member Trace r, Member (Exception DockerEx) r)
=> Eff (Docker ': r) a
-> Eff r a
runDockerTrace = handleRelay return handle
where
handle :: Handler Docker r a
handle (RemoveImage img imgs) k = traceRemoveImage (img:imgs) >>= k
handle (BuildImage path img) k = traceBuildImage path img >>= k
handle (TagImage img tag) k = traceTagImage img tag >>= k
handle (PushImage img) k = tracePushImage img >>= k
handle (PullImage img) k = tracePullImage img >>= k
traceRemoveImage
:: ( Member Trace r, Member (Exception DockerEx) r)
=> [Image]
-> Eff r ()
traceRemoveImage [] = throwException (MissingArguments "Cannot remove images if you don't give me images!")
traceRemoveImage is = trace $ "docker rmi " <> unwords (T.unpack . imageRepr <$> is)
traceBuildImage
:: (Member Trace r, Member (Exception DockerEx) r)
=> Path -> Image -> Eff r Image
traceBuildImage path img = do
trace . T.unpack $ "docker build --tag " <> imageRepr img <> " " <> pathToText unixSeparator path
return img
traceTagImage
:: (Member Trace r, Member (Exception DockerEx) r)
=> Image -> Tag -> Eff r Image
traceTagImage img@(Image name _tag) tag' = do
let img' = Image name tag'
trace . T.unpack $ "docker tag " <> imageRepr img <> " " <> imageRepr img'
return img'
tracePushImage
:: (Member Trace r, Member (Exception DockerEx) r)
=> Image -> Eff r ()
tracePushImage img =
trace $ "docker push " <> T.unpack (imageRepr img)
tracePullImage
:: (Member Trace r, Member (Exception DockerEx) r)
=> Image -> Eff r ()
tracePullImage img =
trace $ "docker pull " <> T.unpack (imageRepr img)
| lancelet/bored-robot | src/CI/Docker.hs | apache-2.0 | 8,610 | 0 | 16 | 2,224 | 2,557 | 1,321 | 1,236 | 194 | 5 |
module FreePalace.Messages.PalaceProtocol.InboundReader where
import Control.Applicative
import Control.Exception
import qualified Data.Convertible.Base as Convert
import Data.Word
import qualified FreePalace.Domain.Net as Net
import qualified FreePalace.Messages.Inbound as Inbound
import qualified FreePalace.Messages.PalaceProtocol.MessageTypes as PalaceMsgTypes
import qualified FreePalace.Messages.PalaceProtocol.Obfuscate as Illuminator
import qualified FreePalace.Net.Receive as Receive
readHeader :: Net.PalaceConnection -> Net.PalaceMessageConverters -> IO Inbound.Header
readHeader connection messageConverters =
do
let byteSource = Net.palaceByteSource connection
intReader = Net.palaceIntReader messageConverters
readNextInt = Receive.readIntFromNetwork intReader byteSource
msgType <- PalaceMsgTypes.idToMessageType <$> readNextInt
size <- readNextInt
referenceNumber <- readNextInt
return Inbound.PalaceHeader {
Inbound.messageType = msgType,
Inbound.messageSize = size,
Inbound.messageRefNumber = referenceNumber
}
readMessage :: Net.PalaceConnection -> Net.PalaceMessageConverters -> Inbound.Header -> IO Inbound.InboundMessage
readMessage connection messageConverters header =
let messageType = Inbound.messageType header
byteSource = Net.palaceByteSource connection
readByte = Receive.readByteFromNetwork byteSource
readBytes = Receive.readBytesFromNetwork byteSource
readShort = Receive.readShortFromNetwork (Net.palaceShortReader messageConverters) byteSource
readInt = Receive.readIntFromNetwork (Net.palaceIntReader messageConverters) byteSource
readText = Receive.readTextFromNetwork byteSource
readNullTerminatedText = Receive.readNullTerminatedTextFromNetwork byteSource
in case messageType of
PalaceMsgTypes.BigEndianServer -> readHandshake PalaceMsgTypes.BigEndianServer connection header
PalaceMsgTypes.LittleEndianServer -> readHandshake PalaceMsgTypes.LittleEndianServer connection header
PalaceMsgTypes.UnknownServer -> readHandshake PalaceMsgTypes.UnknownServer connection header
PalaceMsgTypes.AlternateLogonReply -> readAlternateLogonReply readByte readShort readInt readText
PalaceMsgTypes.ServerVersion -> readServerVersion header
PalaceMsgTypes.ServerInfo -> readServerInfo readByte readInt readText
PalaceMsgTypes.UserStatus -> readUserStatus readBytes readShort header
PalaceMsgTypes.UserLoggedOnAndMax -> readUserLogonNotification readInt header
PalaceMsgTypes.GotHttpServerLocation -> readMediaServerInfo readNullTerminatedText header
PalaceMsgTypes.GotRoomDescription -> readRoomDescription readBytes readShort readInt header
PalaceMsgTypes.GotUserList -> readUserList readByte readBytes readShort readInt readText header
PalaceMsgTypes.RoomDescend -> return $ Inbound.NoOpMessage (Inbound.NoOp $ show messageType)
-- RoomDescend message just means we're done receiving the room description & user list
PalaceMsgTypes.UserNew -> readUserEnteredRoomNotification readByte readBytes readShort readInt readText
-- End logon sequence
PalaceMsgTypes.Talk -> readTalk readNullTerminatedText header Inbound.PublicChat
PalaceMsgTypes.CrossRoomWhisper -> readTalk readNullTerminatedText header Inbound.PrivateChat
PalaceMsgTypes.Say -> readEncodedTalk readBytes readShort header Inbound.PublicChat
PalaceMsgTypes.Whisper -> readEncodedTalk readBytes readShort header Inbound.PrivateChat
PalaceMsgTypes.Move -> readMovement readShort header
PalaceMsgTypes.UserExitRoom -> readUserExitedRoomNotification header
PalaceMsgTypes.UserLeaving -> readUserDisconnectedNotification readInt header
PalaceMsgTypes.Superuser -> readUnknownMessage readBytes header
PalaceMsgTypes.SusrMsg -> readUnknownMessage readBytes header
PalaceMsgTypes.GlobalMsg -> readUnknownMessage readBytes header
PalaceMsgTypes.RoomMsg -> readUnknownMessage readBytes header
PalaceMsgTypes.GotRoomDescriptionAlt -> readUnknownMessage readBytes header
PalaceMsgTypes.RequestRoomList -> readUnknownMessage readBytes header
PalaceMsgTypes.GotRoomList -> readUnknownMessage readBytes header
PalaceMsgTypes.GotReplyOfAllRooms -> readUnknownMessage readBytes header
PalaceMsgTypes.RequestUserList -> readUnknownMessage readBytes header
PalaceMsgTypes.GotReplyOfAllUsers -> readUnknownMessage readBytes header
PalaceMsgTypes.Logon -> readUnknownMessage readBytes header
PalaceMsgTypes.Authenticate -> readUnknownMessage readBytes header
PalaceMsgTypes.Authresponse -> readUnknownMessage readBytes header
PalaceMsgTypes.Bye -> readUnknownMessage readBytes header
PalaceMsgTypes.ChangeName -> readUnknownMessage readBytes header
PalaceMsgTypes.UserRename -> readUnknownMessage readBytes header
PalaceMsgTypes.UserDescription -> readUnknownMessage readBytes header
PalaceMsgTypes.UserColor -> readUnknownMessage readBytes header
PalaceMsgTypes.UserFace -> readUnknownMessage readBytes header
PalaceMsgTypes.UserProp -> readUnknownMessage readBytes header
PalaceMsgTypes.GotoRoom -> readUnknownMessage readBytes header
PalaceMsgTypes.Blowthru -> readUnknownMessage readBytes header
PalaceMsgTypes.NavError -> readUnknownMessage readBytes header
PalaceMsgTypes.PropNew -> readUnknownMessage readBytes header
PalaceMsgTypes.PropMove -> readUnknownMessage readBytes header
PalaceMsgTypes.PropDelete -> readUnknownMessage readBytes header
PalaceMsgTypes.PictMove -> readUnknownMessage readBytes header
PalaceMsgTypes.IncomingFile -> readUnknownMessage readBytes header
PalaceMsgTypes.RequestAsset -> readUnknownMessage readBytes header
PalaceMsgTypes.AssetQuery -> readUnknownMessage readBytes header
PalaceMsgTypes.AssetIncoming -> readUnknownMessage readBytes header
PalaceMsgTypes.AssetRegi -> readUnknownMessage readBytes header
PalaceMsgTypes.DoorLock -> readUnknownMessage readBytes header
PalaceMsgTypes.DoorUnlock -> readUnknownMessage readBytes header
PalaceMsgTypes.SpotState -> readUnknownMessage readBytes header
PalaceMsgTypes.SpotMove -> readUnknownMessage readBytes header
PalaceMsgTypes.Draw -> readUnknownMessage readBytes header
PalaceMsgTypes.DrawCmd -> readUnknownMessage readBytes header
PalaceMsgTypes.Pinged -> readUnknownMessage readBytes header
PalaceMsgTypes.PingBack -> readUnknownMessage readBytes header
PalaceMsgTypes.ServerDown -> readUnknownMessage readBytes header
PalaceMsgTypes.ConnectionDied -> readUnknownMessage readBytes header
PalaceMsgTypes.UnknownMessage -> readUnknownMessage readBytes header
readHandshake :: PalaceMsgTypes.MessageType -> Net.PalaceConnection -> Inbound.Header -> IO Inbound.InboundMessage
readHandshake PalaceMsgTypes.BigEndianServer connection header = do
let userRefId = Inbound.messageRefNumber header
handshake = Inbound.Handshake userRefId (Inbound.PalaceProtocol connection Inbound.BigEndian)
return $ Inbound.HandshakeMessage handshake
readHandshake PalaceMsgTypes.LittleEndianServer connection header = do
let userRefId = Inbound.messageRefNumber header
handshake = Inbound.Handshake userRefId (Inbound.PalaceProtocol connection Inbound.LittleEndian)
return $ Inbound.HandshakeMessage handshake
readHandshake PalaceMsgTypes.UnknownServer _ _ = throwIO $ userError "Unknown server type"
readHandshake _ _ _ = throwIO $ userError "Invalid server type"
readAlternateLogonReply :: IO Word8 -> IO Word16 -> IO Int -> (Int -> IO String) -> IO Inbound.InboundMessage
readAlternateLogonReply readByte readShort readInt readText =
do
crc <- readInt
counter <- readInt
userNameLength <- readByte
userName <- readText 31
wizardPassword <- readText 32
auxFlags <- readInt
puidCounter <- readInt
puidCrc <- readInt
demoElapsed <- readInt
totalElapsed <- readInt
demoLimit <- readInt
desiredRoom <- readShort
reserved <- readText 6
uploadRequestedProtocolVersion <- readInt
uploadCapabilities <- readInt
downloadCapabilities <- readInt
upload2DEngineCapabilities <- readInt
upload2DGraphicsCapabilities <- readInt
upload3DEngineCapabilities <- readInt
return . Inbound.LogonReplyMessage $ Inbound.LogonReply puidCounter puidCrc -- TODO When do these get used?
readServerInfo :: IO Word8 -> IO Int -> (Int -> IO String) -> IO Inbound.InboundMessage
readServerInfo readByte readInt readText =
do
permissions <- readInt
size <- fromIntegral <$> readByte
serverName <- readText size
return . Inbound.ServerInfoMessage $ Inbound.ServerInfoNotification serverName permissions
{- OpenPalace notes:
Weird -- this message is supposed to include options and upload/download capabilities, but doesn't.
options = socket.readUnsignedInt();
uploadCapabilities = socket.readUnsignedInt();
downloadCapabilities = socket.readUnsignedInt();
-}
readServerVersion :: Inbound.Header -> IO Inbound.InboundMessage
readServerVersion header = return . Inbound.ServerVersionMessage $ Inbound.ServerVersion (Inbound.messageRefNumber header)
readUserStatus :: (Int -> IO [Word8]) -> IO Word16 -> Inbound.Header -> IO Inbound.InboundMessage
readUserStatus readBytes readShort header =
do
let trailingBytes = (Inbound.messageSize header) - 2
userFlags <- readShort
_ <- readBytes trailingBytes
return . Inbound.UserStatusMessage $ Inbound.UserStatusNotification userFlags
readUserLogonNotification :: IO Int -> Inbound.Header -> IO Inbound.InboundMessage
readUserLogonNotification readInt header =
do
let userWhoLoggedOn = Inbound.messageRefNumber header
population <- readInt
return . Inbound.UserLogonMessage $ Inbound.UserLogonNotification userWhoLoggedOn population
readMediaServerInfo :: (Int -> IO String) -> Inbound.Header -> IO Inbound.InboundMessage
readMediaServerInfo readNullTerminatedText header =
do
url <- readNullTerminatedText $ Inbound.messageSize header
return . Inbound.MediaServerMessage $ Inbound.MediaServerInfo url
-- room name, background image, overlay images, props, hotspots, draw commands
-- TODO Finish this
readRoomDescription :: (Int -> IO [Word8]) -> IO Word16 -> IO Int -> Inbound.Header -> IO Inbound.InboundMessage
readRoomDescription readBytes readShort readInt header =
do
roomFlags <- readInt -- unused
face <- readInt -- unused
roomId <- fromIntegral <$> readShort
roomNameOffset <- fromIntegral <$> readShort
backgroundImageNameOffset <- fromIntegral <$> readShort
artistNameOffset <- fromIntegral <$> readShort
passwordOffset <- fromIntegral <$> readShort
hotSpotCount <- fromIntegral <$> readShort
hotSpotOffset <- fromIntegral <$> readShort
overlayImageCount <- fromIntegral <$> readShort
overlayImageOffset <- fromIntegral <$> readShort
drawCommandsCount <- fromIntegral <$> readShort
firstDrawCommand <- readShort
peopleCount <- fromIntegral <$> readShort
loosePropCount <- fromIntegral <$> readShort
firstLooseProp <- readShort
unused <- readShort
roomDataLength <- fromIntegral <$> readShort
roomData <- readBytes $ roomDataLength
let paddingLength = (Inbound.messageSize header) - roomDataLength - 40 -- We have used (roomDataLength + 40 bytes so far)
padding <- readBytes paddingLength
-- This message doesn't come in very often so we're not going to use arrays unless it really makes things slow.
let roomNameLength = fromIntegral $ head $ drop roomNameOffset roomData
roomName = map Convert.convert $ take roomNameLength $ drop (roomNameOffset + 1) roomData
backgroundImageNameLength = fromIntegral $ head $ drop backgroundImageNameOffset roomData
backgroundImageName = map Convert.convert $ take backgroundImageNameLength $ drop (backgroundImageNameOffset + 1) roomData
roomDescription = Inbound.RoomDescription {
Inbound.roomDescId = roomId
, Inbound.roomDescName = roomName
, Inbound.roomDescBackground = backgroundImageName
}
return $ Inbound.RoomDescriptionMessage roomDescription
{- Next, load:
-- overlay images
-- hotspots
-- loose props
-- draw commands
For each overlay image:
refCon = imageBA.readInt(); -- unused
id = imageBA.readShort();
picNameOffset = imageBA.readShort();
transparencyIndex = imageBA.readShort();
readShort(); -- Reserved: padding for field alignment
picNameLength <- readByte
picName <- readBytes -- from picNameOffset using picNameLength.
-- This is the filename. May need URL escaping based on configuration
For each hotspot:
scriptEventMask <- readInt
flags <- readInt -- unused?
secureInfo <- readInt
refCon <- readInt
location.y <- readShort
location.x <- readShort
id <- readShort -- unused?
dest <- readShort
numPoints <- readShort -- local, used for loading vertices (below)
pointsOffset <- readShort
type <- readShort
groupId <- readShort
nbrScripts <- readShort
scriptRecordOffset <- readShort
state <- readShort
numStates <- readShort
var stateRecordOffset:int <- readShort
var nameOffset:int <- readShort
var scriptTextOffset:int <- readShort
readShort -- unused?
nameLength
name -- using nameOffset and nameLength
Now look for script info using the scriptTextOffset:
scriptString <- readBytes ... -- all the bytes to the end of the hotspot bytes (this then gets parsed and loaded)
Now go back into the array and read the vertices of the points of the hotspot, starting with pointsOffset, loop numPoints times:
y <- readShort
x <- readShort
Now go back into the array and read the hotspot states starting at stateOffset and looping numStates times. A state is 8 bytes:
pictureId <- readShort
readShort -- unused
y <- readShort
x <- readShort
For each loose prop -- this is 24 bytes:
nextOffset <- readShort -- This is the offset into the room data bytes for the next loose prop
readShort
id <- readUnsignedInt
crc <- readUnsignedInt
flags <- readUnsignedInt
readInt
y <- readShort
x <- readShort
For each draw command -- has a 10-byte header and then a length specified by commandLength:
Header:
nextOffset <- readShort -- offset into the room data bytes for the next draw command
ba.readShort -- reserved, unused
command <- readUnsignedShort -- contains both flags and command, obtained by bit shifting/masking. Ignore CMD_DETONATE and CMD_DELETE (?)
commandLength <- readUnsignedShort
commandStart <- readShort -- if it's 0, reset to 10 to start after header. (?)
Starting at commandStart, read pen size and colors (add a preset alpha):
penSize <- readShort
numPoints <- readShort
red <- readUnsignedByte
readUnsignedByte -- Values are doubled; unclear why.
green <- readUnsignedByte
readUnsignedByte -- doubled greem
blue <- readUnsignedByte
readUnsignedByte -- doubled blue
For each point in the polygon up to numPoints:
y <- readShort
x <- readShort
If there are remaining bytes (if this fails, fall back to using pen color for everything - this means PalaceChat 3 style packets?)
alphaInt <- readUnsignedByte -- line color and alpha
red <- readUnsignedByte
green <- readUnsignedByte
blue <- readUnsignedByte
alphaInt <- readUnsignedByte -- fill color and alpha
red <- readUnsignedByte
green <- readUnsignedByte
blue <- readUnsignedByte
-}
-- List of users in the current room
readUserList :: IO Word8 -> (Int -> IO [Word8]) -> IO Word16 -> IO Int -> (Int -> IO String) -> Inbound.Header -> IO Inbound.InboundMessage
readUserList readByte readBytes readShort readInt readText header =
do
let numberOfUsers = Inbound.messageRefNumber header
userList <- sequence $ replicate numberOfUsers (readSingleUser readByte readBytes readShort readInt readText)
return . Inbound.UserListMessage $ Inbound.UserListing userList
readSingleUser :: IO Word8 -> (Int -> IO [Word8]) -> IO Word16 -> IO Int -> (Int -> IO String) -> IO Inbound.UserData
readSingleUser readByte readBytes readShort readInt readText =
do
let toPairs (propId:propCrc:xs) = (propId,propCrc) : toPairs xs
toPairs _ = []
userId <- readInt
y <- fromIntegral <$> readShort
x <- fromIntegral <$> readShort
propInfos <- sequence $ replicate 18 readInt -- 9 slots for prop images - pairs of prop ID and propCrc (PalaceProtocol specific?)
roomId <- fromIntegral <$> readShort
face <- fromIntegral <$> readShort
color <- fromIntegral <$> readShort
_ <- readShort -- 0?
_ <- readShort -- 0?
numberOfProps <- fromIntegral <$> readShort
userNameLength <- fromIntegral <$> readByte
userName <- readText userNameLength
_ <- readBytes $ 31 - userNameLength
let propsList = toPairs propInfos
propInfo = Inbound.PropInfo {
Inbound.numberOfProps = numberOfProps
, Inbound.props = take numberOfProps propsList
}
return $ Inbound.UserData {
Inbound.userId = userId
, Inbound.userName = userName
, Inbound.userRoomId = roomId
, Inbound.userCoordinates = Inbound.CartesianCoordinates { Inbound.xPos = x, Inbound.yPos = y }
, Inbound.userFaceInfo = Inbound.UserFaceInfo { Inbound.userFace = face, Inbound.userColor = color }
, Inbound.userPropInfo = propInfo
}
readUserEnteredRoomNotification :: IO Word8 -> (Int -> IO [Word8]) -> IO Word16 -> IO Int -> (Int -> IO String) -> IO Inbound.InboundMessage
readUserEnteredRoomNotification readByte readBytes readShort readInt readText =
do
userData <- readSingleUser readByte readBytes readShort readInt readText
return $ Inbound.UserEnteredRoomMessage userData
readUserExitedRoomNotification :: Inbound.Header -> IO Inbound.InboundMessage
readUserExitedRoomNotification header =
do
let userId = Inbound.messageRefNumber header
return . Inbound.UserExitedRoomMessage $ Inbound.UserExitedRoom userId
readUserDisconnectedNotification :: IO Int -> Inbound.Header -> IO Inbound.InboundMessage
readUserDisconnectedNotification readInt header =
do
population <- readInt
return . Inbound.UserDisconnectedMessage $ Inbound.UserDisconnected population (Inbound.messageRefNumber header)
readTalk :: (Int -> IO String) -> Inbound.Header -> Inbound.ChatExposure -> IO Inbound.InboundMessage
readTalk readNullTerminatedText header exposure =
do
let speaking = Inbound.messageRefNumber header
messageLength = Inbound.messageSize header
message <- truncateChatMessage <$> readNullTerminatedText messageLength
let chat = Inbound.Chat {
Inbound.chatSpeaker = speaking
, Inbound.chatRecipient = Nothing
, Inbound.chatMessage = message
, Inbound.chatExposure = exposure
}
return $ Inbound.ChatMessage chat
readEncodedTalk :: (Int -> IO [Word8]) -> IO Word16 -> Inbound.Header -> Inbound.ChatExposure -> IO Inbound.InboundMessage
readEncodedTalk readBytes readShort header exposure =
do
let speaking = Inbound.messageRefNumber header
-- header messageSize field is actually the message checksum + 1 ??
fieldLength <- fromIntegral <$> readShort -- This is apparently the total length including these two bytes and the terminator
obfuscated <- truncateChatMessage <$> init <$> readBytes (fieldLength - 2)
let message = Illuminator.illuminate obfuscated
chat = Inbound.Chat {
Inbound.chatSpeaker = speaking
, Inbound.chatRecipient = Nothing
, Inbound.chatMessage = message
, Inbound.chatExposure = exposure
}
return $ Inbound.ChatMessage chat
-- Chat string can't be > 254 characters long
-- OpenPalace carries along original message but unclear why it's needed
-- Even iptscrae shouldn't use what isn't displayed, no?
truncateChatMessage :: [a] -> [a]
truncateChatMessage message = take 254 message
readMovement :: IO Word16 -> Inbound.Header -> IO Inbound.InboundMessage
readMovement readShort header =
do
let mover = Inbound.messageRefNumber header
y <- fromIntegral <$> readShort
x <- fromIntegral <$> readShort
let notification = Inbound.MovementNotification { Inbound.x = x, Inbound.y = y, Inbound.userWhoMoved = mover }
return $ Inbound.MovementMessage notification
readUnknownMessage :: (Int -> IO [Word8]) -> Inbound.Header -> IO Inbound.InboundMessage
readUnknownMessage readBytes header =
do
_ <- readBytes $ Inbound.messageSize header
let diagnosticMessage = "Unknown messsage: " ++ (show header)
return $ Inbound.NoOpMessage (Inbound.NoOp diagnosticMessage)
| psfblair/freepalace | src/FreePalace/Messages/PalaceProtocol/InboundReader.hs | apache-2.0 | 21,020 | 0 | 14 | 3,869 | 3,869 | 1,879 | 1,990 | 282 | 63 |
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
module Network.Eureka (
withEurekaH,
withEureka,
EurekaConfig(..),
InstanceConfig(..),
def,
discoverDataCenterAmazon,
setStatus,
lookupByAppName,
lookupAllApplications,
InstanceInfo(..),
InstanceStatus(..),
DataCenterInfo(..),
AmazonDataCenterInfo(..),
EurekaConnection,
AvailabilityZone,
Region,
addMetadata,
lookupMetadata
) where
import qualified Data.ByteString.Lazy as LBS
import Data.Maybe (fromJust)
import qualified Data.Text as T
import Data.Text.Encoding (decodeUtf8)
import Data.Default (def)
import Network.Eureka.Types (AmazonDataCenterInfo (..),
AvailabilityZone,
DataCenterInfo (..),
EurekaConfig (..),
InstanceConfig (..),
InstanceInfo (..),
InstanceStatus (..), Region)
import Network.HTTP.Client (Manager, responseBody, parseUrlThrow, httpLbs)
import Network.Eureka.Application (lookupByAppName, lookupAllApplications)
import Network.Eureka.Connection (withEureka, withEurekaH, setStatus, EurekaConnection)
import Network.Eureka.Metadata (addMetadata, lookupMetadata)
-- | Interrogate the magical URL http://169.254.169.254/latest/meta-data to
-- fill in an DataCenterAmazon.
discoverDataCenterAmazon :: Manager -> IO AmazonDataCenterInfo
discoverDataCenterAmazon manager =
AmazonDataCenterInfo <$>
getMeta "ami-id" <*>
(read <$> getMeta "ami-launch-index") <*>
getMeta "instance-id" <*>
getMeta "instance-type" <*>
getMeta "local-ipv4" <*>
getMeta "placement/availability-zone" <*>
getMeta "public-hostname" <*>
getMeta "public-ipv4"
where
getMeta :: String -> IO String
getMeta pathName = fromBS . responseBody <$> httpLbs metaRequest manager
where
metaRequest = fromJust . parseUrlThrow $ "http://169.254.169.254/latest/meta-data/" ++ pathName
fromBS = T.unpack . decodeUtf8 . LBS.toStrict
| SumAll/haskell-eureka-client | src/Network/Eureka.hs | apache-2.0 | 2,302 | 0 | 14 | 693 | 416 | 252 | 164 | 52 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Finance.Hqfl.Convention.DayCount
-- Copyright : (C) 2018 Mika'il Khan
-- License : (see the file LICENSE)
-- Maintainer : Mika'il Khan <[email protected]>
-- Stability : stable
-- Portability : portable
--
----------------------------------------------------------------------------
module Finance.Hqfl.Convention.DayCount
(
DayCountConvention
)
where
data DayCountConvention = OneToOne
| Thirty360
| ThirtyE360
| ThirtyE360ISDA
| ThirtyEPlus350ISA
| Act360
| Act365Fixed
| Act365L
| Act365A
| NL365
| ActActISA
| ActActICMA
| Business252
-- TODO: date calculation functions
| cokleisli/hqfl | src/Finance/Hqfl/Convention/DayCount.hs | apache-2.0 | 998 | 0 | 5 | 400 | 67 | 48 | 19 | 16 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module Buster.Types (Config(..),
UrlConfig(..),
Worker,
ConfigWatch,
BusterPool(..)) where
import Control.Applicative ((<$>), (<*>))
import Control.Concurrent (ThreadId)
import Control.Concurrent.MVar (MVar)
import Data.Yaml (FromJSON(..), (.:?), (.:), (.!=), Value(..))
import Network.HTTP.Conduit (Manager)
import Network.HTTP.Types (Method)
type ConfigWatch = MVar (Config)
data Config = Config {
configVerbose :: Bool,
configMonitor :: Bool,
urlConfigs :: [UrlConfig],
configLogFile :: Maybe FilePath
} deriving (Show, Eq)
instance FromJSON Config where
parseJSON (Object v) = Config <$> v .:? "verbose" .!= False
<*> v .:? "monitor" .!= False
<*> v .: "urls"
<*> v .:? "log_file"
parseJSON _ = fail "Expecting Object"
data UrlConfig = UrlConfig {
url :: String,
requestInterval :: Integer,
requestMethod :: Method
} deriving (Show, Eq)
instance FromJSON UrlConfig where
parseJSON (Object v) = UrlConfig <$> v .: "url"
<*> v .: "interval"
<*> v .:? "method" .!= "GET"
parseJSON _ = fail "Expecting Object"
data BusterPool = BusterPool {
connectionManager :: Manager,
config :: Config,
workers :: [Worker]
}
instance Show BusterPool where
show BusterPool { config = cfg,
workers = ws} = unwords ["BusterPool",
show cfg,
show ws]
type Worker = ThreadId
| MichaelXavier/Buster | src/Buster/Types.hs | bsd-2-clause | 1,730 | 0 | 15 | 623 | 451 | 265 | 186 | 45 | 0 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QStackedLayout.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:18
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QStackedLayout (
QqStackedLayout(..)
,qStackedLayout_delete
,qStackedLayout_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QStackedLayout
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QStackedLayout ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QStackedLayout_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QStackedLayout_userMethod" qtc_QStackedLayout_userMethod :: Ptr (TQStackedLayout a) -> CInt -> IO ()
instance QuserMethod (QStackedLayoutSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QStackedLayout_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QStackedLayout ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QStackedLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QStackedLayout_userMethodVariant" qtc_QStackedLayout_userMethodVariant :: Ptr (TQStackedLayout a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QStackedLayoutSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QStackedLayout_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqStackedLayout x1 where
qStackedLayout :: x1 -> IO (QStackedLayout ())
instance QqStackedLayout (()) where
qStackedLayout ()
= withQStackedLayoutResult $
qtc_QStackedLayout
foreign import ccall "qtc_QStackedLayout" qtc_QStackedLayout :: IO (Ptr (TQStackedLayout ()))
instance QqStackedLayout ((QWidget t1)) where
qStackedLayout (x1)
= withQStackedLayoutResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout1 cobj_x1
foreign import ccall "qtc_QStackedLayout1" qtc_QStackedLayout1 :: Ptr (TQWidget t1) -> IO (Ptr (TQStackedLayout ()))
instance QqStackedLayout ((QLayout t1)) where
qStackedLayout (x1)
= withQStackedLayoutResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout2 cobj_x1
foreign import ccall "qtc_QStackedLayout2" qtc_QStackedLayout2 :: Ptr (TQLayout t1) -> IO (Ptr (TQStackedLayout ()))
instance QaddItem (QStackedLayout ()) ((QLayoutItem t1)) (IO ()) where
addItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addItem_h cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_addItem_h" qtc_QStackedLayout_addItem_h :: Ptr (TQStackedLayout a) -> Ptr (TQLayoutItem t1) -> IO ()
instance QaddItem (QStackedLayoutSc a) ((QLayoutItem t1)) (IO ()) where
addItem x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addItem_h cobj_x0 cobj_x1
instance QaddWidget (QStackedLayout ()) ((QWidget t1)) (IO (Int)) where
addWidget x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addWidget cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_addWidget" qtc_QStackedLayout_addWidget :: Ptr (TQStackedLayout a) -> Ptr (TQWidget t1) -> IO CInt
instance QaddWidget (QStackedLayoutSc a) ((QWidget t1)) (IO (Int)) where
addWidget x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addWidget cobj_x0 cobj_x1
instance Qcount (QStackedLayout ()) (()) where
count x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_count_h cobj_x0
foreign import ccall "qtc_QStackedLayout_count_h" qtc_QStackedLayout_count_h :: Ptr (TQStackedLayout a) -> IO CInt
instance Qcount (QStackedLayoutSc a) (()) where
count x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_count_h cobj_x0
instance QcurrentIndex (QStackedLayout a) (()) (IO (Int)) where
currentIndex x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_currentIndex cobj_x0
foreign import ccall "qtc_QStackedLayout_currentIndex" qtc_QStackedLayout_currentIndex :: Ptr (TQStackedLayout a) -> IO CInt
instance QcurrentWidget (QStackedLayout a) (()) where
currentWidget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_currentWidget cobj_x0
foreign import ccall "qtc_QStackedLayout_currentWidget" qtc_QStackedLayout_currentWidget :: Ptr (TQStackedLayout a) -> IO (Ptr (TQWidget ()))
instance QinsertWidget (QStackedLayout a) ((Int, QWidget t2)) (IO (Int)) where
insertWidget x0 (x1, x2)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QStackedLayout_insertWidget cobj_x0 (toCInt x1) cobj_x2
foreign import ccall "qtc_QStackedLayout_insertWidget" qtc_QStackedLayout_insertWidget :: Ptr (TQStackedLayout a) -> CInt -> Ptr (TQWidget t2) -> IO CInt
instance QitemAt (QStackedLayout ()) ((Int)) (IO (QLayoutItem ())) where
itemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_itemAt_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStackedLayout_itemAt_h" qtc_QStackedLayout_itemAt_h :: Ptr (TQStackedLayout a) -> CInt -> IO (Ptr (TQLayoutItem ()))
instance QitemAt (QStackedLayoutSc a) ((Int)) (IO (QLayoutItem ())) where
itemAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_itemAt_h cobj_x0 (toCInt x1)
instance QqminimumSize (QStackedLayout ()) (()) where
qminimumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_minimumSize_h cobj_x0
foreign import ccall "qtc_QStackedLayout_minimumSize_h" qtc_QStackedLayout_minimumSize_h :: Ptr (TQStackedLayout a) -> IO (Ptr (TQSize ()))
instance QqminimumSize (QStackedLayoutSc a) (()) where
qminimumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_minimumSize_h cobj_x0
instance QminimumSize (QStackedLayout ()) (()) where
minimumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_minimumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QStackedLayout_minimumSize_qth_h" qtc_QStackedLayout_minimumSize_qth_h :: Ptr (TQStackedLayout a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSize (QStackedLayoutSc a) (()) where
minimumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_minimumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QsetCurrentIndex (QStackedLayout a) ((Int)) where
setCurrentIndex x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_setCurrentIndex cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStackedLayout_setCurrentIndex" qtc_QStackedLayout_setCurrentIndex :: Ptr (TQStackedLayout a) -> CInt -> IO ()
instance QsetCurrentWidget (QStackedLayout a) ((QWidget t1)) where
setCurrentWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_setCurrentWidget cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_setCurrentWidget" qtc_QStackedLayout_setCurrentWidget :: Ptr (TQStackedLayout a) -> Ptr (TQWidget t1) -> IO ()
instance QqsetGeometry (QStackedLayout ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_setGeometry_h cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_setGeometry_h" qtc_QStackedLayout_setGeometry_h :: Ptr (TQStackedLayout a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QStackedLayoutSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_setGeometry_h cobj_x0 cobj_x1
instance QsetGeometry (QStackedLayout ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStackedLayout_setGeometry_qth_h cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QStackedLayout_setGeometry_qth_h" qtc_QStackedLayout_setGeometry_qth_h :: Ptr (TQStackedLayout a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QStackedLayoutSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStackedLayout_setGeometry_qth_h cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
setStackingMode :: QStackedLayout a -> ((StackingMode)) -> IO ()
setStackingMode x0 x1
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_setStackingMode cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QStackedLayout_setStackingMode" qtc_QStackedLayout_setStackingMode :: Ptr (TQStackedLayout a) -> CLong -> IO ()
stackingMode :: QStackedLayout a -> (()) -> IO StackingMode
stackingMode x0 ()
= withQEnumResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_stackingMode cobj_x0
foreign import ccall "qtc_QStackedLayout_stackingMode" qtc_QStackedLayout_stackingMode :: Ptr (TQStackedLayout a) -> IO CLong
instance QqsizeHint (QStackedLayout ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_sizeHint_h cobj_x0
foreign import ccall "qtc_QStackedLayout_sizeHint_h" qtc_QStackedLayout_sizeHint_h :: Ptr (TQStackedLayout a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QStackedLayoutSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_sizeHint_h cobj_x0
instance QsizeHint (QStackedLayout ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QStackedLayout_sizeHint_qth_h" qtc_QStackedLayout_sizeHint_qth_h :: Ptr (TQStackedLayout a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QStackedLayoutSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QtakeAt (QStackedLayout ()) ((Int)) where
takeAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_takeAt_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStackedLayout_takeAt_h" qtc_QStackedLayout_takeAt_h :: Ptr (TQStackedLayout a) -> CInt -> IO (Ptr (TQLayoutItem ()))
instance QtakeAt (QStackedLayoutSc a) ((Int)) where
takeAt x0 (x1)
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_takeAt_h cobj_x0 (toCInt x1)
instance Qwidget (QStackedLayout ()) (()) where
widget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_widget_h cobj_x0
foreign import ccall "qtc_QStackedLayout_widget_h" qtc_QStackedLayout_widget_h :: Ptr (TQStackedLayout a) -> IO (Ptr (TQWidget ()))
instance Qwidget (QStackedLayoutSc a) (()) where
widget x0 ()
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_widget_h cobj_x0
instance Qwidget (QStackedLayout ()) ((Int)) where
widget x0 (x1)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_widget1_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStackedLayout_widget1_h" qtc_QStackedLayout_widget1_h :: Ptr (TQStackedLayout a) -> CInt -> IO (Ptr (TQWidget ()))
instance Qwidget (QStackedLayoutSc a) ((Int)) where
widget x0 (x1)
= withQWidgetResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_widget1_h cobj_x0 (toCInt x1)
qStackedLayout_delete :: QStackedLayout a -> IO ()
qStackedLayout_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_delete cobj_x0
foreign import ccall "qtc_QStackedLayout_delete" qtc_QStackedLayout_delete :: Ptr (TQStackedLayout a) -> IO ()
qStackedLayout_deleteLater :: QStackedLayout a -> IO ()
qStackedLayout_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_deleteLater cobj_x0
foreign import ccall "qtc_QStackedLayout_deleteLater" qtc_QStackedLayout_deleteLater :: Ptr (TQStackedLayout a) -> IO ()
instance QaddChildLayout (QStackedLayout ()) ((QLayout t1)) where
addChildLayout x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addChildLayout cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_addChildLayout" qtc_QStackedLayout_addChildLayout :: Ptr (TQStackedLayout a) -> Ptr (TQLayout t1) -> IO ()
instance QaddChildLayout (QStackedLayoutSc a) ((QLayout t1)) where
addChildLayout x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addChildLayout cobj_x0 cobj_x1
instance QaddChildWidget (QStackedLayout ()) ((QWidget t1)) where
addChildWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addChildWidget cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_addChildWidget" qtc_QStackedLayout_addChildWidget :: Ptr (TQStackedLayout a) -> Ptr (TQWidget t1) -> IO ()
instance QaddChildWidget (QStackedLayoutSc a) ((QWidget t1)) where
addChildWidget x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_addChildWidget cobj_x0 cobj_x1
instance QqalignmentRect (QStackedLayout ()) ((QRect t1)) where
qalignmentRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_alignmentRect cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_alignmentRect" qtc_QStackedLayout_alignmentRect :: Ptr (TQStackedLayout a) -> Ptr (TQRect t1) -> IO (Ptr (TQRect ()))
instance QqalignmentRect (QStackedLayoutSc a) ((QRect t1)) where
qalignmentRect x0 (x1)
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_alignmentRect cobj_x0 cobj_x1
instance QalignmentRect (QStackedLayout ()) ((Rect)) where
alignmentRect x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStackedLayout_alignmentRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QStackedLayout_alignmentRect_qth" qtc_QStackedLayout_alignmentRect_qth :: Ptr (TQStackedLayout a) -> CInt -> CInt -> CInt -> CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance QalignmentRect (QStackedLayoutSc a) ((Rect)) where
alignmentRect x0 (x1)
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QStackedLayout_alignmentRect_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QchildEvent (QStackedLayout ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_childEvent" qtc_QStackedLayout_childEvent :: Ptr (TQStackedLayout a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QStackedLayoutSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_childEvent cobj_x0 cobj_x1
instance QexpandingDirections (QStackedLayout ()) (()) where
expandingDirections x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_expandingDirections_h cobj_x0
foreign import ccall "qtc_QStackedLayout_expandingDirections_h" qtc_QStackedLayout_expandingDirections_h :: Ptr (TQStackedLayout a) -> IO CLong
instance QexpandingDirections (QStackedLayoutSc a) (()) where
expandingDirections x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_expandingDirections_h cobj_x0
instance QindexOf (QStackedLayout ()) ((QWidget t1)) where
indexOf x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_indexOf_h cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_indexOf_h" qtc_QStackedLayout_indexOf_h :: Ptr (TQStackedLayout a) -> Ptr (TQWidget t1) -> IO CInt
instance QindexOf (QStackedLayoutSc a) ((QWidget t1)) where
indexOf x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_indexOf_h cobj_x0 cobj_x1
instance Qinvalidate (QStackedLayout ()) (()) where
invalidate x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_invalidate_h cobj_x0
foreign import ccall "qtc_QStackedLayout_invalidate_h" qtc_QStackedLayout_invalidate_h :: Ptr (TQStackedLayout a) -> IO ()
instance Qinvalidate (QStackedLayoutSc a) (()) where
invalidate x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_invalidate_h cobj_x0
instance QqisEmpty (QStackedLayout ()) (()) where
qisEmpty x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_isEmpty_h cobj_x0
foreign import ccall "qtc_QStackedLayout_isEmpty_h" qtc_QStackedLayout_isEmpty_h :: Ptr (TQStackedLayout a) -> IO CBool
instance QqisEmpty (QStackedLayoutSc a) (()) where
qisEmpty x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_isEmpty_h cobj_x0
instance Qlayout (QStackedLayout ()) (()) (IO (QLayout ())) where
layout x0 ()
= withQLayoutResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_layout_h cobj_x0
foreign import ccall "qtc_QStackedLayout_layout_h" qtc_QStackedLayout_layout_h :: Ptr (TQStackedLayout a) -> IO (Ptr (TQLayout ()))
instance Qlayout (QStackedLayoutSc a) (()) (IO (QLayout ())) where
layout x0 ()
= withQLayoutResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_layout_h cobj_x0
instance QqmaximumSize (QStackedLayout ()) (()) where
qmaximumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_maximumSize_h cobj_x0
foreign import ccall "qtc_QStackedLayout_maximumSize_h" qtc_QStackedLayout_maximumSize_h :: Ptr (TQStackedLayout a) -> IO (Ptr (TQSize ()))
instance QqmaximumSize (QStackedLayoutSc a) (()) where
qmaximumSize x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_maximumSize_h cobj_x0
instance QmaximumSize (QStackedLayout ()) (()) where
maximumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_maximumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QStackedLayout_maximumSize_qth_h" qtc_QStackedLayout_maximumSize_qth_h :: Ptr (TQStackedLayout a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QmaximumSize (QStackedLayoutSc a) (()) where
maximumSize x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_maximumSize_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QsetSpacing (QStackedLayout ()) ((Int)) where
setSpacing x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_setSpacing cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStackedLayout_setSpacing" qtc_QStackedLayout_setSpacing :: Ptr (TQStackedLayout a) -> CInt -> IO ()
instance QsetSpacing (QStackedLayoutSc a) ((Int)) where
setSpacing x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_setSpacing cobj_x0 (toCInt x1)
instance Qspacing (QStackedLayout ()) (()) where
spacing x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_spacing cobj_x0
foreign import ccall "qtc_QStackedLayout_spacing" qtc_QStackedLayout_spacing :: Ptr (TQStackedLayout a) -> IO CInt
instance Qspacing (QStackedLayoutSc a) (()) where
spacing x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_spacing cobj_x0
instance QwidgetEvent (QStackedLayout ()) ((QEvent t1)) where
widgetEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_widgetEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_widgetEvent" qtc_QStackedLayout_widgetEvent :: Ptr (TQStackedLayout a) -> Ptr (TQEvent t1) -> IO ()
instance QwidgetEvent (QStackedLayoutSc a) ((QEvent t1)) where
widgetEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_widgetEvent cobj_x0 cobj_x1
instance Qqgeometry (QStackedLayout ()) (()) where
qgeometry x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_geometry_h cobj_x0
foreign import ccall "qtc_QStackedLayout_geometry_h" qtc_QStackedLayout_geometry_h :: Ptr (TQStackedLayout a) -> IO (Ptr (TQRect ()))
instance Qqgeometry (QStackedLayoutSc a) (()) where
qgeometry x0 ()
= withQRectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_geometry_h cobj_x0
instance Qgeometry (QStackedLayout ()) (()) where
geometry x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_geometry_qth_h cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
foreign import ccall "qtc_QStackedLayout_geometry_qth_h" qtc_QStackedLayout_geometry_qth_h :: Ptr (TQStackedLayout a) -> Ptr CInt -> Ptr CInt -> Ptr CInt -> Ptr CInt -> IO ()
instance Qgeometry (QStackedLayoutSc a) (()) where
geometry x0 ()
= withRectResult $ \crect_ret_x crect_ret_y crect_ret_w crect_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_geometry_qth_h cobj_x0 crect_ret_x crect_ret_y crect_ret_w crect_ret_h
instance QhasHeightForWidth (QStackedLayout ()) (()) where
hasHeightForWidth x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_hasHeightForWidth_h cobj_x0
foreign import ccall "qtc_QStackedLayout_hasHeightForWidth_h" qtc_QStackedLayout_hasHeightForWidth_h :: Ptr (TQStackedLayout a) -> IO CBool
instance QhasHeightForWidth (QStackedLayoutSc a) (()) where
hasHeightForWidth x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_hasHeightForWidth_h cobj_x0
instance QheightForWidth (QStackedLayout ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStackedLayout_heightForWidth_h" qtc_QStackedLayout_heightForWidth_h :: Ptr (TQStackedLayout a) -> CInt -> IO CInt
instance QheightForWidth (QStackedLayoutSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_heightForWidth_h cobj_x0 (toCInt x1)
instance QminimumHeightForWidth (QStackedLayout ()) ((Int)) where
minimumHeightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_minimumHeightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QStackedLayout_minimumHeightForWidth_h" qtc_QStackedLayout_minimumHeightForWidth_h :: Ptr (TQStackedLayout a) -> CInt -> IO CInt
instance QminimumHeightForWidth (QStackedLayoutSc a) ((Int)) where
minimumHeightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_minimumHeightForWidth_h cobj_x0 (toCInt x1)
instance QspacerItem (QStackedLayout ()) (()) where
spacerItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_spacerItem_h cobj_x0
foreign import ccall "qtc_QStackedLayout_spacerItem_h" qtc_QStackedLayout_spacerItem_h :: Ptr (TQStackedLayout a) -> IO (Ptr (TQSpacerItem ()))
instance QspacerItem (QStackedLayoutSc a) (()) where
spacerItem x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_spacerItem_h cobj_x0
instance QconnectNotify (QStackedLayout ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStackedLayout_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QStackedLayout_connectNotify" qtc_QStackedLayout_connectNotify :: Ptr (TQStackedLayout a) -> CWString -> IO ()
instance QconnectNotify (QStackedLayoutSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStackedLayout_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QStackedLayout ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_customEvent" qtc_QStackedLayout_customEvent :: Ptr (TQStackedLayout a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QStackedLayoutSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QStackedLayout ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStackedLayout_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QStackedLayout_disconnectNotify" qtc_QStackedLayout_disconnectNotify :: Ptr (TQStackedLayout a) -> CWString -> IO ()
instance QdisconnectNotify (QStackedLayoutSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStackedLayout_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QStackedLayout ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_event_h" qtc_QStackedLayout_event_h :: Ptr (TQStackedLayout a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QStackedLayoutSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_event_h cobj_x0 cobj_x1
instance QeventFilter (QStackedLayout ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QStackedLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QStackedLayout_eventFilter_h" qtc_QStackedLayout_eventFilter_h :: Ptr (TQStackedLayout a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QStackedLayoutSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QStackedLayout_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QStackedLayout ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStackedLayout_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QStackedLayout_receivers" qtc_QStackedLayout_receivers :: Ptr (TQStackedLayout a) -> CWString -> IO CInt
instance Qreceivers (QStackedLayoutSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QStackedLayout_receivers cobj_x0 cstr_x1
instance Qsender (QStackedLayout ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_sender cobj_x0
foreign import ccall "qtc_QStackedLayout_sender" qtc_QStackedLayout_sender :: Ptr (TQStackedLayout a) -> IO (Ptr (TQObject ()))
instance Qsender (QStackedLayoutSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QStackedLayout_sender cobj_x0
instance QtimerEvent (QStackedLayout ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QStackedLayout_timerEvent" qtc_QStackedLayout_timerEvent :: Ptr (TQStackedLayout a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QStackedLayoutSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QStackedLayout_timerEvent cobj_x0 cobj_x1
| uduki/hsQt | Qtc/Gui/QStackedLayout.hs | bsd-2-clause | 29,268 | 0 | 16 | 4,568 | 8,819 | 4,456 | 4,363 | -1 | -1 |
{-# LANGUAGE CPP #-}
import Data.Char
import Data.Function (on)
import System.Environment
import System.FilePath
import Test.Haddock
import Test.Haddock.Xhtml
checkConfig :: CheckConfig Xml
checkConfig = CheckConfig
{ ccfgRead = parseXml
, ccfgClean = stripIfRequired
, ccfgDump = dumpXml
, ccfgEqual = (==) `on` dumpXml
}
dirConfig :: DirConfig
dirConfig = (defaultDirConfig $ takeDirectory __FILE__)
{ dcfgCheckIgnore = checkIgnore
}
main :: IO ()
main = do
cfg <- parseArgs checkConfig dirConfig =<< getArgs
runAndCheck $ cfg
{ cfgHaddockArgs = cfgHaddockArgs cfg ++ ["--pretty-html", "--html"]
}
stripIfRequired :: String -> Xml -> Xml
stripIfRequired mdl =
stripLinks' . stripFooter
where
stripLinks'
| mdl `elem` preserveLinksModules = id
| otherwise = stripLinks
-- | List of modules in which we don't 'stripLinks'
preserveLinksModules :: [String]
preserveLinksModules = ["Bug253.html", "NamespacedIdentifiers.html"]
ingoredTests :: [FilePath]
ingoredTests =
[
-- Currently some declarations are exported twice
-- we need a reliable way to deduplicate here.
-- Happens since PR #688.
"B"
]
checkIgnore :: FilePath -> Bool
checkIgnore file | takeBaseName file `elem` ingoredTests = True
checkIgnore file@(c:_) | takeExtension file == ".html" && isUpper c = False
checkIgnore _ = True
| haskell/haddock | html-test/Main.hs | bsd-2-clause | 1,404 | 0 | 11 | 298 | 342 | 190 | 152 | 37 | 1 |
{-# LANGUAGE CPP #-}
{- | Compatibility helper module.
This module holds definitions that help with supporting multiple
library versions or transitions between versions.
-}
{-
Copyright (C) 2011, 2012 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Compat
( filePath'
, maybeFilePath'
, toInotifyPath
, getPid'
) where
import qualified Data.ByteString.UTF8 as UTF8
import System.FilePath (FilePath)
import System.Posix.ByteString.FilePath (RawFilePath)
import qualified System.INotify
import qualified Text.JSON
import qualified Control.Monad.Fail as Fail
import System.Process.Internals
import System.Posix.Types (CPid (..))
#if MIN_VERSION_process(1,6,3)
import System.Process (getPid)
#else
import Control.Concurrent.Lifted (readMVar)
#endif
-- | Wrappers converting ByteString filepaths to Strings and vice versa
--
-- hinotify 0.3.10 switched to using RawFilePaths instead of FilePaths, the
-- former being Data.ByteString and the latter String.
#if MIN_VERSION_hinotify(0,3,10)
filePath' :: System.INotify.Event -> FilePath
filePath' = UTF8.toString . System.INotify.filePath
maybeFilePath' :: System.INotify.Event -> Maybe FilePath
maybeFilePath' ev = UTF8.toString <$> System.INotify.maybeFilePath ev
toInotifyPath :: FilePath -> RawFilePath
toInotifyPath = UTF8.fromString
#else
filePath' :: System.INotify.Event -> FilePath
filePath' = System.INotify.filePath
maybeFilePath' :: System.INotify.Event -> Maybe FilePath
maybeFilePath' = System.INotify.maybeFilePath
toInotifyPath :: FilePath -> FilePath
toInotifyPath = id
#endif
-- | MonadFail.Fail instance definitions for JSON results
-- Required as of GHC 8.6 because MonadFailDesugaring is on by default:
-- https://gitlab.haskell.org/ghc/ghc/wikis/migration/8.6
instance Fail.MonadFail Text.JSON.Result where
fail = Fail.fail
-- | Process 1.6.3. introduced the getPid function, for older versions
-- provide an implemention here (https://github.com/haskell/process/pull/109)
type Pid = CPid
getPid' :: ProcessHandle -> IO (Maybe Pid)
#if MIN_VERSION_process(1,6,3)
getPid' = getPid
#else
getPid' (ProcessHandle mh _) = do
p_ <- readMVar mh
case p_ of
OpenHandle pid -> return $ Just pid
_ -> return Nothing
#endif
| mbakke/ganeti | src/Ganeti/Compat.hs | bsd-2-clause | 3,455 | 0 | 8 | 493 | 250 | 159 | 91 | 30 | 2 |
import System.Process.Extra
main = system_ "runhaskell -isrc Generate"
| mgmeier/extra | travis.hs | bsd-3-clause | 73 | 0 | 5 | 10 | 15 | 8 | 7 | 2 | 1 |
-- | Includes the Sound type and associated operations, for audio playback
-- in Tea.
module Tea.Sound ( loadSound
, maxVolume
, play
, playLoop
, pause
, resume
, stop
, setVolume
, getVolume
, isPlaying
, isPaused
, pauseAll
, resumeAll
, stopAll
, setMasterVolume
, getMasterVolume
, Sound
) where
import Prelude hiding (lookup)
import qualified Graphics.UI.SDL.Mixer as Mixer
import Control.Monad.State
import Control.Applicative((<$>))
import Data.Map(insert, lookup)
import Tea.TeaState
import Tea.Tea
-- |A data type representing a sound that can be played in Tea.
data Sound = Sound Mixer.Chunk
-- |The maximum volume level
maxVolume :: Int
maxVolume = 128
noChannel :: Mixer.Channel
noChannel = -1
-- | Load a sound from the given filename. Supports CMD, Wav, Trackers
-- such as MOD files, MIDI, Ogg, MP3, however MIDI and MP3 support
-- is platform dependant and shaky.
loadSound :: FilePath -> Tea s Sound
loadSound f = Sound <$> liftIO (Mixer.loadWAV f)
-- | Play a sound
play :: Sound -> Tea s ()
play snd = playLoop snd 0
-- | Play a sound, looping the provided number of times.
playLoop :: Sound -> Int -> Tea s ()
playLoop s@(Sound chun) loops = do stop s
chan <- liftIO $ Mixer.playChannel (-1) chun loops
modifyT $ \s@TS{_channels = c} -> s { _channels = insert (read $ show chun :: Int) chan c }
withChannel = withChannelRet ()
withChannelRet ret chun f = let key = read $ show chun :: Int
in do c <- fmap _channels getT
case lookup key c of
Just channel -> f channel
Nothing -> return ret
-- |Pause a sound
pause :: Sound -> Tea s ()
pause (Sound chun) = withChannel chun $ liftIO . Mixer.pause
-- |Resume a sound
resume :: Sound -> Tea s ()
resume (Sound chun) = withChannel chun $ liftIO . Mixer.resume
-- |Stop a sound playing
stop :: Sound -> Tea s ()
stop (Sound chun) = withChannel chun $ liftIO . Mixer.haltChannel
-- |Set a sound's playback volume.
setVolume :: Sound -> Int -> Tea s ()
setVolume (Sound chun) vol = withChannel chun $ \chan -> liftIO $ do Mixer.volume chan vol
return ()
-- |Get a sound's playback volume
getVolume :: Sound -> Tea s Int
getVolume (Sound chun) = withChannelRet (-1) chun $ \chan -> liftIO $ Mixer.volume chan (-1)
-- |Return if a sound is currently playing
isPlaying :: Sound -> Tea s Bool
isPlaying (Sound chun) = withChannelRet False chun $ liftIO . Mixer.isChannelPlaying
-- |Return if a sound is currently paused.
isPaused :: Sound -> Tea s Bool
isPaused (Sound chun) = withChannelRet False chun $ liftIO . Mixer.isChannelPaused
-- |Pause all currently playing sounds.
pauseAll :: Tea s ()
pauseAll = liftIO $ Mixer.pause noChannel
-- |Resume all sounds that have been paused.
resumeAll :: Tea s ()
resumeAll = liftIO $ Mixer.resume noChannel
-- |Stop playback of all sounds.
stopAll :: Tea s ()
stopAll = liftIO $ Mixer.haltChannel noChannel
-- |Set the master volume of sound playback
setMasterVolume :: Int -> Tea s ()
setMasterVolume v = liftIO $ Mixer.volume noChannel v >> return ()
-- |Get the master volume of sound playback
getMasterVolume :: Tea s Int
getMasterVolume = liftIO $ Mixer.volume noChannel (-1)
| liamoc/tea-hs | Tea/Sound.hs | bsd-3-clause | 3,680 | 0 | 14 | 1,141 | 952 | 500 | 452 | 68 | 2 |
{-# language CPP #-}
module OpenXR.CStruct
( ToCStruct(..)
, FromCStruct(..)
) where
#if defined(USE_VULKAN_TYPES)
import Vulkan.CStruct
#else
import Control.Exception.Base ( bracket )
import Foreign.Marshal.Alloc ( allocaBytesAligned )
import Foreign.Marshal.Alloc ( callocBytes )
import Foreign.Marshal.Alloc ( free )
import Foreign.Ptr ( Ptr )
-- | A class for types which can be marshalled into a C style
-- structure.
class ToCStruct a where
-- | Allocates a C type structure and all dependencies and passes
-- it to a continuation. The space is deallocated when this
-- continuation returns and the C type structure must not be
-- returned out of it.
withCStruct :: a -> (Ptr a -> IO b) -> IO b
withCStruct x f = allocaBytesAligned (cStructSize @a) (cStructAlignment @a)
$ \p -> pokeCStruct p x (f p)
-- | Write a C type struct into some existing memory and run a
-- continuation. The pointed to structure is not necessarily valid
-- outside the continuation as additional allocations may have been
-- made.
pokeCStruct :: Ptr a -> a -> IO b -> IO b
-- | Allocate space for an "empty" @a@ and populate any univalued
-- members with their value.
withZeroCStruct :: (Ptr a -> IO b) -> IO b
withZeroCStruct f =
bracket (callocBytes @a (cStructSize @a)) free $ \p -> pokeZeroCStruct p (f p)
-- | And populate any univalued members with their value, run a
-- function and then clean up any allocated resources.
pokeZeroCStruct :: Ptr a -> IO b -> IO b
-- | The size of this struct, note that this doesn't account for any
-- extra pointed-to data
cStructSize :: Int
-- | The required memory alignment for this type
cStructAlignment :: Int
-- | A class for types which can be marshalled from a C style
-- structure.
class FromCStruct a where
-- | Read an @a@ and any other pointed to data from memory
peekCStruct :: Ptr a -> IO a
#endif
| expipiplus1/vulkan | openxr/src-manual/OpenXR/CStruct.hs | bsd-3-clause | 2,028 | 0 | 5 | 518 | 31 | 22 | 9 | -1 | -1 |
-- !!! Testing Haskell 1.3 syntax
-- Haskell 1.3 syntax differs from Haskell 1.2 syntax in several ways:
-- * Qualified names in export lists
module TestSyntax where
-- * Qualified import/export
-- 1) Syntax:
import qualified Prelude as P
import Prelude
import qualified Prelude
import Prelude ()
import Prelude (fst,snd)
import qualified Prelude(fst,snd)
-- bizarre syntax allowed in draft of Haskell 1.3
import Prelude(,)
import Prelude(fst,snd,)
import Prelude(Ord(..),Eq((==),(/=)),)
import Prelude hiding (fst,snd,)
import Prelude hiding (fst,snd)
import qualified Prelude hiding (fst,snd)
import Prelude as P
import qualified Prelude as P
import Prelude as P(fst,snd)
import Prelude as P(,)
import qualified Prelude as P(fst,snd)
import Prelude as P hiding (fst,snd)
import qualified Prelude as P hiding (fst,snd)
-- 2) Use of qualified type names
-- 3) Use of qualified constructors
-- 4) Use of qualified variables
-- * No n+k patterns (yippee!)
-- (No tests yet)
-- Some things are unchanged.
-- * Unqualified imports and use of hiding/selective import.
--
-- Note: it's not clear how these various imports are supposed to
-- interact with one another.
-- John explains:
-- 1) "hiding" lists etc are just abbreviations for very long
-- lists.
-- 2) Multiple imports are additive.
-- (This makes the meaning order-independent!)
-- Note: Hugs allows imports anywhere a topdecl is allowed.
-- This isn't legal Haskell - but it does no harm.
-- import Prelude(lex)
-- import Prelude
-- import Prelude hiding (lex)
-- lex = 1 :: Int -- error unless we've hidden lex.
-- * Qualified names
-- Function/operator names
myfilter x = Prelude.filter x -- argument added to avoid monomorphism restn
mycompose = (Prelude..)
-- Use of module synonyms
myfilter2 p = P.filter p
-- Method names
myplus :: Num a => a -> a -> a
myplus = (Prelude.+)
-- Tycons
myminus = (Prelude.-) :: Prelude.Int -> Prelude.Int -> Prelude.Int
-- Type synonyms
foo :: P.ShowS
foo = foo
-- Class names in instances
instance P.Num P.Bool where
(+) = (P.||)
(*) = (P.&&)
negate = P.not
instance (P.Num a, P.Num b) => P.Num (a,b) where
x + y = (fst x + fst y, snd x + snd y)
-- Constructor names in expressions
-- this used to break tidyInfix in parser.y
-- Note that P.[] is _not_ legal!
testInfixQualifiedCon = 'a' P.: [] :: String
-- Constructor names in patterns
f (P.Just x) = True
f (P.Nothing) = False
g (x P.: xs) = x
y P.: ys = ['a'..]
-- * Support for octal and hexadecimal numbers
-- Note: 0xff and 0xFF are legal but 0Xff and 0XFF are not.
-- ToDo: negative tests to make sure invalid numbers are excluded.
d = ( -1, -0, 0, 1) :: (Int,Int,Int,Int)
o = (-0o1,-0o0,0o0,0o1) :: (Int,Int,Int,Int)
x = (-0x1,-0x0,0x0,0x1) :: (Int,Int,Int,Int)
x' = (0xff,0xFf,0xfF,0xFF) :: (Int,Int,Int,Int)
-- * No renaming or interface files
-- We test that "interface", "renaming" and "to" are not reserved.
interface = 1 :: Int
renaming = 42 :: Int
to = 2 :: Int
| FranklinChen/Hugs | tests/static/syntax.hs | bsd-3-clause | 3,071 | 4 | 8 | 647 | 707 | 455 | 252 | -1 | -1 |
--------------------------------------------------------------------------------
-- |
-- Module : Graphics.Rendering.OpenGL.Raw.ATI.TextureEnvCombine3
-- Copyright : (c) Sven Panne 2015
-- License : BSD3
--
-- Maintainer : Sven Panne <[email protected]>
-- Stability : stable
-- Portability : portable
--
-- The <https://www.opengl.org/registry/specs/ATI/texture_env_combine3.txt ATI_texture_env_combine3> extension.
--
--------------------------------------------------------------------------------
module Graphics.Rendering.OpenGL.Raw.ATI.TextureEnvCombine3 (
-- * Enums
gl_MODULATE_ADD_ATI,
gl_MODULATE_SIGNED_ADD_ATI,
gl_MODULATE_SUBTRACT_ATI
) where
import Graphics.Rendering.OpenGL.Raw.Tokens
| phaazon/OpenGLRaw | src/Graphics/Rendering/OpenGL/Raw/ATI/TextureEnvCombine3.hs | bsd-3-clause | 732 | 0 | 4 | 84 | 43 | 35 | 8 | 5 | 0 |
{-# LANGUAGE TypeHoles #-}
module Language.Elementscript.Micro (EvalState(..),
initialEvalState,
evaluate,
Val(..),
normalize,
prettyPrint) where
import Control.Applicative
import Control.Monad.Error.Class
import Control.Monad.Reader.Class
import Control.Monad.State.Class
import Data.IntMap.Strict (IntMap)
import qualified Data.IntMap.Strict as IntMap
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as Map
import Data.Monoid (Monoid (..), (<>))
import Data.Sequence (Seq, ViewL (..), ViewR (..), viewl,
viewr)
import qualified Data.Sequence as Seq
import Data.String (IsString (..))
import Data.Text.Lazy (Text)
import qualified Data.Text.Lazy as Text
import Text.Parsec
import Text.Parsec.Text.Lazy
data EvalState = ES { nameMap :: Map Text Val,
precMap :: IntMap Text }
data Val = Lam { lamVar :: Text,
lamBody :: Val }
| Var { varName :: Text }
| App { appFunc :: Val,
appArg :: Val }
normalize :: Val -> Val
normalize (Lam var body) = Lam var $ normalize body
normalize (Var name) = Var name
normalize (App (Lam var body) arg) = normalize $ subst var arg body
normalize (App (Var name) arg) = App (Var name) $ normalize arg
subst :: Text -> Val -> Val -> Val
subst outerVar expr (Lam innerVar body) | outerVar == innerVar = Lam innerVar body
| otherwise = Lam innerVar (subst outerVar expr body)
subst var expr (Var name) | var == name = expr
| otherwise = Var name
subst var expr (App func arg) = App (subst var expr func) (subst var expr arg)
prettyPrint :: Val -> Text
prettyPrint = go False
where
go :: Bool -> Val -> Text
go underApp (Lam var body) = ppParens underApp (var <> " -> " <> go False body)
go _ (Var name) = name
go underApp (App func arg) = ppParens underApp (go True func <> " " <> go True arg)
ppParens :: Bool -> Text -> Text
ppParens wanted inner = if wanted then "(" <> inner <> ")" else inner
evaluate :: ParsecT Text EvalState IO Val
evaluate = _
initialEvalStateList :: [(Text, Int, Val)]
initialEvalStateList = _
initialEvalState :: EvalState
initialEvalState = ES { nameMap = Map.fromList $ map (\(name, _, val) -> (name, val)) initialEvalStateList,
precMap = IntMap.fromList $ map (\(name, prec, _) -> (prec, name)) initialEvalStateList }
| pthariensflame/elementscript-micro | src/Language/Elementscript/Micro.hs | bsd-3-clause | 2,884 | 0 | 11 | 1,050 | 872 | 489 | 383 | 57 | 4 |
module Opaleye.Internal.Tag where
data Tag = UnsafeTag Int deriving (Read, Show)
start :: Tag
start = UnsafeTag 1
next :: Tag -> Tag
next = UnsafeTag . (+1) . unsafeUnTag
unsafeUnTag :: Tag -> Int
unsafeUnTag (UnsafeTag i) = i
tagWith :: Tag -> String -> String
tagWith t s = s ++ "_" ++ show (unsafeUnTag t)
| silkapp/haskell-opaleye | src/Opaleye/Internal/Tag.hs | bsd-3-clause | 314 | 0 | 8 | 63 | 129 | 70 | 59 | 10 | 1 |
module Control.Cozip where
import Prelude(Either)
class Cozip f where
cozip ::
f (Either a b)
-> Either (f a) (f b)
| tonymorris/lens-proposal | src/Control/Cozip.hs | bsd-3-clause | 128 | 0 | 10 | 33 | 60 | 31 | 29 | 6 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE UndecidableInstances #-}
#ifndef MIN_VERSION_GLASGOW_HASKELL
#define MIN_VERSION_GLASGOW_HASKELL(a,b,c,d) 0
#endif
-- MIN_VERSION_GLASGOW_HASKELL was introduced in GHC 7.10
#if MIN_VERSION_GLASGOW_HASKELL(7,10,0,0)
#else
{-# LANGUAGE OverlappingInstances #-}
#endif
-- | This module is only to limit the scope of the @OverlappingInstances@ flag
module Data.TypeRep.Sub where
-- TODO Merge this module with `Data.TypeRep.Representation` when support for < 7.10 is dropped
import Language.Syntactic
import Data.TypeRep.Representation
-- | Sub-universe relation
--
-- In general, a universe @t@ is a sub-universe of @u@ if @u@ has the form
--
-- > t1 :+: t2 :+: ... :+: t
class SubUniverse sub sup
where
-- | Cast a type representation to a larger universe
weakenUniverse :: TypeRep sub a -> TypeRep sup a
instance {-# OVERLAPPING #-} SubUniverse t t
where
weakenUniverse = id
instance {-# OVERLAPPING #-} (SubUniverse sub sup', sup ~ (t :+: sup')) => SubUniverse sub sup
where
weakenUniverse = sugar . mapAST InjR . desugar . weakenUniverse
| emilaxelsson/open-typerep | src/Data/TypeRep/Sub.hs | bsd-3-clause | 1,113 | 0 | 9 | 197 | 138 | 82 | 56 | -1 | -1 |
module Signal
( module Signal.Sig
, module Signal.Str
, module Signal.Compiler
) where
import Signal.Core as Signal.Sig hiding (Symbol, S, U, Wit, Witness)
import Signal.Core.Stream as Signal.Str hiding (map, repeat)
import Signal.Compiler
| markus-git/signal | src/Signal.hs | bsd-3-clause | 256 | 0 | 5 | 48 | 75 | 50 | 25 | 7 | 0 |
import Control.Applicative
import Control.Concurrent
import Control.Monad
import Data.List
import System.Directory
import System.Environment
import System.Exit
import System.FilePath
import System.IO
import System.Process
main :: IO ()
main = do
hSetBuffering stdout LineBuffering
hSetBuffering stderr LineBuffering
args <- getArgs
repo <- case args of
[] -> hPutStrLn stderr "Please pass the repository as argument" >> exitFailure
r : _ -> return r
testRepoPath <- (</> "test-repo") <$> getCurrentDirectory
checkExistence <- doesDirectoryExist testRepoPath
unless checkExistence $ do
hPutStrLn stderr $ "Getting " ++ repo ++ " ..."
exitCode <- rawSystem "darcs" ["get", repo, testRepoPath, "--lazy"]
unless (exitCode == ExitSuccess) $ exitWith exitCode
setCurrentDirectory testRepoPath
forever $ do
hPutStrLn stderr "Checking ..."
output <- readProcess "darcs" ["pull", "--all"] ""
unless ("No remote changes to pull in" `isInfixOf` output) $ putStrLn testRepoPath
threadDelay $ 30 * 1000 * 1000
| thoferon/court | plugins/Darcs.hs | bsd-3-clause | 1,059 | 0 | 13 | 195 | 305 | 148 | 157 | 30 | 2 |
import System.Directory (setCurrentDirectory)
import System.Process (callCommand)
main :: IO ()
main = do
setCurrentDirectory "Tests"
callCommand "sh allTests.sh"
| willdonnelly/dyre | test/Main.hs | bsd-3-clause | 168 | 0 | 7 | 23 | 48 | 24 | 24 | 6 | 1 |
module Distribution.Client.Dependency.Modular.IndexConversion
( convPIs
) where
import Data.List as L
import Data.Map as M
import Data.Maybe
import Data.Monoid as Mon
import Prelude hiding (pi)
import qualified Distribution.Client.PackageIndex as CI
import Distribution.Client.Types
import Distribution.Client.ComponentDeps (Component(..))
import Distribution.Compiler
import Distribution.InstalledPackageInfo as IPI
import Distribution.Package -- from Cabal
import Distribution.PackageDescription as PD -- from Cabal
import Distribution.PackageDescription.Configuration as PDC
import qualified Distribution.Simple.PackageIndex as SI
import Distribution.System
import Distribution.Client.Dependency.Modular.Dependency as D
import Distribution.Client.Dependency.Modular.Flag as F
import Distribution.Client.Dependency.Modular.Index
import Distribution.Client.Dependency.Modular.Package
import Distribution.Client.Dependency.Modular.Tree
import Distribution.Client.Dependency.Modular.Version
-- | Convert both the installed package index and the source package
-- index into one uniform solver index.
--
-- We use 'allPackagesBySourcePackageId' for the installed package index
-- because that returns us several instances of the same package and version
-- in order of preference. This allows us in principle to \"shadow\"
-- packages if there are several installed packages of the same version.
-- There are currently some shortcomings in both GHC and Cabal in
-- resolving these situations. However, the right thing to do is to
-- fix the problem there, so for now, shadowing is only activated if
-- explicitly requested.
convPIs :: OS -> Arch -> CompilerInfo -> Bool -> Bool ->
SI.InstalledPackageIndex -> CI.PackageIndex SourcePackage -> Index
convPIs os arch comp sip strfl iidx sidx =
mkIndex (convIPI' sip iidx ++ convSPI' os arch comp strfl sidx)
-- | Convert a Cabal installed package index to the simpler,
-- more uniform index format of the solver.
convIPI' :: Bool -> SI.InstalledPackageIndex -> [(PN, I, PInfo)]
convIPI' sip idx =
-- apply shadowing whenever there are multiple installed packages with
-- the same version
[ maybeShadow (convIP idx pkg)
| (_pkgid, pkgs) <- SI.allPackagesBySourcePackageId idx
, (maybeShadow, pkg) <- zip (id : repeat shadow) pkgs ]
where
-- shadowing is recorded in the package info
shadow (pn, i, PInfo fdeps fds _) | sip = (pn, i, PInfo fdeps fds (Just Shadowed))
shadow x = x
-- | Convert a single installed package into the solver-specific format.
convIP :: SI.InstalledPackageIndex -> InstalledPackageInfo -> (PN, I, PInfo)
convIP idx ipi =
let ipid = IPI.installedUnitId ipi
i = I (pkgVersion (sourcePackageId ipi)) (Inst ipid)
pn = pkgName (sourcePackageId ipi)
in case mapM (convIPId pn idx) (IPI.depends ipi) of
Nothing -> (pn, i, PInfo [] M.empty (Just Broken))
Just fds -> (pn, i, PInfo (setComp fds) M.empty Nothing)
where
-- We assume that all dependencies of installed packages are _library_ deps
setComp = setCompFlaggedDeps ComponentLib
-- TODO: Installed packages should also store their encapsulations!
-- | Convert dependencies specified by an installed package id into
-- flagged dependencies of the solver.
--
-- May return Nothing if the package can't be found in the index. That
-- indicates that the original package having this dependency is broken
-- and should be ignored.
convIPId :: PN -> SI.InstalledPackageIndex -> UnitId -> Maybe (FlaggedDep () PN)
convIPId pn' idx ipid =
case SI.lookupUnitId idx ipid of
Nothing -> Nothing
Just ipi -> let i = I (pkgVersion (sourcePackageId ipi)) (Inst ipid)
pn = pkgName (sourcePackageId ipi)
in Just (D.Simple (Dep pn (Fixed i (Goal (P pn') []))) ())
-- | Convert a cabal-install source package index to the simpler,
-- more uniform index format of the solver.
convSPI' :: OS -> Arch -> CompilerInfo -> Bool ->
CI.PackageIndex SourcePackage -> [(PN, I, PInfo)]
convSPI' os arch cinfo strfl = L.map (convSP os arch cinfo strfl) . CI.allPackages
-- | Convert a single source package into the solver-specific format.
convSP :: OS -> Arch -> CompilerInfo -> Bool -> SourcePackage -> (PN, I, PInfo)
convSP os arch cinfo strfl (SourcePackage (PackageIdentifier pn pv) gpd _ _pl) =
let i = I pv InRepo
in (pn, i, convGPD os arch cinfo strfl (PI pn i) gpd)
-- We do not use 'flattenPackageDescription' or 'finalizePackageDescription'
-- from 'Distribution.PackageDescription.Configuration' here, because we
-- want to keep the condition tree, but simplify much of the test.
-- | Convert a generic package description to a solver-specific 'PInfo'.
convGPD :: OS -> Arch -> CompilerInfo -> Bool ->
PI PN -> GenericPackageDescription -> PInfo
convGPD os arch cinfo strfl pi
(GenericPackageDescription pkg flags libs exes tests benchs) =
let
fds = flagInfo strfl flags
conv :: Mon.Monoid a => Component -> (a -> BuildInfo) ->
CondTree ConfVar [Dependency] a -> FlaggedDeps Component PN
conv comp getInfo = convCondTree os arch cinfo pi fds comp getInfo .
PDC.addBuildableCondition getInfo
in
PInfo
(maybe [] (conv ComponentLib libBuildInfo ) libs ++
maybe [] (convSetupBuildInfo pi) (setupBuildInfo pkg) ++
concatMap (\(nm, ds) -> conv (ComponentExe nm) buildInfo ds) exes ++
prefix (Stanza (SN pi TestStanzas))
(L.map (\(nm, ds) -> conv (ComponentTest nm) testBuildInfo ds) tests) ++
prefix (Stanza (SN pi BenchStanzas))
(L.map (\(nm, ds) -> conv (ComponentBench nm) benchmarkBuildInfo ds) benchs))
fds
Nothing
prefix :: (FlaggedDeps comp qpn -> FlaggedDep comp' qpn) -> [FlaggedDeps comp qpn] -> FlaggedDeps comp' qpn
prefix _ [] = []
prefix f fds = [f (concat fds)]
-- | Convert flag information. Automatic flags are now considered weak
-- unless strong flags have been selected explicitly.
flagInfo :: Bool -> [PD.Flag] -> FlagInfo
flagInfo strfl = M.fromList . L.map (\ (MkFlag fn _ b m) -> (fn, FInfo b m (not (strfl || m))))
-- | Convert condition trees to flagged dependencies.
convCondTree :: OS -> Arch -> CompilerInfo -> PI PN -> FlagInfo ->
Component ->
(a -> BuildInfo) ->
CondTree ConfVar [Dependency] a -> FlaggedDeps Component PN
convCondTree os arch cinfo pi@(PI pn _) fds comp getInfo (CondNode info ds branches) =
L.map (\d -> D.Simple (convDep pn d) comp) ds -- unconditional package dependencies
++ L.map (\e -> D.Simple (Ext e) comp) (PD.allExtensions bi) -- unconditional extension dependencies
++ L.map (\l -> D.Simple (Lang l) comp) (PD.allLanguages bi) -- unconditional language dependencies
++ L.map (\(Dependency pkn vr) -> D.Simple (Pkg pkn vr) comp) (PD.pkgconfigDepends bi) -- unconditional pkg-config dependencies
++ concatMap (convBranch os arch cinfo pi fds comp getInfo) branches
where
bi = getInfo info
-- | Branch interpreter.
--
-- Here, we try to simplify one of Cabal's condition tree branches into the
-- solver's flagged dependency format, which is weaker. Condition trees can
-- contain complex logical expression composed from flag choices and special
-- flags (such as architecture, or compiler flavour). We try to evaluate the
-- special flags and subsequently simplify to a tree that only depends on
-- simple flag choices.
convBranch :: OS -> Arch -> CompilerInfo ->
PI PN -> FlagInfo ->
Component ->
(a -> BuildInfo) ->
(Condition ConfVar,
CondTree ConfVar [Dependency] a,
Maybe (CondTree ConfVar [Dependency] a)) -> FlaggedDeps Component PN
convBranch os arch cinfo pi@(PI pn _) fds comp getInfo (c', t', mf') =
go c' ( convCondTree os arch cinfo pi fds comp getInfo t')
(maybe [] (convCondTree os arch cinfo pi fds comp getInfo) mf')
where
go :: Condition ConfVar ->
FlaggedDeps Component PN -> FlaggedDeps Component PN -> FlaggedDeps Component PN
go (Lit True) t _ = t
go (Lit False) _ f = f
go (CNot c) t f = go c f t
go (CAnd c d) t f = go c (go d t f) f
go (COr c d) t f = go c t (go d t f)
go (Var (Flag fn)) t f = extractCommon t f ++ [Flagged (FN pi fn) (fds ! fn) t f]
go (Var (OS os')) t f
| os == os' = t
| otherwise = f
go (Var (Arch arch')) t f
| arch == arch' = t
| otherwise = f
go (Var (Impl cf cvr)) t f
| matchImpl (compilerInfoId cinfo) ||
-- fixme: Nothing should be treated as unknown, rather than empty
-- list. This code should eventually be changed to either
-- support partial resolution of compiler flags or to
-- complain about incompletely configured compilers.
any matchImpl (fromMaybe [] $ compilerInfoCompat cinfo) = t
| otherwise = f
where
matchImpl (CompilerId cf' cv) = cf == cf' && checkVR cvr cv
-- If both branches contain the same package as a simple dep, we lift it to
-- the next higher-level, but without constraints. This heuristic together
-- with deferring flag choices will then usually first resolve this package,
-- and try an already installed version before imposing a default flag choice
-- that might not be what we want.
--
-- Note that we make assumptions here on the form of the dependencies that
-- can occur at this point. In particular, no occurrences of Fixed, and no
-- occurrences of multiple version ranges, as all dependencies below this
-- point have been generated using 'convDep'.
extractCommon :: FlaggedDeps Component PN -> FlaggedDeps Component PN -> FlaggedDeps Component PN
extractCommon ps ps' = [ D.Simple (Dep pn1 (Constrained [(vr1 .||. vr2, Goal (P pn) [])])) comp
| D.Simple (Dep pn1 (Constrained [(vr1, _)])) _ <- ps
, D.Simple (Dep pn2 (Constrained [(vr2, _)])) _ <- ps'
, pn1 == pn2
]
-- | Convert a Cabal dependency to a solver-specific dependency.
convDep :: PN -> Dependency -> Dep PN
convDep pn' (Dependency pn vr) = Dep pn (Constrained [(vr, Goal (P pn') [])])
-- | Convert setup dependencies
convSetupBuildInfo :: PI PN -> SetupBuildInfo -> FlaggedDeps Component PN
convSetupBuildInfo (PI pn _i) nfo =
L.map (\d -> D.Simple (convDep pn d) ComponentSetup) (PD.setupDepends nfo)
| garetxe/cabal | cabal-install/Distribution/Client/Dependency/Modular/IndexConversion.hs | bsd-3-clause | 10,782 | 0 | 20 | 2,624 | 2,805 | 1,477 | 1,328 | 132 | 9 |
{-# language DataKinds #-}
{-# language TypeFamilies #-}
{-# language GADTs #-}
{-# language MultiParamTypeClasses #-}
{-# language DeriveDataTypeable #-}
{-# language StandaloneDeriving #-}
{-# language FlexibleInstances #-}
{-# language FlexibleContexts #-}
{-# language UndecidableInstances #-}
{-# language Rank2Types #-}
{-# language TemplateHaskell #-}
{-# language ScopedTypeVariables #-}
{-# language ConstraintKinds #-}
{-# language DeriveAnyClass #-}
{-# language OverloadedStrings #-}
{-# language RecursiveDo #-}
{-# language QuasiQuotes #-}
{-# language TypeInType #-}
{-# language ViewPatterns #-}
{-# language OverloadedLists #-}
{-# language InstanceSigs #-}
module UI.Acceptance where
import Data.Dependent.Map (DMap,DSum((:=>)), singleton)
import qualified Data.Dependent.Map as DMap
import Data.GADT.Compare (GCompare)
import Data.GADT.Compare.TH
import UI.Lib -- (MS,ES,DS, Reason, domMorph, EitherG(LeftG,RightG), rightG,leftG, Cable,sselect)
import Reflex.Dom hiding (Delete, Insert, Link, Abort)
import Data.Bifunctor
import Control.Lens hiding (dropping)
import Data.Data.Lens
import Data.Data
import Data.Typeable
import Control.Lens.TH
import System.Random
import qualified Data.Map as M
import Status
import World
import Data.Text (Text,pack,unpack)
import Data.String.Here
import Data.String
import Control.Monad
import Data.Maybe
import Data.Monoid
import Control.Monad.Trans
import Data.Either
import Text.Read (readMaybe)
import UI.Constraints
import UI.ValueInput
import Control.Monad.Reader
import UI.Constraints
import Constraints
import HList
aborting
:: ()
=> (MS m, MonadReader (DS r) m, In Bool r)
=> IconsU m Taker a
=> IconsU m Giver a
=> Eqs Taker a
=> Eqs Giver a
=> Eqs u a
=> IconsU m u a
=> Show (Slot a)
=> Bargain a ~ String
=> Step 'OtherT u a
=> Idx 'ProposalT ('Present u)
-> ProposalData u a
-> Part u a
-> m (ES (World a -> Ctx OtherT a (World a)))
aborting i p u = check (p ^. proponent == u) . divClass "record abort" $ do
el "ul" $ do
el "li" $ do
elAttr "span" [("class","field")] $ text "when"
divClass "timeshow" $ text $ pack $ show $ p ^. slot
el "li" $ do
elAttr "span" [("class","field")] $ text "where"
divClass "placeshow" $ getIcon $ p ^. zone
el "li" $ do
elAttr "span" [("class","field")] $ text "what"
divClass "bargainshow" $ text $ pack $ p ^. bargain
abortDriver (step (Abort i) u)
abortWidget
:: forall m r . (MS m)
=> (MS m, MonadReader (DS r) m, In Bool r)
=> Iconified
-> m (Cable (EitherG Iconified ()))
abortWidget Iconified = do
b <- floater $ (icon ["close","3x"] "forget")
return $ wire (LeftG :=> Disclosed <$ b)
abortWidget Disclosed = do
p <- el "ul" $ do
divClass "modal" $ text "really want to abort the proposal?"
(b,n) <- yesno (constDyn True)
return $ leftmost [True <$ b ,False <$ n]
return $ merge [RightG :=> () <$ ffilter id p , LeftG :=> Iconified <$ ffilter not p]
abortDriver
:: ()
=> (In Bool r, MonadReader (DS r) m, MS m)
-- => IconsU m Taker a
-- => IconsU m Giver a
=> a
-> m (ES a)
abortDriver x = do
rec ws <- domMorph abortWidget s
s <- holdDyn Iconified (pick LeftG ws)
return $ x <$ pick RightG ws
----------------------------------------------------------------
---------------- Appointment ----------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
accepting
:: ()
=> (MS m, MonadReader (DS r) m, In Bool r)
=> Reflexive u
=> Eqs u a
=> IconsU m (Opponent u) a
=> IconsU m u a
=> Show (Slot a)
=> Bargain a ~ String
=> Step 'OtherT (Opponent u) a
=> ShowPart a
=> Valid (Zone u a) (Place (Opponent u) a)
=> Idx 'ProposalT ('Present u)
-> ProposalData u a
-> Part (Opponent u) a
-> Transaction ProposalT (Present u) a
-> (Part u a -> Roled Part a)
-> m (ES (World a -> Ctx OtherT a (World a)))
accepting i p u x e = divClass "record accept" $ do
el "ul" $ do
el "li" $ do
elAttr "span" [("class","field")] $ text "when"
divClass "timeshow" $ text $ pack $ show $ p ^. slot
el "li" $ do
elAttr "span" [("class","field")] $ text "where"
divClass "placeshow" $ getIcon $ p ^. zone
el "li" $ do
elAttr "span" [("class","field")] $ text "what"
divClass "bargainshow" $ text $ pack $ p ^. bargain
el "li" $ do
elAttr "span" [("class","field")] $ text "proponent"
divClass "opponent" $ showPart $ e (p ^. proponent)
acceptDriver (\ch -> step (Appointment i ch) u) x
acceptWidget
:: forall a r m z u. ()
=> (In Bool r, MonadReader (DS r) m, MS m)
=> IconsU m u a
=> Valid (Zone u a) (Place (Opponent u) a)
=> (Place (Opponent u) a -> z)
-> Transaction ProposalT (Present u) a
-> Iconified
-> m (Cable (EitherG Iconified z))
acceptWidget _ _ Iconified = do
b <- floater (icon ["handshake-o","3x"] "accept")
return $ wire (LeftG :=> Disclosed <$ b)
acceptWidget step (Proposal d) Disclosed = el "li" $ do
elAttr "span" [("class","question")] $ text "choose a place"
divClass "placepick" $ do
let rs = filter (valid $ d ^. zone) [minBound .. maxBound]
-- pd :: m (DS (Maybe (Place (Opponent u) a)))
pd <- divClass "radiochecks" $ radioChecks $ rs
(y,n) <- yesno $ maybe False (const True) <$> pd
return $ merge [
RightG :=> fmapMaybe id ((fmap step <$> pd) `tagPromptlyDyn` y)
, LeftG :=> Iconified <$ n --
]
acceptDriver
:: ()
=> (In Bool r, MonadReader (DS r) m, MS m)
=> IconsU m u a
=> IconsU m (Opponent u) a
=> Valid (Zone u a) (Place (Opponent u) a)
=> (Place (Opponent u) a -> z)
-> Transaction ProposalT (Present u) a
-> m (ES z)
acceptDriver step u = do
rec ws <- domMorph (acceptWidget step u) s
s <- holdDyn Iconified (pick LeftG ws)
return $ pick RightG ws
| paolino/book-a-visit | client/UI/Acceptance.hs | bsd-3-clause | 6,238 | 0 | 28 | 1,533 | 2,245 | 1,135 | 1,110 | 171 | 1 |
{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}
{-|
Module : TestTypes
Description : Types and Generators needed for general testing
-}
module TestTypes where
import Test.QuickCheck
import Control.Monad (liftM, liftM2, liftM3)
import Control.Arrow (first)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Network.Socket (PortNumber)
import Data.Word(Word16)
import Data.List (nubBy)
import Data.Function (on)
import Network.Kademlia.Types
newtype IdType = IT { getBS :: B.ByteString } deriving (Eq, Ord)
-- Custom show instance
instance Show IdType where
show = show . C.unpack . getBS
-- A simple 5-byte ByteString
instance Serialize IdType where
toBS = getBS
fromBS bs = if B.length bs >= 5
then Right $ first IT . B.splitAt 5 $ bs
else Left "ByteString to short."
instance Serialize String where
toBS = C.pack . show
fromBS s =
case (reads :: ReadS String) . C.unpack $ s of
[] -> Left "Failed to parse string."
(result, rest):_ -> Right (result, C.pack rest)
instance Arbitrary IdType where
arbitrary = do
str <- vectorOf 5 arbitrary
return $ IT $ C.pack str
instance Arbitrary PortNumber where
arbitrary = liftM fromIntegral (arbitrary :: Gen Word16)
instance Arbitrary Peer where
arbitrary = do
host <- arbitrary `suchThat` \s -> ' ' `notElem` s && not (null s)
&& length s < 20
port <- arbitrary
return $ Peer host port
instance (Arbitrary i, Arbitrary v) => Arbitrary (Command i v) where
arbitrary = oneof [
return PING
, return PONG
, liftM2 STORE arbitrary arbitrary
, liftM FIND_NODE arbitrary
, liftM2 RETURN_NODES arbitrary $ vectorOf 15 arbitrary
, liftM FIND_VALUE arbitrary
, liftM2 RETURN_VALUE arbitrary arbitrary
]
instance (Arbitrary i, Arbitrary v) => Arbitrary (Signal i v) where
arbitrary = liftM2 Signal arbitrary arbitrary
instance (Arbitrary i) => Arbitrary (Node i) where
arbitrary = liftM2 Node arbitrary arbitrary
-- | This enables me to specifiy a new Arbitrary instance
newtype NodeBunch i = NB {
nodes :: [Node i]
} deriving (Show)
-- | Make sure all Ids are unique
instance (Arbitrary i, Eq i) => Arbitrary (NodeBunch i) where
arbitrary = liftM NB $ vectorOf 20 arbitrary `suchThat` individualIds
where individualIds = individual ((==) `on` nodeId)
individual :: (a -> a -> Bool) -> [a] -> Bool
individual eq s = length s == (length . clear $ s)
where clear = nubBy eq
-- | This is needed for the Implementation tests
newtype IdBunch i = IB {
getIds :: [i]
} deriving (Show)
instance (Arbitrary i, Eq i) => Arbitrary (IdBunch i) where
arbitrary = liftM IB $ vectorOf 20 arbitrary `suchThat` individual (==)
| froozen/kademlia | test/TestTypes.hs | bsd-3-clause | 2,909 | 0 | 16 | 744 | 882 | 477 | 405 | 65 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
module System.FilePath.Dicom(
isDicomFile
, dicomFileR
, dicomExitCodeFileR
, exitCodeFileR
, FileR(..)
) where
import Control.Category(Category((.)))
import Control.Monad(Monad(return))
import Data.Bool(Bool)
import Data.Char(Char)
import Data.Eq(Eq((==)))
import Data.Foldable(Foldable, any)
import Data.Functor(Functor(fmap))
import Data.Maybe(Maybe(Nothing, Just))
import Data.Ord(Ord)
import Prelude (($), Show)
import System.Directory(doesFileExist, doesDirectoryExist, getPermissions, readable)
import System.Exit(ExitCode(ExitFailure, ExitSuccess))
import System.FilePath(FilePath)
import System.IO(IO, Handle, hClose, hReady, hGetChar, hSeek, openFile, SeekMode(AbsoluteSeek), IOMode(ReadMode))
data FileR =
IsNotDicom
| DoesNotExist
| IsNotReadable
| IsDirectory
| IsDicom
deriving (Eq, Show, Ord)
exitCodeFileR ::
FileR
-> ExitCode
exitCodeFileR IsNotDicom =
ExitFailure 1
exitCodeFileR DoesNotExist =
ExitFailure 2
exitCodeFileR IsNotReadable =
ExitFailure 3
exitCodeFileR IsDirectory =
ExitFailure 4
exitCodeFileR IsDicom =
ExitSuccess
dicomExitCodeFileR ::
FilePath
-> IO ExitCode
dicomExitCodeFileR =
fmap exitCodeFileR . dicomFileR
dicomFileR ::
FilePath
-> IO FileR
dicomFileR p =
do e <- doesFileExist p
if e
then
do o <- getPermissions p
if readable o
then
do b <- isDicomFile p
return $ if b
then
IsDicom
else
IsNotDicom
else
return IsNotReadable
else
do e' <- doesDirectoryExist p
return $ if e'
then
IsDirectory
else
DoesNotExist
isDicomFile ::
FilePath
-> IO Bool
isDicomFile p =
do h <- openFile p ReadMode
hSeek h AbsoluteSeek 128
d <- hChar4 h
hClose h
return (isDicom d)
isDicom ::
Foldable f =>
f (Char, Char, Char, Char)
-> Bool
isDicom =
any (\(c1, c2, c3, c4) -> [c1, c2, c3, c4] == "DICM")
hChar ::
Handle
-> IO (Maybe Char)
hChar h =
do r <- hReady h
if r
then
do c <- hGetChar h
return (Just c)
else
return Nothing
hChar4 ::
Handle
-> IO (Maybe (Char, Char, Char, Char))
hChar4 h =
-- MaybeT
let (.>>=.) :: Monad f => f (Maybe a) -> (a -> f (Maybe b)) -> f (Maybe b)
i .>>=. f =
do m <- i
case m of
Nothing -> return Nothing
Just a -> f a
in hChar h .>>=. \c1 ->
hChar h .>>=. \c2 ->
hChar h .>>=. \c3 ->
hChar h .>>=. \c4 ->
return (Just (c1, c2, c3, c4))
| tonymorris/isdicom | src/System/FilePath/Dicom.hs | bsd-3-clause | 2,810 | 0 | 18 | 922 | 918 | 495 | 423 | 102 | 5 |
-- | 'Cofunctor' is a structure from category theory dual to 'Functor'
--
-- A 'Functor' is defined by the operation 'fmap':
--
-- > fmap :: (a -> b) -> (f a -> f b)
--
-- This means that its dual must be defined by the following operation:
--
-- > cofmap :: (b -> a) -> (f b -> f a)
--
-- Since beginning his investigations, the author of this package has discovered
-- that this pattern is /at least/ as commonly used as 'Functor'. In fact, many
-- ubiquitous Haskell types (e.g. @[]@, 'Maybe', @((->) a)@ turn out to have a
-- 'Cofunctor' instance.
module Data.Cofunctor
( Cofunctor (..)
) where
import Control.Monad (liftM)
-- | 'Cofunctor' is a structure from category theory dual to 'Functor'
class Cofunctor f where
cofmap :: (b -> a) -> f b -> f a
instance Cofunctor [] where
cofmap _ [] = []
cofmap f (x : xs) = f x : cofmap f xs
instance Cofunctor Maybe where
cofmap _ Nothing = Nothing
cofmap f (Just x) = Just (f x)
instance Cofunctor (Either e) where
cofmap _ (Left e) = Left e
cofmap f (Right x) = Right (f x)
instance Cofunctor ((->) a) where
cofmap = (.)
instance Cofunctor ((,) a) where
cofmap f (e, x) = (e, f x)
instance Cofunctor IO where
cofmap = liftM
| jaspervdj/acme-cofunctor | src/Data/Cofunctor.hs | bsd-3-clause | 1,238 | 0 | 9 | 296 | 308 | 167 | 141 | 20 | 0 |
module Usage where
import Data.Monoid
import Data.Generics
import Data.List (isSuffixOf)
import qualified GHC
import GHC (GenLocated(L))
import qualified TypeRep
import TypeRep (Type(..))
import qualified Unify
import qualified OccName
import qualified Var
import qualified Type
import VarEnv
import VarSet
foldBindsOfType :: (Monoid r)
=> GHC.Type -> (GHC.LHsBind GHC.Id -> r)
-> GHC.LHsBinds GHC.Id -> r
foldBindsOfType ty f = everything mappend (mempty `mkQ` go)
where
go bind@(L _ (GHC.FunBind {GHC.fun_id=L _ fid}))
| GHC.idType fid `Type.eqType` ty = f bind
go _ = mempty
foldBindsContainingType :: Monoid r
=> GHC.Type -> (GHC.LHsBind GHC.Id -> r)
-> GHC.LHsBinds GHC.Id -> r
foldBindsContainingType ty f = everything mappend (mempty `mkQ` go)
where
go bind@(L _ (GHC.FunBind {GHC.fun_id=L _ fid}))
| getAny $ everything mappend (mempty `mkQ` containsType) (GHC.idType fid) = f bind
where
-- a type variable will unify with anything
--containsType (TyVarTy _) = mempty
-- We first check whether the types match, allowing all type variables to vary.
-- This, however, is too lenient: the matcher is free to introduce equalities
-- between our template variables. So, if this matches we then take the
-- resulting substitution
containsType ty'
| Just subst <- Unify.tcMatchTy tyVars strippedTy ty'
, bijectiveSubst subst
= --trace (showSDoc unsafeGlobalDynFlags $ ppr (strippedTy, ty', Type.tyVarsOfType ty', subst, tyVars)) $
Any True
| otherwise = --trace (showSDoc unsafeGlobalDynFlags $ ppr
-- $ let subst = Unify.tcMatchTy tyVars strippedTy ty'
-- in (subst, Type.tyVarsOfType ty'))
mempty
where
bijectiveSubst :: Type.TvSubst -> Bool
bijectiveSubst (Type.TvSubst _ subst) = iter emptyVarSet (varEnvElts subst)
where
iter :: VarSet -> [Type] -> Bool
iter _ [] = True
iter claimedTyVars (TypeRep.TyVarTy tyVar:rest)
| tyVar `elemVarSet` claimedTyVars = False
| otherwise = iter (extendVarSet claimedTyVars tyVar) rest
iter claimedTyVars (_:rest) = iter claimedTyVars rest
go _ = mempty
-- We don't necessarily want to match on the foralls the user needed to
-- merely bring type variables into scope
stripForAlls :: VarSet -> Type -> (Type, VarSet)
stripForAlls vars (ForAllTy var ty) = stripForAlls (VarSet.extendVarSet vars var) ty
stripForAlls vars ty = (ty, vars)
(strippedTy, tyVars) = stripForAlls VarSet.emptyVarSet ty
isPrimed var = "'" `isSuffixOf` OccName.occNameString (OccName.occName $ Var.varName var)
templVars = VarSet.filterVarSet (not . isPrimed) tyVars
foldBindsContainingTyCon :: Monoid r
=> GHC.TyCon -> (GHC.LHsBind GHC.Id -> r)
-> GHC.LHsBinds GHC.Id -> r
foldBindsContainingTyCon tyCon f = everything mappend (mempty `mkQ` go)
where
go bind@(L _ (GHC.FunBind {GHC.fun_id=L _ fid}))
| getAny $ everything mappend (mempty `mkQ` containsTyCon) (GHC.idType fid) = f bind
where
containsTyCon tyCon' | tyCon == tyCon' = Any True
containsTyCon _ = mempty
go _ = mempty
foldBindsContainingIdent :: Monoid r
=> GHC.Id -> (GHC.LHsBind GHC.Id -> r)
-> GHC.LHsBinds GHC.Id -> r
foldBindsContainingIdent ident f = everything mappend (mempty `mkQ` go)
where
go bind
| getAny $ everything mappend (mempty `mkQ` containsId) bind = f bind
where
containsId ident' | ident == ident' = Any True
containsId _ = mempty
go _ = mempty
| bgamari/play-type-search | Usage.hs | bsd-3-clause | 4,089 | 0 | 17 | 1,330 | 1,071 | 556 | 515 | 66 | 5 |
module InputParser where
import Control.Applicative
import Data.Attoparsec.ByteString.Char8
import qualified Data.ByteString.Char8 as B
import Types
lineNumberP :: Parser LineNumber
lineNumberP = choice [lineEOF, lineNumber]
where
lineNumber = do
n <- read <$> many digit
return (LineNumber (n - 1))
lineEOF = char '$' >> return EndOfFile
lineNumber' :: Parser LineRange
lineNumber' = do
first <- lineNumberP
return (LineRange first first)
lineNumberRange :: Parser LineRange
lineNumberRange = do
first <- lineNumberP
char ','
second <- lineNumberP
return (LineRange first second)
printLines :: Parser InputLine
printLines = PrintLineRange <$> (lineNumberRange <|> lineNumber') <* char 'p'
printLinesWithNumbers :: Parser InputLine
printLinesWithNumbers =
PrintLineRangeWithNumbers <$> (lineNumberRange <|> lineNumber') <* char 'n'
deleteLines :: Parser InputLine
deleteLines =
DeleteRange <$> (lineNumberRange <|> lineNumber') <* char 'd'
deleteCurrent :: Parser InputLine
deleteCurrent = char 'd' *> return Delete
printCurrent :: Parser InputLine
printCurrent = char 'p' *> return Print
printCurrentNumeric :: Parser InputLine
printCurrentNumeric = char 'n' *> return PrintNumeric
write :: Parser InputLine
write = char 'w' *> return Write
writeFilename :: Parser InputLine
writeFilename = do
char 'w'
many1 (char ' ')
filename <- many1 (notChar ' ')
return (WriteFilename filename)
runCommand :: Parser InputLine
runCommand = do
char '!'
cmd <- many1 anyChar
return (RunCommand cmd)
quit :: Parser InputLine
quit = char 'q' *> return Quit
changeLine :: Parser InputLine
changeLine = do
nr <- lineNumberP
return (Number nr)
append :: Parser InputLine
append = char 'a' *> return Append
change :: Parser InputLine
change = char 'c' *> return Change
parseInput :: Parser InputLine
parseInput =
choice [ printCurrent
, printCurrentNumeric
, deleteCurrent
, printLines
, printLinesWithNumbers
, deleteLines
, writeFilename
, runCommand
, write
, quit
, append
, change
, changeLine
]
| relrod/hed | src/InputParser.hs | bsd-3-clause | 2,175 | 0 | 13 | 475 | 627 | 313 | 314 | 73 | 1 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
-- https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-custom-resources.html
module Qi.Config.AWS.CfCustomResource where
import Control.Lens hiding (view, (.=))
import Control.Monad.Freer
import Data.Aeson hiding (Result)
import Data.Aeson.Types (fieldLabelModifier,
typeMismatch)
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Char8 as LBS
import qualified Data.HashMap.Strict as SHM
import qualified Data.Text as T
import GHC.Generics
import Network.HTTP.Client (Request (..),
RequestBody (..),
parseRequest_)
import Network.HTTP.Client.TLS (tlsManagerSettings)
import Protolude
import Qi.AWS.CF
import Qi.AWS.Types
import Qi.Config.AWS.CF
import Qi.Config.AWS.CfCustomResource.Types
import Qi.Program.Gen.Lang (amazonka, http, say)
type CfCustomResourceLambdaProgram effs = CfCustomResourceEvent -> Eff effs LBS.ByteString
{-
data CustomResourceProvider = CustomResourceProvider {
onCreate :: LambdaProgram (Either Text Result)
, onUpdate :: CustomResourceId -> LambdaProgram (Either Text Result)
, onDelete :: CustomResourceId -> LambdaProgram (Either Text Result)
}
customResourceProviderLambda
:: CustomResourceProvider
-> CfCustomResourceLambdaProgram
customResourceProviderLambda CustomResourceProvider{..} event = do
let responseTemplate = Response{
rStatus = CustomResourceSuccess
, rReason = "undefined"
, rStackId = event ^. cfeStackId
, rRequestId = event ^. cfeRequestId
, rLogicalResourceId = event ^. cfeLogicalResourceId
, rPhysicalResourceId = Nothing
, rData = SHM.empty
}
eitherResult <- case event of
CfCustomResourceCreate{} -> onCreate
CfCustomResourceUpdate{ _cfePhysicalResourceId } -> onUpdate _cfePhysicalResourceId
-- NOTE: (looks like) the handler should return the same PhysicalResourceId that was
-- passed to it. Otherwise CF thinks that the resource have not been deleted and
-- gets stuck
CfCustomResourceDelete{ _cfePhysicalResourceId } -> onDelete _cfePhysicalResourceId
let parsedRequest = parseRequest_ . toS $ event ^. cfeResponseURL
encodedResponse = encode response
encodedResponseSize = LBS.length encodedResponse
response = case eitherResult of
Left err ->
responseTemplate{
rStatus = CustomResourceFailure
, rReason = err
}
Right Result{rId, rAttrs} ->
responseTemplate{
rStatus = CustomResourceSuccess
, rPhysicalResourceId = rId
, rData = rAttrs
}
request = parsedRequest{
method = "PUT"
, requestBody = RequestBodyLBS encodedResponse
, requestHeaders = [
("content-type", "")
, ("content-length", show encodedResponseSize)
]
}
say $ "submitting provider lambda response payload to S3: '" <> toS encodedResponse <> "'"
-- assume successfully written response to S3 object
responseResp <- http tlsManagerSettings request
pure $ show responseResp
-}
| ababkin/qmuli | library/Qi/Config/AWS/CfCustomResource.hs | mit | 4,427 | 0 | 7 | 1,736 | 210 | 147 | 63 | 31 | 0 |
import Distribution.Superdoc
main = superdocMain
| achirkin/qua-kit | apps/hs/qua-server/Setup.hs | mit | 49 | 0 | 4 | 5 | 11 | 6 | 5 | 2 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Redshift.DeleteHSMClientCertificate
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Deletes the specified HSM client certificate.
--
-- /See:/ <http://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteHSMClientCertificate.html AWS API Reference> for DeleteHSMClientCertificate.
module Network.AWS.Redshift.DeleteHSMClientCertificate
(
-- * Creating a Request
deleteHSMClientCertificate
, DeleteHSMClientCertificate
-- * Request Lenses
, dhsmccHSMClientCertificateIdentifier
-- * Destructuring the Response
, deleteHSMClientCertificateResponse
, DeleteHSMClientCertificateResponse
) where
import Network.AWS.Prelude
import Network.AWS.Redshift.Types
import Network.AWS.Redshift.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- |
--
-- /See:/ 'deleteHSMClientCertificate' smart constructor.
newtype DeleteHSMClientCertificate = DeleteHSMClientCertificate'
{ _dhsmccHSMClientCertificateIdentifier :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteHSMClientCertificate' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'dhsmccHSMClientCertificateIdentifier'
deleteHSMClientCertificate
:: Text -- ^ 'dhsmccHSMClientCertificateIdentifier'
-> DeleteHSMClientCertificate
deleteHSMClientCertificate pHSMClientCertificateIdentifier_ =
DeleteHSMClientCertificate'
{ _dhsmccHSMClientCertificateIdentifier = pHSMClientCertificateIdentifier_
}
-- | The identifier of the HSM client certificate to be deleted.
dhsmccHSMClientCertificateIdentifier :: Lens' DeleteHSMClientCertificate Text
dhsmccHSMClientCertificateIdentifier = lens _dhsmccHSMClientCertificateIdentifier (\ s a -> s{_dhsmccHSMClientCertificateIdentifier = a});
instance AWSRequest DeleteHSMClientCertificate where
type Rs DeleteHSMClientCertificate =
DeleteHSMClientCertificateResponse
request = postQuery redshift
response
= receiveNull DeleteHSMClientCertificateResponse'
instance ToHeaders DeleteHSMClientCertificate where
toHeaders = const mempty
instance ToPath DeleteHSMClientCertificate where
toPath = const "/"
instance ToQuery DeleteHSMClientCertificate where
toQuery DeleteHSMClientCertificate'{..}
= mconcat
["Action" =:
("DeleteHsmClientCertificate" :: ByteString),
"Version" =: ("2012-12-01" :: ByteString),
"HsmClientCertificateIdentifier" =:
_dhsmccHSMClientCertificateIdentifier]
-- | /See:/ 'deleteHSMClientCertificateResponse' smart constructor.
data DeleteHSMClientCertificateResponse =
DeleteHSMClientCertificateResponse'
deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'DeleteHSMClientCertificateResponse' with the minimum fields required to make a request.
--
deleteHSMClientCertificateResponse
:: DeleteHSMClientCertificateResponse
deleteHSMClientCertificateResponse = DeleteHSMClientCertificateResponse'
| fmapfmapfmap/amazonka | amazonka-redshift/gen/Network/AWS/Redshift/DeleteHSMClientCertificate.hs | mpl-2.0 | 3,761 | 0 | 9 | 657 | 365 | 224 | 141 | 55 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.Redshift.CreateClusterSnapshot
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Creates a manual snapshot of the specified cluster. The cluster must be
-- in the 'available' state.
--
-- For more information about working with snapshots, go to
-- <http://docs.aws.amazon.com/redshift/latest/mgmt/working-with-snapshots.html Amazon Redshift Snapshots>
-- in the /Amazon Redshift Cluster Management Guide/.
--
-- /See:/ <http://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateClusterSnapshot.html AWS API Reference> for CreateClusterSnapshot.
module Network.AWS.Redshift.CreateClusterSnapshot
(
-- * Creating a Request
createClusterSnapshot
, CreateClusterSnapshot
-- * Request Lenses
, ccsTags
, ccsSnapshotIdentifier
, ccsClusterIdentifier
-- * Destructuring the Response
, createClusterSnapshotResponse
, CreateClusterSnapshotResponse
-- * Response Lenses
, crersSnapshot
, crersResponseStatus
) where
import Network.AWS.Prelude
import Network.AWS.Redshift.Types
import Network.AWS.Redshift.Types.Product
import Network.AWS.Request
import Network.AWS.Response
-- |
--
-- /See:/ 'createClusterSnapshot' smart constructor.
data CreateClusterSnapshot = CreateClusterSnapshot'
{ _ccsTags :: !(Maybe [Tag])
, _ccsSnapshotIdentifier :: !Text
, _ccsClusterIdentifier :: !Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateClusterSnapshot' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccsTags'
--
-- * 'ccsSnapshotIdentifier'
--
-- * 'ccsClusterIdentifier'
createClusterSnapshot
:: Text -- ^ 'ccsSnapshotIdentifier'
-> Text -- ^ 'ccsClusterIdentifier'
-> CreateClusterSnapshot
createClusterSnapshot pSnapshotIdentifier_ pClusterIdentifier_ =
CreateClusterSnapshot'
{ _ccsTags = Nothing
, _ccsSnapshotIdentifier = pSnapshotIdentifier_
, _ccsClusterIdentifier = pClusterIdentifier_
}
-- | A list of tag instances.
ccsTags :: Lens' CreateClusterSnapshot [Tag]
ccsTags = lens _ccsTags (\ s a -> s{_ccsTags = a}) . _Default . _Coerce;
-- | A unique identifier for the snapshot that you are requesting. This
-- identifier must be unique for all snapshots within the AWS account.
--
-- Constraints:
--
-- - Cannot be null, empty, or blank
-- - Must contain from 1 to 255 alphanumeric characters or hyphens
-- - First character must be a letter
-- - Cannot end with a hyphen or contain two consecutive hyphens
--
-- Example: 'my-snapshot-id'
ccsSnapshotIdentifier :: Lens' CreateClusterSnapshot Text
ccsSnapshotIdentifier = lens _ccsSnapshotIdentifier (\ s a -> s{_ccsSnapshotIdentifier = a});
-- | The cluster identifier for which you want a snapshot.
ccsClusterIdentifier :: Lens' CreateClusterSnapshot Text
ccsClusterIdentifier = lens _ccsClusterIdentifier (\ s a -> s{_ccsClusterIdentifier = a});
instance AWSRequest CreateClusterSnapshot where
type Rs CreateClusterSnapshot =
CreateClusterSnapshotResponse
request = postQuery redshift
response
= receiveXMLWrapper "CreateClusterSnapshotResult"
(\ s h x ->
CreateClusterSnapshotResponse' <$>
(x .@? "Snapshot") <*> (pure (fromEnum s)))
instance ToHeaders CreateClusterSnapshot where
toHeaders = const mempty
instance ToPath CreateClusterSnapshot where
toPath = const "/"
instance ToQuery CreateClusterSnapshot where
toQuery CreateClusterSnapshot'{..}
= mconcat
["Action" =: ("CreateClusterSnapshot" :: ByteString),
"Version" =: ("2012-12-01" :: ByteString),
"Tags" =: toQuery (toQueryList "Tag" <$> _ccsTags),
"SnapshotIdentifier" =: _ccsSnapshotIdentifier,
"ClusterIdentifier" =: _ccsClusterIdentifier]
-- | /See:/ 'createClusterSnapshotResponse' smart constructor.
data CreateClusterSnapshotResponse = CreateClusterSnapshotResponse'
{ _crersSnapshot :: !(Maybe Snapshot)
, _crersResponseStatus :: !Int
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'CreateClusterSnapshotResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'crersSnapshot'
--
-- * 'crersResponseStatus'
createClusterSnapshotResponse
:: Int -- ^ 'crersResponseStatus'
-> CreateClusterSnapshotResponse
createClusterSnapshotResponse pResponseStatus_ =
CreateClusterSnapshotResponse'
{ _crersSnapshot = Nothing
, _crersResponseStatus = pResponseStatus_
}
-- | Undocumented member.
crersSnapshot :: Lens' CreateClusterSnapshotResponse (Maybe Snapshot)
crersSnapshot = lens _crersSnapshot (\ s a -> s{_crersSnapshot = a});
-- | The response status code.
crersResponseStatus :: Lens' CreateClusterSnapshotResponse Int
crersResponseStatus = lens _crersResponseStatus (\ s a -> s{_crersResponseStatus = a});
| fmapfmapfmap/amazonka | amazonka-redshift/gen/Network/AWS/Redshift/CreateClusterSnapshot.hs | mpl-2.0 | 5,704 | 0 | 13 | 1,106 | 736 | 444 | 292 | 90 | 1 |
{-# LANGUAGE DeriveDataTypeable, DeriveGeneric #-}
-- |
-- Module : Statistics.Distribution.Binomial
-- Copyright : (c) 2009 Bryan O'Sullivan
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- The binomial distribution. This is the discrete probability
-- distribution of the number of successes in a sequence of /n/
-- independent yes\/no experiments, each of which yields success with
-- probability /p/.
module Statistics.Distribution.Binomial
(
BinomialDistribution
-- * Constructors
, binomial
-- * Accessors
, bdTrials
, bdProbability
) where
import Data.Aeson (FromJSON, ToJSON)
import Data.Binary (Binary)
import Data.Data (Data, Typeable)
import GHC.Generics (Generic)
import qualified Statistics.Distribution as D
import qualified Statistics.Distribution.Poisson.Internal as I
import Numeric.SpecFunctions (choose,incompleteBeta)
import Numeric.MathFunctions.Constants (m_epsilon)
import Data.Binary (put, get)
import Control.Applicative ((<$>), (<*>))
-- | The binomial distribution.
data BinomialDistribution = BD {
bdTrials :: {-# UNPACK #-} !Int
-- ^ Number of trials.
, bdProbability :: {-# UNPACK #-} !Double
-- ^ Probability.
} deriving (Eq, Read, Show, Typeable, Data, Generic)
instance FromJSON BinomialDistribution
instance ToJSON BinomialDistribution
instance Binary BinomialDistribution where
put (BD x y) = put x >> put y
get = BD <$> get <*> get
instance D.Distribution BinomialDistribution where
cumulative = cumulative
instance D.DiscreteDistr BinomialDistribution where
probability = probability
instance D.Mean BinomialDistribution where
mean = mean
instance D.Variance BinomialDistribution where
variance = variance
instance D.MaybeMean BinomialDistribution where
maybeMean = Just . D.mean
instance D.MaybeVariance BinomialDistribution where
maybeStdDev = Just . D.stdDev
maybeVariance = Just . D.variance
instance D.Entropy BinomialDistribution where
entropy (BD n p)
| n == 0 = 0
| n <= 100 = directEntropy (BD n p)
| otherwise = I.poissonEntropy (fromIntegral n * p)
instance D.MaybeEntropy BinomialDistribution where
maybeEntropy = Just . D.entropy
-- This could be slow for big n
probability :: BinomialDistribution -> Int -> Double
probability (BD n p) k
| k < 0 || k > n = 0
| n == 0 = 1
| otherwise = choose n k * p^k * (1-p)^(n-k)
-- Summation from different sides required to reduce roundoff errors
cumulative :: BinomialDistribution -> Double -> Double
cumulative (BD n p) x
| isNaN x = error "Statistics.Distribution.Binomial.cumulative: NaN input"
| isInfinite x = if x > 0 then 1 else 0
| k < 0 = 0
| k >= n = 1
| otherwise = incompleteBeta (fromIntegral (n-k)) (fromIntegral (k+1)) (1 - p)
where
k = floor x
mean :: BinomialDistribution -> Double
mean (BD n p) = fromIntegral n * p
variance :: BinomialDistribution -> Double
variance (BD n p) = fromIntegral n * p * (1 - p)
directEntropy :: BinomialDistribution -> Double
directEntropy d@(BD n _) =
negate . sum $
takeWhile (< negate m_epsilon) $
dropWhile (not . (< negate m_epsilon)) $
[ let x = probability d k in x * log x | k <- [0..n]]
-- | Construct binomial distribution. Number of trials must be
-- non-negative and probability must be in [0,1] range
binomial :: Int -- ^ Number of trials.
-> Double -- ^ Probability.
-> BinomialDistribution
binomial n p
| n < 0 =
error $ msg ++ "number of trials must be non-negative. Got " ++ show n
| p < 0 || p > 1 =
error $ msg++"probability must be in [0,1] range. Got " ++ show p
| otherwise = BD n p
where msg = "Statistics.Distribution.Binomial.binomial: "
| fpco/statistics | Statistics/Distribution/Binomial.hs | bsd-2-clause | 3,857 | 0 | 11 | 852 | 1,043 | 554 | 489 | 79 | 2 |
--
-- Copyright (C) 2012 Parallel Scientific. All rights reserved.
--
-- See the accompanying LICENSE file for license information.
--
-- | This module implements machinery to generate test cases
-- for the CCI Haskell bindings.
--
{-# LANGUAGE PatternGuards #-}
{-# LANGUAGE DeriveDataTypeable #-}
module TestGen
( testProp, TestConfig(..), defaultTestConfig, runCommands, Response(..)
, Command(..),Msg(..), TestError, testCommands, ProcCommand, generateCTest
) where
import Control.Arrow ( second )
import Control.Exception ( catch, finally, IOException, evaluate, SomeException, bracket )
import Control.Monad ( unless, void, forM_, replicateM, when, liftM, foldM, forM )
import Control.Monad.State ( StateT(..), MonadState(..),modify, lift, State, runState )
import Data.Function ( on )
import Data.List ( sort, nub, sortBy, groupBy, intersect, isInfixOf )
import Data.Typeable ( Typeable )
import Data.Data ( Data )
import Foreign.Ptr ( WordPtr )
import System.FilePath ( (</>) )
import System.IO ( Handle, hGetLine, hPrint, hFlush, hWaitForInput, openBinaryFile, IOMode(..), hGetContents, hClose )
import System.Process ( waitForProcess, terminateProcess, ProcessHandle
, CreateProcess(..), createProcess, StdStream(..), CmdSpec(..)
)
import System.Random ( Random(..), StdGen, mkStdGen )
import Text.PrettyPrint (render,empty,vcat,text,char,($$),nest,(<>),hcat)
import Commands ( Command(..), Response(..), Msg(..) )
testFolder :: FilePath
testFolder = "dist" </> "build" </> "test-worker"
workerPath :: FilePath
workerPath = testFolder </> "test-worker"
-- | Parameters for running tests
data TestConfig = TestConfig
{ nProcesses :: Int -- ^ Number of processes in tests
, nSends :: Int -- ^ Number of sends in each interaction
, nTries :: Int -- ^ Number of tests to run
, nErrors :: Int -- ^ Number of errors to collect before stopping
, nMinMsgLen :: Int -- ^ Minimum length of active messages
, nMaxMsgLen :: Int -- ^ Maximum length of active messages
, nPerProcessInteractions :: Int -- ^ Number of interactions per process
, withValgrind :: Bool -- ^ Run tests with valgrind.
, testRMA :: Bool -- ^ Test rma operations
}
deriving (Show,Data,Typeable)
defaultTestConfig :: TestConfig
defaultTestConfig = TestConfig
{ nProcesses = 2
, nSends = 4
, nTries = 300
, nErrors = 2
, nMinMsgLen = 16
, nMaxMsgLen = 16
, nPerProcessInteractions = 2
, withValgrind = False
, testRMA = False
}
type TestError = ([ProcCommand],[[Response]],String)
-- | Tests a property with a custom generated commands.
-- The property takes the issued commands, the responses that each process provided
-- and must answer if they are correct.
--
-- Several command sequences are generated. Sequences that make the property fail are
-- yielded as part of the result.
--
-- @testProp@ takes the configuration parameters and a callback which is
-- evaluated for every error. The callback takes the error and an error-indentifying
-- index.
--
testProp :: TestConfig -> (TestError -> Int -> IO ()) -> ([ProcCommand] -> [[Response]] -> [(String,Bool)]) -> IO [TestError]
testProp c onError f = go (mkStdGen 0) [] (nErrors c) (nTries c)
where
go _g errors _ 0 = return errors
go _g errors 0 _ = return errors
go g errors errCount tryCount = do
(tr,g') <- genCommands c g
let tr' = map snd tr
me <- testCommands c tr' f
case me of
Just err -> do err' <- shrink c [SrkRemoveInteraction] tr err f
onError err' (length errors)
go g' (err':errors) (errCount-1) (tryCount-1)
Nothing -> go g' errors errCount (tryCount-1)
-- | Runs a sequence of commands and verifies that the given predicate holds on the results.
testCommands :: TestConfig -> [ProcCommand] -> ([ProcCommand] -> [[Response]] -> [(String,Bool)]) -> IO (Maybe TestError)
testCommands c t f = do
r <- (fmap (Right . snd)$ runProcessM c$ runProcs t
) `catch` \e -> return$ Left (t,[],show (e :: IOException))
case r of
Left err -> return$ Just err
Right rss -> let res = f t rss
in if all snd res then return Nothing
else return$ Just (t,rss,"failed props: " ++ show (map fst (filter (not . snd) res)))
-- | Shrinking operations that are available to reduce a command sequence.
data ShrinkOperation = SrkRemoveInteraction | SrkRemoveMessages
deriving Eq
-- | Provides the possible ways to reduce a command sequence.
shrinkCommands :: [ShrinkOperation] -> Interaction -> [Interaction]
shrinkCommands sops tr =
let op0 = filter (not.null) [ filter ((i/=) . fst) tr | i<-nub (map fst tr) ]
op1 = filter (not . null) [ removeSend tr ]
in (if SrkRemoveInteraction `elem` sops then op0 else [])
++ (if SrkRemoveMessages `elem` sops then op1 else [])
where
removeSend tr = reverse$
case break isSend (reverse tr) of
(bfs,(_,(ps,Send c sid _)):rs) ->
filter (\cm -> not (isWaitRecv ps c sid cm) && not (isWaitSendCompletion ps c sid cm)) bfs ++ rs
_ -> []
isSend (_,(_,Send _ _ _)) = True
isSend _ = False
isWaitSendCompletion ps c sid (_,(ps',WaitSendCompletion c' sid')) = c==c' && sid==sid' && not (null (intersect ps ps'))
isWaitSendCompletion _ _ _ _ = False
isWaitRecv ps c sid (_,(ps',WaitRecv c' sid')) = c==c' && sid==sid' && null (intersect ps ps')
isWaitRecv _ _ _ _ = False
-- | Shrinks a command sequence as much as possible while preserving a faulty behavior
-- with respect to the provided predicate.
shrink :: TestConfig -> [ShrinkOperation] -> Interaction -> TestError -> ([ProcCommand] -> [[Response]] -> [(String,Bool)]) -> IO TestError
shrink c sops tr err f = go (shrinkCommands sops tr)
where
go [] | SrkRemoveInteraction `elem` sops = shrink c [SrkRemoveMessages] tr err f
go [] = return err
go (tr':trs) = do
me <- testCommands c (map snd tr') f
case me of
Just err' -> shrink c sops tr' err' f
Nothing -> go trs
runCommands :: [ProcCommand] -> IO [[Response]]
runCommands t = fmap snd$ runProcessM (defaultTestConfig { nProcesses = (1 + maximum (concatMap fst t)), withValgrind = False })$ runProcs t
-- | Generates a C program reproducing a given sequence of commands.
-- The generated program relies on definitions in testlib.h and testlib.c.
generateCTest :: [ProcCommand] -> String
generateCTest cmds = let procCmds = groupBy ((==) `on` fst)
$ sortBy (compare `on` fst)
$ concatMap (\(ps,c) -> map (flip (,) c) ps) cmds
in render$ includes $$ vcat (map wrapProcCmds procCmds) $$ driver cmds $$ genMain cmds
where
cciStatement (ConnectTo _ pd c _) = text "" $$ text ("connect(p,"++show c++",test_uri["++show pd++"]);")
cciStatement (WaitConnection c) = text "" $$ text ("cci_connection_t* c"++show c++" = wait_connection(p,"++show c++");")
cciStatement (Send c si msg) = text "" $$ text ("send(p,c"++show c++","++show si++","++show (msgLen msg)++");")
cciStatement (Disconnect c) = text "" $$ text ("disconnect(p,c"++show c++");")
cciStatement (WaitSendCompletion cid sid) = text "" $$ text ("wait_send(p,"++show cid++","++show sid++");")
cciStatement (WaitRecv cid rid) = text "" $$ text ("wait_recv(p,"++show cid++","++show rid++");")
cciStatement (Accept _) = empty
cciStatement (RMAReuseRMAHandle cid) = text "" $$ text ("rma_reuse(p,"++show cid++");")
cciStatement (RMAHandleExchange cid sid) = text "" $$ text ("rma_handle_exchange(p,"++show cid++","++show sid++");")
cciStatement (RMAFreeHandles cid) = text "" $$ text ("rma_free_handle(p,"++show cid++");")
cciStatement (RMAWaitExchange cid) = text "" $$ text ("rma_wait_exchange(p,"++show cid++");")
cciStatement (RMAPrepareRead cid sid) = text "" $$ text ("rma_prepare_read(p,"++show cid++","++show sid++");")
cciStatement (RMARead cid sid) = text "" $$ text ("rma_read(p,"++show cid++","++show sid++");")
cciStatement (RMAWaitRead cid sid) = text "" $$ text ("rma_wait_read(p,"++show cid++","++show sid++");")
cciStatement (RMAWrite cid sid) = text "" $$ text ("rma_write(p,"++show cid++","++show sid++");")
cciStatement (RMAWaitWrite cid sid) = text "" $$ text ("rma_wait_write(p,"++show cid++","++show sid++");")
cciStatement cmd = text "" $$ text ("unknown command: " ++ show cmd ++";")
msgLen (Msg _ l) = l
msgLen _ = error "generateCTest: unexpected message"
wrapProcCmds cs@((i,_):_) =
text ("void process"++show i++"(proc_t* p) {")
$$ nest 4 (vcat (map (cciStatement . snd) cs)
$$ text ""
$$ text "finalize(p);"
)
$$ char '}'
$$ text ""
wrapProcCmds _ = error "TestGen.wrapProcCmds"
driver cs =
text "void drive(proc_t** p) {"
$$ nest 4 (text "char buf[100];")
$$ nest 4 (vcat$ map readWrites cs)
$$ char '}'
$$ text ""
readWrites (_,Accept _) = empty
readWrites (ps,_) = vcat$ text "" : map (\i->text$ "write_msg(p["++show i++"],\"\");") ps
++ map (\i->text$ "read_msg(p["++show i++"],buf);") ps
includes = vcat$ map text
[ "#include <stdio.h>"
, "#include <string.h>"
, "#include <strings.h>"
, "#include <stdlib.h>"
, "#include <unistd.h>"
, "#include <inttypes.h>"
, "#include <assert.h>"
, "#include <sys/time.h>"
, "#include <time.h>"
, "#include \"cci.h\""
, "#include \"testlib.h\""
, ""
]
genMain cs =
let maxProcIndex = maximum$ concatMap fst cs
ps = sort$ nub$ concatMap fst cs
in text "int main(int argc, char *argv[]) {"
$$ (nest 4$ vcat$
[ text "proc_t* p[100];"
, text "memset(p,0,100*sizeof(proc_t*));"
, text ""
, hcat (map vcat$ map1 (mapFirst (nest 7))$ map (genSpawn (maxProcIndex+1)) ps)
<> vcat
[ nest 7$ text "{"
, nest 4$ vcat
[ text ("write_uris(p,"++show (maxProcIndex+1)++");")
, text "drive(p);"
, text "wait();"
]
, char '}'
, text "return 0;"
]
]
)
$$ char '}'
genSpawn n i = [ text$ "if (!spawn(&p["++show i++"],"++show i++")) {"
, nest 4 (
text ("read_uris(p["++show i++"],"++show n++");")
$$ text ("process"++show i++"(p["++show i++"]);")
)
, text "} else "
]
map1 _ [] = []
map1 f (x:xs) = x : map f xs
mapFirst _ [] = []
mapFirst f (x:xs) = f x : xs
-- Command generation
-- | Takes the amount of processes, and generates commands for an interaction among them.
genCommands :: TestConfig -> StdGen -> IO (Interaction,StdGen)
genCommands c g = return$ runCommandGenDefault g$
(replicateM (nPerProcessInteractions c)$ permute [0..nProcesses c-1])
>>= mapM (uncurry (genInteraction c)) . concat . map (zip [0..])
>>= foldM mergeI []
where
permute :: [a] -> CommandGen [a]
permute ls = go (length ls) ls
where
go _ [] = return []
go _ [x] = return [x]
go len (x:xs) = do
i <- getRandomR (0,len-2)
let (x',xs') = swapAt i x xs
xs'' <- go (len-1) xs'
return$ x' : xs''
swapAt :: Int -> a -> [a] -> (a,[a])
swapAt 0 y (x:xs) = (x,y:xs)
swapAt i y (x:xs) = second (x:)$ swapAt (i-1) y xs
swapAt _ y [] = (y,[])
-- | An interaction is a list of commands for a given process.
-- Because an interaction might be the result of merging simpler
-- interactions, each command is attached with an identifier of the
-- simplest interaction that contained it.
--
-- @[(interaction_id,(destinatary_process_ids,command))]@
--
-- The purpose of the interaction identifier is to allow to shrink
-- a failing test case by removing the interactions that do not affect
-- the bug reproduction (see function 'shrink').
type Interaction = [(Int,ProcCommand)]
type ProcCommand = ([Int],Command)
runCommandGen :: CommandGenState -> CommandGen a -> (a,CommandGenState)
runCommandGen = flip runState
runCommandGenDefault :: StdGen -> CommandGen a -> (a,StdGen)
runCommandGenDefault g = (\(a,s)->(a,rG s)) .
runCommandGen CommandGenState
{ connG = 0
, sendG = 0
, interactionG = 0
, rG = g
}
modifyR :: (StdGen -> (a,StdGen)) -> CommandGen a
modifyR f = modifyCGS (\s -> let (a,g) = f (rG s) in (a,s { rG = g}) )
getRandom :: Random a => CommandGen a
getRandom = modifyR random
getRandomR :: Random a => (a,a) -> CommandGen a
getRandomR = modifyR . randomR
-- | Merges two interactions by randomly interleaving the commands. The
-- order of the commands in each interaction is preserved.
mergeI :: [a] -> [a] -> CommandGen [a]
mergeI xs [] = return xs
mergeI [] ys = return ys
mergeI i0 i1 = if l0<=l1 then mergeI' i0 l0 i1 l1 else mergeI' i1 l1 i0 l0
where
l0 = length i0
l1 = length i1
mergeI' :: [a] -> Int -> [a] -> Int -> CommandGen [a]
mergeI' i0 l0 i1 l1 = do
iss <- replicateM l0$ getRandomR (0,l0+l1)
let (i:is) = sort iss
return$ insertI 0 i is i0 i1
where
-- | Given indexes (i:is) in [0..l0+l1-1] inserts elements of i0 among elements of i1
-- so the positions of the i0 elements in the result match those of the indexes (i:is)
insertI p i is i0 i1
| p<i, (ir1:irs1) <- i1 = ir1 : insertI (p+1) i is i0 irs1
| (i':is') <- is, (ir0:irs0) <- i0 = ir0 : insertI (p+1) i' is' irs0 i1
| otherwise = i0 ++ i1
-- | There are quite a few identifiers which are used to organize the data.
--
-- This datatype stores generators for each kind of identifier.
data CommandGenState = CommandGenState
{ connG :: WordPtr
, sendG :: WordPtr
, interactionG :: Int
, rG :: StdGen
}
type CommandGen a = State CommandGenState a
modifyCGS :: (CommandGenState -> (a,CommandGenState)) -> CommandGen a
modifyCGS f = liftM f get >>= \(a,g) -> put g >> return a
generateInteractionId :: CommandGen Int
generateInteractionId = modifyCGS (\g -> (interactionG g,g { interactionG = interactionG g+1}))
generateConnectionId :: CommandGen WordPtr
generateConnectionId = modifyCGS (\g -> (connG g,g { connG = connG g+1}))
-- | Takes two processes identifiers and generates an interaction between them.
--
-- Right now the interactions consist on stablishing an initial connection and
-- then having the processes send messages to each other.
--
genInteraction :: TestConfig -> Int -> Int -> CommandGen Interaction
genInteraction c p0 p1 = do
i <- generateInteractionId
mt <- getRandomTimeout
cid <- generateConnectionId
sends <- genSends [] [] cid p0 p1 1
cmds <- if testRMA c then do
rmaOps <- genRMAInteraction cid p0 p1
mergeI sends rmaOps
else return sends
return$ (i,([p1],Accept cid)):
(zip (repeat i) ( ([p0],ConnectTo "" p1 cid mt) : ([p0,p1],WaitConnection cid) : cmds ++ [ ([p0,p1],Disconnect cid) ]
)) -- ++ [([p0],WaitEvents (nSends c+1)),([p1],WaitEvents (nSends c+2))] ))
where
getRandomTimeout = do
b <- getRandom
if b then return Nothing
else return Nothing -- fmap (Just . (+6*1000000))$ getRandom
genSends :: [ProcCommand] -> [ProcCommand] -> WordPtr -> Int -> Int -> Int -> CommandGen [ProcCommand]
genSends waits0 waits _cid _p0 _p1 mid | mid-1 >= nSends c = return$ reverse waits0 ++ reverse waits
genSends waits0 waits1 cid p0 p1 mid = do
insertWaits0 <- getRandom
insertWaits1 <- getRandom
msgLen <- getRandomR (nMinMsgLen c,nMaxMsgLen c)
direction <- getRandom
let (p0',p1') = if direction then (p0,p1) else (p1,p0)
waits0' = ([p0'],WaitSendCompletion cid (fromIntegral mid)) : if insertWaits0 then [] else waits0
waits1' = ([p1'],WaitRecv cid (fromIntegral mid)) : if insertWaits1 then [] else waits1
waits0'' = if insertWaits0 then reverse waits0 else []
waits1'' = if insertWaits1 then reverse waits1 else []
rest <- genSends waits0' waits1' cid p0' p1' (mid+1)
return$ waits0'' ++ waits1'' ++ ([p0'],Send cid (fromIntegral mid) (Msg (fromIntegral mid) msgLen)) : rest
genRMAInteraction :: WordPtr -> Int -> Int -> CommandGen [ProcCommand]
genRMAInteraction cid p0 p1 = do
b0 <- getRandom
b1 <- getRandom
let maybeReuse = (if b0 then (([p0],RMAReuseRMAHandle cid):) else id)
. (if b1 then (([p1],RMAReuseRMAHandle cid):) else id)
sends <- genRMAMsgs [] cid p0 p1 (nSends c+1)
let rmaSendId = fromIntegral (3*nSends c)+cid+1
return$ maybeReuse$ ([p0],RMAHandleExchange cid rmaSendId)
: ([p1],RMAHandleExchange cid rmaSendId) : ([p0,p1],RMAWaitExchange cid)
: sends
++ ([p0],RMAFreeHandles cid) : ([p1],RMAFreeHandles cid) : []
genRMAMsgs :: [ProcCommand] -> WordPtr -> Int -> Int -> Int -> CommandGen [ProcCommand]
genRMAMsgs waits _cid _p0 _p1 mid | mid-1 >= (2*nSends c) = return$ reverse waits
genRMAMsgs waits cid p0 p1 mid = do
genWrite <- getRandom
insertWaits <- return True -- getRandom
direction <- getRandom
let (p0',p1') = if direction then (p0,p1) else (p1,p0)
waits' = ([p0',p1'],(if genWrite then RMAWaitWrite
else RMAWaitRead) cid (fromIntegral mid))
: if insertWaits then [] else waits
waits1 = if insertWaits then reverse waits else []
rest <- genRMAMsgs waits' cid p0' p1' (mid+1)
let sendCmd = if genWrite then RMAWrite else RMARead
prepareRead = if genWrite then [] else [([p1'],RMAPrepareRead cid (fromIntegral mid))]
return$ waits1 ++ prepareRead ++ ([p0'],sendCmd cid (fromIntegral mid)) : rest
-- | A monad for processes. It carries along a state with the file handles
-- used to comunicate with each process. It collects, in addition, the
-- responses provided by such processes.
--
type ProcessM a = StateT ([Process],[[Response]]) IO a
runProcessM :: TestConfig -> ProcessM a -> IO (a,[[Response]])
runProcessM c m = do
ps <- mapM (launchWorker c) [0..nProcesses c-1]
(fmap (\(a,(_,rs))-> (a,map reverse rs))$ runStateT m (ps,map (const []) ps))
`finally` (do forM_ ps (\p -> terminateProcess (ph p))
forM_ ps (\p -> waitForProcess (ph p))
when (withValgrind c)$
forM_ [0..length ps-1] checkValgrindMessages
)
where
checkValgrindMessages pid =
bracket
(openBinaryFile (workerStderr pid) ReadMode)
hClose
(\h -> do
s <- hGetContents h
when ("== at " `isInfixOf` s)$ ioError$ userError$ "valgrind found errors"
)
addResponse :: Response -> Int -> ProcessM ()
addResponse resp n = modify (\(ps,rs) -> (ps,insertR n resp rs))
where
insertR 0 r (rs:rss) = (r:rs) : rss
insertR i r (rs:rss) = rs : insertR (i-1) r rss
insertR i _ [] = error$ "Process "++show i++" does not exist."
getProc :: Int -> ProcessM Process
getProc i = get >>= return . (!!i) . fst
runProcs :: [ProcCommand] -> ProcessM ()
runProcs tr = do
forM_ tr$ \(pids,c) -> do
ps <- forM pids$ \pid -> do
p <- getProc pid
sendCommand' c p
return (p,pid)
forM_ ps$ uncurry readResponses
fmap fst get >>= \ps -> forM_ [0..length ps-1]$ sendCommand Quit
workerStderr :: Int -> String
workerStderr pid = "worker-stderr"++show pid++".txt"
-- | Process communication
data Process = Process
{ h_in :: Handle
, h_out :: Handle
, ph :: ProcessHandle
, uri :: String
}
launchWorker :: TestConfig -> Int -> IO Process
launchWorker c pid = do
-- (hin,hout,herr,phandle) <- runInteractiveProcess workerPath [] Nothing (Just [("CCI_CONFIG","cci.ini"),("LD_LIBRARY_PATH","cci/built/lib")])
herr <- openBinaryFile (workerStderr pid) WriteMode
(Just hin,Just hout,_herr,phandle) <- createProcess CreateProcess
{ cmdspec = if withValgrind c then RawCommand "valgrind" ["--suppressions=cci.supp","--quiet", workerPath]
else RawCommand workerPath []
, cwd = Nothing
, env = Nothing
, std_in = CreatePipe
, std_out = CreatePipe
, std_err = UseHandle herr
, close_fds = False
, create_group = False
}
-- (hin,hout,herr,phandle) <- runInteractiveCommand$ "CCI_CONFIG=cci.ini "++workerPath++" 2> worker-stderr"++show pid++".txt"
-- void$ forkIO$ hGetContents herr >>= writeFile ("worker-stderr"++show pid++".txt") >> putStrLn ("wrote "++show pid)
puri <- hGetLine hout
return Process
{ h_in = hin
, h_out = hout
, ph = phandle
, uri = puri
}
sendCommand :: Command -> Int -> ProcessM ()
sendCommand c i = do
p <- getProc i
sendCommand' c p
readResponses p i
sendCommand' :: Command -> Process -> ProcessM ()
sendCommand' c p = do
c' <- case c of
ConnectTo _ pid cid mt ->
getProc pid >>= \pd -> return$ ConnectTo (uri pd) pid cid mt
_ -> return c
lift$ hPrint (h_in p) c'
lift$ hFlush (h_in p)
readResponses :: Process -> Int -> ProcessM ()
readResponses p i = void$ loopWhileM (/=Idle)$ readResponse p i
readResponse :: Process -> Int -> ProcessM Response
readResponse p i = do
someInput <- lift$ hWaitForInput (h_out p) 2000
lift$ when (not someInput)$ ioError$ userError$ "process "++show i++" blocked"
line <- lift$ hGetLine (h_out p)
r <- lift$ evaluate (read line) `catch`
(\e -> ioError$ userError$ "failed reading response: "++show line++" with "++show (e :: SomeException))
unless (r==Idle)$ addResponse r i
return r
-- | @loopWhileM p io@ performs @io@ repeteadly while its result satisfies @p@.
-- Yields the first offending result.
loopWhileM :: Monad m => (a -> Bool) -> m a -> m a
loopWhileM p io = io >>= \a -> if p a then loopWhileM p io else return a
| tkonolige/haskell-cci | test/TestGen.hs | bsd-3-clause | 23,460 | 0 | 26 | 6,784 | 7,660 | 4,020 | 3,640 | 384 | 22 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE Rank2Types #-}
{-# LANGUAGE FlexibleInstances #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Machine.Type
-- Copyright : (C) 2012 Edward Kmett
-- License : BSD-style (see the file LICENSE)
--
-- Maintainer : Edward Kmett <[email protected]>
-- Stability : provisional
-- Portability : rank-2, GADTs
--
----------------------------------------------------------------------------
module Data.Machine.Type
(
-- * Machines
MachineT(..)
, Step(..)
, Machine
, runT_
, runT
, run
, runMachine
, encased
-- ** Building machines from plans
, construct
, repeatedly
, unfoldPlan
, before
, preplan
-- , sink
-- ** Deconstructing machines back into plans
, deconstruct
, tagDone
, finishWith
-- * Reshaping machines
, fit
, fitM
, pass
, starve
, stopped
, stepMachine
-- * Applicative Machines
, Appliance(..)
) where
import Control.Applicative
import Control.Category
import Control.Monad (liftM)
import Data.Foldable
import Data.Functor.Identity
import Data.Machine.Plan
import Data.Monoid hiding ((<>))
import Data.Pointed
import Data.Profunctor.Unsafe ((#.))
import Data.Semigroup
import Prelude hiding ((.),id)
-------------------------------------------------------------------------------
-- Transduction Machines
-------------------------------------------------------------------------------
-- | This is the base functor for a 'Machine' or 'MachineT'.
--
-- Note: A 'Machine' is usually constructed from 'Plan', so it does not need to be CPS'd.
data Step k o r
= Stop
| Yield o r
| forall t. Await (t -> r) (k t) r
instance Functor (Step k o) where
fmap _ Stop = Stop
fmap f (Yield o k) = Yield o (f k)
fmap f (Await g kg fg) = Await (f . g) kg (f fg)
-- | A 'MachineT' reads from a number of inputs and may yield results before stopping
-- with monadic side-effects.
newtype MachineT m k o = MachineT { runMachineT :: m (Step k o (MachineT m k o)) }
-- | A 'Machine' reads from a number of inputs and may yield results before stopping.
--
-- A 'Machine' can be used as a @'MachineT' m@ for any @'Monad' m@.
type Machine k o = forall m. Monad m => MachineT m k o
-- | @'runMachine' = 'runIdentity' . 'runMachineT'@
runMachine :: MachineT Identity k o -> Step k o (MachineT Identity k o)
runMachine = runIdentity . runMachineT
-- | Pack a 'Step' of a 'Machine' into a 'Machine'.
encased :: Monad m => Step k o (MachineT m k o) -> MachineT m k o
encased = MachineT #. return
-- | Transform a 'Machine' by looking at a single step of that machine.
stepMachine :: Monad m => MachineT m k o -> (Step k o (MachineT m k o) -> MachineT m k' o') -> MachineT m k' o'
stepMachine m f = MachineT (runMachineT #. f =<< runMachineT m)
instance Monad m => Functor (MachineT m k) where
fmap f (MachineT m) = MachineT (liftM f' m) where
f' (Yield o xs) = Yield (f o) (f <$> xs)
f' (Await k kir e) = Await (fmap f . k) kir (f <$> e)
f' Stop = Stop
instance Monad m => Pointed (MachineT m k) where
point = repeatedly . yield
instance Monad m => Semigroup (MachineT m k o) where
a <> b = stepMachine a $ \step -> case step of
Yield o a' -> encased (Yield o (mappend a' b))
Await k kir e -> encased (Await (\x -> k x <> b) kir (e <> b))
Stop -> b
instance Monad m => Monoid (MachineT m k o) where
mempty = stopped
mappend = (<>)
-- | An input type that supports merging requests from multiple machines.
class Appliance k where
applied :: Monad m => MachineT m k (a -> b) -> MachineT m k a -> MachineT m k b
instance (Monad m, Appliance k) => Applicative (MachineT m k) where
pure = point
(<*>) = applied
{-
-- TODO
instance Appliance (Is i) where
applied = appliedTo (Just mempty) (Just mempty) id (flip id) where
-- applied
appliedTo
:: Maybe (Seq i)
-> Maybe (i -> MachineT m (Is i) b, MachineT m (Is i) b)
-> Either (Seq a) (Seq b)
-> (a -> b -> c)
-> (b -> a -> c)
-> MachineT m (Is i) a
-> MachineT m (Is i) b
-> MachineT m (Is i) c
appliedTo mis blocking ss f g m n = MachineT $ runMachineT m >>= \v -> case v of
Stop -> return Stop
Yield a k -> case ss of
Left as ->
Right bs -> case viewl bs of
b :< bs' -> return $ Yield (f a b) (appliedTo mis bs' f g m n)
EmptyL -> runMachine $ appliedTo mis blocking (singleton a) g f n m
Await ak Refl e -> case mis of
Nothing -> runMachine $ appliedTo Nothing blocking bs f g e n
Just is -> case viewl is of
i :< is' -> runMachine $ appliedTo (Just is') blocking bs f g (ak i) m
EmptyL -> case blocking of
Just (bk, be) ->
Nothing -> runMachine $ appliedTo mis (Just (ak, e))
| blocking -> return $ Await (\i -> appliedTo (Just (singleton i)) False f g (ak i) n) Refl $
| otherwise ->
-}
-- | Stop feeding input into model, taking only the effects.
runT_ :: Monad m => MachineT m k b -> m ()
runT_ m = runMachineT m >>= \v -> case v of
Stop -> return ()
Yield _ k -> runT_ k
Await _ _ e -> runT_ e
-- | Stop feeding input into model and extract an answer
runT :: Monad m => MachineT m k b -> m [b]
runT (MachineT m) = m >>= \v -> case v of
Stop -> return []
Yield o k -> liftM (o:) (runT k)
Await _ _ e -> runT e
-- | Run a pure machine and extract an answer.
run :: MachineT Identity k b -> [b]
run = runIdentity . runT
-- | This permits toList to be used on a Machine.
instance (m ~ Identity) => Foldable (MachineT m k) where
foldMap f (MachineT (Identity m)) = go m where
go Stop = mempty
go (Yield o k) = f o `mappend` foldMap f k
go (Await _ _ fg) = foldMap f fg
-- |
-- Connect different kinds of machines.
--
-- @'fit' 'id' = 'id'@
fit :: Monad m => (forall a. k a -> k' a) -> MachineT m k o -> MachineT m k' o
fit f (MachineT m) = MachineT (liftM f' m) where
f' (Yield o k) = Yield o (fit f k)
f' Stop = Stop
f' (Await g kir h) = Await (fit f . g) (f kir) (fit f h)
--- | Connect machine transformers over different monads using a monad
--- morphism.
fitM :: (Monad m, Monad m')
=> (forall a. m a -> m' a) -> MachineT m k o -> MachineT m' k o
fitM f (MachineT m) = MachineT $ f (liftM aux m)
where aux Stop = Stop
aux (Yield o k) = Yield o (fitM f k)
aux (Await g kg gg) = Await (fitM f . g) kg (fitM f gg)
-- | Compile a machine to a model.
construct :: Monad m => PlanT k o m a -> MachineT m k o
construct m = MachineT $ runPlanT m
(const (return Stop))
(\o k -> return (Yield o (MachineT k)))
(\f k g -> return (Await (MachineT #. f) k (MachineT g)))
(return Stop)
-- | Generates a model that runs a machine until it stops, then start it up again.
--
-- @'repeatedly' m = 'construct' ('Control.Monad.forever' m)@
repeatedly :: Monad m => PlanT k o m a -> MachineT m k o
repeatedly m = r where
r = MachineT $ runPlanT m
(const (runMachineT r))
(\o k -> return (Yield o (MachineT k)))
(\f k g -> return (Await (MachineT #. f) k (MachineT g)))
(return Stop)
-- | Unfold a stateful PlanT into a MachineT.
unfoldPlan :: Monad m => s -> (s -> PlanT k o m s) -> MachineT m k o
unfoldPlan s0 sp = r s0 where
r s = MachineT $ runPlanT (sp s)
(\sx -> runMachineT $ r sx)
(\o k -> return (Yield o (MachineT k)))
(\f k g -> return (Await (MachineT #. f) k (MachineT g)))
(return Stop)
-- | Evaluate a machine until it stops, and then yield answers according to the supplied model.
before :: Monad m => MachineT m k o -> PlanT k o m a -> MachineT m k o
before (MachineT n) m = MachineT $ runPlanT m
(const n)
(\o k -> return (Yield o (MachineT k)))
(\f k g -> return (Await (MachineT #. f) k (MachineT g)))
(return Stop)
-- | Incorporate a 'Plan' into the resulting machine.
preplan :: Monad m => PlanT k o m (MachineT m k o) -> MachineT m k o
preplan m = MachineT $ runPlanT m
runMachineT
(\o k -> return (Yield o (MachineT k)))
(\f k g -> return (Await (MachineT #. f) k (MachineT g)))
(return Stop)
-- | Given a handle, ignore all other inputs and just stream input from that handle.
--
-- @
-- 'pass' 'id' :: 'Data.Machine.Process.Process' a a
-- 'pass' 'Data.Machine.Tee.L' :: 'Data.Machine.Tee.Tee' a b a
-- 'pass' 'Data.Machine.Tee.R' :: 'Data.Machine.Tee.Tee' a b b
-- 'pass' 'Data.Machine.Wye.X' :: 'Data.Machine.Wye.Wye' a b a
-- 'pass' 'Data.Machine.Wye.Y' :: 'Data.Machine.Wye.Wye' a b b
-- 'pass' 'Data.Machine.Wye.Z' :: 'Data.Machine.Wye.Wye' a b (Either a b)
-- @
pass :: k o -> Machine k o
pass k = repeatedly $ do
a <- awaits k
yield a
-- | Run a machine with no input until it stops, then behave as another machine.
starve :: Monad m => MachineT m k0 b -> MachineT m k b -> MachineT m k b
starve m cont = MachineT $ runMachineT m >>= \v -> case v of
Stop -> runMachineT cont -- Continue with cont instead of stopping
Yield o r -> return $ Yield o (starve r cont)
Await _ _ r -> runMachineT (starve r cont)
-- | This is a stopped 'Machine'
stopped :: Machine k b
stopped = encased Stop
--------------------------------------------------------------------------------
-- Deconstruction
--------------------------------------------------------------------------------
--- | Convert a 'Machine' back into a 'Plan'. The first value the
--- machine yields that is tagged with the 'Left' data constructor is
--- used as the return value of the resultant 'Plan'. Machine-yielded
--- values tagged with 'Right' are yielded -- sans tag -- by the
--- result 'Plan'. This may be used when monadic binding of results is
--- required.
deconstruct :: Monad m => MachineT m k (Either a o) -> PlanT k o m a
deconstruct m = PlanT $ \r y a f ->
let aux k = runPlanT (deconstruct k) r y a f
in runMachineT m >>= \v -> case v of
Stop -> f
Yield (Left o) _ -> r o
Yield (Right o) k -> y o (aux k)
Await g fk h -> a (aux . g) fk (aux h)
-- | Use a predicate to mark a yielded value as the terminal value of
-- this 'Machine'. This is useful in combination with 'deconstruct' to
-- combine 'Plan's.
tagDone :: Monad m => (o -> Bool) -> MachineT m k o -> MachineT m k (Either o o)
tagDone f = fmap aux
where aux x = if f x then Left x else Right x
-- | Use a function to produce and mark a yielded value as the
-- terminal value of a 'Machine'. All yielded values for which the
-- given function returns 'Nothing' are yielded down the pipeline, but
-- the first value for which the function returns a 'Just' value will
-- be returned by a 'Plan' created via 'deconstruct'.
finishWith :: Monad m
=> (o -> Maybe r) -> MachineT m k o -> MachineT m k (Either r o)
finishWith f = fmap aux
where aux x = maybe (Right x) Left $ f x
-------------------------------------------------------------------------------
-- Sink
-------------------------------------------------------------------------------
{-
-- |
-- A Sink in this model is a 'Data.Machine.Process.Process'
-- (or 'Data.Machine.Tee.Tee', etc) that produces a single answer.
--
-- \"Is that your final answer?\"
sink :: Monad m => (forall o. PlanT k o m a) -> MachineT m k a
sink m = runPlanT m (\a -> Yield a Stop) id (Await id) Stop
-}
| bitemyapp/machines | src/Data/Machine/Type.hs | bsd-3-clause | 11,261 | 0 | 17 | 2,641 | 3,091 | 1,601 | 1,490 | -1 | -1 |
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE TypeSynonymInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
--
-- Copyright (c) 2009-2011, ERICSSON AB
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- * Redistributions of source code must retain the above copyright notice,
-- this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the ERICSSON AB nor the names of its contributors
-- may be used to endorse or promote products derived from this software
-- without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-- DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-- SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-- CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-- OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-- OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
module Feldspar.Core.Frontend.Mutable
where
import Prelude hiding (not)
import Language.Syntactic
import Language.Syntactic.Frontend.Monad
import Feldspar.Core.Types
import Feldspar.Core.Constructs
import Feldspar.Core.Frontend.Logic
import qualified Feldspar.Core.Constructs.Mutable as Feature
import Control.Applicative
newtype M a = M { unM :: Mon FeldDomain Mut a }
deriving (Functor, Applicative, Monad)
instance Syntax a => Syntactic (M a)
where
type Domain (M a) = FeldDomain
type Internal (M a) = Mut (Internal a)
desugar = desugar . unM
sugar = M . sugar
runMutable :: (Syntax a) => M a -> a
runMutable = sugarSymC Feature.Run
when :: Data Bool -> M () -> M ()
when = sugarSymC Feature.When
unless :: Data Bool -> M () -> M ()
unless = when . not
| emwap/feldspar-language | src/Feldspar/Core/Frontend/Mutable.hs | bsd-3-clause | 2,637 | 0 | 8 | 472 | 313 | 189 | 124 | 29 | 1 |
{-# LANGUAGE OverloadedStrings #-}
{-| Utility functions for several parsers
This module holds the definition for some utility functions for two
parsers. The parser for the @/proc/stat@ file and the parser for the
@/proc/diskstats@ file.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Ganeti.Parsers where
import Prelude ()
import Ganeti.Prelude
import qualified Data.Attoparsec.Text as A
import Data.Attoparsec.Text (Parser)
import Data.Text (unpack)
-- * Utility functions
-- | Our own space-skipping function, because A.skipSpace also skips
-- newline characters. It skips ZERO or more spaces, so it does not
-- fail if there are no spaces.
skipSpaces :: Parser ()
skipSpaces = A.skipWhile A.isHorizontalSpace
-- | A parser recognizing a number preceeded by spaces.
numberP :: Parser Int
numberP = skipSpaces *> A.decimal
-- | A parser recognizing a number preceeded by spaces.
integerP :: Parser Integer
integerP = skipSpaces *> A.decimal
-- | A parser recognizing a word preceded by spaces, and closed by a space.
stringP :: Parser String
stringP = skipSpaces *> fmap unpack (A.takeWhile $ not . A.isHorizontalSpace)
| leshchevds/ganeti | src/Ganeti/Parsers.hs | bsd-2-clause | 2,392 | 0 | 10 | 376 | 154 | 91 | 63 | 15 | 1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module Network.WebSockets.Http.Tests
( tests
) where
--------------------------------------------------------------------------------
import qualified Data.Attoparsec.ByteString as A
import qualified Data.ByteString.Char8 as BC
import Test.Framework (Test, testGroup)
import Test.Framework.Providers.HUnit (testCase)
import Test.HUnit (Assertion, assert)
--------------------------------------------------------------------------------
import Network.WebSockets.Http
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "Network.WebSockets.Http.Tests"
[ testCase "jwebsockets response" jWebSocketsResponse
, testCase "chromium response" chromiumResponse
]
--------------------------------------------------------------------------------
-- | This is a specific response sent by jwebsockets which caused trouble
jWebSocketsResponse :: Assertion
jWebSocketsResponse = assert $ case A.parseOnly decodeResponseHead input of
Left err -> error err
Right _ -> True
where
input = BC.intercalate "\r\n"
[ "HTTP/1.1 101 Switching Protocols"
, "Upgrade: websocket"
, "Connection: Upgrade"
, "Sec-WebSocket-Accept: Ha0QR1T9CoYx/nqwHsVnW8KVTSo="
, "Sec-WebSocket-Origin: "
, "Sec-WebSocket-Location: ws://127.0.0.1"
, "Set-Cookie: JWSSESSIONID=2e0690e2e328f327056a5676b6a890e3; HttpOnly"
, ""
, ""
]
--------------------------------------------------------------------------------
-- | This is a specific response sent by chromium which caused trouble
chromiumResponse :: Assertion
chromiumResponse = assert $ case A.parseOnly decodeResponseHead input of
Left err -> error err
Right _ -> True
where
input = BC.intercalate "\r\n"
[ "HTTP/1.1 500 Internal Error"
, "Content-Type:text/html"
, "Content-Length:23"
, ""
, "No such target id: 20_1"
]
| nsluss/websockets | tests/haskell/Network/WebSockets/Http/Tests.hs | bsd-3-clause | 2,188 | 0 | 9 | 462 | 277 | 162 | 115 | 37 | 2 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeSynonymInstances #-}
module Stackage.BuildPlan
( readBuildPlan
, writeBuildPlan
, writeBuildPlanCsv
) where
import qualified Data.Map as Map
import qualified Data.Set as Set
import Distribution.Text (display, simpleParse)
import Stackage.Types
import qualified System.IO.UTF8
import Data.Char (isSpace)
import Stackage.Util
import Data.List (intercalate)
readBuildPlan :: FilePath -> IO BuildPlan
readBuildPlan fp = do
str <- System.IO.UTF8.readFile fp
case fromString str of
Left s -> error $ "Could not read build plan: " ++ s
Right (x, "") -> return x
Right (_, _:_) -> error "Trailing content when reading build plan"
writeBuildPlan :: FilePath -> BuildPlan -> IO ()
writeBuildPlan fp bp = System.IO.UTF8.writeFile fp $ toString bp
class AsString a where
toString :: a -> String
fromString :: String -> Either String (a, String)
instance AsString BuildPlan where
toString BuildPlan {..} = concat
[ makeSection "tools" bpTools
, makeSection "packages" $ Map.toList bpPackages
, makeSection "core" $ Map.toList bpCore
, makeSection "optional-core" $ Map.toList bpOptionalCore
, makeSection "skipped-tests" $ Set.toList bpSkippedTests
, makeSection "expected-failures" $ Set.toList bpExpectedFailures
]
fromString s1 = do
(tools, s2) <- getSection "tools" s1
(packages, s3) <- getSection "packages" s2
(core, s4) <- getSection "core" s3
(optionalCore, s5) <- getSection "optional-core" s4
(skipped, s6) <- getSection "skipped-tests" s5
(failures, s7) <- getSection "expected-failures" s6
let bp = BuildPlan
{ bpTools = tools
, bpPackages = Map.fromList packages
, bpCore = Map.fromList core
, bpOptionalCore = Map.fromList optionalCore
, bpSkippedTests = Set.fromList skipped
, bpExpectedFailures = Set.fromList failures
}
return (bp, s7)
makeSection :: AsString a => String -> [a] -> String
makeSection title contents = unlines
$ ("-- BEGIN " ++ title)
: map toString contents
++ ["-- END " ++ title, ""]
instance AsString String where
toString = id
fromString s = Right (s, "")
instance AsString PackageName where
toString (PackageName pn) = pn
fromString s = Right (PackageName s, "")
instance AsString (Maybe Version) where
toString Nothing = ""
toString (Just x) = toString x
fromString s
| all isSpace s = return (Nothing, s)
| otherwise = do
(v, s') <- fromString s
return (Just v, s')
instance AsString a => AsString (PackageName, a) where
toString (PackageName pn, s) = concat [pn, " ", toString s]
fromString s = do
(pn, rest) <- takeWord s
(rest', s') <- fromString rest
return ((PackageName pn, rest'), s')
takeWord :: AsString a => String -> Either String (a, String)
takeWord s =
case break (== ' ') s of
(x, _:y) -> do
(x', s') <- fromString x
if null s'
then Right (x', y)
else Left $ "Unconsumed input in takeWord call"
(_, []) -> Left "takeWord failed"
instance AsString SelectedPackageInfo where
toString SelectedPackageInfo {..} = unwords
[ display spiVersion
, toString spiHasTests
, (\v -> if null v then "@" else v) $ githubMentions spiGithubUser
, unMaintainer spiMaintainer
]
fromString s1 = do
(version, s2) <- takeWord s1
(hasTests, s3) <- takeWord s2
(gu, m) <- takeWord s3
Right (SelectedPackageInfo
{ spiVersion = version
, spiHasTests = hasTests
, spiGithubUser = [gu]
, spiMaintainer = Maintainer m
}, "")
instance AsString (Maybe String) where
toString Nothing = "@"
toString (Just x) = "@" ++ x
fromString "@" = Right (Nothing, "")
fromString ('@':rest) = Right (Just rest, "")
fromString x = Left $ "Invalid Github user: " ++ x
instance AsString Bool where
toString True = "test"
toString False = "notest"
fromString "test" = Right (True, "")
fromString "notest" = Right (False, "")
fromString x = Left $ "Invalid test value: " ++ x
instance AsString Version where
toString = display
fromString s =
case simpleParse s of
Nothing -> Left $ "Invalid version: " ++ s
Just v -> Right (v, "")
getSection :: AsString a => String -> String -> Either String ([a], String)
getSection title orig =
case lines orig of
[] -> Left "Unexpected EOF when looking for a section"
l1:ls1
| l1 == begin ->
case break (== end) ls1 of
(here, _:"":rest) -> do
here' <- mapM fromString' here
Right (here', unlines rest)
(_, _) -> Left $ "Could not find section end: " ++ title
| otherwise -> Left $ "Could not find section start: " ++ title
where
begin = "-- BEGIN " ++ title
end = "-- END " ++ title
fromString' x = do
(y, z) <- fromString x
if null z
then return y
else Left $ "Unconsumed input on line: " ++ x
-- | Used for Hackage distribution purposes.
writeBuildPlanCsv :: FilePath -> BuildPlan -> IO ()
writeBuildPlanCsv fp bp =
-- Obviously a proper CSV library should be used... but we're minimizing
-- deps
System.IO.UTF8.writeFile fp $ unlines' $ map toRow $ Map.toList fullMap
where
-- Hackage server is buggy, and won't accept trailing newlines. See:
-- https://github.com/haskell/hackage-server/issues/141#issuecomment-34615935
unlines' = intercalate "\n"
fullMap = Map.unions
[ fmap spiVersion $ bpPackages bp
, Map.mapMaybe id $ bpCore bp
, bpOptionalCore bp
]
toRow (PackageName name, version) = concat
[ "\""
, name
, "\",\""
, display version
, "\",\"http://www.stackage.org/package/"
, name
, "\""
]
| feuerbach/stackage | Stackage/BuildPlan.hs | mit | 6,358 | 0 | 16 | 1,981 | 1,871 | 965 | 906 | 153 | 4 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Control.Distributed.Process.Tests.Tracing (tests) where
import Control.Distributed.Process.Tests.Internal.Utils
import Network.Transport.Test (TestTransport(..))
import Control.Concurrent (threadDelay)
import Control.Concurrent.MVar
( MVar
, newEmptyMVar
, newMVar
, putMVar
, takeMVar
)
import Control.Distributed.Process
import Control.Distributed.Process.Node
import Control.Distributed.Process.Debug
import Control.Distributed.Process.Management
( MxEvent(..)
)
#if ! MIN_VERSION_base(4,6,0)
import Prelude hiding (catch, log)
#endif
import Test.Framework
( Test
, testGroup
)
import Test.Framework.Providers.HUnit (testCase)
testSpawnTracing :: TestResult Bool -> Process ()
testSpawnTracing result = do
setTraceFlags defaultTraceFlags {
traceSpawned = (Just TraceAll)
, traceDied = (Just TraceAll)
}
evSpawned <- liftIO $ newEmptyMVar
evDied <- liftIO $ newEmptyMVar
tracer <- startTracer $ \ev -> do
case ev of
(MxSpawned p) -> liftIO $ putMVar evSpawned p
(MxProcessDied p r) -> liftIO $ putMVar evDied (p, r)
_ -> return ()
(sp, rp) <- newChan
pid <- spawnLocal $ sendChan sp ()
() <- receiveChan rp
tracedAlive <- liftIO $ takeMVar evSpawned
(tracedDead, tracedReason) <- liftIO $ takeMVar evDied
mref <- monitor tracer
stopTracer -- this is asynchronous, so we need to wait...
receiveWait [
matchIf (\(ProcessMonitorNotification ref _ _) -> ref == mref)
((\_ -> return ()))
]
setTraceFlags defaultTraceFlags
stash result (tracedAlive == pid &&
tracedDead == pid &&
tracedReason == DiedNormal)
testTraceRecvExplicitPid :: TestResult Bool -> Process ()
testTraceRecvExplicitPid result = do
res <- liftIO $ newEmptyMVar
pid <- spawnLocal $ do
self <- getSelfPid
expect >>= (flip sendChan) self
withFlags defaultTraceFlags {
traceRecv = traceOnly [pid]
} $ do
withTracer
(\ev ->
case ev of
(MxReceived pid' _) -> stash res (pid == pid')
_ -> return ()) $ do
(sp, rp) <- newChan
send pid sp
p <- receiveChan rp
res' <- liftIO $ takeMVar res
stash result (res' && (p == pid))
return ()
testTraceRecvNamedPid :: TestResult Bool -> Process ()
testTraceRecvNamedPid result = do
res <- liftIO $ newEmptyMVar
pid <- spawnLocal $ do
self <- getSelfPid
register "foobar" self
expect >>= (flip sendChan) self
withFlags defaultTraceFlags {
traceRecv = traceOnly ["foobar"]
} $ do
withTracer
(\ev ->
case ev of
(MxReceived pid' _) -> stash res (pid == pid')
_ -> return ()) $ do
(sp, rp) <- newChan
send pid sp
p <- receiveChan rp
res' <- liftIO $ takeMVar res
stash result (res' && (p == pid))
return ()
testTraceSending :: TestResult Bool -> Process ()
testTraceSending result = do
pid <- spawnLocal $ (expect :: Process String) >> return ()
self <- getSelfPid
res <- liftIO $ newEmptyMVar
withFlags defaultTraceFlags { traceSend = traceOn } $ do
withTracer
(\ev ->
case ev of
(MxSent to from msg) -> do
(Just s) <- unwrapMessage msg :: Process (Maybe String)
stash res (to == pid && from == self && s == "hello there")
stash res (to == pid && from == self)
_ ->
return ()) $ do
send pid "hello there"
res' <- liftIO $ takeMVar res
stash result res'
testTraceRegistration :: TestResult Bool -> Process ()
testTraceRegistration result = do
(sp, rp) <- newChan
pid <- spawnLocal $ do
self <- getSelfPid
() <- expect
register "foobar" self
sendChan sp ()
() <- expect
return ()
res <- liftIO $ newEmptyMVar
withFlags defaultTraceFlags { traceRegistered = traceOn } $ do
withTracer
(\ev ->
case ev of
MxRegistered p s ->
stash res (p == pid && s == "foobar")
_ ->
return ()) $ do
_ <- monitor pid
send pid ()
() <- receiveChan rp
send pid ()
receiveWait [
match (\(ProcessMonitorNotification _ _ _) -> return ())
]
res' <- liftIO $ takeMVar res
stash result res'
testTraceUnRegistration :: TestResult Bool -> Process ()
testTraceUnRegistration result = do
pid <- spawnLocal $ do
() <- expect
unregister "foobar"
() <- expect
return ()
register "foobar" pid
res <- liftIO $ newEmptyMVar
withFlags defaultTraceFlags { traceUnregistered = traceOn } $ do
withTracer
(\ev ->
case ev of
MxUnRegistered p n -> do
stash res (p == pid && n == "foobar")
send pid ()
_ ->
return ()) $ do
mref <- monitor pid
send pid ()
receiveWait [
matchIf (\(ProcessMonitorNotification mref' _ _) -> mref == mref')
(\_ -> return ())
]
res' <- liftIO $ takeMVar res
stash result res'
testTraceLayering :: TestResult () -> Process ()
testTraceLayering result = do
pid <- spawnLocal $ do
getSelfPid >>= register "foobar"
() <- expect
traceMessage ("traceMsg", 123 :: Int)
return ()
withFlags defaultTraceFlags {
traceDied = traceOnly [pid]
, traceRecv = traceOnly ["foobar"]
} $ doTest pid result
return ()
where
doTest :: ProcessId -> MVar () -> Process ()
doTest pid result' = do
-- TODO: this is pretty gross, even for a test case
died <- liftIO $ newEmptyMVar
withTracer
(\ev ->
case ev of
MxProcessDied _ _ -> liftIO $ putMVar died ()
_ -> return ())
( do {
recv <- liftIO $ newEmptyMVar
; withTracer
(\ev' ->
case ev' of
MxReceived _ _ -> liftIO $ putMVar recv ()
_ -> return ())
( do {
user <- liftIO $ newEmptyMVar
; withTracer
(\ev'' ->
case ev'' of
MxUser _ -> liftIO $ putMVar user ()
_ -> return ())
(send pid () >> (liftIO $ takeMVar user))
; liftIO $ takeMVar recv
})
; liftIO $ takeMVar died
})
liftIO $ putMVar result' ()
testRemoteTraceRelay :: TestTransport -> TestResult Bool -> Process ()
testRemoteTraceRelay TestTransport{..} result =
let flags = defaultTraceFlags { traceSpawned = traceOn }
in do
node2 <- liftIO $ newLocalNode testTransport initRemoteTable
mvNid <- liftIO $ newEmptyMVar
-- As well as needing node2's NodeId, we want to
-- redirect all its logs back here, to avoid generating
-- garbage on stderr for the duration of the test run.
-- Here we set up that relay, and then wait for a signal
-- that the tracer (on node1) has seen the expected
-- MxSpawned message, at which point we're finished
(Just log') <- whereis "logger"
pid <- liftIO $ forkProcess node2 $ do
logRelay <- spawnLocal $ relay log'
reregister "logger" logRelay
getSelfNode >>= stash mvNid >> (expect :: Process ())
nid <- liftIO $ takeMVar mvNid
mref <- monitor pid
observedPid <- liftIO $ newEmptyMVar
spawnedPid <- liftIO $ newEmptyMVar
setTraceFlagsRemote flags nid
withFlags defaultTraceFlags { traceSpawned = traceOn } $ do
withTracer
(\ev ->
case ev of
MxSpawned p -> stash observedPid p >> send pid ()
_ -> return ()) $ do
relayPid <- startTraceRelay nid
liftIO $ threadDelay 1000000
p <- liftIO $ forkProcess node2 $ do
expectTimeout 1000000 :: Process (Maybe ())
return ()
stash spawnedPid p
-- Now we wait for (the outer) pid to exit. This won't happen until
-- our tracer has seen the trace event for `p' and sent `p' the
-- message it's waiting for prior to exiting
receiveWait [
matchIf (\(ProcessMonitorNotification mref' _ _) -> mref == mref')
(\_ -> return ())
]
relayRef <- monitor relayPid
kill relayPid "stop"
receiveWait [
matchIf (\(ProcessMonitorNotification rref' _ _) -> rref' == relayRef)
(\_ -> return ())
]
observed <- liftIO $ takeMVar observedPid
expected <- liftIO $ takeMVar spawnedPid
stash result (observed == expected)
-- and just to be polite...
liftIO $ closeLocalNode node2
tests :: TestTransport -> IO [Test]
tests testtrans@TestTransport{..} = do
node1 <- newLocalNode testTransport initRemoteTable
-- if we execute the test cases in parallel, the
-- various tracers will race with one another and
-- we'll get garbage results (or worse, deadlocks)
lock <- liftIO $ newMVar ()
return [
testGroup "Tracing" [
testCase "Spawn Tracing"
(synchronisedAssertion
"expected dead process-info to be ProcessInfoNone"
node1 True testSpawnTracing lock)
, testCase "Recv Tracing (Explicit Pid)"
(synchronisedAssertion
"expected a recv trace for the supplied pid"
node1 True testTraceRecvExplicitPid lock)
, testCase "Recv Tracing (Named Pid)"
(synchronisedAssertion
"expected a recv trace for the process registered as 'foobar'"
node1 True testTraceRecvNamedPid lock)
, testCase "Trace Send(er)"
(synchronisedAssertion
"expected a 'send' trace with the requisite fields set"
node1 True testTraceSending lock)
, testCase "Trace Registration"
(synchronisedAssertion
"expected a 'registered' trace"
node1 True testTraceRegistration lock)
, testCase "Trace Unregistration"
(synchronisedAssertion
"expected an 'unregistered' trace"
node1 True testTraceUnRegistration lock)
, testCase "Trace Layering"
(synchronisedAssertion
"expected blah"
node1 () testTraceLayering lock)
, testCase "Remote Trace Relay"
(synchronisedAssertion
"expected blah"
node1 True (testRemoteTraceRelay testtrans) lock)
] ]
| qnikst/distributed-process-tests | src/Control/Distributed/Process/Tests/Tracing.hs | bsd-3-clause | 10,700 | 0 | 25 | 3,488 | 3,006 | 1,452 | 1,554 | -1 | -1 |
{-# OPTIONS_GHC -w #-}
{-# LANGUAGE CPP, NamedFieldPuns, GeneralizedNewtypeDeriving, FlexibleContexts #-}
-----------------------------------------------------------------------------
-- |
-- Module : Plugins.EWMH
-- Copyright : (c) Spencer Janssen
-- License : BSD-style (see LICENSE)
--
-- Maintainer : Spencer Janssen <[email protected]>
-- Stability : unstable
-- Portability : unportable
--
-- An experimental plugin to display EWMH pager information
--
-----------------------------------------------------------------------------
module Plugins.EWMH (EWMH(..)) where
import Control.Applicative (Applicative(..))
import Control.Monad.State
import Control.Monad.Reader
import Graphics.X11 hiding (Modifier, Color)
import Graphics.X11.Xlib.Extras
import Plugins
#ifdef UTF8
#undef UTF8
import Codec.Binary.UTF8.String as UTF8
#define UTF8
#endif
import Foreign.C (CChar, CLong)
import XUtil (nextEvent')
import Data.List (intersperse, intercalate)
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
data EWMH = EWMH | EWMHFMT Component deriving (Read, Show)
instance Exec EWMH where
alias EWMH = "EWMH"
start ew cb = allocaXEvent $ \ep -> execM $ do
d <- asks display
r <- asks root
liftIO xSetErrorHandler
liftIO $ selectInput d r propertyChangeMask
handlers' <- mapM (\(a, h) -> liftM2 (,) (getAtom a) (return h)) handlers
mapM_ ((=<< asks root) . snd) handlers'
forever $ do
liftIO . cb . fmtOf ew =<< get
liftIO $ nextEvent' d ep
e <- liftIO $ getEvent ep
case e of
PropertyEvent { ev_atom = a, ev_window = w } ->
case lookup a handlers' of
Just f -> f w
_ -> return ()
_ -> return ()
return ()
defaultPP = Sep (Text " : ") [ Workspaces [Color "white" "black" :% Current, Hide :% Empty]
, Layout
, Color "#00ee00" "" :$ Short 120 :$ WindowName]
fmtOf EWMH = flip fmt defaultPP
fmtOf (EWMHFMT f) = flip fmt f
sep :: [a] -> [[a]] -> [a]
sep x xs = intercalate x $ filter (not . null) xs
fmt :: EwmhState -> Component -> String
fmt e (Text s) = s
fmt e (l :+ r) = fmt e l ++ fmt e r
fmt e (m :$ r) = modifier m $ fmt e r
fmt e (Sep c xs) = sep (fmt e c) $ map (fmt e) xs
fmt e WindowName = windowName $ Map.findWithDefault initialClient (activeWindow e) (clients e)
fmt e Layout = layout e
fmt e (Workspaces opts) = sep " "
[foldr ($) n [modifier m | (m :% a) <- opts, a `elem` as]
| (n, as) <- attrs]
where
stats i = [ (Current, i == currentDesktop e)
, (Empty, Set.notMember i nonEmptys && i /= currentDesktop e)
-- TODO for visible , (Visibl
]
attrs :: [(String, [WsType])]
attrs = [(n, [s | (s, b) <- stats i, b]) | (i, n) <- zip [0 ..] (desktopNames e)]
nonEmptys = Set.unions . map desktops . Map.elems $ clients e
modifier :: Modifier -> String -> String
modifier Hide = const ""
modifier (Color fg bg) = \x -> concat ["<fc=", fg, if null bg then "" else "," ++ bg
, ">", x, "</fc>"]
modifier (Short n) = take n
modifier (Wrap l r) = \x -> l ++ x ++ r
data Component = Text String
| Component :+ Component
| Modifier :$ Component
| Sep Component [Component]
| WindowName
| Layout
| Workspaces [WsOpt]
deriving (Read, Show)
infixr 0 :$
infixr 5 :+
data Modifier = Hide
| Color String String
| Short Int
| Wrap String String
deriving (Read, Show)
data WsOpt = Modifier :% WsType
| WSep Component
deriving (Read, Show)
infixr 0 :%
data WsType = Current | Empty | Visible
deriving (Read, Show, Eq)
data EwmhConf = C { root :: Window
, display :: Display }
data EwmhState = S { currentDesktop :: CLong
, activeWindow :: Window
, desktopNames :: [String]
, layout :: String
, clients :: Map Window Client }
deriving Show
data Client = Cl { windowName :: String
, desktops :: Set CLong }
deriving Show
getAtom :: String -> M Atom
getAtom s = do
d <- asks display
liftIO $ internAtom d s False
windowProperty32 :: String -> Window -> M (Maybe [CLong])
windowProperty32 s w = do
(C {display}) <- ask
a <- getAtom s
liftIO $ getWindowProperty32 display a w
windowProperty8 :: String -> Window -> M (Maybe [CChar])
windowProperty8 s w = do
(C {display}) <- ask
a <- getAtom s
liftIO $ getWindowProperty8 display a w
initialState :: EwmhState
initialState = S 0 0 [] [] Map.empty
initialClient :: Client
initialClient = Cl "" Set.empty
handlers, clientHandlers :: [(String, Updater)]
handlers = [ ("_NET_CURRENT_DESKTOP", updateCurrentDesktop)
, ("_NET_DESKTOP_NAMES", updateDesktopNames )
, ("_NET_ACTIVE_WINDOW", updateActiveWindow)
, ("_NET_CLIENT_LIST", updateClientList)
] ++ clientHandlers
clientHandlers = [ ("_NET_WM_NAME", updateName)
, ("_NET_WM_DESKTOP", updateDesktop) ]
newtype M a = M (ReaderT EwmhConf (StateT EwmhState IO) a)
deriving (Monad, Functor, Applicative, MonadIO, MonadReader EwmhConf, MonadState EwmhState)
execM :: M a -> IO a
execM (M m) = do
d <- openDisplay ""
r <- rootWindow d (defaultScreen d)
let conf = C r d
evalStateT (runReaderT m (C r d)) initialState
type Updater = Window -> M ()
updateCurrentDesktop, updateDesktopNames, updateActiveWindow :: Updater
updateCurrentDesktop _ = do
(C {root}) <- ask
mwp <- windowProperty32 "_NET_CURRENT_DESKTOP" root
case mwp of
Just [x] -> modify (\s -> s { currentDesktop = x })
_ -> return ()
updateActiveWindow _ = do
(C {root}) <- ask
mwp <- windowProperty32 "_NET_ACTIVE_WINDOW" root
case mwp of
Just [x] -> modify (\s -> s { activeWindow = fromIntegral x })
_ -> return ()
updateDesktopNames _ = do
(C {root}) <- ask
mwp <- windowProperty8 "_NET_DESKTOP_NAMES" root
case mwp of
Just xs -> modify (\s -> s { desktopNames = parse xs })
_ -> return ()
where
dropNull ('\0':xs) = xs
dropNull xs = xs
split [] = []
split xs = case span (/= '\0') xs of
(x, ys) -> x : split (dropNull ys)
parse = split . decodeCChar
updateClientList _ = do
(C {root}) <- ask
mwp <- windowProperty32 "_NET_CLIENT_LIST" root
case mwp of
Just xs -> do
cl <- gets clients
let cl' = Map.fromList $ map (flip (,) initialClient . fromIntegral) xs
dels = Map.difference cl cl'
new = Map.difference cl' cl
modify (\s -> s { clients = Map.union (Map.intersection cl cl') cl'})
mapM_ (unmanage . fst) (Map.toList dels)
mapM_ (listen . fst) (Map.toList cl')
mapM_ (update . fst) (Map.toList new)
_ -> return ()
where
unmanage w = asks display >>= \d -> liftIO $ selectInput d w 0
listen w = asks display >>= \d -> liftIO $ selectInput d w propertyChangeMask
update w = mapM_ (($ w) . snd) clientHandlers
modifyClient :: Window -> (Client -> Client) -> M ()
modifyClient w f = modify (\s -> s { clients = Map.alter f' w $ clients s })
where
f' Nothing = Just $ f initialClient
f' (Just x) = Just $ f x
updateName w = do
mwp <- windowProperty8 "_NET_WM_NAME" w
case mwp of
Just xs -> modifyClient w (\c -> c { windowName = decodeCChar xs })
_ -> return ()
updateDesktop w = do
mwp <- windowProperty32 "_NET_WM_DESKTOP" w
case mwp of
Just x -> modifyClient w (\c -> c { desktops = Set.fromList x })
_ -> return ()
decodeCChar :: [CChar] -> String
#ifdef UTF8
#undef UTF8
decodeCChar = UTF8.decode . map fromIntegral
#define UTF8
#else
decodeCChar = map (toEnum . fromIntegral)
#endif
| dragosboca/xmobar | src/Plugins/EWMH.hs | bsd-3-clause | 8,350 | 0 | 21 | 2,574 | 2,883 | 1,510 | 1,373 | 190 | 4 |
{-# OPTIONS_GHC -fwarn-unused-top-binds #-}
-- #17
module Temp (foo, bar, quux) where
top :: Int
top = 1
foo :: ()
foo = let True = True in ()
bar :: Int -> Int
bar match = 1
quux :: Int
quux = let local = True
in 2
| sdiehl/ghc | testsuite/tests/rename/should_compile/T17a.hs | bsd-3-clause | 229 | 0 | 8 | 62 | 91 | 51 | 40 | 11 | 1 |
{-# LANGUAGE TypeInType, RankNTypes, TypeFamilies #-}
module T15740a where
import Data.Kind
import Data.Proxy
type family F2 :: forall k. k -> Type
-- This should succeed
type instance F2 = Proxy
| sdiehl/ghc | testsuite/tests/indexed-types/should_compile/T15740a.hs | bsd-3-clause | 201 | 0 | 6 | 36 | 41 | 26 | 15 | -1 | -1 |
module Goo where
{-@ foo :: Num a => { z : (xs:t -> {v : (t -> a) | this = rubbish }) | wow = hi } @-}
foo :: Num a => t -> t -> a
foo _ _ = 0
| mightymoose/liquidhaskell | tests/crash/FunRef2.hs | bsd-3-clause | 144 | 0 | 7 | 46 | 35 | 19 | 16 | 3 | 1 |
{-# LANGUAGE RecursiveDo, DoRec #-}
{-# OPTIONS_GHC -fno-warn-deprecated-flags #-}
module M where
-- do, mdo and rec should all open layouts
f :: IO ()
f = do print 'a'
print 'b'
g :: IO ()
g = mdo print 'a'
print 'b'
h :: IO ()
h = do print 'a'
rec print 'b'
print 'c'
print 'd'
| urbanslug/ghc | testsuite/tests/layout/layout008.hs | bsd-3-clause | 327 | 0 | 9 | 106 | 103 | 47 | 56 | 14 | 1 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
-- |
-- Module: Math.NumberTheory.GaussianIntegersTests
-- Copyright: (c) 2016 Chris Fredrickson
-- Licence: MIT
-- Maintainer: Chris Fredrickson <[email protected]>
-- Stability: Provisional
--
-- Tests for Math.NumberTheory.GaussianIntegers
--
module Math.NumberTheory.GaussianIntegersTests
( testSuite
) where
import Test.Tasty
import Test.Tasty.HUnit
import Math.NumberTheory.GaussianIntegers
import Math.NumberTheory.TestUtils
-- | Number is zero or is equal to the product of its factors.
factoriseProperty :: Integer -> Integer -> Bool
factoriseProperty x y
= x == 0 && y == 0
|| g == g'
where
g = x :+ y
factors = factorise g
g' = product $ map (uncurry (.^)) factors
-- | Number is prime iff it is non-zero
-- and has exactly one (non-unit) factor.
isPrimeProperty :: Integer -> Integer -> Bool
isPrimeProperty x y
= x == 0 && y == 0
|| isPrime g && n == 1
|| not (isPrime g) && n /= 1
where
g = x :+ y
factors = factorise g
nonUnitFactors = filter (\(p, _) -> norm p /= 1) factors
-- Count factors taking into account multiplicity
n = sum $ map snd nonUnitFactors
-- | The list of primes should include only primes.
primesGeneratesPrimesProperty :: NonNegative Int -> Bool
primesGeneratesPrimesProperty (NonNegative i) = isPrime (primes !! i)
-- | signum and abs should satisfy: z == signum z * abs z
signumAbsProperty :: Integer -> Integer -> Bool
signumAbsProperty x y = z == signum z * abs z
where
z = x :+ y
-- | abs maps a Gaussian integer to its associate in first quadrant.
absProperty :: Integer -> Integer -> Bool
absProperty x y = isOrigin || (inFirstQuadrant && isAssociate)
where
z = x :+ y
z'@(x' :+ y') = abs z
isOrigin = z' == 0 && z == 0
inFirstQuadrant = x' > 0 && y' >= 0 -- first quadrant includes the positive real axis, but not the origin or the positive imaginary axis
isAssociate = z' `elem` map (\e -> z * (0 :+ 1) .^ e) [0 .. 3]
-- | a special case that tests rounding/truncating in GCD.
gcdGSpecialCase1 :: Assertion
gcdGSpecialCase1 = assertEqual "gcdG" 1 $ gcdG (12 :+ 23) (23 :+ 34)
testSuite :: TestTree
testSuite = testGroup "GaussianIntegers"
[ testSmallAndQuick "factorise" factoriseProperty
, testSmallAndQuick "isPrime" isPrimeProperty
, testSmallAndQuick "primes" primesGeneratesPrimesProperty
, testSmallAndQuick "signumAbsProperty" signumAbsProperty
, testSmallAndQuick "absProperty" absProperty
, testCase "gcdG (12 :+ 23) (23 :+ 34)" gcdGSpecialCase1
]
| cfredric/arithmoi | test-suite/Math/NumberTheory/GaussianIntegersTests.hs | mit | 2,628 | 0 | 14 | 572 | 601 | 327 | 274 | 45 | 1 |
-----------------------------------------------------------------------------
-- |
-- Module : Data.EXT2.Internal.LensHacks
-- Copyright : (C) 2014 Ricky Elrod
-- License : BSD2 (see LICENSE file)
-- Maintainer : Ricky Elrod <[email protected]>
-- Stability : experimental
-- Portability : lens, template-haskell
----------------------------------------------------------------------------
module Data.EXT2.Internal.LensHacks where
import Data.Char
import Data.List as List
import Data.Maybe
import Control.Lens
import Control.Lens.Internal.FieldTH
import Language.Haskell.TH
namespaceLensRules :: LensRules
namespaceLensRules = defaultFieldRules { _fieldToDef = abbreviatedNamer }
{-# INLINE namespaceLensRules #-}
-- | This is taken straight out of 'Control.Lens.TH' but modified to give
-- a 'TopName' back instead of a 'MethodName'. This means we can
-- 'makeLensesWith'out classes using abbreviated fields.
abbreviatedNamer :: Name -> [Name] -> Name -> [DefName]
abbreviatedNamer _ fields field = maybeToList $ do
fieldPart <- stripMaxLc (nameBase field)
method <- computeMethod fieldPart
let cls = "Has" ++ fieldPart
return (MethodName (mkName cls) (mkName method))
where
stripMaxLc f = do x <- stripPrefix optUnderscore f
case break isUpper x of
(p,s) | List.null p || List.null s -> Nothing
| otherwise -> Just s
optUnderscore = ['_' | any (isPrefixOf "_" . nameBase) fields ]
computeMethod (x:xs) | isUpper x = Just (toLower x : xs)
computeMethod _ = Nothing
| meoblast001/ext2-info | src/Data/EXT2/Internal/LensHacks.hs | mit | 1,611 | 0 | 17 | 339 | 328 | 173 | 155 | 23 | 2 |
{-# LANGUAGE UnicodeSyntax #-}
-- |
-- Module : Exercise2
-- Description : Generics by Overloading
-- Copyright : (c) Tom Westerhout, 2017
-- License : MIT
module Exercise2 (
-- * Predefined Types
UNIT(..),
EITHER(..),
PAIR(..),
CONS(..),
Bin(..),
BinG(..),
ListG(..),
-- * Review Questions
-- $answers
-- * Generic Serialisation
-- $design-problem
fromList,
toList,
fromBin,
toBin,
-- ** With Generic Information
VSerialise(vreadPrec', vwritePrec'),
vread',
vwrite',
-- ** Without Generic Information
Serialise(readPrec', writePrec'),
read',
write',
test
) where
import Prelude.Unicode
import Data.Maybe
import Control.Arrow
import Control.Applicative
import Control.Monad
-- | Unit
data UNIT = UNIT deriving (Eq, Read, Show)
-- | Sum
data EITHER a b = LEFT a | RIGHT b deriving (Eq, Read, Show)
-- | Product
data PAIR a b = PAIR a b deriving (Eq, Read, Show)
-- | Constructor
data CONS a = CONS String a deriving (Eq, Read, Show)
-- | Binary trees
data Bin a = Leaf | Bin (Bin a) a (Bin a) deriving (Eq, Read, Show)
-- | Generic representation of a Binary tree
type BinG a = EITHER (CONS UNIT)
(CONS (PAIR (Bin a)
(PAIR a (Bin a))))
-- | Generic representation of a List
type ListG a = EITHER (CONS UNIT)
(CONS (PAIR a [a]))
-- $answers
-- 1) We have three implementations of @(==)@ for 'UNIT'. All three give
-- the same results because 'UNIT' only has one state. As for the code, I
-- like third implementation the most.
--
-- 2) The 'String' parameter in 'CONS' constructor should, in principle, by
-- a function of type @a@. So there's no need to compare these names --
-- they are the same by construction.
--
-- 3) Generic representations of both @Leaf@ and @[]@ is 'UNIT'. @Leaf ==
-- []@ gives compile-time error :) No matter how you define it. Type of
-- @(==)@ is @a β a@, so comparing 'Bin' with 'List' is illformed.
-- $design-problem
-- There's a design problem with our definition of 'CONS'. It /tries/ to
-- keep the info about constructor names storing them in a 'String' field.
-- This info, however, in only available at runtime. So if we @read@ a
-- @CONS UNIT@, there's no way to verify that constructor name we read
-- actually makes sense. So 'CONS' is OK with both
--
-- > ["CONS", "[]", "UNIT"]
--
-- and
--
-- > ["CONS", "Abrakadabra", "UNIT"]
--
-- So why is this a problem? According to the exercise, 'toList' function
-- __doesn't__ fail! This means that @LEFT (CONS \"Abrakadabra\" UNIT)@
-- must produce a valid list. OK, suppose we neglect the name parameter and
-- just construct an empty list. Then we'll have problems when no generic
-- information is provided. Consider
--
-- > ["[]"]
--
-- vs.
--
-- > ["(:)", "123", "(", "[]", ")"]
--
-- We can distinguish these two cases by looking at number of arguments,
-- right? But what if out type is
--
-- > data Foo = A Int Int | B Int Int
--
-- Now we really __need__ to take the constructor name into account. This,
-- however, is impossible when reading a 'CONS' object, because constructor
-- name is not part of the type and is hence unknown at compile-time. We
-- thus can only trigger an error when converting to @List@. So it should
-- be
--
-- > toList β· ListG a β Maybe [a]
--
-- This, however, is not enough. We need to keep track of /all/ possible
-- ways of parsing input. So our generic @read@ function should be
--
-- > read' β· [String] β [(a, [String])]
--
-- And because Haskell has support for 'ReadS', let's make it
--
-- > read' β· String β [(a, String)]
--
-- With these modifications we can now implement everything :)
--
-- /P.S./ I think this also answers the \"Reflection\" questions.
-- | Converts a list to its generic representation. This function is
-- inverse of 'toList'. Constructor for unit list is called @"[]"@, for
-- composite list -- @"(:)"@.
fromList β· [a] β ListG a
fromList [] = LEFT . CONS "[]" $ UNIT
fromList (x:xs) = RIGHT . CONS "(:)" $ PAIR x xs
-- | Converts a generic representation of a list to an actual list. This
-- function is inverse of 'fromList'. It may fail if constructors have
-- wrong names.
toList β· ListG a β Maybe [a]
toList (LEFT (CONS "[]" UNIT)) = Just []
toList (RIGHT (CONS "(:)" (PAIR x xs))) = Just (x:xs)
toList _ = Nothing
-- | Converts a binary tree to its generic representaion. This function is
-- inverse of 'toBin'. Constructor for unit tree is called @"Leaf"@, for
-- composite tree -- @"Bin"@.
fromBin β· Bin a β BinG a
fromBin Leaf = LEFT . CONS "Leaf" $ UNIT
fromBin (Bin l x r) = RIGHT . CONS "Bin" . PAIR l $ PAIR x r
-- | Converts a generic representation of a binary tree back to an actual
-- binary tree. This function is inverse of 'fromBin'. It may fail if
-- constructors have wrong names
toBin β· BinG a β Maybe (Bin a)
toBin (LEFT (CONS "Leaf" UNIT)) = Just Leaf
toBin (RIGHT (CONS "Bin" (PAIR l (PAIR x r)))) = Just (Bin l x r)
toBin _ = Nothing
-- | Verbose version of @Serialise@ typeclass, i.e. generic type
-- constructors are included in the serialised data.
class VSerialise Ξ± where
vreadPrec' β· Int β ReadS Ξ±
vwritePrec' β· Int β Ξ± β String
-- | Creates a reades that expects a certain token. Very similar to
-- 'GHC.Read.expectP'.
_expect β· String β ReadS String
_expect s text = case lex text of
[(s, r)] β return (s, r)
_ β []
-- | Surrounds input 'String' with brackets if condition is 'True'.
_surround β· Bool β String β String
_surround p s = if p then "(" ++ s ++ ")" else s
instance VSerialise UNIT where
vreadPrec' _ s = case lex s of
[("UNIT", rest)] β return (UNIT, rest)
_ β []
vwritePrec' _ _ = "UNIT"
instance (VSerialise Ξ±, VSerialise Ξ²) β VSerialise (EITHER Ξ± Ξ²) where
-- | Monads + Arrows = Magic :)
vreadPrec' p = readParen (p > 10) $
(_expect "LEFT" >=> (vreadPrec' 11 β snd)
>=> return β first LEFT)
&&& (_expect "RIGHT" >=> (vreadPrec' 11 β snd)
>=> return β first RIGHT)
>>> arr (uncurry (++))
vwritePrec' p (LEFT x) = _surround (p > 10) β unwords $
["LEFT", vwritePrec' 11 x]
vwritePrec' p (RIGHT x) = _surround (p > 10) β unwords $
["RIGHT", vwritePrec' 11 x]
instance (VSerialise Ξ±, VSerialise Ξ²) β VSerialise (PAIR Ξ± Ξ²) where
vreadPrec' p = readParen (p > 10) $
_expect "PAIR" >=> \s β do (a, rest1) β vreadPrec' 11 (snd s)
(b, rest2) β vreadPrec' 11 rest1
return (PAIR a b, rest2)
vwritePrec' p (PAIR a b) = _surround (p > 10) β unwords $
["PAIR", vwritePrec' 11 a, vwritePrec' 11 b]
instance (VSerialise Ξ±) β VSerialise (CONS Ξ±) where
vreadPrec' p = readParen (p > 10) $
_expect "CONS" >=> (readsPrec 11 β snd) >=> \(name, rest) β
vreadPrec' 11 rest >>= return β first (CONS name)
vwritePrec' p (CONS name a) = _surround (p > 10) β unwords $
["CONS", show name, vwritePrec' 11 a]
-- | Our hand-made verbose analogue of 'Prelude.read'.
vread' β· (VSerialise Ξ±) β String β Maybe Ξ±
vread' s = case vreadPrec' 0 s of
[(a,"")] β Just a
_ β Nothing
-- | Our hand-made verbose analogue of 'Prelude.show'.
vwrite' β· (VSerialise Ξ±) β Ξ± β String
vwrite' = vwritePrec' 0
instance VSerialise Int where
vreadPrec' = readsPrec
vwritePrec' p x = showsPrec p x ""
instance VSerialise Char where
vreadPrec' = readsPrec
vwritePrec' p x = showsPrec p x ""
instance (VSerialise Ξ±) β VSerialise [Ξ±] where
vreadPrec' p = vreadPrec' p >=> \(l, rest) β
case toList l of
Just xs β return (xs, rest)
Nothing β []
vwritePrec' p = vwritePrec' p β fromList
instance (VSerialise Ξ±) β VSerialise (Bin Ξ±) where
vreadPrec' p = vreadPrec' p >=> \(l, rest) β
case toBin l of
Just xs β return (xs, rest)
Nothing β []
vwritePrec' p = vwritePrec' p β fromBin
-- | Compact @Serialise@ typeclass, i.e. no generic information is included
-- in the serialised data.
class Serialise Ξ± where
readPrec' β· Int β ReadS Ξ±
writePrec' β· Int β Ξ± β String
instance Serialise UNIT where
readPrec' _ s = return (UNIT, s)
writePrec' _ _ = ""
instance (Serialise Ξ±, Serialise Ξ²) β Serialise (EITHER Ξ± Ξ²) where
readPrec' p =
(readPrec' p >=> return β first LEFT)
&&& (readPrec' p >=> return β first RIGHT)
>>> arr (uncurry (++))
writePrec' p (LEFT x) = writePrec' p x
writePrec' p (RIGHT x) = writePrec' p x
instance (Serialise Ξ±) β Serialise (CONS Ξ±) where
readPrec' p = readParen False $
readsPrec p >=> \(name, rest) β
readPrec' 11 rest >>= return β first (CONS name)
writePrec' p (CONS name a) =
let a' = writePrec' 10 a
in if null a' then show name
else _surround (p > 10) $ unwords [show name, a']
instance (Serialise Ξ±, Serialise Ξ²) β Serialise (PAIR Ξ± Ξ²) where
readPrec' p = readParen False $ \s β
do (a, rest1) β readPrec' (p + 1 `mod` 11) s
(b, rest2) β readPrec' (p + 1 `mod` 11) rest1
return (PAIR a b, rest2)
writePrec' p (PAIR a b) =
let a' = writePrec' (p + 1 `mod` 11) a
b' = writePrec' (p + 1 `mod` 11) b
c = filter (not β null) [a', b']
in _surround (p > 10 && length c > 1) $ unwords c
instance Serialise Int where
readPrec' = readsPrec
writePrec' p x = showsPrec p x ""
instance Serialise Char where
readPrec' = readsPrec
writePrec' p x = showsPrec p x ""
instance (Serialise Ξ±) β Serialise [Ξ±] where
readPrec' p = readPrec' p >=> \(l, rest) β
case toList l of
Just xs β return (xs, rest)
Nothing β []
writePrec' p = writePrec' p β fromList
instance (Serialise Ξ±) β Serialise (Bin Ξ±) where
readPrec' p = readPrec' p >=> \(l, rest) β
case toBin l of
Just xs β return (xs, rest)
Nothing β []
writePrec' p = writePrec' p β fromBin
-- | Our hand-made analogue of 'Prelude.show'.
read' β· (Serialise Ξ±) β String β Maybe Ξ±
read' s = case readPrec' 0 s of
[(a,"")] β Just a
_ β Nothing
-- | Our hand-made analogue of 'Prelude.show'.
write' β· (Serialise Ξ±) β Ξ± β String
write' = writePrec' 0
-- | Main
test β· IO ()
test = let x1 = [] β· [Int]
x2 = [1,2,3] β· [Int]
x3 = [1..100] β· [Int]
y1 = Leaf β· Bin Int
y2 = Bin Leaf 123 Leaf β· Bin Int
y3 = Bin (Bin Leaf 432 Leaf) 123 Leaf β· Bin Int
in do putStrLn "[*] Verbose:"
putStrLn $ unwords ["x1 =", show x1]
putStrLn $ unwords ["x1 =", vwrite' x1]
putStrLn $ unwords ["x1 =", show $ fromList x1, "(says GHC)"]
putStrLn $ unwords ["cycle ->", show $ vread' (vwrite' x1) == Just x1]
putStrLn $ unwords ["x2 =", show x2]
putStrLn $ unwords ["x2 =", vwrite' x2]
putStrLn $ unwords ["x2 =", show $ fromList x2, "(says GHC)"]
putStrLn $ unwords ["cycle ->", show $ vread' (vwrite' x2) == Just x2]
putStrLn $ unwords ["x3 =", show x3]
putStrLn $ unwords ["x3 =", vwrite' x3]
putStrLn $ unwords ["cycle ->", show $ vread' (vwrite' x3) == Just x3]
putStrLn $ unwords ["y1 =", show y1]
putStrLn $ unwords ["y1 =", vwrite' y1]
putStrLn $ unwords ["y1 =", show $ fromBin y1, "(says GHC)"]
putStrLn $ unwords ["cycle ->", show $ vread' (vwrite' y1) == Just y1]
putStrLn $ unwords ["y2 =", show y2]
putStrLn $ unwords ["y2 =", vwrite' y2]
putStrLn $ unwords ["y2 =", show $ fromBin y2, "(says GHC)"]
putStrLn $ unwords ["cycle ->", show $ vread' (vwrite' y2) == Just y2]
putStrLn $ unwords ["y3 =", show y3]
putStrLn $ unwords ["y3 =", vwrite' y3]
putStrLn $ unwords ["y3 =", show $ fromBin y3, "(says GHC)"]
putStrLn $ unwords ["cycle ->", show $ vread' (vwrite' y3) == Just y3]
putStrLn "[*] Compact:"
putStrLn $ unwords ["x1 =", show x1]
putStrLn $ unwords ["x1 =", write' x1]
putStrLn $ unwords ["cycle ->", show $ read' (write' x1) == Just x1]
putStrLn $ unwords ["x2 =", show x2]
putStrLn $ unwords ["x2 =", write' x2]
putStrLn $ unwords ["cycle ->", show $ read' (write' x2) == Just x2]
putStrLn $ unwords ["x3 =", show x3]
putStrLn $ unwords ["x3 =", write' x3]
putStrLn $ unwords ["cycle ->", show $ read' (write' x3) == Just x3]
putStrLn $ unwords ["y1 =", show y1]
putStrLn $ unwords ["y1 =", write' y1]
putStrLn $ unwords ["cycle ->", show $ read' (write' y1) == Just y1]
putStrLn $ unwords ["y2 =", show y2]
putStrLn $ unwords ["y2 =", write' y2]
putStrLn $ unwords ["cycle ->", show $ read' (write' y2) == Just y2]
putStrLn $ unwords ["y3 =", show y3]
putStrLn $ unwords ["y3 =", write' y3]
putStrLn $ unwords ["cycle ->", show $ read' (write' y3) == Just y3]
| twesterhout/NWI-I00032-2017-Assignments | Exercise_2/Exercise2.hs | mit | 13,829 | 0 | 16 | 4,036 | 4,010 | 2,087 | 1,923 | 221 | 2 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE PatternSynonyms #-}
module Data.Functor.Infix.TH
( declareInfixFmapForFunctorCompositionOfDegree
, declareFlippedInfixFmapForFunctorCompositionOfDegree
, declareInfixFmapN
, declareInfixPamfN
) where
import Control.Applicative ((<$>), (<*>), pure)
import Control.Monad (replicateM)
import Language.Haskell.TH (Q, Exp(..), Type(..), Dec(..), Pat(..), TyVarBndr(..), Pred(..), Body(..), newName, mkName, Fixity(..), FixityDirection(..))
(~>) :: Type -> Type -> Type
x ~> y = AppT ArrowT x `AppT` y
infixr 0 ~>
fmapTypeOfDegree :: Int -> Q Type
fmapTypeOfDegree n = do
names@(a:b:fs) <- (mkName "a":) <$> (mkName "b":) <$> replicateM n (newName "f")
let variables = map PlainTV names
#if MIN_VERSION_template_haskell(2,10,0)
constraints = AppT (ConT $ mkName "Functor") . VarT <$> fs
#else
constraints = map (ClassP (mkName "Functor") . pure . VarT) fs
#endif
wrap hask = foldr AppT (VarT hask) $ map VarT fs
type_ = (VarT a ~> VarT b) ~> wrap a ~> wrap b
pure $ ForallT variables constraints type_
fmapExpressionOfDegree :: Int -> Q Exp
fmapExpressionOfDegree n = do
(id_, fmap_) <- (,) <$> [|id|] <*> [|fmap|]
pure $ foldr (AppE . AppE fmap_) id_ (replicate n fmap_)
declareInfixWithDegree :: (Int -> Q Exp) -> (Int -> Q Type) -> Fixity -> Char -> (Int -> Q [Dec])
declareInfixWithDegree expressionOfDegree typeOfDegree fixity symbol n = do
let name = mkName $ "<" ++ replicate n symbol ++ ">"
(expression, type_) <- (,) <$> expressionOfDegree n <*> typeOfDegree n
pure $ SigD name type_
: ValD (VarP name) (NormalB expression) []
: InfixD fixity name
: []
declareInfixFmapForFunctorCompositionOfDegree :: Int -> Q [Dec]
declareInfixFmapForFunctorCompositionOfDegree = declareInfixWithDegree fmapExpressionOfDegree fmapTypeOfDegree (Fixity 4 InfixL) '$'
pattern x :> y = AppT ArrowT x `AppT` y
(<$$>) :: Functor f => Functor g => (a -> b) -> f (g a) -> f (g b)
(<$$>) = fmap fmap fmap
infixl 1 <$$>
declareFlippedInfixFmapForFunctorCompositionOfDegree :: Int -> Q [Dec]
declareFlippedInfixFmapForFunctorCompositionOfDegree = do
let flipExpression = AppE $ VarE (mkName "flip")
flipType (ForallT variables constraints (a :> (b :> c))) = ForallT variables constraints (b ~> (a ~> c))
flipType _ = error "The impossible happened!"
declareInfixWithDegree (flipExpression <$$> fmapExpressionOfDegree) (flipType <$$> fmapTypeOfDegree) (Fixity 1 InfixL) '&'
{-# DEPRECATED declareInfixFmapN "Use 'declareInfixFmapForFunctorCompositionOfDegree' and/or reconsider your life choices." #-}
declareInfixFmapN :: Int -> Q [Dec]
declareInfixFmapN = declareInfixFmapForFunctorCompositionOfDegree
{-# DEPRECATED declareInfixPamfN "Use 'declareFlippedInfixFmapForFunctorCompositionOfDegree' and/or reconsider your life choices." #-}
declareInfixPamfN :: Int -> Q [Dec]
declareInfixPamfN = declareFlippedInfixFmapForFunctorCompositionOfDegree
| fmap/functor-infix | src/Data/Functor/Infix/TH.hs | mit | 3,025 | 0 | 16 | 498 | 942 | 506 | 436 | -1 | -1 |
module SuperMemo where
-- Number of times in a row remembered.
type Repetitions = Integer
-- SuperMemo "Easiness Factor".
type Easiness = Rational
minEasiness = 1.3
-- Number of days until next review.
type Days = Int
data Interval = Interval {
reps :: Repetitions,
easiness :: Easiness,
days :: Days
} deriving (Eq, Show)
-- Subjective ease of remembering item.
data Quality = Blackout | Forgot | Fuzzy | Hard | Normal | Perfect
deriving (Eq, Enum, Bounded, Show, Read)
forgot :: Quality -> Bool
forgot Blackout = True
forgot Forgot = True
forgot Fuzzy = True
forgot _ = False
-- Convert quality to numeric value for SuperMemo algorithm.
qualityLevel :: Quality -> Rational
qualityLevel = toRational . fromEnum
nextEasiness :: Easiness -> Quality -> Easiness
nextEasiness e q = maximum [ne, 1.3]
where ne = e - 0.8 + 0.28 * ql - 0.02 * ql * ql
ql = qualityLevel q
nextInterval :: Interval -> Quality -> Interval
nextInterval (Interval 1 ef _) _ = Interval 2 ef 2
nextInterval (Interval 2 ef _) _ = Interval 3 ef 6
nextInterval (Interval r ef d) q = Interval nextReps nextEase nextDays
where nextReps = if forgot q then 1 else r+1
nextEase = nextEasiness ef q
nextDays = if forgot q then 1 else round $ (toRational d) * ef
-- Interval for the first review.
defaultInterval :: Interval
defaultInterval = Interval 1 2.5 1
reviews :: Interval -> [Quality] -> [Interval]
reviews i [q] = [nextInterval i q]
reviews i (q:qs) = ni:reviews ni qs
where ni = nextInterval i q
| briansunter/haskell-supermemo | src/SuperMemo.hs | mit | 1,539 | 0 | 12 | 339 | 497 | 270 | 227 | 36 | 3 |
{-# LANGUAGE OverloadedStrings #-}
module Prismic.Sample
( main
)
where
import Prismic.Api
main :: IO ()
main = do
a <- api "http://lesbonneschoses.prismic.io/api" Nothing
r <- submit a $ (search "everything")
{ searchPage = Just 1
, searchPageSize = Just 10
}
print r
| Herzult/haskell-kit | src/Prismic/Sample.hs | mit | 380 | 0 | 11 | 155 | 90 | 46 | 44 | 11 | 1 |
module LlvmParser where
import Text.Parsec
import Text.Parsec.Language (emptyDef)
import Text.Parsec.String (Parser)
import Control.Applicative ((<$>))
import qualified Text.Parsec.Expr as Ex
import qualified Text.Parsec.Token as Tok
import Lexer
import Syntax
binary s assoc = Ex.Infix (reservedOp s >> return (BinOp s)) assoc
binop = Ex.Infix (BinOp <$> op) Ex.AssocLeft
unop = Ex.Prefix (UnaryOp <$> op)
binops = [[binary "*" Ex.AssocLeft,
binary "/" Ex.AssocLeft]
,[binary "+" Ex.AssocLeft,
binary "-" Ex.AssocLeft]
,[binary "<" Ex.AssocLeft]]
operator :: Parser String
operator = do
c <- Tok.opStart emptyDef
cs <- many $ Tok.opLetter emptyDef
return (c:cs)
op :: Parser String
op = do
whitespace
o <- operator
whitespace
return o
int :: Parser Expr
int = integer >>= return . Float . fromInteger
floating :: Parser Expr
floating = Float <$> float
expr :: Parser Expr
expr = Ex.buildExpressionParser (binops ++ [[unop], [binop]]) factor
binarydef :: Parser Expr
binarydef = do
reserved "def"
reserved "binary"
o <- op
prec <- int
args <- parens $ many identifier
body <- expr
return $ BinaryDef o args body
unarydef :: Parser Expr
unarydef = do
reserved "def"
reserved "unary"
o <- op
args <- parens $ many identifier
body <- expr
return $ UnaryDef o args body
variable :: Parser Expr
variable = Var <$> identifier
ifthen :: Parser Expr
ifthen = do
reserved "if"
cond <- expr
reserved "then"
tr <- expr
reserved "else"
fl <- expr
return $ If cond tr fl
for :: Parser Expr
for = do
reserved "for"
var <- identifier
reservedOp "="
start <- expr
reservedOp ","
cond <- expr
reservedOp ","
step <- expr
reserved "in"
body <- expr
return $ For var start cond step body
function :: Parser Expr
function = do
reserved "def"
name <- identifier
args <- parens $ many identifier
body <- expr
return $ Function name args body
extern :: Parser Expr
extern = do
reserved "extern"
name <- identifier
args <- parens $ many identifier
return $ Extern name args
call :: Parser Expr
call = do
name <- identifier
args <- parens $ commaSep expr
return $ Call name args
factor :: Parser Expr
factor = try floating
<|> try int
<|> try call
<|> try variable
<|> ifthen
<|> for
<|> (parens expr)
defn :: Parser Expr
defn = try extern
<|> try function
<|> try unarydef
<|> try binarydef
<|> expr
contents :: Parser a -> Parser a
contents p = do
Tok.whiteSpace lexer
r <- p
eof
return r
toplevel :: Parser [Expr]
toplevel = many $ do
def <- defn
reservedOp ";"
return def
parseExpr :: String -> Either ParseError Expr
parseExpr s = parse (contents expr) "<stdin>" s
parseTopLevel :: String -> Either ParseError [Expr]
parseTopLevel s = parse (contents toplevel) "<stdin>" s
| mankyKitty/haskell-to-llvm-compiler | src/LlvmParser.hs | mit | 2,924 | 0 | 11 | 725 | 1,106 | 528 | 578 | 122 | 1 |
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeSynonymInstances #-}
module IHaskell.Display.Widgets.Int.BoundedInt.IntProgress (
-- * The IntProgress Widget
IntProgress,
-- * Constructor
mkIntProgress) where
-- To keep `cabal repl` happy when running from the ihaskell repo
import Prelude
import Data.Aeson
import Data.IORef (newIORef)
import Data.Vinyl (Rec(..), (<+>))
import IHaskell.Display
import IHaskell.Eval.Widgets
import IHaskell.IPython.Message.UUID as U
import IHaskell.Display.Widgets.Types
import IHaskell.Display.Widgets.Common
-- | 'IntProgress' represents an IntProgress widget from IPython.html.widgets.
type IntProgress = IPythonWidget IntProgressType
-- | Create a new widget
mkIntProgress :: IO IntProgress
mkIntProgress = do
-- Default properties, with a random uuid
uuid <- U.random
let boundedIntAttrs = defaultBoundedIntWidget "ProgressView" "ProgressModel"
progressAttrs = (Orientation =:: HorizontalOrientation)
:& (BarStyle =:: DefaultBar)
:& RNil
widgetState = WidgetState $ boundedIntAttrs <+> progressAttrs
stateIO <- newIORef widgetState
let widget = IPythonWidget uuid stateIO
-- Open a comm for this widget, and store it in the kernel state
widgetSendOpen widget $ toJSON widgetState
-- Return the widget
return widget
instance IHaskellDisplay IntProgress where
display b = do
widgetSendView b
return $ Display []
instance IHaskellWidget IntProgress where
getCommUUID = uuid
| sumitsahrawat/IHaskell | ihaskell-display/ihaskell-widgets/src/IHaskell/Display/Widgets/Int/BoundedInt/IntProgress.hs | mit | 1,693 | 0 | 13 | 399 | 276 | 156 | 120 | 35 | 1 |
import Data.Function
import Data.List
nSolutions :: Integral a => (a, a) -> a
nSolutions (a,b) = a * (a+1) * b * (b+1) `div` 4
nmax = 500
target = 2000000
pairs = [ (i,j) | i <- [1..nmax], j <- [i..nmax] ]
allAreas = zip pairs $ map nSolutions pairs
byDiff = map (\(p, a) -> (p, abs (a - target))) allAreas
answer = sortBy (compare `on` snd) byDiff
main = do
let ans = answer
print $ take 50 ans
print $ head ans
putStrLn $ "area=" ++ show (uncurry (*) $ fst $ head ans)
| arekfu/project_euler | p0085/p0085.hs | mit | 511 | 0 | 12 | 138 | 274 | 147 | 127 | 15 | 1 |
{-# LANGUAGE ScopedTypeVariables #-}
module ShrinkingAndShowingFunctions3 where
-- from https://www.youtube.com/watch?v=CH8UQJiv9Q4
import Test.QuickCheck
import Test.QuickCheck.Function
import Text.Show.Functions
prop_HaskellML (Fun _ p) =
p "Haskell 98" ==> p "Standard ML"
| NickAger/LearningHaskell | HaskellProgrammingFromFirstPrinciples/Chapter15.hsproj/ShrinkingAndShowingFunctions3.hs | mit | 282 | 0 | 7 | 34 | 49 | 28 | 21 | 7 | 1 |
{-# LANGUAGE DeriveGeneric #-}
module Kit.ListZip where
import Data.Foldable
import Data.Monoid
import GHC.Generics
import Kit.BwdFwd
data ListZip a = ListZip
{ later :: Bwd a
, focus :: a
, earlier :: Fwd a
} deriving Generic
listZipFromFwd :: Fwd a -> Maybe (ListZip a)
listZipFromFwd (a :> as) = Just (ListZip B0 a as)
listZipFromFwd _ = Nothing
listZipFromList :: [a] -> Maybe (ListZip a)
listZipFromList = listZipFromFwd . fwdList
moveEarlier :: ListZip a -> Maybe (ListZip a)
moveEarlier (ListZip late a (a' :> early)) =
Just (ListZip (late :< a) a' early)
moveEarlier _ = Nothing
moveLater :: ListZip a -> Maybe (ListZip a)
moveLater (ListZip (late :< a') a early) =
Just (ListZip late a' (a :> early))
moveLater _ = Nothing
instance Functor ListZip where
fmap f (ListZip late focus early) =
ListZip (fmap f late) (f focus) (fmap f early)
instance Foldable ListZip where
foldMap f (ListZip late focus early) =
foldMap f late <> f focus <> foldMap f early
| kwangkim/pigment | src-lib/Kit/ListZip.hs | mit | 1,022 | 0 | 9 | 226 | 405 | 208 | 197 | 30 | 1 |
{-# htermination foldM :: (a -> b -> IO a) -> a -> [b] -> IO a #-}
import Monad
| ComputationWithBoundedResources/ara-inference | doc/tpdb_trs/Haskell/full_haskell/Monad_foldM_4.hs | mit | 81 | 0 | 3 | 21 | 5 | 3 | 2 | 1 | 0 |
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE TypeFamilies #-}
module Fibbo where
import SoOSiM
import Expr.Syntax
import Expr.Combinators
-- import Expr.SimpleSemantics
import Expr.SoOSSemantics
fibbo = fix $ \fib ->
lam $ \n ->
newvar 0 $ \n1 ->
newIVar $ \n2 ->
newIVar $ \n3 ->
update n1 n >:
if_ (lt (deref n1) 2)
1
( par (wrIVar n2 (app fib ((deref n1) - 1))) >:
par (wrIVar n3 (app fib ((deref n1) - 2))) >:
(rdIVar n2) + (rdIvar n3)
)
fibbo5 :: EDSL exp => exp IntT
fibbo5 = fibbo $$ 5
fibbo5Component ::
Int
-> Input ()
-> Sim Int
fibbo5Component s (Message () _) = do
(a,s') <- runExpr fibbo5 s
traceMsg ("Result: " ++ show a)
yield s'
data Fibbo = Fibbo
instance ComponentInterface Fibbo where
type State Fibbo = Int
type Receive Fibbo = ()
type Send Fibbo = ()
initState _ = 0
componentName _ = "Fibbo5"
componentBehaviour _ = fibbo5Component
| christiaanb/SoOSiM | examples/Fibbo.hs | mit | 1,047 | 0 | 29 | 313 | 375 | 194 | 181 | 37 | 1 |
module Data.Either.Extra where
import Prelude
import Data.Either
sameEither :: Either a b -> Either c d -> Bool
x `sameEither` y = isLeft x == isLeft y
fromEither :: Either a a -> a
fromEither (Left x) = x
fromEither (Right x) = x
| circuithub/circuithub-prelude | Data/Either/Extra.hs | mit | 234 | 0 | 7 | 47 | 103 | 53 | 50 | 8 | 1 |
{-
Copyright (c) 2015 Nils 'bash0r' Jonsson
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-}
{- |
Module : $Header$
Description : The expression definitions of the EDSL.
Author : Nils 'bash0r' Jonsson
Copyright : (c) 2015 Nils 'bash0r' Jonsson
License : MIT
Maintainer : [email protected]
Stability : unstable
Portability : non-portable (Portability is untested.)
The expression definitions of the EDSL.
-}
module Language.JavaScript.DSL.Operators
( module Export
) where
import Language.JavaScript.DSL.Operators.Bitwise as Export
import Language.JavaScript.DSL.Operators.Comparison as Export
import Language.JavaScript.DSL.Operators.Logical as Export
import Language.JavaScript.DSL.Operators.Numeric as Export
import Language.JavaScript.DSL.Operators.Others as Export
| project-horizon/framework | src/lib/Language/JavaScript/DSL/Operators.hs | mit | 1,844 | 0 | 4 | 341 | 66 | 52 | 14 | 7 | 0 |
module Test.Hspec.Core.UtilSpec (spec) where
import Prelude ()
import Helper
import Control.Concurrent
import qualified Control.Exception as E
import Test.Hspec.Core.Util
spec :: Spec
spec = do
describe "pluralize" $ do
it "returns singular when used with 1" $ do
pluralize 1 "thing" `shouldBe` "1 thing"
it "returns plural when used with number greater 1" $ do
pluralize 2 "thing" `shouldBe` "2 things"
it "returns plural when used with 0" $ do
pluralize 0 "thing" `shouldBe` "0 things"
describe "formatException" $ do
it "converts exception to string" $ do
formatException (E.toException E.DivideByZero) `shouldBe` "ArithException\ndivide by zero"
context "when used with an IOException" $ do
it "includes the IOErrorType" $ do
inTempDirectory $ do
Left e <- E.try (readFile "foo")
formatException e `shouldBe` intercalate "\n" [
"IOException of type NoSuchThing"
, "foo: openFile: does not exist (No such file or directory)"
]
describe "lineBreaksAt" $ do
it "inserts line breaks at word boundaries" $ do
lineBreaksAt 20 "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod"
`shouldBe` [
"Lorem ipsum dolor"
, "sit amet,"
, "consectetur"
, "adipisicing elit,"
, "sed do eiusmod"
]
describe "safeTry" $ do
it "returns Right on success" $ do
Right e <- safeTry (return 23 :: IO Int)
e `shouldBe` 23
it "returns Left on exception" $ do
Left e <- safeTry throwException
E.fromException e `shouldBe` Just E.DivideByZero
it "evaluates result to weak head normal form" $ do
Left e <- safeTry (return $ E.throw $ E.ErrorCall "foo")
show e `shouldBe` "foo"
it "does not catch asynchronous exceptions" $ do
mvar <- newEmptyMVar
sync <- newEmptyMVar
threadId <- forkIO $ do
safeTry (putMVar sync () >> threadDelay 1000000) >> return ()
`E.catch` putMVar mvar
takeMVar sync
throwTo threadId E.UserInterrupt
readMVar mvar `shouldReturn` E.UserInterrupt
describe "filterPredicate" $ do
it "tries to match a pattern against a path" $ do
let p = filterPredicate "foo/bar/example 1"
p (["foo", "bar"], "example 1") `shouldBe` True
p (["foo", "bar"], "example 2") `shouldBe` False
it "is ambiguous" $ do
let p = filterPredicate "foo/bar/baz"
p (["foo", "bar"], "baz") `shouldBe` True
p (["foo"], "bar/baz") `shouldBe` True
it "succeeds on a partial match" $ do
let p = filterPredicate "bar/baz"
p (["foo", "bar", "baz"], "example 1") `shouldBe` True
it "succeeds with a pattern that matches the message given in the failure list" $ do
let p = filterPredicate "ModuleA.ModuleB.foo does something"
p (["ModuleA", "ModuleB", "foo"], "does something") `shouldBe` True
context "with an absolute path that begins or ends with a slash" $ do
it "succeeds" $ do
let p = filterPredicate "/foo/bar/baz/example 1/"
p (["foo", "bar", "baz"], "example 1") `shouldBe` True
describe "formatRequirement" $ do
it "creates a sentence from a subject and a requirement" $ do
formatRequirement (["reverse"], "reverses a list") `shouldBe` "reverse reverses a list"
it "creates a sentence from a subject and a requirement when the subject consits of multiple words" $ do
formatRequirement (["The reverse function"], "reverses a list") `shouldBe` "The reverse function reverses a list"
it "returns the requirement if no subject is given" $ do
formatRequirement ([], "reverses a list") `shouldBe` "reverses a list"
it "inserts context separated by commas" $ do
formatRequirement (["reverse", "when applied twice"], "reverses a list") `shouldBe` "reverse, when applied twice, reverses a list"
it "joins components of a subject with a dot" $ do
formatRequirement (["Data", "List", "reverse"], "reverses a list") `shouldBe` "Data.List.reverse reverses a list"
it "properly handles context after a subject that consists of several components" $ do
formatRequirement (["Data", "List", "reverse", "when applied twice"], "reverses a list") `shouldBe` "Data.List.reverse, when applied twice, reverses a list"
| hspec/hspec | hspec-core/test/Test/Hspec/Core/UtilSpec.hs | mit | 4,405 | 0 | 23 | 1,109 | 1,070 | 528 | 542 | 85 | 1 |
Subsets and Splits