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 TemplateHaskell, DeriveDataTypeable #-} {- Copyright (C) 2012-2017 Kacper Bak, Jimmy Liang, Michal Antkiewicz, Luke Michael Brown <http://gsd.uwaterloo.ca> 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. -} -- | Intermediate representation (IR) of a Clafer model module Language.Clafer.Intermediate.Intclafer where import Language.Clafer.Front.AbsClafer import Control.Lens import Data.Aeson import Data.Aeson.TH import Data.Data import Data.Monoid import Data.Foldable import Prelude -- | unique identifier of a clafer type UID = String -- | clafer name as declared in the source model type CName = String -- | file:// ftp:// or http:// prefixed URL type URL = String -- | A "supertype" of all IR types data Ir = IRIModule IModule | IRIElement IElement | IRIType IType | IRClafer IClafer | IRIExp IExp | IRPExp PExp | IRIReference (Maybe IReference) | IRIQuant IQuant | IRIDecl IDecl | IRIGCard (Maybe IGCard) deriving (Eq, Show) data IType = TBoolean | TString | TInteger | TDouble | TReal | TClafer { _hi :: [UID] -- ^ [UID] represents an inheritance hierarchy obtained using @Common.findHierarchy } | TMap -- Represents a map from the src class to the target class { _so :: IType -- ^ must only be a TClass , _ta :: IType -- ^ must only be a TClass } | TUnion { _un :: [IType] -- ^ [IType] is a list of basic types (not union types) } deriving (Eq,Ord,Show,Data,Typeable) -- | each file contains exactly one mode. A module is a list of declarations data IModule = IModule { _mName :: String -- ^ always empty (no syntax for declaring modules) , _mDecls :: [IElement] -- ^ List of top-level elements } deriving (Eq,Ord,Show,Data,Typeable) -- | Clafer has a list of fields that specify its properties. Some fields, marked as (o) are for generating optimized code data IClafer = IClafer { _cinPos :: Span -- ^ the position of the syntax in source code , _modifiers :: IClaferModifiers -- ^ abstract, initial, final , _gcard :: Maybe IGCard -- ^ group cardinality , _ident :: CName -- ^ name declared in the model , _uid :: UID -- ^ a unique identifier , _parentUID :: UID -- ^ "root" if top-level concrete, "clafer" if top-level abstract, "" if unresolved or for root clafer, otherwise UID of the parent clafer , _super :: Maybe PExp -- ^ superclafer - only allowed PExp is IClaferId. Nothing = default super "clafer" , _reference :: Maybe IReference -- ^ reference type, bag or set , _card :: Maybe Interval -- ^ clafer cardinality , _glCard :: Interval -- ^ (o) global cardinality , _elements :: [IElement] -- ^ nested elements } deriving (Eq,Ord,Show,Data,Typeable) isMutable :: IClafer -> Bool isMutable = not . _final . _modifiers data IClaferModifiers = IClaferModifiers { _abstract :: Bool -- ^ declared as "abstract" , _initial :: Bool -- ^ declared as "initial" , _final :: Bool -- ^ declared as "final" } deriving (Eq,Ord,Show,Data,Typeable) _isAbstract :: IClafer -> Bool -- ^ whether abstract or not (i.e., concrete) _isAbstract = _abstract . _modifiers _isFinal :: IClafer -> Bool -- ^ whether declared final or not _isFinal = _final . _modifiers _isInitial :: IClafer -> Bool -- ^ whether declared initial or not _isInitial = _initial . _modifiers -- | Clafer's subelement is either a clafer, a constraint, or a goal (objective) -- This is a wrapper type needed to have polymorphic lists of elements data IElement = IEClafer { _iClafer :: IClafer -- ^ the actual clafer } | IEConstraint { _isHard :: Bool -- ^ whether hard constraint or assertion , _cpexp :: PExp -- ^ the container of the actual expression } -- | Goal (optimization objective) | IEGoal { _isMaximize :: Bool -- ^ whether maximize or minimize , _cpexp :: PExp -- ^ the expression } deriving (Eq,Ord,Show,Data,Typeable) -- | A type of reference. -- -> values unique (set) -- ->> values non-unique (bag) data IReference = IReference { _isSet :: Bool -- ^ whether set or bag , _refModifier :: Maybe IReferenceModifier , _ref :: PExp -- ^ the only allowed reference expressions are IClafer and set expr. (++, **, --s) } deriving (Eq,Ord,Show,Data,Typeable) data IReferenceModifier = FinalRefTarget | FinalRef | FinalTarget deriving (Eq, Ord, Show, Data, Typeable) -- | Group cardinality is specified as an interval. It may also be given by a keyword. -- xor 1..1 isKeyword = True -- 1..1 1..1 isKeyword = False data IGCard = IGCard { _isKeyword :: Bool -- ^ whether given by keyword: or, xor, mux , _interval :: Interval } deriving (Eq,Ord,Show,Data,Typeable) -- | (Min, Max) integer interval. -1 denotes * type Interval = (Integer, Integer) type Mutability = Bool -- | This is expression container (parent). -- It has meta information about an actual expression 'exp' data PExp = PExp { _iType :: Maybe IType -- ^ the inferred type , _pid :: String -- ^ non-empty unique id for expressions with span, \"\" for noSpan , _inPos :: Span -- ^ position in the input Clafer file , _exp :: IExp -- ^ the actual expression } deriving (Eq,Ord,Show,Data,Typeable) -- | Embedes reference to a resolved Clafer {-type ClaferBinding = Maybe UID-} data ClaferBinding = GlobalBind UID | LocalBind CName | NoBind deriving (Eq,Ord,Show,Data,Typeable) data IExp -- | quantified expression with declarations -- e.g., [ all x1; x2 : X | x1.ref != x2.ref ] = IDeclPExp { _quant :: IQuant , _oDecls :: [IDecl] , _bpexp :: PExp } -- | expression with a -- unary function, e.g., -1 -- binary function, e.g., 2 + 3 -- ternary function, e.g., if x then 4 else 5 | IFunExp { _op :: String , _exps :: [PExp] } -- | integer number | IInt { _iint :: Integer } -- | real number | IReal { _ireal :: Double } -- | double-precision floating point number | IDouble { _idouble :: Double } -- | string | IStr { _istr :: String } -- | a reference to a clafer name | IClaferId { _modName :: String -- ^ module name - currently not used and empty since we have no module system , _sident :: CName -- ^ name of the clafer being referred to , _isTop :: Bool -- ^ identifier refers to a top-level definition , _binding :: ClaferBinding -- ^ the UID of the bound IClafer, if resolved } deriving (Eq,Ord,Show,Data,Typeable) {- | For IFunExp standard set of operators includes: 1. Unary operators: ! - not (logical) # - set counting operator - - negation (arithmetic) max - maximum (created for goals and maximum of a set) min - minimum (created for goals and minimum of a set) 2. Binary operators: \<=\> - equivalence =\> - implication || - disjunction xor - exclusive or && - conjunction \< - less than \> - greater than = - equality \<= - less than or equal \>= - greater than or equal != - inequality in - belonging to a set/being a subset nin - not belonging to a set/not being a subset + - addition/string concatenation - - substraction * - multiplication / - division ++ - set union \-\- - set difference ** - set intersection \<: - domain restriction :\> - range restriction . - relational join 3. Ternary operators ifthenelse -- if then else -} -- | Local declaration -- disj x1; x2 : X ++ Y -- y1 : Y data IDecl = IDecl { _isDisj :: Bool -- ^ is disjunct , _decls :: [CName] -- ^ a list of local names , _body :: PExp -- ^ set to which local names refer to } deriving (Eq,Ord,Show,Data,Typeable) -- | quantifier data IQuant = INo -- ^ does not exist | ILone -- ^ less than one | IOne -- ^ exactly one | ISome -- ^ at least one (i.e., exists) | IAll -- ^ for all deriving (Eq,Ord,Show,Data,Typeable) type LineNo = Integer type ColNo = Integer {-Ir Traverse Functions-} ------------------------- -- | map over IR mapIR :: (Ir -> Ir) -> IModule -> IModule -- fmap/map for IModule mapIR f (IModule name decls') = unWrapIModule $ f $ IRIModule $ IModule name $ map (unWrapIElement . iMap f . IRIElement) decls' -- | foldMap over IR foldMapIR :: (Monoid m) => (Ir -> m) -> IModule -> m -- foldMap for IModule foldMapIR f i@(IModule _ decls') = (f $ IRIModule i) `mappend` foldMap (iFoldMap f . IRIElement) decls' -- | fold the IR foldIR :: (Ir -> a -> a) -> a -> IModule -> a -- a basic fold for IModule foldIR f e m = appEndo (foldMapIR (Endo . f) m) e {- Note: even though the above functions take an IModule, the functions they use take an Ir (wrapped version see top of module). Also the bellow functions are just helpers for the above, you may use them if you wish to start from somewhere other than IModule. -} iMap :: (Ir -> Ir) -> Ir -> Ir iMap f (IRIElement (IEClafer c)) = f $ IRIElement $ IEClafer $ unWrapIClafer $ iMap f $ IRClafer c iMap f (IRIElement (IEConstraint h pexp)) = f $ IRIElement $ IEConstraint h $ unWrapPExp $ iMap f $ IRPExp pexp iMap f (IRIElement (IEGoal m pexp)) = f $ IRIElement $ IEGoal m $ unWrapPExp $ iMap f $ IRPExp pexp iMap f (IRClafer (IClafer p a grc i u pu Nothing r c goc elems)) = f $ IRClafer $ IClafer p a (unWrapIGCard $ iMap f $ IRIGCard grc) i u pu Nothing (unWrapIReference $ iMap f $ IRIReference r) c goc $ map (unWrapIElement . iMap f . IRIElement) elems iMap f (IRClafer (IClafer p a grc i u pu (Just s) r c goc elems)) = f $ IRClafer $ IClafer p a (unWrapIGCard $ iMap f $ IRIGCard grc) i u pu (Just $ unWrapPExp $ iMap f $ IRPExp s) (unWrapIReference $ iMap f $ IRIReference r) c goc $ map (unWrapIElement . iMap f . IRIElement) elems iMap f (IRIExp (IDeclPExp q decs p)) = f $ IRIExp $ IDeclPExp (unWrapIQuant $ iMap f $ IRIQuant q) (map (unWrapIDecl . iMap f . IRIDecl) decs) $ unWrapPExp $ iMap f $ IRPExp p iMap f (IRIExp (IFunExp o pexps)) = f $ IRIExp $ IFunExp o $ map (unWrapPExp . iMap f . IRPExp) pexps iMap f (IRPExp (PExp (Just iType') pID p iExp)) = f $ IRPExp $ PExp (Just $ unWrapIType $ iMap f $ IRIType iType') pID p $ unWrapIExp $ iMap f $ IRIExp iExp iMap f (IRPExp (PExp Nothing pID p iExp)) = f $ IRPExp $ PExp Nothing pID p $ unWrapIExp $ iMap f $ IRIExp iExp iMap _ x@(IRIReference Nothing) = x iMap f (IRIReference (Just (IReference is mod' ref))) = f $ IRIReference $ Just $ IReference is mod' ((unWrapPExp . iMap f . IRPExp) ref) iMap f (IRIDecl (IDecl i d body')) = f $ IRIDecl $ IDecl i d $ unWrapPExp $ iMap f $ IRPExp body' iMap f i = f i iFoldMap :: (Monoid m) => (Ir -> m) -> Ir -> m iFoldMap f i@(IRIElement (IEConstraint _ pexp)) = f i `mappend` (iFoldMap f $ IRPExp pexp) iFoldMap f i@(IRIElement (IEGoal _ pexp)) = f i `mappend` (iFoldMap f $ IRPExp pexp) iFoldMap f i@(IRClafer (IClafer _ _ grc _ _ _ Nothing r _ _ elems)) = f i `mappend` (iFoldMap f $ IRIReference r) `mappend` (iFoldMap f $ IRIGCard grc) `mappend` foldMap (iFoldMap f . IRIElement) elems iFoldMap f i@(IRClafer (IClafer _ _ grc _ _ _ (Just s) r _ _ elems)) = f i `mappend` (iFoldMap f $ IRPExp s) `mappend` (iFoldMap f $ IRIReference r) `mappend` (iFoldMap f $ IRIGCard grc) `mappend` foldMap (iFoldMap f . IRIElement) elems iFoldMap f i@(IRIExp (IDeclPExp q decs p)) = f i `mappend` (iFoldMap f $ IRIQuant q) `mappend` (iFoldMap f $ IRPExp p) `mappend` foldMap (iFoldMap f . IRIDecl) decs iFoldMap f i@(IRIExp (IFunExp _ pexps)) = f i `mappend` foldMap (iFoldMap f . IRPExp) pexps iFoldMap f i@(IRPExp (PExp (Just iType') _ _ iExp)) = f i `mappend` (iFoldMap f $ IRIType iType') `mappend` (iFoldMap f $ IRIExp iExp) iFoldMap f i@(IRPExp (PExp Nothing _ _ iExp)) = f i `mappend` (iFoldMap f $ IRIExp iExp) iFoldMap f i@(IRIReference Nothing) = f i iFoldMap f i@(IRIReference (Just (IReference _ _ ref))) = f i `mappend` (iFoldMap f . IRPExp) ref iFoldMap f i@(IRIDecl (IDecl _ _ body')) = f i `mappend` (iFoldMap f $ IRPExp body') iFoldMap f (IRIElement (IEClafer c)) = iFoldMap f $ IRClafer c iFoldMap f i = f i iFold :: (Ir -> a -> a) -> a -> Ir -> a iFold f e m = appEndo (iFoldMap (Endo . f) m) e unWrapIModule :: Ir -> IModule unWrapIModule (IRIModule x) = x unWrapIModule x = error $ "Can't call unWarpIModule on " ++ show x unWrapIElement :: Ir -> IElement unWrapIElement (IRIElement x) = x unWrapIElement x = error $ "Can't call unWarpIElement on " ++ show x unWrapIType :: Ir -> IType unWrapIType (IRIType x) = x unWrapIType x = error $ "Can't call unWarpIType on " ++ show x unWrapIClafer :: Ir -> IClafer unWrapIClafer (IRClafer x) = x unWrapIClafer x = error $ "Can't call unWarpIClafer on " ++ show x unWrapIExp :: Ir -> IExp unWrapIExp (IRIExp x) = x unWrapIExp x = error $ "Can't call unWarpIExp on " ++ show x unWrapPExp :: Ir -> PExp unWrapPExp (IRPExp x) = x unWrapPExp x = error $ "Can't call unWarpPExp on " ++ show x unWrapIReference :: Ir -> Maybe IReference unWrapIReference (IRIReference x) = x unWrapIReference x = error $ "Can't call unWarpIReference on " ++ show x unWrapIQuant :: Ir -> IQuant unWrapIQuant (IRIQuant x) = x unWrapIQuant x = error $ "Can't call unWarpIQuant on " ++ show x unWrapIDecl :: Ir -> IDecl unWrapIDecl (IRIDecl x) = x unWrapIDecl x = error $ "Can't call unWarpIDecl on " ++ show x unWrapIGCard :: Ir -> Maybe IGCard unWrapIGCard (IRIGCard x) = x unWrapIGCard x = error $ "Can't call unWarpIGcard on " ++ show x instance Plated IModule instance Plated IClafer instance Plated PExp instance Plated IExp makeLenses ''IType makeLenses ''IModule makeLenses ''IClafer makeLenses ''IElement makeLenses ''IClaferModifiers makeLenses ''IReferenceModifier makeLenses ''IReference makeLenses ''IGCard makeLenses ''PExp makeLenses ''IExp makeLenses ''IDecl $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IType) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IModule) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IClaferModifiers) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''ClaferBinding) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IElement) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IReferenceModifier) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IReference) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IClafer) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IGCard) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''PExp) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IExp) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IDecl) $(deriveToJSON defaultOptions{fieldLabelModifier = tail, omitNothingFields=True} ''IQuant) instance ToJSON Span where toJSON _ = Null instance ToJSON Pos where toJSON _ = Null -- | Datatype used for JSON output. See Language.Clafer.gatherObjectivesAndAttributes data ObjectivesAndAttributes = ObjectivesAndAttributes { _qualities :: [String] , _attributes :: [String] } $(deriveToJSON defaultOptions{fieldLabelModifier = tail} ''ObjectivesAndAttributes)
gsdlab/clafer
src/Language/Clafer/Intermediate/Intclafer.hs
mit
16,995
0
15
4,012
4,187
2,242
1,945
274
1
{-# LANGUAGE TemplateHaskell, DeriveDataTypeable, GeneralizedNewtypeDeriving #-} module Program.Cexp.Annotated where import Program.Cexp.Type hiding ( Symbol, Literal ) import qualified Program.Cexp.Type as T import Data.Map ( Map ) import qualified Data.Map as M import Autolib.FiniteMap import Control.Monad ( forM_ ) import Autolib.Reporter import Autolib.ToDoc import Autolib.Reader import Autolib.Util.Size import Data.Typeable import Data.Tree import Data.Maybe ( isJust ) import qualified Data.List data Annotated = Annotated { node :: Node , lvalue :: Maybe Identifier , rvalue :: Maybe Integer , actions :: [ (Time, Action) ] , children :: [ Annotated ] } deriving Typeable instance Size Annotated where size = succ . sum . map size . children blank :: Annotated blank = Annotated { children = [], lvalue = Nothing, rvalue = Nothing, actions = [] } newtype Time = Time Int deriving ( Eq, Ord, Enum ) data Action = Read Identifier Integer -- ^ this includes the expected result of the reading | Write Identifier Integer deriving ( Eq, Ord ) data Node = Literal Integer | Symbol Identifier | Operator Oper $(derives [makeToDoc,makeReader] [''Node, ''Annotated, ''Time, ''Action]) ------------------------------------------------------------------- -- | produce tree that is partially annotated start :: Exp -> Annotated start x = case x of T.Literal i -> blank { node = Literal i, rvalue = Just i } T.Symbol s -> blank { node = Symbol s, lvalue = Just s } Apply op xs -> blank { node = Operator $ oper op , children = map start xs } ------------------------------------------------------------------- all_actions :: Annotated -> [ (Time, Action) ] all_actions a = actions a ++ ( children a >>= all_actions ) type Store = FiniteMap Identifier Integer -- | execute actions in order given by timestamps. -- checks that Read actions get the values they expect. execute :: Annotated -> Reporter () execute a = do let acts = Data.List.sort $ all_actions a let distinct ( x : y : zs ) = if fst x == fst y then reject $ text "gleichzeitige Aktionen" </> vcat [ toDoc x, toDoc y ] else distinct ( y : zs ) distinct _ = return () distinct acts let step st ( ta @ (time, act) ) = do inform $ toDoc ta case act of Read p x -> case M.lookup p st of Nothing -> reject $ text "Wert nicht gebunden" Just y -> if x == y then return st else reject $ text "Falscher Wert gebunden" Write p x -> return $ M.insert p x st foldM step emptyFM acts return () ------------------------------------------------------------------- check :: Annotated -> Reporter () check a = case node a of Literal i -> do case lvalue a of Just _ -> reject $ text "Literal ist kein lvalue" </> toDoc a Nothing -> return () case rvalue a of Just v | i /= v -> reject $ text "rvalue falsch" </> toDoc a _ -> return () when ( not $ null $ actions a ) $ reject $ text "keine Aktionen in Literalknoten" </> toDoc a Symbol s -> do case lvalue a of Just v | s /= v -> reject ( text "lvalue falsch" </> toDoc a ) _ -> return () case rvalue a of Nothing -> do when ( not $ null $ actions a ) $ reject $ text "rvalue nicht benutzt => keine Aktionen in Symbolknoten" </> toDoc a Just v -> do p <- case lvalue a of Just p -> return p Nothing -> reject $ text "lvalue erforderlich" </> toDoc a w <- case actions a of [ ( time, Read q w) ] -> do when ( p /= q ) $ reject $ text "Read benutzt falschen lvalue" </> toDoc a return w _ -> reject $ text "Bestimmung des rvalues erfordert Read-Aktion" when ( v /= w ) $ reject $ text "rvalue falsch" </> toDoc a Operator op -> do forM_ ( children a ) check case ( op, children a ) of ( Assign, [ l,r ] ) -> do p <- case lvalue l of Nothing -> reject $ text "Zuweisungsziel muß lvalue haben" </> toDoc a Just p -> return p v <- case rvalue r of Nothing -> reject $ text "Zuweisungsquelle muß rvalue haben" </> toDoc a Just v -> return v case actions a of [ (time, Write q w ) ] -> do when ( q /= p ) $ reject $ text "falsches Ziel für Write" </> toDoc a when ( w /= v ) $ reject $ text "falscher Wert für Write" </> toDoc a _ -> reject $ text "Zuweisung erfordert genau eine Write-Aktion" </> toDoc a ( op , [ l ] ) | elem op [ Prefix Increment, Prefix Decrement , Postfix Increment, Postfix Decrement ] -> do when ( isJust $ lvalue a ) $ reject $ text "ist kein lvalue" </> toDoc a p <- case lvalue l of Nothing -> reject $ text "Argument muß lvalue haben" </> toDoc a Just p -> return p case Data.List.sort $ actions a of [ (rtime, Read q w), (wtime, Write q' w') ] -> do when ( p /= q || p /= q' ) $ reject $ text "Lese/Schreibziel muß mit lvalue übereinstimmen" </> toDoc a when ( succ rtime /= wtime ) $ reject $ text "Schreiben muß direkt auf Lesen folgen" </> toDoc a let ( result, store ) = case op of Prefix Increment -> ( succ w, succ w ) Postfix Increment -> ( w, succ w ) Prefix Decrement -> ( pred w, pred w ) Postfix Decrement -> ( w, pred w ) when ( store /= w' ) $ reject $ text "falscher Wert geschrieben" </> toDoc a when ( Just result /= rvalue a ) $ reject $ text "falsches Resultat in rvalue" </> toDoc a _ -> reject $ text "Präfix/Postfix-Operator erforder Read- und Write-Aktion" </> toDoc a ( Sequence , [ l, r ] ) -> do when ( lvalue r /= lvalue a ) $ reject $ text "lvalues von Wurzel und zweitem Argument müssen übereinstimmen" </> toDoc a when ( rvalue r /= rvalue a ) $ reject $ text "rvalues von Wurzel und zweitem Argument müssen übereinstimmen" </> toDoc a ( _ , [ l, r ] ) | Just f <- standard op -> do vl <- case rvalue l of Nothing -> reject $ text "erstes Argument hat kein rvalue" </> toDoc a Just vl -> return vl vr <- case rvalue r of Nothing -> reject $ text "zweites Argument hat kein rvalue" </> toDoc a Just vr -> return vr let result = f vl vr when ( rvalue a /= Just result ) $ reject $ text "falsches Resultat in rvalue" </> toDoc a standard op = case op of Plus -> Just (+) Minus -> Just (-) Times -> Just (*) Divide -> Just div Remainder -> Just rem _ -> Nothing ----------------------------------------------------- same_skeleton :: (Exp, Annotated) -> Reporter () same_skeleton (x, a) = case (x,node a) of (T.Symbol xs, Symbol ys) -> when ( xs /= ys ) $ mismatch (text "verschiedene Bezeichner") x a (T.Literal i, Literal j) -> when ( i /= j ) $ mismatch (text "verschiedene Literale") x a (Apply xop xargs, Operator cs ) -> do when ( oper xop /= cs) $ mismatch (text "verschiedene Operatoren") x a when ( length xargs /= length ( children a )) $ mismatch (text "verschiede Argumentanzahlen") x a forM_ ( zip xargs $ children a ) $ same_skeleton mismatch msg x a = reject $ msg </> vcat [ text "original" </> toDoc a , text "annotiert" </> toDoc x ] -------------------------------------------------------------------
Erdwolf/autotool-bonn
src/Program/Cexp/Annotated.hs
gpl-2.0
8,867
1
28
3,485
2,634
1,285
1,349
171
22
module Paths_haskell_scheme ( version, getBinDir, getLibDir, getDataDir, getLibexecDir, getDataFileName ) where import qualified Control.Exception as Exception import Data.Version (Version(..)) import System.Environment (getEnv) catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a catchIO = Exception.catch version :: Version version = Version {versionBranch = [0,1,0,0], versionTags = []} bindir, libdir, datadir, libexecdir :: FilePath bindir = "/home/gandalf/.cabal/bin" libdir = "/home/gandalf/.cabal/lib/haskell-scheme-0.1.0.0/ghc-7.4.2" datadir = "/home/gandalf/.cabal/share/haskell-scheme-0.1.0.0" libexecdir = "/home/gandalf/.cabal/libexec" getBinDir, getLibDir, getDataDir, getLibexecDir :: IO FilePath getBinDir = catchIO (getEnv "haskell_scheme_bindir") (\_ -> return bindir) getLibDir = catchIO (getEnv "haskell_scheme_libdir") (\_ -> return libdir) getDataDir = catchIO (getEnv "haskell_scheme_datadir") (\_ -> return datadir) getLibexecDir = catchIO (getEnv "haskell_scheme_libexecdir") (\_ -> return libexecdir) getDataFileName :: FilePath -> IO FilePath getDataFileName name = do dir <- getDataDir return (dir ++ "/" ++ name)
pennetti/scheme-repl
dist/build/autogen/Paths_haskell_scheme.hs
gpl-2.0
1,184
0
10
164
329
188
141
25
1
-- MisclassificationRate.hs --- -- -- Filename: MisclassificationRate.hs -- Description: -- Author: Manuel Schneckenreither -- Maintainer: -- Created: Sun Mar 1 17:25:15 2015 (+0100) -- Version: -- Package-Requires: () -- Last-Updated: Sun Mar 1 17:25:40 2015 (+0100) -- By: Manuel Schneckenreither -- Update #: 2 -- URL: -- Doc URL: -- Keywords: -- Compatibility: -- -- -- Commentary: -- -- -- -- -- Change Log: -- -- -- -- -- -- -- -- Code: -- | TODO: comment this module module Data.ML.MisclassificationRate ( module Data.ML.MisclassificationRate.Ops ) where import Data.ML.MisclassificationRate.Ops -- -- MisclassificationRate.hs ends here
schnecki/HaskellMachineLearning
src/Data/ML/MisclassificationRate.hs
gpl-3.0
679
0
5
128
59
52
7
3
0
{-| Module : Bench Description : Benchmark of Multilinear library Copyright : (c) Artur M. Brodzki, 2018 License : BSD3 Maintainer : artur@brodzki.org Stability : experimental Portability : Windows/POSIX -} module Main ( main ) where import Criterion.Main import Criterion.Types import Multilinear.Generic.GPU import qualified Multilinear.Matrix as Matrix -- | Simple generator function for bencharking matrices gen :: Int -> Int -> Double gen j k = sin (fromIntegral j) + cos (fromIntegral k) -- | Generate benchmark of matrix multiplication sizedMatrixMultBench :: Int -- ^ size of square matrix to multiplicate -> Benchmark sizedMatrixMultBench s = bench (show s ++ "x" ++ show s) $ nf ((Matrix.fromIndices "ij" s s gen :: Tensor Double) *) (Matrix.fromIndices "jk" s s gen :: Tensor Double) -- | Generate benchmark of matrix addition sizedMatrixAddBench :: Int -- ^ size of square matrix to add -> Benchmark sizedMatrixAddBench s = bench (show s ++ "x" ++ show s) $ nf ((Matrix.fromIndices "ij" s s gen :: Tensor Double) +) (Matrix.fromIndices "ij" s s gen :: Tensor Double) -- | ENTRY POINT main :: IO () main = defaultMainWith defaultConfig { reportFile = Just "benchmark/gpu-bench.html"} [ bgroup "matrix addition" $ sizedMatrixAddBench <$> [64, 128, 256, 512, 1024], bgroup "matrix multiplication" $ sizedMatrixMultBench <$> [64, 128, 256, 512, 1024] ]
ArturB/Multilinear
benchmark/gpu/time/Bench.hs
gpl-3.0
1,485
0
10
338
354
191
163
24
1
{-# LANGUAGE TemplateHaskell #-} -- Copyright (C) 2010-2012 John Millikin <jmillikin@gmail.com> -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module DBusTests.Introspection (test_Introspection) where import Test.Chell import Test.Chell.QuickCheck import Test.QuickCheck hiding (property) import Control.Applicative ((<$>), (<*>)) import Control.Monad (liftM, liftM2) import DBus import qualified DBus.Introspection as Introspection import DBusTests.InterfaceName () import DBusTests.MemberName () import DBusTests.ObjectPath () import DBusTests.Signature () import DBusTests.Util (halfSized) test_Introspection :: Suite test_Introspection = suite "Introspection" test_XmlPassthrough test_XmlParse test_XmlParseFailed test_XmlWriteFailed test_XmlPassthrough :: Test test_XmlPassthrough = property "xml-passthrough" $ \obj -> let path = Introspection.objectPath obj Just xml = Introspection.formatXML obj in Introspection.parseXML path xml == Just obj test_XmlParse :: Test test_XmlParse = assertions "xml-parse" $ do -- root object path can be inferred $expect (equal (Introspection.parseXML (objectPath_ "/") "<node><node name='foo'/></node>") (Just (Introspection.object (objectPath_ "/")) { Introspection.objectChildren = [ Introspection.object (objectPath_ "/foo") ] } )) test_XmlParseFailed :: Test test_XmlParseFailed = assertions "xml-parse-failed" $ do $expect (nothing (Introspection.parseXML (objectPath_ "/") "<invalid>")) $expect (nothing (Introspection.parseXML (objectPath_ "/") "<invalid/>")) -- invalid property access $expect (nothing (Introspection.parseXML (objectPath_ "/") "<node>\ \ <interface name='com.example.Foo'>\ \ <property type='s' access='invalid'>\ \ </property>\ \ </interface>\ \</node>")) -- invalid parameter type $expect (nothing (Introspection.parseXML (objectPath_ "/") "<node>\ \ <interface name='com.example.Foo'>\ \ <method name='Foo'>\ \ <arg type='yy'/>\ \ </method>\ \ </interface>\ \</node>")) test_XmlWriteFailed :: Test test_XmlWriteFailed = assertions "xml-write-failed" $ do -- child's object path isn't under parent's $expect (nothing (Introspection.formatXML (Introspection.object (objectPath_ "/foo")) { Introspection.objectChildren = [ Introspection.object (objectPath_ "/bar") ] })) -- invalid type $expect (nothing (Introspection.formatXML (Introspection.object (objectPath_ "/foo")) { Introspection.objectInterfaces = [ (Introspection.interface (interfaceName_ "/bar")) { Introspection.interfaceProperties = [ Introspection.property "prop" (TypeDictionary TypeVariant TypeVariant) ] } ] })) instance Arbitrary Type where arbitrary = oneof [atom, container] where atom = elements [ TypeBoolean , TypeWord8 , TypeWord16 , TypeWord32 , TypeWord64 , TypeInt16 , TypeInt32 , TypeInt64 , TypeDouble , TypeString , TypeObjectPath , TypeSignature ] container = oneof [ return TypeVariant , liftM TypeArray arbitrary , liftM2 TypeDictionary atom arbitrary , liftM TypeStructure (listOf1 (halfSized arbitrary)) ] instance Arbitrary Introspection.Object where arbitrary = arbitrary >>= subObject subObject :: ObjectPath -> Gen Introspection.Object subObject parentPath = sized $ \n -> resize (min n 4) $ do let nonRoot = do x <- resize 10 arbitrary case formatObjectPath x of "/" -> nonRoot x' -> return x' thisPath <- nonRoot let path' = case formatObjectPath parentPath of "/" -> thisPath x -> x ++ thisPath let path = objectPath_ path' ifaces <- arbitrary children <- halfSized (listOf (subObject path)) return (Introspection.object path) { Introspection.objectInterfaces = ifaces , Introspection.objectChildren = children } instance Arbitrary Introspection.Interface where arbitrary = do name <- arbitrary methods <- arbitrary signals <- arbitrary properties <- arbitrary return (Introspection.interface name) { Introspection.interfaceMethods = methods , Introspection.interfaceSignals = signals , Introspection.interfaceProperties = properties } instance Arbitrary Introspection.Method where arbitrary = do name <- arbitrary args <- arbitrary return (Introspection.method name) { Introspection.methodArgs = args } instance Arbitrary Introspection.Signal where arbitrary = do name <- arbitrary args <- arbitrary return (Introspection.signal name) { Introspection.signalArgs = args } instance Arbitrary Introspection.MethodArg where arbitrary = Introspection.methodArg <$> gen_Ascii <*> arbitrary <*> arbitrary instance Arbitrary Introspection.Direction where arbitrary = elements [Introspection.directionIn, Introspection.directionOut] instance Arbitrary Introspection.SignalArg where arbitrary = Introspection.signalArg <$> gen_Ascii <*> arbitrary instance Arbitrary Introspection.Property where arbitrary = do name <- gen_Ascii t <- arbitrary canRead <- arbitrary canWrite <- arbitrary return (Introspection.property name t) { Introspection.propertyRead = canRead , Introspection.propertyWrite = canWrite } gen_Ascii :: Gen String gen_Ascii = listOf (elements ['!'..'~'])
tmishima/haskell-dbus
tests/DBusTests/Introspection.hs
gpl-3.0
5,946
81
21
1,106
1,413
731
682
133
3
module TownParser where import Text.Parsec import Control.Monad (liftM) import WorldParser (Coord, parseCoord) data TownData = TownData { name :: String } deriving (Show, Read) parseName :: Parsec String () String parseName = do n <- many anyChar return n parseTownData :: Parsec String () (Coord,TownData) parseTownData = do c <- parseCoord spaces string "Name" spaces n <- parseName return $ (c, TownData n) parseTownFile = do let contents = (liftM lines) $ readFile "inputTownParser.txt" f = liftM $ (mapM (parse parseTownData "source")) res <- f contents return res
maxwelljoslyn/DnDMapAndEcon
TownParser.hs
gpl-3.0
605
0
14
123
224
113
111
23
1
{-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- | -- Module : Network.Google.DFAReporting.Types.Sum -- Copyright : (c) 2015-2016 Brendan Hay -- License : Mozilla Public License, v. 2.0. -- Maintainer : Brendan Hay <brendan.g.hay@gmail.com> -- Stability : auto-generated -- Portability : non-portable (GHC extensions) -- module Network.Google.DFAReporting.Types.Sum where import Network.Google.Prelude hiding (Bytes) -- | Order of sorted results. data PlacementsListSortOrder = Ascending -- ^ @ASCENDING@ | Descending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementsListSortOrder instance FromHttpApiData PlacementsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right Ascending "DESCENDING" -> Right Descending x -> Left ("Unable to parse PlacementsListSortOrder from: " <> x) instance ToHttpApiData PlacementsListSortOrder where toQueryParam = \case Ascending -> "ASCENDING" Descending -> "DESCENDING" instance FromJSON PlacementsListSortOrder where parseJSON = parseJSONText "PlacementsListSortOrder" instance ToJSON PlacementsListSortOrder where toJSON = toJSONText -- | The date range relative to the date of when the report is run. data DateRangeRelativeDateRange = Today -- ^ @TODAY@ | Yesterday -- ^ @YESTERDAY@ | WeekToDate -- ^ @WEEK_TO_DATE@ | MonthToDate -- ^ @MONTH_TO_DATE@ | QuarterToDate -- ^ @QUARTER_TO_DATE@ | YearToDate -- ^ @YEAR_TO_DATE@ | PreviousWeek -- ^ @PREVIOUS_WEEK@ | PreviousMonth -- ^ @PREVIOUS_MONTH@ | PreviousQuarter -- ^ @PREVIOUS_QUARTER@ | PreviousYear -- ^ @PREVIOUS_YEAR@ | Last7Days -- ^ @LAST_7_DAYS@ | Last30Days -- ^ @LAST_30_DAYS@ | Last90Days -- ^ @LAST_90_DAYS@ | Last365Days -- ^ @LAST_365_DAYS@ | Last24Months -- ^ @LAST_24_MONTHS@ | Last14Days -- ^ @LAST_14_DAYS@ | Last60Days -- ^ @LAST_60_DAYS@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DateRangeRelativeDateRange instance FromHttpApiData DateRangeRelativeDateRange where parseQueryParam = \case "TODAY" -> Right Today "YESTERDAY" -> Right Yesterday "WEEK_TO_DATE" -> Right WeekToDate "MONTH_TO_DATE" -> Right MonthToDate "QUARTER_TO_DATE" -> Right QuarterToDate "YEAR_TO_DATE" -> Right YearToDate "PREVIOUS_WEEK" -> Right PreviousWeek "PREVIOUS_MONTH" -> Right PreviousMonth "PREVIOUS_QUARTER" -> Right PreviousQuarter "PREVIOUS_YEAR" -> Right PreviousYear "LAST_7_DAYS" -> Right Last7Days "LAST_30_DAYS" -> Right Last30Days "LAST_90_DAYS" -> Right Last90Days "LAST_365_DAYS" -> Right Last365Days "LAST_24_MONTHS" -> Right Last24Months "LAST_14_DAYS" -> Right Last14Days "LAST_60_DAYS" -> Right Last60Days x -> Left ("Unable to parse DateRangeRelativeDateRange from: " <> x) instance ToHttpApiData DateRangeRelativeDateRange where toQueryParam = \case Today -> "TODAY" Yesterday -> "YESTERDAY" WeekToDate -> "WEEK_TO_DATE" MonthToDate -> "MONTH_TO_DATE" QuarterToDate -> "QUARTER_TO_DATE" YearToDate -> "YEAR_TO_DATE" PreviousWeek -> "PREVIOUS_WEEK" PreviousMonth -> "PREVIOUS_MONTH" PreviousQuarter -> "PREVIOUS_QUARTER" PreviousYear -> "PREVIOUS_YEAR" Last7Days -> "LAST_7_DAYS" Last30Days -> "LAST_30_DAYS" Last90Days -> "LAST_90_DAYS" Last365Days -> "LAST_365_DAYS" Last24Months -> "LAST_24_MONTHS" Last14Days -> "LAST_14_DAYS" Last60Days -> "LAST_60_DAYS" instance FromJSON DateRangeRelativeDateRange where parseJSON = parseJSONText "DateRangeRelativeDateRange" instance ToJSON DateRangeRelativeDateRange where toJSON = toJSONText -- | Field by which to sort the list. data AdvertisersListSortField = ID -- ^ @ID@ | Name -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertisersListSortField instance FromHttpApiData AdvertisersListSortField where parseQueryParam = \case "ID" -> Right ID "NAME" -> Right Name x -> Left ("Unable to parse AdvertisersListSortField from: " <> x) instance ToHttpApiData AdvertisersListSortField where toQueryParam = \case ID -> "ID" Name -> "NAME" instance FromJSON AdvertisersListSortField where parseJSON = parseJSONText "AdvertisersListSortField" instance ToJSON AdvertisersListSortField where toJSON = toJSONText -- | Order of sorted results. data CreativeFieldsListSortOrder = CFLSOAscending -- ^ @ASCENDING@ | CFLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeFieldsListSortOrder instance FromHttpApiData CreativeFieldsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right CFLSOAscending "DESCENDING" -> Right CFLSODescending x -> Left ("Unable to parse CreativeFieldsListSortOrder from: " <> x) instance ToHttpApiData CreativeFieldsListSortOrder where toQueryParam = \case CFLSOAscending -> "ASCENDING" CFLSODescending -> "DESCENDING" instance FromJSON CreativeFieldsListSortOrder where parseJSON = parseJSONText "CreativeFieldsListSortOrder" instance ToJSON CreativeFieldsListSortOrder where toJSON = toJSONText -- | Order of sorted results. data TargetingTemplatesListSortOrder = TTLSOAscending -- ^ @ASCENDING@ | TTLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetingTemplatesListSortOrder instance FromHttpApiData TargetingTemplatesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right TTLSOAscending "DESCENDING" -> Right TTLSODescending x -> Left ("Unable to parse TargetingTemplatesListSortOrder from: " <> x) instance ToHttpApiData TargetingTemplatesListSortOrder where toQueryParam = \case TTLSOAscending -> "ASCENDING" TTLSODescending -> "DESCENDING" instance FromJSON TargetingTemplatesListSortOrder where parseJSON = parseJSONText "TargetingTemplatesListSortOrder" instance ToJSON TargetingTemplatesListSortOrder where toJSON = toJSONText -- | Order of sorted results. data AdvertiserLandingPagesListSortOrder = ALPLSOAscending -- ^ @ASCENDING@ | ALPLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertiserLandingPagesListSortOrder instance FromHttpApiData AdvertiserLandingPagesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right ALPLSOAscending "DESCENDING" -> Right ALPLSODescending x -> Left ("Unable to parse AdvertiserLandingPagesListSortOrder from: " <> x) instance ToHttpApiData AdvertiserLandingPagesListSortOrder where toQueryParam = \case ALPLSOAscending -> "ASCENDING" ALPLSODescending -> "DESCENDING" instance FromJSON AdvertiserLandingPagesListSortOrder where parseJSON = parseJSONText "AdvertiserLandingPagesListSortOrder" instance ToJSON AdvertiserLandingPagesListSortOrder where toJSON = toJSONText -- | Field by which to sort the list. data UserRolesListSortField = URLSFID -- ^ @ID@ | URLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable UserRolesListSortField instance FromHttpApiData UserRolesListSortField where parseQueryParam = \case "ID" -> Right URLSFID "NAME" -> Right URLSFName x -> Left ("Unable to parse UserRolesListSortField from: " <> x) instance ToHttpApiData UserRolesListSortField where toQueryParam = \case URLSFID -> "ID" URLSFName -> "NAME" instance FromJSON UserRolesListSortField where parseJSON = parseJSONText "UserRolesListSortField" instance ToJSON UserRolesListSortField where toJSON = toJSONText -- | Tag format type for the floodlight activity. If left blank, the tag -- format will default to HTML. data FloodlightActivityTagFormat = HTML -- ^ @HTML@ | Xhtml -- ^ @XHTML@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityTagFormat instance FromHttpApiData FloodlightActivityTagFormat where parseQueryParam = \case "HTML" -> Right HTML "XHTML" -> Right Xhtml x -> Left ("Unable to parse FloodlightActivityTagFormat from: " <> x) instance ToHttpApiData FloodlightActivityTagFormat where toQueryParam = \case HTML -> "HTML" Xhtml -> "XHTML" instance FromJSON FloodlightActivityTagFormat where parseJSON = parseJSONText "FloodlightActivityTagFormat" instance ToJSON FloodlightActivityTagFormat where toJSON = toJSONText -- | Order of sorted results. data OrderDocumentsListSortOrder = ODLSOAscending -- ^ @ASCENDING@ | ODLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OrderDocumentsListSortOrder instance FromHttpApiData OrderDocumentsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right ODLSOAscending "DESCENDING" -> Right ODLSODescending x -> Left ("Unable to parse OrderDocumentsListSortOrder from: " <> x) instance ToHttpApiData OrderDocumentsListSortOrder where toQueryParam = \case ODLSOAscending -> "ASCENDING" ODLSODescending -> "DESCENDING" instance FromJSON OrderDocumentsListSortOrder where parseJSON = parseJSONText "OrderDocumentsListSortOrder" instance ToJSON OrderDocumentsListSortOrder where toJSON = toJSONText -- | Role of the asset in relation to creative. Applicable to all but the -- following creative types: all REDIRECT and TRACKING_TEXT. This is a -- required field. PRIMARY applies to DISPLAY, FLASH_INPAGE, HTML5_BANNER, -- IMAGE, DISPLAY_IMAGE_GALLERY, all RICH_MEDIA (which may contain multiple -- primary assets), and all VPAID creatives. BACKUP_IMAGE applies to -- FLASH_INPAGE, HTML5_BANNER, all RICH_MEDIA, and all VPAID creatives. -- Applicable to DISPLAY when the primary asset type is not HTML_IMAGE. -- ADDITIONAL_IMAGE and ADDITIONAL_FLASH apply to FLASH_INPAGE creatives. -- OTHER refers to assets from sources other than Campaign Manager, such as -- Studio uploaded assets, applicable to all RICH_MEDIA and all VPAID -- creatives. PARENT_VIDEO refers to videos uploaded by the user in -- Campaign Manager and is applicable to INSTREAM_VIDEO and -- VPAID_LINEAR_VIDEO creatives. TRANSCODED_VIDEO refers to videos -- transcoded by Campaign Manager from PARENT_VIDEO assets and is -- applicable to INSTREAM_VIDEO and VPAID_LINEAR_VIDEO creatives. -- ALTERNATE_VIDEO refers to the Campaign Manager representation of child -- asset videos from Studio, and is applicable to VPAID_LINEAR_VIDEO -- creatives. These cannot be added or removed within Campaign Manager. For -- VPAID_LINEAR_VIDEO creatives, PARENT_VIDEO, TRANSCODED_VIDEO and -- ALTERNATE_VIDEO assets that are marked active serve as backup in case -- the VPAID creative cannot be served. Only PARENT_VIDEO assets can be -- added or removed for an INSTREAM_VIDEO or VPAID_LINEAR_VIDEO creative. -- PARENT_AUDIO refers to audios uploaded by the user in Campaign Manager -- and is applicable to INSTREAM_AUDIO creatives. TRANSCODED_AUDIO refers -- to audios transcoded by Campaign Manager from PARENT_AUDIO assets and is -- applicable to INSTREAM_AUDIO creatives. data CreativeAssetRole = Primary -- ^ @PRIMARY@ | BackupImage -- ^ @BACKUP_IMAGE@ | AdditionalImage -- ^ @ADDITIONAL_IMAGE@ | AdditionalFlash -- ^ @ADDITIONAL_FLASH@ | ParentVideo -- ^ @PARENT_VIDEO@ | TranscodedVideo -- ^ @TRANSCODED_VIDEO@ | Other -- ^ @OTHER@ | AlternateVideo -- ^ @ALTERNATE_VIDEO@ | ParentAudio -- ^ @PARENT_AUDIO@ | TranscodedAudio -- ^ @TRANSCODED_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetRole instance FromHttpApiData CreativeAssetRole where parseQueryParam = \case "PRIMARY" -> Right Primary "BACKUP_IMAGE" -> Right BackupImage "ADDITIONAL_IMAGE" -> Right AdditionalImage "ADDITIONAL_FLASH" -> Right AdditionalFlash "PARENT_VIDEO" -> Right ParentVideo "TRANSCODED_VIDEO" -> Right TranscodedVideo "OTHER" -> Right Other "ALTERNATE_VIDEO" -> Right AlternateVideo "PARENT_AUDIO" -> Right ParentAudio "TRANSCODED_AUDIO" -> Right TranscodedAudio x -> Left ("Unable to parse CreativeAssetRole from: " <> x) instance ToHttpApiData CreativeAssetRole where toQueryParam = \case Primary -> "PRIMARY" BackupImage -> "BACKUP_IMAGE" AdditionalImage -> "ADDITIONAL_IMAGE" AdditionalFlash -> "ADDITIONAL_FLASH" ParentVideo -> "PARENT_VIDEO" TranscodedVideo -> "TRANSCODED_VIDEO" Other -> "OTHER" AlternateVideo -> "ALTERNATE_VIDEO" ParentAudio -> "PARENT_AUDIO" TranscodedAudio -> "TRANSCODED_AUDIO" instance FromJSON CreativeAssetRole where parseJSON = parseJSONText "CreativeAssetRole" instance ToJSON CreativeAssetRole where toJSON = toJSONText -- | Select only dynamic targeting keys with this object type. data DynamicTargetingKeysListObjectType = ObjectAdvertiser -- ^ @OBJECT_ADVERTISER@ | ObjectAd -- ^ @OBJECT_AD@ | ObjectCreative -- ^ @OBJECT_CREATIVE@ | ObjectPlacement -- ^ @OBJECT_PLACEMENT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DynamicTargetingKeysListObjectType instance FromHttpApiData DynamicTargetingKeysListObjectType where parseQueryParam = \case "OBJECT_ADVERTISER" -> Right ObjectAdvertiser "OBJECT_AD" -> Right ObjectAd "OBJECT_CREATIVE" -> Right ObjectCreative "OBJECT_PLACEMENT" -> Right ObjectPlacement x -> Left ("Unable to parse DynamicTargetingKeysListObjectType from: " <> x) instance ToHttpApiData DynamicTargetingKeysListObjectType where toQueryParam = \case ObjectAdvertiser -> "OBJECT_ADVERTISER" ObjectAd -> "OBJECT_AD" ObjectCreative -> "OBJECT_CREATIVE" ObjectPlacement -> "OBJECT_PLACEMENT" instance FromJSON DynamicTargetingKeysListObjectType where parseJSON = parseJSONText "DynamicTargetingKeysListObjectType" instance ToJSON DynamicTargetingKeysListObjectType where toJSON = toJSONText -- | The delivery type for the recipient. data RecipientDeliveryType = Link -- ^ @LINK@ | Attachment -- ^ @ATTACHMENT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RecipientDeliveryType instance FromHttpApiData RecipientDeliveryType where parseQueryParam = \case "LINK" -> Right Link "ATTACHMENT" -> Right Attachment x -> Left ("Unable to parse RecipientDeliveryType from: " <> x) instance ToHttpApiData RecipientDeliveryType where toQueryParam = \case Link -> "LINK" Attachment -> "ATTACHMENT" instance FromJSON RecipientDeliveryType where parseJSON = parseJSONText "RecipientDeliveryType" instance ToJSON RecipientDeliveryType where toJSON = toJSONText -- | Third-party URL type for in-stream video and in-stream audio creatives. data ThirdPartyTrackingURLThirdPartyURLType = Impression -- ^ @IMPRESSION@ | ClickTracking -- ^ @CLICK_TRACKING@ | VideoStart -- ^ @VIDEO_START@ | VideoFirstQuartile -- ^ @VIDEO_FIRST_QUARTILE@ | VideoMidpoint -- ^ @VIDEO_MIDPOINT@ | VideoThirdQuartile -- ^ @VIDEO_THIRD_QUARTILE@ | VideoComplete -- ^ @VIDEO_COMPLETE@ | VideoMute -- ^ @VIDEO_MUTE@ | VideoPause -- ^ @VIDEO_PAUSE@ | VideoRewind -- ^ @VIDEO_REWIND@ | VideoFullscreen -- ^ @VIDEO_FULLSCREEN@ | VideoStop -- ^ @VIDEO_STOP@ | VideoCustom -- ^ @VIDEO_CUSTOM@ | Survey -- ^ @SURVEY@ | RichMediaImpression -- ^ @RICH_MEDIA_IMPRESSION@ | RichMediaRmImpression -- ^ @RICH_MEDIA_RM_IMPRESSION@ | RichMediaBackupImpression -- ^ @RICH_MEDIA_BACKUP_IMPRESSION@ | VideoSkip -- ^ @VIDEO_SKIP@ | VideoProgress -- ^ @VIDEO_PROGRESS@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ThirdPartyTrackingURLThirdPartyURLType instance FromHttpApiData ThirdPartyTrackingURLThirdPartyURLType where parseQueryParam = \case "IMPRESSION" -> Right Impression "CLICK_TRACKING" -> Right ClickTracking "VIDEO_START" -> Right VideoStart "VIDEO_FIRST_QUARTILE" -> Right VideoFirstQuartile "VIDEO_MIDPOINT" -> Right VideoMidpoint "VIDEO_THIRD_QUARTILE" -> Right VideoThirdQuartile "VIDEO_COMPLETE" -> Right VideoComplete "VIDEO_MUTE" -> Right VideoMute "VIDEO_PAUSE" -> Right VideoPause "VIDEO_REWIND" -> Right VideoRewind "VIDEO_FULLSCREEN" -> Right VideoFullscreen "VIDEO_STOP" -> Right VideoStop "VIDEO_CUSTOM" -> Right VideoCustom "SURVEY" -> Right Survey "RICH_MEDIA_IMPRESSION" -> Right RichMediaImpression "RICH_MEDIA_RM_IMPRESSION" -> Right RichMediaRmImpression "RICH_MEDIA_BACKUP_IMPRESSION" -> Right RichMediaBackupImpression "VIDEO_SKIP" -> Right VideoSkip "VIDEO_PROGRESS" -> Right VideoProgress x -> Left ("Unable to parse ThirdPartyTrackingURLThirdPartyURLType from: " <> x) instance ToHttpApiData ThirdPartyTrackingURLThirdPartyURLType where toQueryParam = \case Impression -> "IMPRESSION" ClickTracking -> "CLICK_TRACKING" VideoStart -> "VIDEO_START" VideoFirstQuartile -> "VIDEO_FIRST_QUARTILE" VideoMidpoint -> "VIDEO_MIDPOINT" VideoThirdQuartile -> "VIDEO_THIRD_QUARTILE" VideoComplete -> "VIDEO_COMPLETE" VideoMute -> "VIDEO_MUTE" VideoPause -> "VIDEO_PAUSE" VideoRewind -> "VIDEO_REWIND" VideoFullscreen -> "VIDEO_FULLSCREEN" VideoStop -> "VIDEO_STOP" VideoCustom -> "VIDEO_CUSTOM" Survey -> "SURVEY" RichMediaImpression -> "RICH_MEDIA_IMPRESSION" RichMediaRmImpression -> "RICH_MEDIA_RM_IMPRESSION" RichMediaBackupImpression -> "RICH_MEDIA_BACKUP_IMPRESSION" VideoSkip -> "VIDEO_SKIP" VideoProgress -> "VIDEO_PROGRESS" instance FromJSON ThirdPartyTrackingURLThirdPartyURLType where parseJSON = parseJSONText "ThirdPartyTrackingURLThirdPartyURLType" instance ToJSON ThirdPartyTrackingURLThirdPartyURLType where toJSON = toJSONText -- | Order of sorted results. data TargetableRemarketingListsListSortOrder = TRLLSOAscending -- ^ @ASCENDING@ | TRLLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetableRemarketingListsListSortOrder instance FromHttpApiData TargetableRemarketingListsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right TRLLSOAscending "DESCENDING" -> Right TRLLSODescending x -> Left ("Unable to parse TargetableRemarketingListsListSortOrder from: " <> x) instance ToHttpApiData TargetableRemarketingListsListSortOrder where toQueryParam = \case TRLLSOAscending -> "ASCENDING" TRLLSODescending -> "DESCENDING" instance FromJSON TargetableRemarketingListsListSortOrder where parseJSON = parseJSONText "TargetableRemarketingListsListSortOrder" instance ToJSON TargetableRemarketingListsListSortOrder where toJSON = toJSONText -- | Offset left unit for an asset. This is a read-only field. Applicable to -- the following creative types: all RICH_MEDIA. data CreativeAssetPositionLeftUnit = OffSetUnitPixel -- ^ @OFFSET_UNIT_PIXEL@ | OffSetUnitPercent -- ^ @OFFSET_UNIT_PERCENT@ | OffSetUnitPixelFromCenter -- ^ @OFFSET_UNIT_PIXEL_FROM_CENTER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetPositionLeftUnit instance FromHttpApiData CreativeAssetPositionLeftUnit where parseQueryParam = \case "OFFSET_UNIT_PIXEL" -> Right OffSetUnitPixel "OFFSET_UNIT_PERCENT" -> Right OffSetUnitPercent "OFFSET_UNIT_PIXEL_FROM_CENTER" -> Right OffSetUnitPixelFromCenter x -> Left ("Unable to parse CreativeAssetPositionLeftUnit from: " <> x) instance ToHttpApiData CreativeAssetPositionLeftUnit where toQueryParam = \case OffSetUnitPixel -> "OFFSET_UNIT_PIXEL" OffSetUnitPercent -> "OFFSET_UNIT_PERCENT" OffSetUnitPixelFromCenter -> "OFFSET_UNIT_PIXEL_FROM_CENTER" instance FromJSON CreativeAssetPositionLeftUnit where parseJSON = parseJSONText "CreativeAssetPositionLeftUnit" instance ToJSON CreativeAssetPositionLeftUnit where toJSON = toJSONText -- | Placement cap cost option. data PricingScheduleCapCostOption = CapCostNone -- ^ @CAP_COST_NONE@ | CapCostMonthly -- ^ @CAP_COST_MONTHLY@ | CapCostCumulative -- ^ @CAP_COST_CUMULATIVE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PricingScheduleCapCostOption instance FromHttpApiData PricingScheduleCapCostOption where parseQueryParam = \case "CAP_COST_NONE" -> Right CapCostNone "CAP_COST_MONTHLY" -> Right CapCostMonthly "CAP_COST_CUMULATIVE" -> Right CapCostCumulative x -> Left ("Unable to parse PricingScheduleCapCostOption from: " <> x) instance ToHttpApiData PricingScheduleCapCostOption where toQueryParam = \case CapCostNone -> "CAP_COST_NONE" CapCostMonthly -> "CAP_COST_MONTHLY" CapCostCumulative -> "CAP_COST_CUMULATIVE" instance FromJSON PricingScheduleCapCostOption where parseJSON = parseJSONText "PricingScheduleCapCostOption" instance ToJSON PricingScheduleCapCostOption where toJSON = toJSONText -- | Levels of availability for a user role permission. data UserRolePermissionAvailability = NotAvailableByDefault -- ^ @NOT_AVAILABLE_BY_DEFAULT@ | AccountByDefault -- ^ @ACCOUNT_BY_DEFAULT@ | SubAccountAndAccountByDefault -- ^ @SUBACCOUNT_AND_ACCOUNT_BY_DEFAULT@ | AccountAlways -- ^ @ACCOUNT_ALWAYS@ | SubAccountAndAccountAlways -- ^ @SUBACCOUNT_AND_ACCOUNT_ALWAYS@ | UserProFileOnly -- ^ @USER_PROFILE_ONLY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable UserRolePermissionAvailability instance FromHttpApiData UserRolePermissionAvailability where parseQueryParam = \case "NOT_AVAILABLE_BY_DEFAULT" -> Right NotAvailableByDefault "ACCOUNT_BY_DEFAULT" -> Right AccountByDefault "SUBACCOUNT_AND_ACCOUNT_BY_DEFAULT" -> Right SubAccountAndAccountByDefault "ACCOUNT_ALWAYS" -> Right AccountAlways "SUBACCOUNT_AND_ACCOUNT_ALWAYS" -> Right SubAccountAndAccountAlways "USER_PROFILE_ONLY" -> Right UserProFileOnly x -> Left ("Unable to parse UserRolePermissionAvailability from: " <> x) instance ToHttpApiData UserRolePermissionAvailability where toQueryParam = \case NotAvailableByDefault -> "NOT_AVAILABLE_BY_DEFAULT" AccountByDefault -> "ACCOUNT_BY_DEFAULT" SubAccountAndAccountByDefault -> "SUBACCOUNT_AND_ACCOUNT_BY_DEFAULT" AccountAlways -> "ACCOUNT_ALWAYS" SubAccountAndAccountAlways -> "SUBACCOUNT_AND_ACCOUNT_ALWAYS" UserProFileOnly -> "USER_PROFILE_ONLY" instance FromJSON UserRolePermissionAvailability where parseJSON = parseJSONText "UserRolePermissionAvailability" instance ToJSON UserRolePermissionAvailability where toJSON = toJSONText -- | VPAID adapter setting for this placement. Controls which VPAID format -- the measurement adapter will use for in-stream video creatives assigned -- to this placement. *Note:* Flash is no longer supported. This field now -- defaults to HTML5 when the following values are provided: FLASH, BOTH. data PlacementVpaidAdapterChoice = Default -- ^ @DEFAULT@ | Flash -- ^ @FLASH@ | HTML5 -- ^ @HTML5@ | Both -- ^ @BOTH@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementVpaidAdapterChoice instance FromHttpApiData PlacementVpaidAdapterChoice where parseQueryParam = \case "DEFAULT" -> Right Default "FLASH" -> Right Flash "HTML5" -> Right HTML5 "BOTH" -> Right Both x -> Left ("Unable to parse PlacementVpaidAdapterChoice from: " <> x) instance ToHttpApiData PlacementVpaidAdapterChoice where toQueryParam = \case Default -> "DEFAULT" Flash -> "FLASH" HTML5 -> "HTML5" Both -> "BOTH" instance FromJSON PlacementVpaidAdapterChoice where parseJSON = parseJSONText "PlacementVpaidAdapterChoice" instance ToJSON PlacementVpaidAdapterChoice where toJSON = toJSONText -- | Placement compatibility. DISPLAY and DISPLAY_INTERSTITIAL refer to -- rendering on desktop, on mobile devices or in mobile apps for regular or -- interstitial ads respectively. APP and APP_INTERSTITIAL are no longer -- allowed for new placement insertions. Instead, use DISPLAY or -- DISPLAY_INTERSTITIAL. IN_STREAM_VIDEO refers to rendering in in-stream -- video ads developed with the VAST standard. This field is required on -- insertion. data PlacementCompatibility = Display -- ^ @DISPLAY@ | DisplayInterstitial -- ^ @DISPLAY_INTERSTITIAL@ | App -- ^ @APP@ | AppInterstitial -- ^ @APP_INTERSTITIAL@ | InStreamVideo -- ^ @IN_STREAM_VIDEO@ | InStreamAudio -- ^ @IN_STREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementCompatibility instance FromHttpApiData PlacementCompatibility where parseQueryParam = \case "DISPLAY" -> Right Display "DISPLAY_INTERSTITIAL" -> Right DisplayInterstitial "APP" -> Right App "APP_INTERSTITIAL" -> Right AppInterstitial "IN_STREAM_VIDEO" -> Right InStreamVideo "IN_STREAM_AUDIO" -> Right InStreamAudio x -> Left ("Unable to parse PlacementCompatibility from: " <> x) instance ToHttpApiData PlacementCompatibility where toQueryParam = \case Display -> "DISPLAY" DisplayInterstitial -> "DISPLAY_INTERSTITIAL" App -> "APP" AppInterstitial -> "APP_INTERSTITIAL" InStreamVideo -> "IN_STREAM_VIDEO" InStreamAudio -> "IN_STREAM_AUDIO" instance FromJSON PlacementCompatibility where parseJSON = parseJSONText "PlacementCompatibility" instance ToJSON PlacementCompatibility where toJSON = toJSONText -- | Comparison operator of this term. This field is only relevant when type -- is left unset or set to CUSTOM_VARIABLE_TERM or REFERRER_TERM. data ListPopulationTermOperator = NumEquals -- ^ @NUM_EQUALS@ | NumLessThan -- ^ @NUM_LESS_THAN@ | NumLessThanEqual -- ^ @NUM_LESS_THAN_EQUAL@ | NumGreaterThan -- ^ @NUM_GREATER_THAN@ | NumGreaterThanEqual -- ^ @NUM_GREATER_THAN_EQUAL@ | StringEquals -- ^ @STRING_EQUALS@ | StringContains -- ^ @STRING_CONTAINS@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ListPopulationTermOperator instance FromHttpApiData ListPopulationTermOperator where parseQueryParam = \case "NUM_EQUALS" -> Right NumEquals "NUM_LESS_THAN" -> Right NumLessThan "NUM_LESS_THAN_EQUAL" -> Right NumLessThanEqual "NUM_GREATER_THAN" -> Right NumGreaterThan "NUM_GREATER_THAN_EQUAL" -> Right NumGreaterThanEqual "STRING_EQUALS" -> Right StringEquals "STRING_CONTAINS" -> Right StringContains x -> Left ("Unable to parse ListPopulationTermOperator from: " <> x) instance ToHttpApiData ListPopulationTermOperator where toQueryParam = \case NumEquals -> "NUM_EQUALS" NumLessThan -> "NUM_LESS_THAN" NumLessThanEqual -> "NUM_LESS_THAN_EQUAL" NumGreaterThan -> "NUM_GREATER_THAN" NumGreaterThanEqual -> "NUM_GREATER_THAN_EQUAL" StringEquals -> "STRING_EQUALS" StringContains -> "STRING_CONTAINS" instance FromJSON ListPopulationTermOperator where parseJSON = parseJSONText "ListPopulationTermOperator" instance ToJSON ListPopulationTermOperator where toJSON = toJSONText -- | Select only placements with this payment source. data PlacementsListPaymentSource = PlacementAgencyPaid -- ^ @PLACEMENT_AGENCY_PAID@ | PlacementPublisherPaid -- ^ @PLACEMENT_PUBLISHER_PAID@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementsListPaymentSource instance FromHttpApiData PlacementsListPaymentSource where parseQueryParam = \case "PLACEMENT_AGENCY_PAID" -> Right PlacementAgencyPaid "PLACEMENT_PUBLISHER_PAID" -> Right PlacementPublisherPaid x -> Left ("Unable to parse PlacementsListPaymentSource from: " <> x) instance ToHttpApiData PlacementsListPaymentSource where toQueryParam = \case PlacementAgencyPaid -> "PLACEMENT_AGENCY_PAID" PlacementPublisherPaid -> "PLACEMENT_PUBLISHER_PAID" instance FromJSON PlacementsListPaymentSource where parseJSON = parseJSONText "PlacementsListPaymentSource" instance ToJSON PlacementsListPaymentSource where toJSON = toJSONText -- | The field by which to sort the list. data ReportsListSortField = RLSFID -- ^ @ID@ -- Sort by report ID. | RLSFLastModifiedTime -- ^ @LAST_MODIFIED_TIME@ -- Sort by \'lastModifiedTime\' field. | RLSFName -- ^ @NAME@ -- Sort by name of reports. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportsListSortField instance FromHttpApiData ReportsListSortField where parseQueryParam = \case "ID" -> Right RLSFID "LAST_MODIFIED_TIME" -> Right RLSFLastModifiedTime "NAME" -> Right RLSFName x -> Left ("Unable to parse ReportsListSortField from: " <> x) instance ToHttpApiData ReportsListSortField where toQueryParam = \case RLSFID -> "ID" RLSFLastModifiedTime -> "LAST_MODIFIED_TIME" RLSFName -> "NAME" instance FromJSON ReportsListSortField where parseJSON = parseJSONText "ReportsListSortField" instance ToJSON ReportsListSortField where toJSON = toJSONText -- | Ad slot compatibility. DISPLAY and DISPLAY_INTERSTITIAL refer to -- rendering either on desktop, mobile devices or in mobile apps for -- regular or interstitial ads respectively. APP and APP_INTERSTITIAL are -- for rendering in mobile apps. IN_STREAM_VIDEO refers to rendering in -- in-stream video ads developed with the VAST standard. data AdSlotCompatibility = ASCDisplay -- ^ @DISPLAY@ | ASCDisplayInterstitial -- ^ @DISPLAY_INTERSTITIAL@ | ASCApp -- ^ @APP@ | ASCAppInterstitial -- ^ @APP_INTERSTITIAL@ | ASCInStreamVideo -- ^ @IN_STREAM_VIDEO@ | ASCInStreamAudio -- ^ @IN_STREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdSlotCompatibility instance FromHttpApiData AdSlotCompatibility where parseQueryParam = \case "DISPLAY" -> Right ASCDisplay "DISPLAY_INTERSTITIAL" -> Right ASCDisplayInterstitial "APP" -> Right ASCApp "APP_INTERSTITIAL" -> Right ASCAppInterstitial "IN_STREAM_VIDEO" -> Right ASCInStreamVideo "IN_STREAM_AUDIO" -> Right ASCInStreamAudio x -> Left ("Unable to parse AdSlotCompatibility from: " <> x) instance ToHttpApiData AdSlotCompatibility where toQueryParam = \case ASCDisplay -> "DISPLAY" ASCDisplayInterstitial -> "DISPLAY_INTERSTITIAL" ASCApp -> "APP" ASCAppInterstitial -> "APP_INTERSTITIAL" ASCInStreamVideo -> "IN_STREAM_VIDEO" ASCInStreamAudio -> "IN_STREAM_AUDIO" instance FromJSON AdSlotCompatibility where parseJSON = parseJSONText "AdSlotCompatibility" instance ToJSON AdSlotCompatibility where toJSON = toJSONText -- | Field by which to sort the list. data CampaignsListSortField = CLSFID -- ^ @ID@ | CLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CampaignsListSortField instance FromHttpApiData CampaignsListSortField where parseQueryParam = \case "ID" -> Right CLSFID "NAME" -> Right CLSFName x -> Left ("Unable to parse CampaignsListSortField from: " <> x) instance ToHttpApiData CampaignsListSortField where toQueryParam = \case CLSFID -> "ID" CLSFName -> "NAME" instance FromJSON CampaignsListSortField where parseJSON = parseJSONText "CampaignsListSortField" instance ToJSON CampaignsListSortField where toJSON = toJSONText -- | Orientation of a video placement. If this value is set, placement will -- return assets matching the specified orientation. data VideoSettingsOrientation = Any -- ^ @ANY@ | Landscape -- ^ @LANDSCAPE@ | Portrait -- ^ @PORTRAIT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable VideoSettingsOrientation instance FromHttpApiData VideoSettingsOrientation where parseQueryParam = \case "ANY" -> Right Any "LANDSCAPE" -> Right Landscape "PORTRAIT" -> Right Portrait x -> Left ("Unable to parse VideoSettingsOrientation from: " <> x) instance ToHttpApiData VideoSettingsOrientation where toQueryParam = \case Any -> "ANY" Landscape -> "LANDSCAPE" Portrait -> "PORTRAIT" instance FromJSON VideoSettingsOrientation where parseJSON = parseJSONText "VideoSettingsOrientation" instance ToJSON VideoSettingsOrientation where toJSON = toJSONText -- | Trafficker type of this user profile. This is a read-only field. data AccountUserProFileTraffickerType = InternalNonTrafficker -- ^ @INTERNAL_NON_TRAFFICKER@ | InternalTrafficker -- ^ @INTERNAL_TRAFFICKER@ | ExternalTrafficker -- ^ @EXTERNAL_TRAFFICKER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountUserProFileTraffickerType instance FromHttpApiData AccountUserProFileTraffickerType where parseQueryParam = \case "INTERNAL_NON_TRAFFICKER" -> Right InternalNonTrafficker "INTERNAL_TRAFFICKER" -> Right InternalTrafficker "EXTERNAL_TRAFFICKER" -> Right ExternalTrafficker x -> Left ("Unable to parse AccountUserProFileTraffickerType from: " <> x) instance ToHttpApiData AccountUserProFileTraffickerType where toQueryParam = \case InternalNonTrafficker -> "INTERNAL_NON_TRAFFICKER" InternalTrafficker -> "INTERNAL_TRAFFICKER" ExternalTrafficker -> "EXTERNAL_TRAFFICKER" instance FromJSON AccountUserProFileTraffickerType where parseJSON = parseJSONText "AccountUserProFileTraffickerType" instance ToJSON AccountUserProFileTraffickerType where toJSON = toJSONText data CreativeAssetMetadataDetectedFeaturesItem = CssFontFace -- ^ @CSS_FONT_FACE@ | CssBackgRoundSize -- ^ @CSS_BACKGROUND_SIZE@ | CssBOrderImage -- ^ @CSS_BORDER_IMAGE@ | CssBOrderRadius -- ^ @CSS_BORDER_RADIUS@ | CssBoxShadow -- ^ @CSS_BOX_SHADOW@ | CssFlexBox -- ^ @CSS_FLEX_BOX@ | CssHsla -- ^ @CSS_HSLA@ | CssMultipleBgs -- ^ @CSS_MULTIPLE_BGS@ | CssOpacity -- ^ @CSS_OPACITY@ | CssRgba -- ^ @CSS_RGBA@ | CssTextShadow -- ^ @CSS_TEXT_SHADOW@ | CssAnimations -- ^ @CSS_ANIMATIONS@ | CssColumns -- ^ @CSS_COLUMNS@ | CssGeneratedContent -- ^ @CSS_GENERATED_CONTENT@ | CssGradients -- ^ @CSS_GRADIENTS@ | CssReflections -- ^ @CSS_REFLECTIONS@ | CssTransforms -- ^ @CSS_TRANSFORMS@ | CssTRANSFORMS3D -- ^ @CSS_TRANSFORMS3D@ | CssTransitions -- ^ @CSS_TRANSITIONS@ | ApplicationCache -- ^ @APPLICATION_CACHE@ | Canvas -- ^ @CANVAS@ | CanvasText -- ^ @CANVAS_TEXT@ | DragAndDrop -- ^ @DRAG_AND_DROP@ | HashChange -- ^ @HASH_CHANGE@ | History -- ^ @HISTORY@ | Audio -- ^ @AUDIO@ | Video -- ^ @VIDEO@ | IndexedDB -- ^ @INDEXED_DB@ | InputAttrAutocomplete -- ^ @INPUT_ATTR_AUTOCOMPLETE@ | InputAttrAutofocus -- ^ @INPUT_ATTR_AUTOFOCUS@ | InputAttrList -- ^ @INPUT_ATTR_LIST@ | InputAttrPlaceholder -- ^ @INPUT_ATTR_PLACEHOLDER@ | InputAttrMax -- ^ @INPUT_ATTR_MAX@ | InputAttrMin -- ^ @INPUT_ATTR_MIN@ | InputAttrMultiple -- ^ @INPUT_ATTR_MULTIPLE@ | InputAttrPattern -- ^ @INPUT_ATTR_PATTERN@ | InputAttrRequired -- ^ @INPUT_ATTR_REQUIRED@ | InputAttrStep -- ^ @INPUT_ATTR_STEP@ | InputTypeSearch -- ^ @INPUT_TYPE_SEARCH@ | InputTypeTel -- ^ @INPUT_TYPE_TEL@ | InputTypeURL -- ^ @INPUT_TYPE_URL@ | InputTypeEmail -- ^ @INPUT_TYPE_EMAIL@ | InputTypeDatetime -- ^ @INPUT_TYPE_DATETIME@ | InputTypeDate -- ^ @INPUT_TYPE_DATE@ | InputTypeMonth -- ^ @INPUT_TYPE_MONTH@ | InputTypeWeek -- ^ @INPUT_TYPE_WEEK@ | InputTypeTime -- ^ @INPUT_TYPE_TIME@ | InputTypeDatetimeLocal -- ^ @INPUT_TYPE_DATETIME_LOCAL@ | InputTypeNumber -- ^ @INPUT_TYPE_NUMBER@ | InputTypeRange -- ^ @INPUT_TYPE_RANGE@ | InputTypeColor -- ^ @INPUT_TYPE_COLOR@ | LocalStorage -- ^ @LOCAL_STORAGE@ | PostMessage -- ^ @POST_MESSAGE@ | SessionStorage -- ^ @SESSION_STORAGE@ | WebSockets -- ^ @WEB_SOCKETS@ | WebSQLDatabase -- ^ @WEB_SQL_DATABASE@ | WebWorkers -- ^ @WEB_WORKERS@ | GeoLocation -- ^ @GEO_LOCATION@ | InlineSvg -- ^ @INLINE_SVG@ | Smil -- ^ @SMIL@ | SvgHref -- ^ @SVG_HREF@ | SvgClipPaths -- ^ @SVG_CLIP_PATHS@ | Touch -- ^ @TOUCH@ | Webgl -- ^ @WEBGL@ | SvgFilters -- ^ @SVG_FILTERS@ | SvgFeImage -- ^ @SVG_FE_IMAGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetMetadataDetectedFeaturesItem instance FromHttpApiData CreativeAssetMetadataDetectedFeaturesItem where parseQueryParam = \case "CSS_FONT_FACE" -> Right CssFontFace "CSS_BACKGROUND_SIZE" -> Right CssBackgRoundSize "CSS_BORDER_IMAGE" -> Right CssBOrderImage "CSS_BORDER_RADIUS" -> Right CssBOrderRadius "CSS_BOX_SHADOW" -> Right CssBoxShadow "CSS_FLEX_BOX" -> Right CssFlexBox "CSS_HSLA" -> Right CssHsla "CSS_MULTIPLE_BGS" -> Right CssMultipleBgs "CSS_OPACITY" -> Right CssOpacity "CSS_RGBA" -> Right CssRgba "CSS_TEXT_SHADOW" -> Right CssTextShadow "CSS_ANIMATIONS" -> Right CssAnimations "CSS_COLUMNS" -> Right CssColumns "CSS_GENERATED_CONTENT" -> Right CssGeneratedContent "CSS_GRADIENTS" -> Right CssGradients "CSS_REFLECTIONS" -> Right CssReflections "CSS_TRANSFORMS" -> Right CssTransforms "CSS_TRANSFORMS3D" -> Right CssTRANSFORMS3D "CSS_TRANSITIONS" -> Right CssTransitions "APPLICATION_CACHE" -> Right ApplicationCache "CANVAS" -> Right Canvas "CANVAS_TEXT" -> Right CanvasText "DRAG_AND_DROP" -> Right DragAndDrop "HASH_CHANGE" -> Right HashChange "HISTORY" -> Right History "AUDIO" -> Right Audio "VIDEO" -> Right Video "INDEXED_DB" -> Right IndexedDB "INPUT_ATTR_AUTOCOMPLETE" -> Right InputAttrAutocomplete "INPUT_ATTR_AUTOFOCUS" -> Right InputAttrAutofocus "INPUT_ATTR_LIST" -> Right InputAttrList "INPUT_ATTR_PLACEHOLDER" -> Right InputAttrPlaceholder "INPUT_ATTR_MAX" -> Right InputAttrMax "INPUT_ATTR_MIN" -> Right InputAttrMin "INPUT_ATTR_MULTIPLE" -> Right InputAttrMultiple "INPUT_ATTR_PATTERN" -> Right InputAttrPattern "INPUT_ATTR_REQUIRED" -> Right InputAttrRequired "INPUT_ATTR_STEP" -> Right InputAttrStep "INPUT_TYPE_SEARCH" -> Right InputTypeSearch "INPUT_TYPE_TEL" -> Right InputTypeTel "INPUT_TYPE_URL" -> Right InputTypeURL "INPUT_TYPE_EMAIL" -> Right InputTypeEmail "INPUT_TYPE_DATETIME" -> Right InputTypeDatetime "INPUT_TYPE_DATE" -> Right InputTypeDate "INPUT_TYPE_MONTH" -> Right InputTypeMonth "INPUT_TYPE_WEEK" -> Right InputTypeWeek "INPUT_TYPE_TIME" -> Right InputTypeTime "INPUT_TYPE_DATETIME_LOCAL" -> Right InputTypeDatetimeLocal "INPUT_TYPE_NUMBER" -> Right InputTypeNumber "INPUT_TYPE_RANGE" -> Right InputTypeRange "INPUT_TYPE_COLOR" -> Right InputTypeColor "LOCAL_STORAGE" -> Right LocalStorage "POST_MESSAGE" -> Right PostMessage "SESSION_STORAGE" -> Right SessionStorage "WEB_SOCKETS" -> Right WebSockets "WEB_SQL_DATABASE" -> Right WebSQLDatabase "WEB_WORKERS" -> Right WebWorkers "GEO_LOCATION" -> Right GeoLocation "INLINE_SVG" -> Right InlineSvg "SMIL" -> Right Smil "SVG_HREF" -> Right SvgHref "SVG_CLIP_PATHS" -> Right SvgClipPaths "TOUCH" -> Right Touch "WEBGL" -> Right Webgl "SVG_FILTERS" -> Right SvgFilters "SVG_FE_IMAGE" -> Right SvgFeImage x -> Left ("Unable to parse CreativeAssetMetadataDetectedFeaturesItem from: " <> x) instance ToHttpApiData CreativeAssetMetadataDetectedFeaturesItem where toQueryParam = \case CssFontFace -> "CSS_FONT_FACE" CssBackgRoundSize -> "CSS_BACKGROUND_SIZE" CssBOrderImage -> "CSS_BORDER_IMAGE" CssBOrderRadius -> "CSS_BORDER_RADIUS" CssBoxShadow -> "CSS_BOX_SHADOW" CssFlexBox -> "CSS_FLEX_BOX" CssHsla -> "CSS_HSLA" CssMultipleBgs -> "CSS_MULTIPLE_BGS" CssOpacity -> "CSS_OPACITY" CssRgba -> "CSS_RGBA" CssTextShadow -> "CSS_TEXT_SHADOW" CssAnimations -> "CSS_ANIMATIONS" CssColumns -> "CSS_COLUMNS" CssGeneratedContent -> "CSS_GENERATED_CONTENT" CssGradients -> "CSS_GRADIENTS" CssReflections -> "CSS_REFLECTIONS" CssTransforms -> "CSS_TRANSFORMS" CssTRANSFORMS3D -> "CSS_TRANSFORMS3D" CssTransitions -> "CSS_TRANSITIONS" ApplicationCache -> "APPLICATION_CACHE" Canvas -> "CANVAS" CanvasText -> "CANVAS_TEXT" DragAndDrop -> "DRAG_AND_DROP" HashChange -> "HASH_CHANGE" History -> "HISTORY" Audio -> "AUDIO" Video -> "VIDEO" IndexedDB -> "INDEXED_DB" InputAttrAutocomplete -> "INPUT_ATTR_AUTOCOMPLETE" InputAttrAutofocus -> "INPUT_ATTR_AUTOFOCUS" InputAttrList -> "INPUT_ATTR_LIST" InputAttrPlaceholder -> "INPUT_ATTR_PLACEHOLDER" InputAttrMax -> "INPUT_ATTR_MAX" InputAttrMin -> "INPUT_ATTR_MIN" InputAttrMultiple -> "INPUT_ATTR_MULTIPLE" InputAttrPattern -> "INPUT_ATTR_PATTERN" InputAttrRequired -> "INPUT_ATTR_REQUIRED" InputAttrStep -> "INPUT_ATTR_STEP" InputTypeSearch -> "INPUT_TYPE_SEARCH" InputTypeTel -> "INPUT_TYPE_TEL" InputTypeURL -> "INPUT_TYPE_URL" InputTypeEmail -> "INPUT_TYPE_EMAIL" InputTypeDatetime -> "INPUT_TYPE_DATETIME" InputTypeDate -> "INPUT_TYPE_DATE" InputTypeMonth -> "INPUT_TYPE_MONTH" InputTypeWeek -> "INPUT_TYPE_WEEK" InputTypeTime -> "INPUT_TYPE_TIME" InputTypeDatetimeLocal -> "INPUT_TYPE_DATETIME_LOCAL" InputTypeNumber -> "INPUT_TYPE_NUMBER" InputTypeRange -> "INPUT_TYPE_RANGE" InputTypeColor -> "INPUT_TYPE_COLOR" LocalStorage -> "LOCAL_STORAGE" PostMessage -> "POST_MESSAGE" SessionStorage -> "SESSION_STORAGE" WebSockets -> "WEB_SOCKETS" WebSQLDatabase -> "WEB_SQL_DATABASE" WebWorkers -> "WEB_WORKERS" GeoLocation -> "GEO_LOCATION" InlineSvg -> "INLINE_SVG" Smil -> "SMIL" SvgHref -> "SVG_HREF" SvgClipPaths -> "SVG_CLIP_PATHS" Touch -> "TOUCH" Webgl -> "WEBGL" SvgFilters -> "SVG_FILTERS" SvgFeImage -> "SVG_FE_IMAGE" instance FromJSON CreativeAssetMetadataDetectedFeaturesItem where parseJSON = parseJSONText "CreativeAssetMetadataDetectedFeaturesItem" instance ToJSON CreativeAssetMetadataDetectedFeaturesItem where toJSON = toJSONText -- | Select default ads with the specified compatibility. Applicable when -- type is AD_SERVING_DEFAULT_AD. DISPLAY and DISPLAY_INTERSTITIAL refer to -- rendering either on desktop or on mobile devices for regular or -- interstitial ads, respectively. APP and APP_INTERSTITIAL are for -- rendering in mobile apps. IN_STREAM_VIDEO refers to rendering an -- in-stream video ads developed with the VAST standard. data AdsListCompatibility = ALCDisplay -- ^ @DISPLAY@ | ALCDisplayInterstitial -- ^ @DISPLAY_INTERSTITIAL@ | ALCApp -- ^ @APP@ | ALCAppInterstitial -- ^ @APP_INTERSTITIAL@ | ALCInStreamVideo -- ^ @IN_STREAM_VIDEO@ | ALCInStreamAudio -- ^ @IN_STREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdsListCompatibility instance FromHttpApiData AdsListCompatibility where parseQueryParam = \case "DISPLAY" -> Right ALCDisplay "DISPLAY_INTERSTITIAL" -> Right ALCDisplayInterstitial "APP" -> Right ALCApp "APP_INTERSTITIAL" -> Right ALCAppInterstitial "IN_STREAM_VIDEO" -> Right ALCInStreamVideo "IN_STREAM_AUDIO" -> Right ALCInStreamAudio x -> Left ("Unable to parse AdsListCompatibility from: " <> x) instance ToHttpApiData AdsListCompatibility where toQueryParam = \case ALCDisplay -> "DISPLAY" ALCDisplayInterstitial -> "DISPLAY_INTERSTITIAL" ALCApp -> "APP" ALCAppInterstitial -> "APP_INTERSTITIAL" ALCInStreamVideo -> "IN_STREAM_VIDEO" ALCInStreamAudio -> "IN_STREAM_AUDIO" instance FromJSON AdsListCompatibility where parseJSON = parseJSONText "AdsListCompatibility" instance ToJSON AdsListCompatibility where toJSON = toJSONText -- | Status of this event tag. Must be ENABLED for this event tag to fire. -- This is a required field. data EventTagStatus = Enabled -- ^ @ENABLED@ | Disabled -- ^ @DISABLED@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EventTagStatus instance FromHttpApiData EventTagStatus where parseQueryParam = \case "ENABLED" -> Right Enabled "DISABLED" -> Right Disabled x -> Left ("Unable to parse EventTagStatus from: " <> x) instance ToHttpApiData EventTagStatus where toQueryParam = \case Enabled -> "ENABLED" Disabled -> "DISABLED" instance FromJSON EventTagStatus where parseJSON = parseJSONText "EventTagStatus" instance ToJSON EventTagStatus where toJSON = toJSONText -- | Field by which to sort the list. data SitesListSortField = SLSFID -- ^ @ID@ | SLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SitesListSortField instance FromHttpApiData SitesListSortField where parseQueryParam = \case "ID" -> Right SLSFID "NAME" -> Right SLSFName x -> Left ("Unable to parse SitesListSortField from: " <> x) instance ToHttpApiData SitesListSortField where toQueryParam = \case SLSFID -> "ID" SLSFName -> "NAME" instance FromJSON SitesListSortField where parseJSON = parseJSONText "SitesListSortField" instance ToJSON SitesListSortField where toJSON = toJSONText -- | Select only event tags with the specified event tag types. Event tag -- types can be used to specify whether to use a third-party pixel, a -- third-party JavaScript URL, or a third-party click-through URL for -- either impression or click tracking. data EventTagsListEventTagTypes = ImpressionImageEventTag -- ^ @IMPRESSION_IMAGE_EVENT_TAG@ | ImpressionJavascriptEventTag -- ^ @IMPRESSION_JAVASCRIPT_EVENT_TAG@ | ClickThroughEventTag -- ^ @CLICK_THROUGH_EVENT_TAG@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EventTagsListEventTagTypes instance FromHttpApiData EventTagsListEventTagTypes where parseQueryParam = \case "IMPRESSION_IMAGE_EVENT_TAG" -> Right ImpressionImageEventTag "IMPRESSION_JAVASCRIPT_EVENT_TAG" -> Right ImpressionJavascriptEventTag "CLICK_THROUGH_EVENT_TAG" -> Right ClickThroughEventTag x -> Left ("Unable to parse EventTagsListEventTagTypes from: " <> x) instance ToHttpApiData EventTagsListEventTagTypes where toQueryParam = \case ImpressionImageEventTag -> "IMPRESSION_IMAGE_EVENT_TAG" ImpressionJavascriptEventTag -> "IMPRESSION_JAVASCRIPT_EVENT_TAG" ClickThroughEventTag -> "CLICK_THROUGH_EVENT_TAG" instance FromJSON EventTagsListEventTagTypes where parseJSON = parseJSONText "EventTagsListEventTagTypes" instance ToJSON EventTagsListEventTagTypes where toJSON = toJSONText -- | The status of the report file. data FileStatus = Processing -- ^ @PROCESSING@ | ReportAvailable -- ^ @REPORT_AVAILABLE@ | Failed -- ^ @FAILED@ | Cancelled -- ^ @CANCELLED@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FileStatus instance FromHttpApiData FileStatus where parseQueryParam = \case "PROCESSING" -> Right Processing "REPORT_AVAILABLE" -> Right ReportAvailable "FAILED" -> Right Failed "CANCELLED" -> Right Cancelled x -> Left ("Unable to parse FileStatus from: " <> x) instance ToHttpApiData FileStatus where toQueryParam = \case Processing -> "PROCESSING" ReportAvailable -> "REPORT_AVAILABLE" Failed -> "FAILED" Cancelled -> "CANCELLED" instance FromJSON FileStatus where parseJSON = parseJSONText "FileStatus" instance ToJSON FileStatus where toJSON = toJSONText -- | Artwork type used by the creative.This is a read-only field. data CreativeCustomEventArtworkType = ArtworkTypeFlash -- ^ @ARTWORK_TYPE_FLASH@ | ArtworkTypeHTML5 -- ^ @ARTWORK_TYPE_HTML5@ | ArtworkTypeMixed -- ^ @ARTWORK_TYPE_MIXED@ | ArtworkTypeImage -- ^ @ARTWORK_TYPE_IMAGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeCustomEventArtworkType instance FromHttpApiData CreativeCustomEventArtworkType where parseQueryParam = \case "ARTWORK_TYPE_FLASH" -> Right ArtworkTypeFlash "ARTWORK_TYPE_HTML5" -> Right ArtworkTypeHTML5 "ARTWORK_TYPE_MIXED" -> Right ArtworkTypeMixed "ARTWORK_TYPE_IMAGE" -> Right ArtworkTypeImage x -> Left ("Unable to parse CreativeCustomEventArtworkType from: " <> x) instance ToHttpApiData CreativeCustomEventArtworkType where toQueryParam = \case ArtworkTypeFlash -> "ARTWORK_TYPE_FLASH" ArtworkTypeHTML5 -> "ARTWORK_TYPE_HTML5" ArtworkTypeMixed -> "ARTWORK_TYPE_MIXED" ArtworkTypeImage -> "ARTWORK_TYPE_IMAGE" instance FromJSON CreativeCustomEventArtworkType where parseJSON = parseJSONText "CreativeCustomEventArtworkType" instance ToJSON CreativeCustomEventArtworkType where toJSON = toJSONText -- | Types of attribution options for natural search conversions. data FloodlightConfigurationNATuralSearchConversionAttributionOption = ExcludeNATuralSearchConversionAttribution -- ^ @EXCLUDE_NATURAL_SEARCH_CONVERSION_ATTRIBUTION@ | IncludeNATuralSearchConversionAttribution -- ^ @INCLUDE_NATURAL_SEARCH_CONVERSION_ATTRIBUTION@ | IncludeNATuralSearchTieredConversionAttribution -- ^ @INCLUDE_NATURAL_SEARCH_TIERED_CONVERSION_ATTRIBUTION@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightConfigurationNATuralSearchConversionAttributionOption instance FromHttpApiData FloodlightConfigurationNATuralSearchConversionAttributionOption where parseQueryParam = \case "EXCLUDE_NATURAL_SEARCH_CONVERSION_ATTRIBUTION" -> Right ExcludeNATuralSearchConversionAttribution "INCLUDE_NATURAL_SEARCH_CONVERSION_ATTRIBUTION" -> Right IncludeNATuralSearchConversionAttribution "INCLUDE_NATURAL_SEARCH_TIERED_CONVERSION_ATTRIBUTION" -> Right IncludeNATuralSearchTieredConversionAttribution x -> Left ("Unable to parse FloodlightConfigurationNATuralSearchConversionAttributionOption from: " <> x) instance ToHttpApiData FloodlightConfigurationNATuralSearchConversionAttributionOption where toQueryParam = \case ExcludeNATuralSearchConversionAttribution -> "EXCLUDE_NATURAL_SEARCH_CONVERSION_ATTRIBUTION" IncludeNATuralSearchConversionAttribution -> "INCLUDE_NATURAL_SEARCH_CONVERSION_ATTRIBUTION" IncludeNATuralSearchTieredConversionAttribution -> "INCLUDE_NATURAL_SEARCH_TIERED_CONVERSION_ATTRIBUTION" instance FromJSON FloodlightConfigurationNATuralSearchConversionAttributionOption where parseJSON = parseJSONText "FloodlightConfigurationNATuralSearchConversionAttributionOption" instance ToJSON FloodlightConfigurationNATuralSearchConversionAttributionOption where toJSON = toJSONText -- | Measurement mode for the wrapped placement. data MeasurementPartnerWrAppingDataTagWrAppingMode = None -- ^ @NONE@ | Blocking -- ^ @BLOCKING@ | Monitoring -- ^ @MONITORING@ | MonitoringOnly -- ^ @MONITORING_ONLY@ | VideoPixelMonitoring -- ^ @VIDEO_PIXEL_MONITORING@ | Tracking -- ^ @TRACKING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MeasurementPartnerWrAppingDataTagWrAppingMode instance FromHttpApiData MeasurementPartnerWrAppingDataTagWrAppingMode where parseQueryParam = \case "NONE" -> Right None "BLOCKING" -> Right Blocking "MONITORING" -> Right Monitoring "MONITORING_ONLY" -> Right MonitoringOnly "VIDEO_PIXEL_MONITORING" -> Right VideoPixelMonitoring "TRACKING" -> Right Tracking x -> Left ("Unable to parse MeasurementPartnerWrAppingDataTagWrAppingMode from: " <> x) instance ToHttpApiData MeasurementPartnerWrAppingDataTagWrAppingMode where toQueryParam = \case None -> "NONE" Blocking -> "BLOCKING" Monitoring -> "MONITORING" MonitoringOnly -> "MONITORING_ONLY" VideoPixelMonitoring -> "VIDEO_PIXEL_MONITORING" Tracking -> "TRACKING" instance FromJSON MeasurementPartnerWrAppingDataTagWrAppingMode where parseJSON = parseJSONText "MeasurementPartnerWrAppingDataTagWrAppingMode" instance ToJSON MeasurementPartnerWrAppingDataTagWrAppingMode where toJSON = toJSONText -- | Artwork type of rich media creative. This is a read-only field. -- Applicable to the following creative types: all RICH_MEDIA. data CreativeAssetArtworkType = CAATArtworkTypeFlash -- ^ @ARTWORK_TYPE_FLASH@ | CAATArtworkTypeHTML5 -- ^ @ARTWORK_TYPE_HTML5@ | CAATArtworkTypeMixed -- ^ @ARTWORK_TYPE_MIXED@ | CAATArtworkTypeImage -- ^ @ARTWORK_TYPE_IMAGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetArtworkType instance FromHttpApiData CreativeAssetArtworkType where parseQueryParam = \case "ARTWORK_TYPE_FLASH" -> Right CAATArtworkTypeFlash "ARTWORK_TYPE_HTML5" -> Right CAATArtworkTypeHTML5 "ARTWORK_TYPE_MIXED" -> Right CAATArtworkTypeMixed "ARTWORK_TYPE_IMAGE" -> Right CAATArtworkTypeImage x -> Left ("Unable to parse CreativeAssetArtworkType from: " <> x) instance ToHttpApiData CreativeAssetArtworkType where toQueryParam = \case CAATArtworkTypeFlash -> "ARTWORK_TYPE_FLASH" CAATArtworkTypeHTML5 -> "ARTWORK_TYPE_HTML5" CAATArtworkTypeMixed -> "ARTWORK_TYPE_MIXED" CAATArtworkTypeImage -> "ARTWORK_TYPE_IMAGE" instance FromJSON CreativeAssetArtworkType where parseJSON = parseJSONText "CreativeAssetArtworkType" instance ToJSON CreativeAssetArtworkType where toJSON = toJSONText -- | The type of custom floodlight variable to supply a value for. These map -- to the \"u[1-20]=\" in the tags. data CustomFloodlightVariableType = U1 -- ^ @U1@ | U2 -- ^ @U2@ | U3 -- ^ @U3@ | U4 -- ^ @U4@ | U5 -- ^ @U5@ | U6 -- ^ @U6@ | U7 -- ^ @U7@ | U8 -- ^ @U8@ | U9 -- ^ @U9@ | U10 -- ^ @U10@ | U11 -- ^ @U11@ | U12 -- ^ @U12@ | U13 -- ^ @U13@ | U14 -- ^ @U14@ | U15 -- ^ @U15@ | U16 -- ^ @U16@ | U17 -- ^ @U17@ | U18 -- ^ @U18@ | U19 -- ^ @U19@ | U20 -- ^ @U20@ | U21 -- ^ @U21@ | U22 -- ^ @U22@ | U23 -- ^ @U23@ | U24 -- ^ @U24@ | U25 -- ^ @U25@ | U26 -- ^ @U26@ | U27 -- ^ @U27@ | U28 -- ^ @U28@ | U29 -- ^ @U29@ | U30 -- ^ @U30@ | U31 -- ^ @U31@ | U32 -- ^ @U32@ | U33 -- ^ @U33@ | U34 -- ^ @U34@ | U35 -- ^ @U35@ | U36 -- ^ @U36@ | U37 -- ^ @U37@ | U38 -- ^ @U38@ | U39 -- ^ @U39@ | U40 -- ^ @U40@ | U41 -- ^ @U41@ | U42 -- ^ @U42@ | U43 -- ^ @U43@ | U44 -- ^ @U44@ | U45 -- ^ @U45@ | U46 -- ^ @U46@ | U47 -- ^ @U47@ | U48 -- ^ @U48@ | U49 -- ^ @U49@ | U50 -- ^ @U50@ | U51 -- ^ @U51@ | U52 -- ^ @U52@ | U53 -- ^ @U53@ | U54 -- ^ @U54@ | U55 -- ^ @U55@ | U56 -- ^ @U56@ | U57 -- ^ @U57@ | U58 -- ^ @U58@ | U59 -- ^ @U59@ | U60 -- ^ @U60@ | U61 -- ^ @U61@ | U62 -- ^ @U62@ | U63 -- ^ @U63@ | U64 -- ^ @U64@ | U65 -- ^ @U65@ | U66 -- ^ @U66@ | U67 -- ^ @U67@ | U68 -- ^ @U68@ | U69 -- ^ @U69@ | U70 -- ^ @U70@ | U71 -- ^ @U71@ | U72 -- ^ @U72@ | U73 -- ^ @U73@ | U74 -- ^ @U74@ | U75 -- ^ @U75@ | U76 -- ^ @U76@ | U77 -- ^ @U77@ | U78 -- ^ @U78@ | U79 -- ^ @U79@ | U80 -- ^ @U80@ | U81 -- ^ @U81@ | U82 -- ^ @U82@ | U83 -- ^ @U83@ | U84 -- ^ @U84@ | U85 -- ^ @U85@ | U86 -- ^ @U86@ | U87 -- ^ @U87@ | U88 -- ^ @U88@ | U89 -- ^ @U89@ | U90 -- ^ @U90@ | U91 -- ^ @U91@ | U92 -- ^ @U92@ | U93 -- ^ @U93@ | U94 -- ^ @U94@ | U95 -- ^ @U95@ | U96 -- ^ @U96@ | U97 -- ^ @U97@ | U98 -- ^ @U98@ | U99 -- ^ @U99@ | U100 -- ^ @U100@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CustomFloodlightVariableType instance FromHttpApiData CustomFloodlightVariableType where parseQueryParam = \case "U1" -> Right U1 "U2" -> Right U2 "U3" -> Right U3 "U4" -> Right U4 "U5" -> Right U5 "U6" -> Right U6 "U7" -> Right U7 "U8" -> Right U8 "U9" -> Right U9 "U10" -> Right U10 "U11" -> Right U11 "U12" -> Right U12 "U13" -> Right U13 "U14" -> Right U14 "U15" -> Right U15 "U16" -> Right U16 "U17" -> Right U17 "U18" -> Right U18 "U19" -> Right U19 "U20" -> Right U20 "U21" -> Right U21 "U22" -> Right U22 "U23" -> Right U23 "U24" -> Right U24 "U25" -> Right U25 "U26" -> Right U26 "U27" -> Right U27 "U28" -> Right U28 "U29" -> Right U29 "U30" -> Right U30 "U31" -> Right U31 "U32" -> Right U32 "U33" -> Right U33 "U34" -> Right U34 "U35" -> Right U35 "U36" -> Right U36 "U37" -> Right U37 "U38" -> Right U38 "U39" -> Right U39 "U40" -> Right U40 "U41" -> Right U41 "U42" -> Right U42 "U43" -> Right U43 "U44" -> Right U44 "U45" -> Right U45 "U46" -> Right U46 "U47" -> Right U47 "U48" -> Right U48 "U49" -> Right U49 "U50" -> Right U50 "U51" -> Right U51 "U52" -> Right U52 "U53" -> Right U53 "U54" -> Right U54 "U55" -> Right U55 "U56" -> Right U56 "U57" -> Right U57 "U58" -> Right U58 "U59" -> Right U59 "U60" -> Right U60 "U61" -> Right U61 "U62" -> Right U62 "U63" -> Right U63 "U64" -> Right U64 "U65" -> Right U65 "U66" -> Right U66 "U67" -> Right U67 "U68" -> Right U68 "U69" -> Right U69 "U70" -> Right U70 "U71" -> Right U71 "U72" -> Right U72 "U73" -> Right U73 "U74" -> Right U74 "U75" -> Right U75 "U76" -> Right U76 "U77" -> Right U77 "U78" -> Right U78 "U79" -> Right U79 "U80" -> Right U80 "U81" -> Right U81 "U82" -> Right U82 "U83" -> Right U83 "U84" -> Right U84 "U85" -> Right U85 "U86" -> Right U86 "U87" -> Right U87 "U88" -> Right U88 "U89" -> Right U89 "U90" -> Right U90 "U91" -> Right U91 "U92" -> Right U92 "U93" -> Right U93 "U94" -> Right U94 "U95" -> Right U95 "U96" -> Right U96 "U97" -> Right U97 "U98" -> Right U98 "U99" -> Right U99 "U100" -> Right U100 x -> Left ("Unable to parse CustomFloodlightVariableType from: " <> x) instance ToHttpApiData CustomFloodlightVariableType where toQueryParam = \case U1 -> "U1" U2 -> "U2" U3 -> "U3" U4 -> "U4" U5 -> "U5" U6 -> "U6" U7 -> "U7" U8 -> "U8" U9 -> "U9" U10 -> "U10" U11 -> "U11" U12 -> "U12" U13 -> "U13" U14 -> "U14" U15 -> "U15" U16 -> "U16" U17 -> "U17" U18 -> "U18" U19 -> "U19" U20 -> "U20" U21 -> "U21" U22 -> "U22" U23 -> "U23" U24 -> "U24" U25 -> "U25" U26 -> "U26" U27 -> "U27" U28 -> "U28" U29 -> "U29" U30 -> "U30" U31 -> "U31" U32 -> "U32" U33 -> "U33" U34 -> "U34" U35 -> "U35" U36 -> "U36" U37 -> "U37" U38 -> "U38" U39 -> "U39" U40 -> "U40" U41 -> "U41" U42 -> "U42" U43 -> "U43" U44 -> "U44" U45 -> "U45" U46 -> "U46" U47 -> "U47" U48 -> "U48" U49 -> "U49" U50 -> "U50" U51 -> "U51" U52 -> "U52" U53 -> "U53" U54 -> "U54" U55 -> "U55" U56 -> "U56" U57 -> "U57" U58 -> "U58" U59 -> "U59" U60 -> "U60" U61 -> "U61" U62 -> "U62" U63 -> "U63" U64 -> "U64" U65 -> "U65" U66 -> "U66" U67 -> "U67" U68 -> "U68" U69 -> "U69" U70 -> "U70" U71 -> "U71" U72 -> "U72" U73 -> "U73" U74 -> "U74" U75 -> "U75" U76 -> "U76" U77 -> "U77" U78 -> "U78" U79 -> "U79" U80 -> "U80" U81 -> "U81" U82 -> "U82" U83 -> "U83" U84 -> "U84" U85 -> "U85" U86 -> "U86" U87 -> "U87" U88 -> "U88" U89 -> "U89" U90 -> "U90" U91 -> "U91" U92 -> "U92" U93 -> "U93" U94 -> "U94" U95 -> "U95" U96 -> "U96" U97 -> "U97" U98 -> "U98" U99 -> "U99" U100 -> "U100" instance FromJSON CustomFloodlightVariableType where parseJSON = parseJSONText "CustomFloodlightVariableType" instance ToJSON CustomFloodlightVariableType where toJSON = toJSONText -- | The error code. data ConversionErrorCode = InvalidArgument -- ^ @INVALID_ARGUMENT@ | Internal -- ^ @INTERNAL@ | PermissionDenied -- ^ @PERMISSION_DENIED@ | NotFound -- ^ @NOT_FOUND@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ConversionErrorCode instance FromHttpApiData ConversionErrorCode where parseQueryParam = \case "INVALID_ARGUMENT" -> Right InvalidArgument "INTERNAL" -> Right Internal "PERMISSION_DENIED" -> Right PermissionDenied "NOT_FOUND" -> Right NotFound x -> Left ("Unable to parse ConversionErrorCode from: " <> x) instance ToHttpApiData ConversionErrorCode where toQueryParam = \case InvalidArgument -> "INVALID_ARGUMENT" Internal -> "INTERNAL" PermissionDenied -> "PERMISSION_DENIED" NotFound -> "NOT_FOUND" instance FromJSON ConversionErrorCode where parseJSON = parseJSONText "ConversionErrorCode" instance ToJSON ConversionErrorCode where toJSON = toJSONText -- | Order of sorted results. data FloodlightActivitiesListSortOrder = FALSOAscending -- ^ @ASCENDING@ | FALSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivitiesListSortOrder instance FromHttpApiData FloodlightActivitiesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right FALSOAscending "DESCENDING" -> Right FALSODescending x -> Left ("Unable to parse FloodlightActivitiesListSortOrder from: " <> x) instance ToHttpApiData FloodlightActivitiesListSortOrder where toQueryParam = \case FALSOAscending -> "ASCENDING" FALSODescending -> "DESCENDING" instance FromJSON FloodlightActivitiesListSortOrder where parseJSON = parseJSONText "FloodlightActivitiesListSortOrder" instance ToJSON FloodlightActivitiesListSortOrder where toJSON = toJSONText -- | The output format of the report. Only available once the file is -- available. data FileFormat = CSV -- ^ @CSV@ | Excel -- ^ @EXCEL@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FileFormat instance FromHttpApiData FileFormat where parseQueryParam = \case "CSV" -> Right CSV "EXCEL" -> Right Excel x -> Left ("Unable to parse FileFormat from: " <> x) instance ToHttpApiData FileFormat where toQueryParam = \case CSV -> "CSV" Excel -> "EXCEL" instance FromJSON FileFormat where parseJSON = parseJSONText "FileFormat" instance ToJSON FileFormat where toJSON = toJSONText -- | The encryption entity type. This should match the encryption -- configuration for ad serving or Data Transfer. data EncryptionInfoEncryptionEntityType = EncryptionEntityTypeUnknown -- ^ @ENCRYPTION_ENTITY_TYPE_UNKNOWN@ | DcmAccount -- ^ @DCM_ACCOUNT@ | DcmAdvertiser -- ^ @DCM_ADVERTISER@ | DBmPartner -- ^ @DBM_PARTNER@ | DBmAdvertiser -- ^ @DBM_ADVERTISER@ | AdwordsCustomer -- ^ @ADWORDS_CUSTOMER@ | DfpNetworkCode -- ^ @DFP_NETWORK_CODE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EncryptionInfoEncryptionEntityType instance FromHttpApiData EncryptionInfoEncryptionEntityType where parseQueryParam = \case "ENCRYPTION_ENTITY_TYPE_UNKNOWN" -> Right EncryptionEntityTypeUnknown "DCM_ACCOUNT" -> Right DcmAccount "DCM_ADVERTISER" -> Right DcmAdvertiser "DBM_PARTNER" -> Right DBmPartner "DBM_ADVERTISER" -> Right DBmAdvertiser "ADWORDS_CUSTOMER" -> Right AdwordsCustomer "DFP_NETWORK_CODE" -> Right DfpNetworkCode x -> Left ("Unable to parse EncryptionInfoEncryptionEntityType from: " <> x) instance ToHttpApiData EncryptionInfoEncryptionEntityType where toQueryParam = \case EncryptionEntityTypeUnknown -> "ENCRYPTION_ENTITY_TYPE_UNKNOWN" DcmAccount -> "DCM_ACCOUNT" DcmAdvertiser -> "DCM_ADVERTISER" DBmPartner -> "DBM_PARTNER" DBmAdvertiser -> "DBM_ADVERTISER" AdwordsCustomer -> "ADWORDS_CUSTOMER" DfpNetworkCode -> "DFP_NETWORK_CODE" instance FromJSON EncryptionInfoEncryptionEntityType where parseJSON = parseJSONText "EncryptionInfoEncryptionEntityType" instance ToJSON EncryptionInfoEncryptionEntityType where toJSON = toJSONText -- | Placement pricing type. This field is required on insertion. data PricingSchedulePricingType = PricingTypeCpm -- ^ @PRICING_TYPE_CPM@ | PricingTypeCpc -- ^ @PRICING_TYPE_CPC@ | PricingTypeCpa -- ^ @PRICING_TYPE_CPA@ | PricingTypeFlatRateImpressions -- ^ @PRICING_TYPE_FLAT_RATE_IMPRESSIONS@ | PricingTypeFlatRateClicks -- ^ @PRICING_TYPE_FLAT_RATE_CLICKS@ | PricingTypeCpmActiveview -- ^ @PRICING_TYPE_CPM_ACTIVEVIEW@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PricingSchedulePricingType instance FromHttpApiData PricingSchedulePricingType where parseQueryParam = \case "PRICING_TYPE_CPM" -> Right PricingTypeCpm "PRICING_TYPE_CPC" -> Right PricingTypeCpc "PRICING_TYPE_CPA" -> Right PricingTypeCpa "PRICING_TYPE_FLAT_RATE_IMPRESSIONS" -> Right PricingTypeFlatRateImpressions "PRICING_TYPE_FLAT_RATE_CLICKS" -> Right PricingTypeFlatRateClicks "PRICING_TYPE_CPM_ACTIVEVIEW" -> Right PricingTypeCpmActiveview x -> Left ("Unable to parse PricingSchedulePricingType from: " <> x) instance ToHttpApiData PricingSchedulePricingType where toQueryParam = \case PricingTypeCpm -> "PRICING_TYPE_CPM" PricingTypeCpc -> "PRICING_TYPE_CPC" PricingTypeCpa -> "PRICING_TYPE_CPA" PricingTypeFlatRateImpressions -> "PRICING_TYPE_FLAT_RATE_IMPRESSIONS" PricingTypeFlatRateClicks -> "PRICING_TYPE_FLAT_RATE_CLICKS" PricingTypeCpmActiveview -> "PRICING_TYPE_CPM_ACTIVEVIEW" instance FromJSON PricingSchedulePricingType where parseJSON = parseJSONText "PricingSchedulePricingType" instance ToJSON PricingSchedulePricingType where toJSON = toJSONText -- | Target type used by the event. data CreativeCustomEventTargetType = TargetBlank -- ^ @TARGET_BLANK@ | TargetTop -- ^ @TARGET_TOP@ | TargetSelf -- ^ @TARGET_SELF@ | TargetParent -- ^ @TARGET_PARENT@ | TargetPopup -- ^ @TARGET_POPUP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeCustomEventTargetType instance FromHttpApiData CreativeCustomEventTargetType where parseQueryParam = \case "TARGET_BLANK" -> Right TargetBlank "TARGET_TOP" -> Right TargetTop "TARGET_SELF" -> Right TargetSelf "TARGET_PARENT" -> Right TargetParent "TARGET_POPUP" -> Right TargetPopup x -> Left ("Unable to parse CreativeCustomEventTargetType from: " <> x) instance ToHttpApiData CreativeCustomEventTargetType where toQueryParam = \case TargetBlank -> "TARGET_BLANK" TargetTop -> "TARGET_TOP" TargetSelf -> "TARGET_SELF" TargetParent -> "TARGET_PARENT" TargetPopup -> "TARGET_POPUP" instance FromJSON CreativeCustomEventTargetType where parseJSON = parseJSONText "CreativeCustomEventTargetType" instance ToJSON CreativeCustomEventTargetType where toJSON = toJSONText -- | The scope that defines which results are returned. data ReportsListScope = All -- ^ @ALL@ -- All reports in account. | Mine -- ^ @MINE@ -- My reports. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportsListScope instance FromHttpApiData ReportsListScope where parseQueryParam = \case "ALL" -> Right All "MINE" -> Right Mine x -> Left ("Unable to parse ReportsListScope from: " <> x) instance ToHttpApiData ReportsListScope where toQueryParam = \case All -> "ALL" Mine -> "MINE" instance FromJSON ReportsListScope where parseJSON = parseJSONText "ReportsListScope" instance ToJSON ReportsListScope where toJSON = toJSONText -- | Orientation of video asset. This is a read-only, auto-generated field. data CreativeAssetOrientation = CAOLandscape -- ^ @LANDSCAPE@ | CAOPortrait -- ^ @PORTRAIT@ | CAOSquare -- ^ @SQUARE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetOrientation instance FromHttpApiData CreativeAssetOrientation where parseQueryParam = \case "LANDSCAPE" -> Right CAOLandscape "PORTRAIT" -> Right CAOPortrait "SQUARE" -> Right CAOSquare x -> Left ("Unable to parse CreativeAssetOrientation from: " <> x) instance ToHttpApiData CreativeAssetOrientation where toQueryParam = \case CAOLandscape -> "LANDSCAPE" CAOPortrait -> "PORTRAIT" CAOSquare -> "SQUARE" instance FromJSON CreativeAssetOrientation where parseJSON = parseJSONText "CreativeAssetOrientation" instance ToJSON CreativeAssetOrientation where toJSON = toJSONText -- | Duration type for which an asset will be displayed. Applicable to the -- following creative types: all RICH_MEDIA. data CreativeAssetDurationType = AssetDurationTypeAuto -- ^ @ASSET_DURATION_TYPE_AUTO@ | AssetDurationTypeNone -- ^ @ASSET_DURATION_TYPE_NONE@ | AssetDurationTypeCustom -- ^ @ASSET_DURATION_TYPE_CUSTOM@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetDurationType instance FromHttpApiData CreativeAssetDurationType where parseQueryParam = \case "ASSET_DURATION_TYPE_AUTO" -> Right AssetDurationTypeAuto "ASSET_DURATION_TYPE_NONE" -> Right AssetDurationTypeNone "ASSET_DURATION_TYPE_CUSTOM" -> Right AssetDurationTypeCustom x -> Left ("Unable to parse CreativeAssetDurationType from: " <> x) instance ToHttpApiData CreativeAssetDurationType where toQueryParam = \case AssetDurationTypeAuto -> "ASSET_DURATION_TYPE_AUTO" AssetDurationTypeNone -> "ASSET_DURATION_TYPE_NONE" AssetDurationTypeCustom -> "ASSET_DURATION_TYPE_CUSTOM" instance FromJSON CreativeAssetDurationType where parseJSON = parseJSONText "CreativeAssetDurationType" instance ToJSON CreativeAssetDurationType where toJSON = toJSONText -- | Product from which this targetable remarketing list was originated. data TargetableRemarketingListListSource = RemarketingListSourceOther -- ^ @REMARKETING_LIST_SOURCE_OTHER@ | RemarketingListSourceAdx -- ^ @REMARKETING_LIST_SOURCE_ADX@ | RemarketingListSourceDfp -- ^ @REMARKETING_LIST_SOURCE_DFP@ | RemarketingListSourceXfp -- ^ @REMARKETING_LIST_SOURCE_XFP@ | RemarketingListSourceDfa -- ^ @REMARKETING_LIST_SOURCE_DFA@ | RemarketingListSourceGa -- ^ @REMARKETING_LIST_SOURCE_GA@ | RemarketingListSourceYouTube -- ^ @REMARKETING_LIST_SOURCE_YOUTUBE@ | RemarketingListSourceDBm -- ^ @REMARKETING_LIST_SOURCE_DBM@ | RemarketingListSourceGplus -- ^ @REMARKETING_LIST_SOURCE_GPLUS@ | RemarketingListSourceDmp -- ^ @REMARKETING_LIST_SOURCE_DMP@ | RemarketingListSourcePlayStore -- ^ @REMARKETING_LIST_SOURCE_PLAY_STORE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetableRemarketingListListSource instance FromHttpApiData TargetableRemarketingListListSource where parseQueryParam = \case "REMARKETING_LIST_SOURCE_OTHER" -> Right RemarketingListSourceOther "REMARKETING_LIST_SOURCE_ADX" -> Right RemarketingListSourceAdx "REMARKETING_LIST_SOURCE_DFP" -> Right RemarketingListSourceDfp "REMARKETING_LIST_SOURCE_XFP" -> Right RemarketingListSourceXfp "REMARKETING_LIST_SOURCE_DFA" -> Right RemarketingListSourceDfa "REMARKETING_LIST_SOURCE_GA" -> Right RemarketingListSourceGa "REMARKETING_LIST_SOURCE_YOUTUBE" -> Right RemarketingListSourceYouTube "REMARKETING_LIST_SOURCE_DBM" -> Right RemarketingListSourceDBm "REMARKETING_LIST_SOURCE_GPLUS" -> Right RemarketingListSourceGplus "REMARKETING_LIST_SOURCE_DMP" -> Right RemarketingListSourceDmp "REMARKETING_LIST_SOURCE_PLAY_STORE" -> Right RemarketingListSourcePlayStore x -> Left ("Unable to parse TargetableRemarketingListListSource from: " <> x) instance ToHttpApiData TargetableRemarketingListListSource where toQueryParam = \case RemarketingListSourceOther -> "REMARKETING_LIST_SOURCE_OTHER" RemarketingListSourceAdx -> "REMARKETING_LIST_SOURCE_ADX" RemarketingListSourceDfp -> "REMARKETING_LIST_SOURCE_DFP" RemarketingListSourceXfp -> "REMARKETING_LIST_SOURCE_XFP" RemarketingListSourceDfa -> "REMARKETING_LIST_SOURCE_DFA" RemarketingListSourceGa -> "REMARKETING_LIST_SOURCE_GA" RemarketingListSourceYouTube -> "REMARKETING_LIST_SOURCE_YOUTUBE" RemarketingListSourceDBm -> "REMARKETING_LIST_SOURCE_DBM" RemarketingListSourceGplus -> "REMARKETING_LIST_SOURCE_GPLUS" RemarketingListSourceDmp -> "REMARKETING_LIST_SOURCE_DMP" RemarketingListSourcePlayStore -> "REMARKETING_LIST_SOURCE_PLAY_STORE" instance FromJSON TargetableRemarketingListListSource where parseJSON = parseJSONText "TargetableRemarketingListListSource" instance ToJSON TargetableRemarketingListListSource where toJSON = toJSONText -- | Field by which to sort the list. data CreativeGroupsListSortField = CGLSFID -- ^ @ID@ | CGLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeGroupsListSortField instance FromHttpApiData CreativeGroupsListSortField where parseQueryParam = \case "ID" -> Right CGLSFID "NAME" -> Right CGLSFName x -> Left ("Unable to parse CreativeGroupsListSortField from: " <> x) instance ToHttpApiData CreativeGroupsListSortField where toQueryParam = \case CGLSFID -> "ID" CGLSFName -> "NAME" instance FromJSON CreativeGroupsListSortField where parseJSON = parseJSONText "CreativeGroupsListSortField" instance ToJSON CreativeGroupsListSortField where toJSON = toJSONText -- | Field by which to sort the list. data PlacementsListSortField = PLSFID -- ^ @ID@ | PLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementsListSortField instance FromHttpApiData PlacementsListSortField where parseQueryParam = \case "ID" -> Right PLSFID "NAME" -> Right PLSFName x -> Left ("Unable to parse PlacementsListSortField from: " <> x) instance ToHttpApiData PlacementsListSortField where toQueryParam = \case PLSFID -> "ID" PLSFName -> "NAME" instance FromJSON PlacementsListSortField where parseJSON = parseJSONText "PlacementsListSortField" instance ToJSON PlacementsListSortField where toJSON = toJSONText data CreativeBackupImageFeaturesItem = CBIFICssFontFace -- ^ @CSS_FONT_FACE@ | CBIFICssBackgRoundSize -- ^ @CSS_BACKGROUND_SIZE@ | CBIFICssBOrderImage -- ^ @CSS_BORDER_IMAGE@ | CBIFICssBOrderRadius -- ^ @CSS_BORDER_RADIUS@ | CBIFICssBoxShadow -- ^ @CSS_BOX_SHADOW@ | CBIFICssFlexBox -- ^ @CSS_FLEX_BOX@ | CBIFICssHsla -- ^ @CSS_HSLA@ | CBIFICssMultipleBgs -- ^ @CSS_MULTIPLE_BGS@ | CBIFICssOpacity -- ^ @CSS_OPACITY@ | CBIFICssRgba -- ^ @CSS_RGBA@ | CBIFICssTextShadow -- ^ @CSS_TEXT_SHADOW@ | CBIFICssAnimations -- ^ @CSS_ANIMATIONS@ | CBIFICssColumns -- ^ @CSS_COLUMNS@ | CBIFICssGeneratedContent -- ^ @CSS_GENERATED_CONTENT@ | CBIFICssGradients -- ^ @CSS_GRADIENTS@ | CBIFICssReflections -- ^ @CSS_REFLECTIONS@ | CBIFICssTransforms -- ^ @CSS_TRANSFORMS@ | CBIFICssTRANSFORMS3D -- ^ @CSS_TRANSFORMS3D@ | CBIFICssTransitions -- ^ @CSS_TRANSITIONS@ | CBIFIApplicationCache -- ^ @APPLICATION_CACHE@ | CBIFICanvas -- ^ @CANVAS@ | CBIFICanvasText -- ^ @CANVAS_TEXT@ | CBIFIDragAndDrop -- ^ @DRAG_AND_DROP@ | CBIFIHashChange -- ^ @HASH_CHANGE@ | CBIFIHistory -- ^ @HISTORY@ | CBIFIAudio -- ^ @AUDIO@ | CBIFIVideo -- ^ @VIDEO@ | CBIFIIndexedDB -- ^ @INDEXED_DB@ | CBIFIInputAttrAutocomplete -- ^ @INPUT_ATTR_AUTOCOMPLETE@ | CBIFIInputAttrAutofocus -- ^ @INPUT_ATTR_AUTOFOCUS@ | CBIFIInputAttrList -- ^ @INPUT_ATTR_LIST@ | CBIFIInputAttrPlaceholder -- ^ @INPUT_ATTR_PLACEHOLDER@ | CBIFIInputAttrMax -- ^ @INPUT_ATTR_MAX@ | CBIFIInputAttrMin -- ^ @INPUT_ATTR_MIN@ | CBIFIInputAttrMultiple -- ^ @INPUT_ATTR_MULTIPLE@ | CBIFIInputAttrPattern -- ^ @INPUT_ATTR_PATTERN@ | CBIFIInputAttrRequired -- ^ @INPUT_ATTR_REQUIRED@ | CBIFIInputAttrStep -- ^ @INPUT_ATTR_STEP@ | CBIFIInputTypeSearch -- ^ @INPUT_TYPE_SEARCH@ | CBIFIInputTypeTel -- ^ @INPUT_TYPE_TEL@ | CBIFIInputTypeURL -- ^ @INPUT_TYPE_URL@ | CBIFIInputTypeEmail -- ^ @INPUT_TYPE_EMAIL@ | CBIFIInputTypeDatetime -- ^ @INPUT_TYPE_DATETIME@ | CBIFIInputTypeDate -- ^ @INPUT_TYPE_DATE@ | CBIFIInputTypeMonth -- ^ @INPUT_TYPE_MONTH@ | CBIFIInputTypeWeek -- ^ @INPUT_TYPE_WEEK@ | CBIFIInputTypeTime -- ^ @INPUT_TYPE_TIME@ | CBIFIInputTypeDatetimeLocal -- ^ @INPUT_TYPE_DATETIME_LOCAL@ | CBIFIInputTypeNumber -- ^ @INPUT_TYPE_NUMBER@ | CBIFIInputTypeRange -- ^ @INPUT_TYPE_RANGE@ | CBIFIInputTypeColor -- ^ @INPUT_TYPE_COLOR@ | CBIFILocalStorage -- ^ @LOCAL_STORAGE@ | CBIFIPostMessage -- ^ @POST_MESSAGE@ | CBIFISessionStorage -- ^ @SESSION_STORAGE@ | CBIFIWebSockets -- ^ @WEB_SOCKETS@ | CBIFIWebSQLDatabase -- ^ @WEB_SQL_DATABASE@ | CBIFIWebWorkers -- ^ @WEB_WORKERS@ | CBIFIGeoLocation -- ^ @GEO_LOCATION@ | CBIFIInlineSvg -- ^ @INLINE_SVG@ | CBIFISmil -- ^ @SMIL@ | CBIFISvgHref -- ^ @SVG_HREF@ | CBIFISvgClipPaths -- ^ @SVG_CLIP_PATHS@ | CBIFITouch -- ^ @TOUCH@ | CBIFIWebgl -- ^ @WEBGL@ | CBIFISvgFilters -- ^ @SVG_FILTERS@ | CBIFISvgFeImage -- ^ @SVG_FE_IMAGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeBackupImageFeaturesItem instance FromHttpApiData CreativeBackupImageFeaturesItem where parseQueryParam = \case "CSS_FONT_FACE" -> Right CBIFICssFontFace "CSS_BACKGROUND_SIZE" -> Right CBIFICssBackgRoundSize "CSS_BORDER_IMAGE" -> Right CBIFICssBOrderImage "CSS_BORDER_RADIUS" -> Right CBIFICssBOrderRadius "CSS_BOX_SHADOW" -> Right CBIFICssBoxShadow "CSS_FLEX_BOX" -> Right CBIFICssFlexBox "CSS_HSLA" -> Right CBIFICssHsla "CSS_MULTIPLE_BGS" -> Right CBIFICssMultipleBgs "CSS_OPACITY" -> Right CBIFICssOpacity "CSS_RGBA" -> Right CBIFICssRgba "CSS_TEXT_SHADOW" -> Right CBIFICssTextShadow "CSS_ANIMATIONS" -> Right CBIFICssAnimations "CSS_COLUMNS" -> Right CBIFICssColumns "CSS_GENERATED_CONTENT" -> Right CBIFICssGeneratedContent "CSS_GRADIENTS" -> Right CBIFICssGradients "CSS_REFLECTIONS" -> Right CBIFICssReflections "CSS_TRANSFORMS" -> Right CBIFICssTransforms "CSS_TRANSFORMS3D" -> Right CBIFICssTRANSFORMS3D "CSS_TRANSITIONS" -> Right CBIFICssTransitions "APPLICATION_CACHE" -> Right CBIFIApplicationCache "CANVAS" -> Right CBIFICanvas "CANVAS_TEXT" -> Right CBIFICanvasText "DRAG_AND_DROP" -> Right CBIFIDragAndDrop "HASH_CHANGE" -> Right CBIFIHashChange "HISTORY" -> Right CBIFIHistory "AUDIO" -> Right CBIFIAudio "VIDEO" -> Right CBIFIVideo "INDEXED_DB" -> Right CBIFIIndexedDB "INPUT_ATTR_AUTOCOMPLETE" -> Right CBIFIInputAttrAutocomplete "INPUT_ATTR_AUTOFOCUS" -> Right CBIFIInputAttrAutofocus "INPUT_ATTR_LIST" -> Right CBIFIInputAttrList "INPUT_ATTR_PLACEHOLDER" -> Right CBIFIInputAttrPlaceholder "INPUT_ATTR_MAX" -> Right CBIFIInputAttrMax "INPUT_ATTR_MIN" -> Right CBIFIInputAttrMin "INPUT_ATTR_MULTIPLE" -> Right CBIFIInputAttrMultiple "INPUT_ATTR_PATTERN" -> Right CBIFIInputAttrPattern "INPUT_ATTR_REQUIRED" -> Right CBIFIInputAttrRequired "INPUT_ATTR_STEP" -> Right CBIFIInputAttrStep "INPUT_TYPE_SEARCH" -> Right CBIFIInputTypeSearch "INPUT_TYPE_TEL" -> Right CBIFIInputTypeTel "INPUT_TYPE_URL" -> Right CBIFIInputTypeURL "INPUT_TYPE_EMAIL" -> Right CBIFIInputTypeEmail "INPUT_TYPE_DATETIME" -> Right CBIFIInputTypeDatetime "INPUT_TYPE_DATE" -> Right CBIFIInputTypeDate "INPUT_TYPE_MONTH" -> Right CBIFIInputTypeMonth "INPUT_TYPE_WEEK" -> Right CBIFIInputTypeWeek "INPUT_TYPE_TIME" -> Right CBIFIInputTypeTime "INPUT_TYPE_DATETIME_LOCAL" -> Right CBIFIInputTypeDatetimeLocal "INPUT_TYPE_NUMBER" -> Right CBIFIInputTypeNumber "INPUT_TYPE_RANGE" -> Right CBIFIInputTypeRange "INPUT_TYPE_COLOR" -> Right CBIFIInputTypeColor "LOCAL_STORAGE" -> Right CBIFILocalStorage "POST_MESSAGE" -> Right CBIFIPostMessage "SESSION_STORAGE" -> Right CBIFISessionStorage "WEB_SOCKETS" -> Right CBIFIWebSockets "WEB_SQL_DATABASE" -> Right CBIFIWebSQLDatabase "WEB_WORKERS" -> Right CBIFIWebWorkers "GEO_LOCATION" -> Right CBIFIGeoLocation "INLINE_SVG" -> Right CBIFIInlineSvg "SMIL" -> Right CBIFISmil "SVG_HREF" -> Right CBIFISvgHref "SVG_CLIP_PATHS" -> Right CBIFISvgClipPaths "TOUCH" -> Right CBIFITouch "WEBGL" -> Right CBIFIWebgl "SVG_FILTERS" -> Right CBIFISvgFilters "SVG_FE_IMAGE" -> Right CBIFISvgFeImage x -> Left ("Unable to parse CreativeBackupImageFeaturesItem from: " <> x) instance ToHttpApiData CreativeBackupImageFeaturesItem where toQueryParam = \case CBIFICssFontFace -> "CSS_FONT_FACE" CBIFICssBackgRoundSize -> "CSS_BACKGROUND_SIZE" CBIFICssBOrderImage -> "CSS_BORDER_IMAGE" CBIFICssBOrderRadius -> "CSS_BORDER_RADIUS" CBIFICssBoxShadow -> "CSS_BOX_SHADOW" CBIFICssFlexBox -> "CSS_FLEX_BOX" CBIFICssHsla -> "CSS_HSLA" CBIFICssMultipleBgs -> "CSS_MULTIPLE_BGS" CBIFICssOpacity -> "CSS_OPACITY" CBIFICssRgba -> "CSS_RGBA" CBIFICssTextShadow -> "CSS_TEXT_SHADOW" CBIFICssAnimations -> "CSS_ANIMATIONS" CBIFICssColumns -> "CSS_COLUMNS" CBIFICssGeneratedContent -> "CSS_GENERATED_CONTENT" CBIFICssGradients -> "CSS_GRADIENTS" CBIFICssReflections -> "CSS_REFLECTIONS" CBIFICssTransforms -> "CSS_TRANSFORMS" CBIFICssTRANSFORMS3D -> "CSS_TRANSFORMS3D" CBIFICssTransitions -> "CSS_TRANSITIONS" CBIFIApplicationCache -> "APPLICATION_CACHE" CBIFICanvas -> "CANVAS" CBIFICanvasText -> "CANVAS_TEXT" CBIFIDragAndDrop -> "DRAG_AND_DROP" CBIFIHashChange -> "HASH_CHANGE" CBIFIHistory -> "HISTORY" CBIFIAudio -> "AUDIO" CBIFIVideo -> "VIDEO" CBIFIIndexedDB -> "INDEXED_DB" CBIFIInputAttrAutocomplete -> "INPUT_ATTR_AUTOCOMPLETE" CBIFIInputAttrAutofocus -> "INPUT_ATTR_AUTOFOCUS" CBIFIInputAttrList -> "INPUT_ATTR_LIST" CBIFIInputAttrPlaceholder -> "INPUT_ATTR_PLACEHOLDER" CBIFIInputAttrMax -> "INPUT_ATTR_MAX" CBIFIInputAttrMin -> "INPUT_ATTR_MIN" CBIFIInputAttrMultiple -> "INPUT_ATTR_MULTIPLE" CBIFIInputAttrPattern -> "INPUT_ATTR_PATTERN" CBIFIInputAttrRequired -> "INPUT_ATTR_REQUIRED" CBIFIInputAttrStep -> "INPUT_ATTR_STEP" CBIFIInputTypeSearch -> "INPUT_TYPE_SEARCH" CBIFIInputTypeTel -> "INPUT_TYPE_TEL" CBIFIInputTypeURL -> "INPUT_TYPE_URL" CBIFIInputTypeEmail -> "INPUT_TYPE_EMAIL" CBIFIInputTypeDatetime -> "INPUT_TYPE_DATETIME" CBIFIInputTypeDate -> "INPUT_TYPE_DATE" CBIFIInputTypeMonth -> "INPUT_TYPE_MONTH" CBIFIInputTypeWeek -> "INPUT_TYPE_WEEK" CBIFIInputTypeTime -> "INPUT_TYPE_TIME" CBIFIInputTypeDatetimeLocal -> "INPUT_TYPE_DATETIME_LOCAL" CBIFIInputTypeNumber -> "INPUT_TYPE_NUMBER" CBIFIInputTypeRange -> "INPUT_TYPE_RANGE" CBIFIInputTypeColor -> "INPUT_TYPE_COLOR" CBIFILocalStorage -> "LOCAL_STORAGE" CBIFIPostMessage -> "POST_MESSAGE" CBIFISessionStorage -> "SESSION_STORAGE" CBIFIWebSockets -> "WEB_SOCKETS" CBIFIWebSQLDatabase -> "WEB_SQL_DATABASE" CBIFIWebWorkers -> "WEB_WORKERS" CBIFIGeoLocation -> "GEO_LOCATION" CBIFIInlineSvg -> "INLINE_SVG" CBIFISmil -> "SMIL" CBIFISvgHref -> "SVG_HREF" CBIFISvgClipPaths -> "SVG_CLIP_PATHS" CBIFITouch -> "TOUCH" CBIFIWebgl -> "WEBGL" CBIFISvgFilters -> "SVG_FILTERS" CBIFISvgFeImage -> "SVG_FE_IMAGE" instance FromJSON CreativeBackupImageFeaturesItem where parseJSON = parseJSONText "CreativeBackupImageFeaturesItem" instance ToJSON CreativeBackupImageFeaturesItem where toJSON = toJSONText -- | Order of sorted results. data AdvertisersListSortOrder = ALSOAscending -- ^ @ASCENDING@ | ALSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertisersListSortOrder instance FromHttpApiData AdvertisersListSortOrder where parseQueryParam = \case "ASCENDING" -> Right ALSOAscending "DESCENDING" -> Right ALSODescending x -> Left ("Unable to parse AdvertisersListSortOrder from: " <> x) instance ToHttpApiData AdvertisersListSortOrder where toQueryParam = \case ALSOAscending -> "ASCENDING" ALSODescending -> "DESCENDING" instance FromJSON AdvertisersListSortOrder where parseJSON = parseJSONText "AdvertisersListSortOrder" instance ToJSON AdvertisersListSortOrder where toJSON = toJSONText -- | Field by which to sort the list. data TargetingTemplatesListSortField = TTLSFID -- ^ @ID@ | TTLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetingTemplatesListSortField instance FromHttpApiData TargetingTemplatesListSortField where parseQueryParam = \case "ID" -> Right TTLSFID "NAME" -> Right TTLSFName x -> Left ("Unable to parse TargetingTemplatesListSortField from: " <> x) instance ToHttpApiData TargetingTemplatesListSortField where toQueryParam = \case TTLSFID -> "ID" TTLSFName -> "NAME" instance FromJSON TargetingTemplatesListSortField where parseJSON = parseJSONText "TargetingTemplatesListSortField" instance ToJSON TargetingTemplatesListSortField where toJSON = toJSONText -- | Field by which to sort the list. data CreativeFieldsListSortField = CFLSFID -- ^ @ID@ | CFLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeFieldsListSortField instance FromHttpApiData CreativeFieldsListSortField where parseQueryParam = \case "ID" -> Right CFLSFID "NAME" -> Right CFLSFName x -> Left ("Unable to parse CreativeFieldsListSortField from: " <> x) instance ToHttpApiData CreativeFieldsListSortField where toQueryParam = \case CFLSFID -> "ID" CFLSFName -> "NAME" instance FromJSON CreativeFieldsListSortField where parseJSON = parseJSONText "CreativeFieldsListSortField" instance ToJSON CreativeFieldsListSortField where toJSON = toJSONText -- | Variable name in the tag. This is a required field. data UserDefinedVariableConfigurationVariableType = UDVCVTU1 -- ^ @U1@ | UDVCVTU2 -- ^ @U2@ | UDVCVTU3 -- ^ @U3@ | UDVCVTU4 -- ^ @U4@ | UDVCVTU5 -- ^ @U5@ | UDVCVTU6 -- ^ @U6@ | UDVCVTU7 -- ^ @U7@ | UDVCVTU8 -- ^ @U8@ | UDVCVTU9 -- ^ @U9@ | UDVCVTU10 -- ^ @U10@ | UDVCVTU11 -- ^ @U11@ | UDVCVTU12 -- ^ @U12@ | UDVCVTU13 -- ^ @U13@ | UDVCVTU14 -- ^ @U14@ | UDVCVTU15 -- ^ @U15@ | UDVCVTU16 -- ^ @U16@ | UDVCVTU17 -- ^ @U17@ | UDVCVTU18 -- ^ @U18@ | UDVCVTU19 -- ^ @U19@ | UDVCVTU20 -- ^ @U20@ | UDVCVTU21 -- ^ @U21@ | UDVCVTU22 -- ^ @U22@ | UDVCVTU23 -- ^ @U23@ | UDVCVTU24 -- ^ @U24@ | UDVCVTU25 -- ^ @U25@ | UDVCVTU26 -- ^ @U26@ | UDVCVTU27 -- ^ @U27@ | UDVCVTU28 -- ^ @U28@ | UDVCVTU29 -- ^ @U29@ | UDVCVTU30 -- ^ @U30@ | UDVCVTU31 -- ^ @U31@ | UDVCVTU32 -- ^ @U32@ | UDVCVTU33 -- ^ @U33@ | UDVCVTU34 -- ^ @U34@ | UDVCVTU35 -- ^ @U35@ | UDVCVTU36 -- ^ @U36@ | UDVCVTU37 -- ^ @U37@ | UDVCVTU38 -- ^ @U38@ | UDVCVTU39 -- ^ @U39@ | UDVCVTU40 -- ^ @U40@ | UDVCVTU41 -- ^ @U41@ | UDVCVTU42 -- ^ @U42@ | UDVCVTU43 -- ^ @U43@ | UDVCVTU44 -- ^ @U44@ | UDVCVTU45 -- ^ @U45@ | UDVCVTU46 -- ^ @U46@ | UDVCVTU47 -- ^ @U47@ | UDVCVTU48 -- ^ @U48@ | UDVCVTU49 -- ^ @U49@ | UDVCVTU50 -- ^ @U50@ | UDVCVTU51 -- ^ @U51@ | UDVCVTU52 -- ^ @U52@ | UDVCVTU53 -- ^ @U53@ | UDVCVTU54 -- ^ @U54@ | UDVCVTU55 -- ^ @U55@ | UDVCVTU56 -- ^ @U56@ | UDVCVTU57 -- ^ @U57@ | UDVCVTU58 -- ^ @U58@ | UDVCVTU59 -- ^ @U59@ | UDVCVTU60 -- ^ @U60@ | UDVCVTU61 -- ^ @U61@ | UDVCVTU62 -- ^ @U62@ | UDVCVTU63 -- ^ @U63@ | UDVCVTU64 -- ^ @U64@ | UDVCVTU65 -- ^ @U65@ | UDVCVTU66 -- ^ @U66@ | UDVCVTU67 -- ^ @U67@ | UDVCVTU68 -- ^ @U68@ | UDVCVTU69 -- ^ @U69@ | UDVCVTU70 -- ^ @U70@ | UDVCVTU71 -- ^ @U71@ | UDVCVTU72 -- ^ @U72@ | UDVCVTU73 -- ^ @U73@ | UDVCVTU74 -- ^ @U74@ | UDVCVTU75 -- ^ @U75@ | UDVCVTU76 -- ^ @U76@ | UDVCVTU77 -- ^ @U77@ | UDVCVTU78 -- ^ @U78@ | UDVCVTU79 -- ^ @U79@ | UDVCVTU80 -- ^ @U80@ | UDVCVTU81 -- ^ @U81@ | UDVCVTU82 -- ^ @U82@ | UDVCVTU83 -- ^ @U83@ | UDVCVTU84 -- ^ @U84@ | UDVCVTU85 -- ^ @U85@ | UDVCVTU86 -- ^ @U86@ | UDVCVTU87 -- ^ @U87@ | UDVCVTU88 -- ^ @U88@ | UDVCVTU89 -- ^ @U89@ | UDVCVTU90 -- ^ @U90@ | UDVCVTU91 -- ^ @U91@ | UDVCVTU92 -- ^ @U92@ | UDVCVTU93 -- ^ @U93@ | UDVCVTU94 -- ^ @U94@ | UDVCVTU95 -- ^ @U95@ | UDVCVTU96 -- ^ @U96@ | UDVCVTU97 -- ^ @U97@ | UDVCVTU98 -- ^ @U98@ | UDVCVTU99 -- ^ @U99@ | UDVCVTU100 -- ^ @U100@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable UserDefinedVariableConfigurationVariableType instance FromHttpApiData UserDefinedVariableConfigurationVariableType where parseQueryParam = \case "U1" -> Right UDVCVTU1 "U2" -> Right UDVCVTU2 "U3" -> Right UDVCVTU3 "U4" -> Right UDVCVTU4 "U5" -> Right UDVCVTU5 "U6" -> Right UDVCVTU6 "U7" -> Right UDVCVTU7 "U8" -> Right UDVCVTU8 "U9" -> Right UDVCVTU9 "U10" -> Right UDVCVTU10 "U11" -> Right UDVCVTU11 "U12" -> Right UDVCVTU12 "U13" -> Right UDVCVTU13 "U14" -> Right UDVCVTU14 "U15" -> Right UDVCVTU15 "U16" -> Right UDVCVTU16 "U17" -> Right UDVCVTU17 "U18" -> Right UDVCVTU18 "U19" -> Right UDVCVTU19 "U20" -> Right UDVCVTU20 "U21" -> Right UDVCVTU21 "U22" -> Right UDVCVTU22 "U23" -> Right UDVCVTU23 "U24" -> Right UDVCVTU24 "U25" -> Right UDVCVTU25 "U26" -> Right UDVCVTU26 "U27" -> Right UDVCVTU27 "U28" -> Right UDVCVTU28 "U29" -> Right UDVCVTU29 "U30" -> Right UDVCVTU30 "U31" -> Right UDVCVTU31 "U32" -> Right UDVCVTU32 "U33" -> Right UDVCVTU33 "U34" -> Right UDVCVTU34 "U35" -> Right UDVCVTU35 "U36" -> Right UDVCVTU36 "U37" -> Right UDVCVTU37 "U38" -> Right UDVCVTU38 "U39" -> Right UDVCVTU39 "U40" -> Right UDVCVTU40 "U41" -> Right UDVCVTU41 "U42" -> Right UDVCVTU42 "U43" -> Right UDVCVTU43 "U44" -> Right UDVCVTU44 "U45" -> Right UDVCVTU45 "U46" -> Right UDVCVTU46 "U47" -> Right UDVCVTU47 "U48" -> Right UDVCVTU48 "U49" -> Right UDVCVTU49 "U50" -> Right UDVCVTU50 "U51" -> Right UDVCVTU51 "U52" -> Right UDVCVTU52 "U53" -> Right UDVCVTU53 "U54" -> Right UDVCVTU54 "U55" -> Right UDVCVTU55 "U56" -> Right UDVCVTU56 "U57" -> Right UDVCVTU57 "U58" -> Right UDVCVTU58 "U59" -> Right UDVCVTU59 "U60" -> Right UDVCVTU60 "U61" -> Right UDVCVTU61 "U62" -> Right UDVCVTU62 "U63" -> Right UDVCVTU63 "U64" -> Right UDVCVTU64 "U65" -> Right UDVCVTU65 "U66" -> Right UDVCVTU66 "U67" -> Right UDVCVTU67 "U68" -> Right UDVCVTU68 "U69" -> Right UDVCVTU69 "U70" -> Right UDVCVTU70 "U71" -> Right UDVCVTU71 "U72" -> Right UDVCVTU72 "U73" -> Right UDVCVTU73 "U74" -> Right UDVCVTU74 "U75" -> Right UDVCVTU75 "U76" -> Right UDVCVTU76 "U77" -> Right UDVCVTU77 "U78" -> Right UDVCVTU78 "U79" -> Right UDVCVTU79 "U80" -> Right UDVCVTU80 "U81" -> Right UDVCVTU81 "U82" -> Right UDVCVTU82 "U83" -> Right UDVCVTU83 "U84" -> Right UDVCVTU84 "U85" -> Right UDVCVTU85 "U86" -> Right UDVCVTU86 "U87" -> Right UDVCVTU87 "U88" -> Right UDVCVTU88 "U89" -> Right UDVCVTU89 "U90" -> Right UDVCVTU90 "U91" -> Right UDVCVTU91 "U92" -> Right UDVCVTU92 "U93" -> Right UDVCVTU93 "U94" -> Right UDVCVTU94 "U95" -> Right UDVCVTU95 "U96" -> Right UDVCVTU96 "U97" -> Right UDVCVTU97 "U98" -> Right UDVCVTU98 "U99" -> Right UDVCVTU99 "U100" -> Right UDVCVTU100 x -> Left ("Unable to parse UserDefinedVariableConfigurationVariableType from: " <> x) instance ToHttpApiData UserDefinedVariableConfigurationVariableType where toQueryParam = \case UDVCVTU1 -> "U1" UDVCVTU2 -> "U2" UDVCVTU3 -> "U3" UDVCVTU4 -> "U4" UDVCVTU5 -> "U5" UDVCVTU6 -> "U6" UDVCVTU7 -> "U7" UDVCVTU8 -> "U8" UDVCVTU9 -> "U9" UDVCVTU10 -> "U10" UDVCVTU11 -> "U11" UDVCVTU12 -> "U12" UDVCVTU13 -> "U13" UDVCVTU14 -> "U14" UDVCVTU15 -> "U15" UDVCVTU16 -> "U16" UDVCVTU17 -> "U17" UDVCVTU18 -> "U18" UDVCVTU19 -> "U19" UDVCVTU20 -> "U20" UDVCVTU21 -> "U21" UDVCVTU22 -> "U22" UDVCVTU23 -> "U23" UDVCVTU24 -> "U24" UDVCVTU25 -> "U25" UDVCVTU26 -> "U26" UDVCVTU27 -> "U27" UDVCVTU28 -> "U28" UDVCVTU29 -> "U29" UDVCVTU30 -> "U30" UDVCVTU31 -> "U31" UDVCVTU32 -> "U32" UDVCVTU33 -> "U33" UDVCVTU34 -> "U34" UDVCVTU35 -> "U35" UDVCVTU36 -> "U36" UDVCVTU37 -> "U37" UDVCVTU38 -> "U38" UDVCVTU39 -> "U39" UDVCVTU40 -> "U40" UDVCVTU41 -> "U41" UDVCVTU42 -> "U42" UDVCVTU43 -> "U43" UDVCVTU44 -> "U44" UDVCVTU45 -> "U45" UDVCVTU46 -> "U46" UDVCVTU47 -> "U47" UDVCVTU48 -> "U48" UDVCVTU49 -> "U49" UDVCVTU50 -> "U50" UDVCVTU51 -> "U51" UDVCVTU52 -> "U52" UDVCVTU53 -> "U53" UDVCVTU54 -> "U54" UDVCVTU55 -> "U55" UDVCVTU56 -> "U56" UDVCVTU57 -> "U57" UDVCVTU58 -> "U58" UDVCVTU59 -> "U59" UDVCVTU60 -> "U60" UDVCVTU61 -> "U61" UDVCVTU62 -> "U62" UDVCVTU63 -> "U63" UDVCVTU64 -> "U64" UDVCVTU65 -> "U65" UDVCVTU66 -> "U66" UDVCVTU67 -> "U67" UDVCVTU68 -> "U68" UDVCVTU69 -> "U69" UDVCVTU70 -> "U70" UDVCVTU71 -> "U71" UDVCVTU72 -> "U72" UDVCVTU73 -> "U73" UDVCVTU74 -> "U74" UDVCVTU75 -> "U75" UDVCVTU76 -> "U76" UDVCVTU77 -> "U77" UDVCVTU78 -> "U78" UDVCVTU79 -> "U79" UDVCVTU80 -> "U80" UDVCVTU81 -> "U81" UDVCVTU82 -> "U82" UDVCVTU83 -> "U83" UDVCVTU84 -> "U84" UDVCVTU85 -> "U85" UDVCVTU86 -> "U86" UDVCVTU87 -> "U87" UDVCVTU88 -> "U88" UDVCVTU89 -> "U89" UDVCVTU90 -> "U90" UDVCVTU91 -> "U91" UDVCVTU92 -> "U92" UDVCVTU93 -> "U93" UDVCVTU94 -> "U94" UDVCVTU95 -> "U95" UDVCVTU96 -> "U96" UDVCVTU97 -> "U97" UDVCVTU98 -> "U98" UDVCVTU99 -> "U99" UDVCVTU100 -> "U100" instance FromJSON UserDefinedVariableConfigurationVariableType where parseJSON = parseJSONText "UserDefinedVariableConfigurationVariableType" instance ToJSON UserDefinedVariableConfigurationVariableType where toJSON = toJSONText -- | Position in the browser where the window will open. data FsCommandPositionOption = Centered -- ^ @CENTERED@ | DistanceFromTopLeftCorner -- ^ @DISTANCE_FROM_TOP_LEFT_CORNER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FsCommandPositionOption instance FromHttpApiData FsCommandPositionOption where parseQueryParam = \case "CENTERED" -> Right Centered "DISTANCE_FROM_TOP_LEFT_CORNER" -> Right DistanceFromTopLeftCorner x -> Left ("Unable to parse FsCommandPositionOption from: " <> x) instance ToHttpApiData FsCommandPositionOption where toQueryParam = \case Centered -> "CENTERED" DistanceFromTopLeftCorner -> "DISTANCE_FROM_TOP_LEFT_CORNER" instance FromJSON FsCommandPositionOption where parseJSON = parseJSONText "FsCommandPositionOption" instance ToJSON FsCommandPositionOption where toJSON = toJSONText -- | Field by which to sort the list. data AdvertiserLandingPagesListSortField = ALPLSFID -- ^ @ID@ | ALPLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertiserLandingPagesListSortField instance FromHttpApiData AdvertiserLandingPagesListSortField where parseQueryParam = \case "ID" -> Right ALPLSFID "NAME" -> Right ALPLSFName x -> Left ("Unable to parse AdvertiserLandingPagesListSortField from: " <> x) instance ToHttpApiData AdvertiserLandingPagesListSortField where toQueryParam = \case ALPLSFID -> "ID" ALPLSFName -> "NAME" instance FromJSON AdvertiserLandingPagesListSortField where parseJSON = parseJSONText "AdvertiserLandingPagesListSortField" instance ToJSON AdvertiserLandingPagesListSortField where toJSON = toJSONText -- | Order of sorted results. data UserRolesListSortOrder = URLSOAscending -- ^ @ASCENDING@ | URLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable UserRolesListSortOrder instance FromHttpApiData UserRolesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right URLSOAscending "DESCENDING" -> Right URLSODescending x -> Left ("Unable to parse UserRolesListSortOrder from: " <> x) instance ToHttpApiData UserRolesListSortOrder where toQueryParam = \case URLSOAscending -> "ASCENDING" URLSODescending -> "DESCENDING" instance FromJSON UserRolesListSortOrder where parseJSON = parseJSONText "UserRolesListSortOrder" instance ToJSON UserRolesListSortOrder where toJSON = toJSONText -- | Select only placements that are associated with these compatibilities. -- DISPLAY and DISPLAY_INTERSTITIAL refer to rendering either on desktop or -- on mobile devices for regular or interstitial ads respectively. APP and -- APP_INTERSTITIAL are for rendering in mobile apps. IN_STREAM_VIDEO -- refers to rendering in in-stream video ads developed with the VAST -- standard. data PlacementsListCompatibilities = PLCDisplay -- ^ @DISPLAY@ | PLCDisplayInterstitial -- ^ @DISPLAY_INTERSTITIAL@ | PLCApp -- ^ @APP@ | PLCAppInterstitial -- ^ @APP_INTERSTITIAL@ | PLCInStreamVideo -- ^ @IN_STREAM_VIDEO@ | PLCInStreamAudio -- ^ @IN_STREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementsListCompatibilities instance FromHttpApiData PlacementsListCompatibilities where parseQueryParam = \case "DISPLAY" -> Right PLCDisplay "DISPLAY_INTERSTITIAL" -> Right PLCDisplayInterstitial "APP" -> Right PLCApp "APP_INTERSTITIAL" -> Right PLCAppInterstitial "IN_STREAM_VIDEO" -> Right PLCInStreamVideo "IN_STREAM_AUDIO" -> Right PLCInStreamAudio x -> Left ("Unable to parse PlacementsListCompatibilities from: " <> x) instance ToHttpApiData PlacementsListCompatibilities where toQueryParam = \case PLCDisplay -> "DISPLAY" PLCDisplayInterstitial -> "DISPLAY_INTERSTITIAL" PLCApp -> "APP" PLCAppInterstitial -> "APP_INTERSTITIAL" PLCInStreamVideo -> "IN_STREAM_VIDEO" PLCInStreamAudio -> "IN_STREAM_AUDIO" instance FromJSON PlacementsListCompatibilities where parseJSON = parseJSONText "PlacementsListCompatibilities" instance ToJSON PlacementsListCompatibilities where toJSON = toJSONText -- | Field by which to sort the list. data OrderDocumentsListSortField = ODLSFID -- ^ @ID@ | ODLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OrderDocumentsListSortField instance FromHttpApiData OrderDocumentsListSortField where parseQueryParam = \case "ID" -> Right ODLSFID "NAME" -> Right ODLSFName x -> Left ("Unable to parse OrderDocumentsListSortField from: " <> x) instance ToHttpApiData OrderDocumentsListSortField where toQueryParam = \case ODLSFID -> "ID" ODLSFName -> "NAME" instance FromJSON OrderDocumentsListSortField where parseJSON = parseJSONText "OrderDocumentsListSortField" instance ToJSON OrderDocumentsListSortField where toJSON = toJSONText data CreativeCompatibilityItem = CCIDisplay -- ^ @DISPLAY@ | CCIDisplayInterstitial -- ^ @DISPLAY_INTERSTITIAL@ | CCIApp -- ^ @APP@ | CCIAppInterstitial -- ^ @APP_INTERSTITIAL@ | CCIInStreamVideo -- ^ @IN_STREAM_VIDEO@ | CCIInStreamAudio -- ^ @IN_STREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeCompatibilityItem instance FromHttpApiData CreativeCompatibilityItem where parseQueryParam = \case "DISPLAY" -> Right CCIDisplay "DISPLAY_INTERSTITIAL" -> Right CCIDisplayInterstitial "APP" -> Right CCIApp "APP_INTERSTITIAL" -> Right CCIAppInterstitial "IN_STREAM_VIDEO" -> Right CCIInStreamVideo "IN_STREAM_AUDIO" -> Right CCIInStreamAudio x -> Left ("Unable to parse CreativeCompatibilityItem from: " <> x) instance ToHttpApiData CreativeCompatibilityItem where toQueryParam = \case CCIDisplay -> "DISPLAY" CCIDisplayInterstitial -> "DISPLAY_INTERSTITIAL" CCIApp -> "APP" CCIAppInterstitial -> "APP_INTERSTITIAL" CCIInStreamVideo -> "IN_STREAM_VIDEO" CCIInStreamAudio -> "IN_STREAM_AUDIO" instance FromJSON CreativeCompatibilityItem where parseJSON = parseJSONText "CreativeCompatibilityItem" instance ToJSON CreativeCompatibilityItem where toJSON = toJSONText -- | The type of delivery for the owner to receive, if enabled. data ReportDeliveryEmailOwnerDeliveryType = RDEODTLink -- ^ @LINK@ | RDEODTAttachment -- ^ @ATTACHMENT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportDeliveryEmailOwnerDeliveryType instance FromHttpApiData ReportDeliveryEmailOwnerDeliveryType where parseQueryParam = \case "LINK" -> Right RDEODTLink "ATTACHMENT" -> Right RDEODTAttachment x -> Left ("Unable to parse ReportDeliveryEmailOwnerDeliveryType from: " <> x) instance ToHttpApiData ReportDeliveryEmailOwnerDeliveryType where toQueryParam = \case RDEODTLink -> "LINK" RDEODTAttachment -> "ATTACHMENT" instance FromJSON ReportDeliveryEmailOwnerDeliveryType where parseJSON = parseJSONText "ReportDeliveryEmailOwnerDeliveryType" instance ToJSON ReportDeliveryEmailOwnerDeliveryType where toJSON = toJSONText -- | Site contact type. data SiteContactContactType = SalesPerson -- ^ @SALES_PERSON@ | Trafficker -- ^ @TRAFFICKER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SiteContactContactType instance FromHttpApiData SiteContactContactType where parseQueryParam = \case "SALES_PERSON" -> Right SalesPerson "TRAFFICKER" -> Right Trafficker x -> Left ("Unable to parse SiteContactContactType from: " <> x) instance ToHttpApiData SiteContactContactType where toQueryParam = \case SalesPerson -> "SALES_PERSON" Trafficker -> "TRAFFICKER" instance FromJSON SiteContactContactType where parseJSON = parseJSONText "SiteContactContactType" instance ToJSON SiteContactContactType where toJSON = toJSONText -- | Order of sorted results. data ReportsListSortOrder = RLSOAscending -- ^ @ASCENDING@ -- Ascending order. | RLSODescending -- ^ @DESCENDING@ -- Descending order. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportsListSortOrder instance FromHttpApiData ReportsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right RLSOAscending "DESCENDING" -> Right RLSODescending x -> Left ("Unable to parse ReportsListSortOrder from: " <> x) instance ToHttpApiData ReportsListSortOrder where toQueryParam = \case RLSOAscending -> "ASCENDING" RLSODescending -> "DESCENDING" instance FromJSON ReportsListSortOrder where parseJSON = parseJSONText "ReportsListSortOrder" instance ToJSON ReportsListSortOrder where toJSON = toJSONText -- | Field by which to sort the list. data TargetableRemarketingListsListSortField = TRLLSFID -- ^ @ID@ | TRLLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetableRemarketingListsListSortField instance FromHttpApiData TargetableRemarketingListsListSortField where parseQueryParam = \case "ID" -> Right TRLLSFID "NAME" -> Right TRLLSFName x -> Left ("Unable to parse TargetableRemarketingListsListSortField from: " <> x) instance ToHttpApiData TargetableRemarketingListsListSortField where toQueryParam = \case TRLLSFID -> "ID" TRLLSFName -> "NAME" instance FromJSON TargetableRemarketingListsListSortField where parseJSON = parseJSONText "TargetableRemarketingListsListSortField" instance ToJSON TargetableRemarketingListsListSortField where toJSON = toJSONText -- | Order of sorted results. data CampaignsListSortOrder = CLSOAscending -- ^ @ASCENDING@ | CLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CampaignsListSortOrder instance FromHttpApiData CampaignsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right CLSOAscending "DESCENDING" -> Right CLSODescending x -> Left ("Unable to parse CampaignsListSortOrder from: " <> x) instance ToHttpApiData CampaignsListSortOrder where toQueryParam = \case CLSOAscending -> "ASCENDING" CLSODescending -> "DESCENDING" instance FromJSON CampaignsListSortOrder where parseJSON = parseJSONText "CampaignsListSortOrder" instance ToJSON CampaignsListSortOrder where toJSON = toJSONText -- | Select only floodlight activity groups with the specified floodlight -- activity group type. data FloodlightActivityGroupsListType = Counter -- ^ @COUNTER@ | Sale -- ^ @SALE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityGroupsListType instance FromHttpApiData FloodlightActivityGroupsListType where parseQueryParam = \case "COUNTER" -> Right Counter "SALE" -> Right Sale x -> Left ("Unable to parse FloodlightActivityGroupsListType from: " <> x) instance ToHttpApiData FloodlightActivityGroupsListType where toQueryParam = \case Counter -> "COUNTER" Sale -> "SALE" instance FromJSON FloodlightActivityGroupsListType where parseJSON = parseJSONText "FloodlightActivityGroupsListType" instance ToJSON FloodlightActivityGroupsListType where toJSON = toJSONText -- | Day that will be counted as the first day of the week in reports. This -- is a required field. data FloodlightConfigurationFirstDayOfWeek = Monday -- ^ @MONDAY@ | Sunday -- ^ @SUNDAY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightConfigurationFirstDayOfWeek instance FromHttpApiData FloodlightConfigurationFirstDayOfWeek where parseQueryParam = \case "MONDAY" -> Right Monday "SUNDAY" -> Right Sunday x -> Left ("Unable to parse FloodlightConfigurationFirstDayOfWeek from: " <> x) instance ToHttpApiData FloodlightConfigurationFirstDayOfWeek where toQueryParam = \case Monday -> "MONDAY" Sunday -> "SUNDAY" instance FromJSON FloodlightConfigurationFirstDayOfWeek where parseJSON = parseJSONText "FloodlightConfigurationFirstDayOfWeek" instance ToJSON FloodlightConfigurationFirstDayOfWeek where toJSON = toJSONText -- | Serving priority of an ad, with respect to other ads. The lower the -- priority number, the greater the priority with which it is served. data DeliverySchedulePriority = AdPriority01 -- ^ @AD_PRIORITY_01@ | AdPriority02 -- ^ @AD_PRIORITY_02@ | AdPriority03 -- ^ @AD_PRIORITY_03@ | AdPriority04 -- ^ @AD_PRIORITY_04@ | AdPriority05 -- ^ @AD_PRIORITY_05@ | AdPriority06 -- ^ @AD_PRIORITY_06@ | AdPriority07 -- ^ @AD_PRIORITY_07@ | AdPriority08 -- ^ @AD_PRIORITY_08@ | AdPriority09 -- ^ @AD_PRIORITY_09@ | AdPriority10 -- ^ @AD_PRIORITY_10@ | AdPriority11 -- ^ @AD_PRIORITY_11@ | AdPriority12 -- ^ @AD_PRIORITY_12@ | AdPriority13 -- ^ @AD_PRIORITY_13@ | AdPriority14 -- ^ @AD_PRIORITY_14@ | AdPriority15 -- ^ @AD_PRIORITY_15@ | AdPriority16 -- ^ @AD_PRIORITY_16@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DeliverySchedulePriority instance FromHttpApiData DeliverySchedulePriority where parseQueryParam = \case "AD_PRIORITY_01" -> Right AdPriority01 "AD_PRIORITY_02" -> Right AdPriority02 "AD_PRIORITY_03" -> Right AdPriority03 "AD_PRIORITY_04" -> Right AdPriority04 "AD_PRIORITY_05" -> Right AdPriority05 "AD_PRIORITY_06" -> Right AdPriority06 "AD_PRIORITY_07" -> Right AdPriority07 "AD_PRIORITY_08" -> Right AdPriority08 "AD_PRIORITY_09" -> Right AdPriority09 "AD_PRIORITY_10" -> Right AdPriority10 "AD_PRIORITY_11" -> Right AdPriority11 "AD_PRIORITY_12" -> Right AdPriority12 "AD_PRIORITY_13" -> Right AdPriority13 "AD_PRIORITY_14" -> Right AdPriority14 "AD_PRIORITY_15" -> Right AdPriority15 "AD_PRIORITY_16" -> Right AdPriority16 x -> Left ("Unable to parse DeliverySchedulePriority from: " <> x) instance ToHttpApiData DeliverySchedulePriority where toQueryParam = \case AdPriority01 -> "AD_PRIORITY_01" AdPriority02 -> "AD_PRIORITY_02" AdPriority03 -> "AD_PRIORITY_03" AdPriority04 -> "AD_PRIORITY_04" AdPriority05 -> "AD_PRIORITY_05" AdPriority06 -> "AD_PRIORITY_06" AdPriority07 -> "AD_PRIORITY_07" AdPriority08 -> "AD_PRIORITY_08" AdPriority09 -> "AD_PRIORITY_09" AdPriority10 -> "AD_PRIORITY_10" AdPriority11 -> "AD_PRIORITY_11" AdPriority12 -> "AD_PRIORITY_12" AdPriority13 -> "AD_PRIORITY_13" AdPriority14 -> "AD_PRIORITY_14" AdPriority15 -> "AD_PRIORITY_15" AdPriority16 -> "AD_PRIORITY_16" instance FromJSON DeliverySchedulePriority where parseJSON = parseJSONText "DeliverySchedulePriority" instance ToJSON DeliverySchedulePriority where toJSON = toJSONText -- | Select only floodlight activities with the specified floodlight activity -- group type. data FloodlightActivitiesListFloodlightActivityGroupType = FALFAGTCounter -- ^ @COUNTER@ | FALFAGTSale -- ^ @SALE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivitiesListFloodlightActivityGroupType instance FromHttpApiData FloodlightActivitiesListFloodlightActivityGroupType where parseQueryParam = \case "COUNTER" -> Right FALFAGTCounter "SALE" -> Right FALFAGTSale x -> Left ("Unable to parse FloodlightActivitiesListFloodlightActivityGroupType from: " <> x) instance ToHttpApiData FloodlightActivitiesListFloodlightActivityGroupType where toQueryParam = \case FALFAGTCounter -> "COUNTER" FALFAGTSale -> "SALE" instance FromJSON FloodlightActivitiesListFloodlightActivityGroupType where parseJSON = parseJSONText "FloodlightActivitiesListFloodlightActivityGroupType" instance ToJSON FloodlightActivitiesListFloodlightActivityGroupType where toJSON = toJSONText -- | Source application where creative was authored. Presently, only DBM -- authored creatives will have this field set. Applicable to all creative -- types. data CreativeAuthoringSource = CreativeAuthoringSourceDcm -- ^ @CREATIVE_AUTHORING_SOURCE_DCM@ | CreativeAuthoringSourceDBm -- ^ @CREATIVE_AUTHORING_SOURCE_DBM@ | CreativeAuthoringSourceStudio -- ^ @CREATIVE_AUTHORING_SOURCE_STUDIO@ | CreativeAuthoringSourceGwd -- ^ @CREATIVE_AUTHORING_SOURCE_GWD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAuthoringSource instance FromHttpApiData CreativeAuthoringSource where parseQueryParam = \case "CREATIVE_AUTHORING_SOURCE_DCM" -> Right CreativeAuthoringSourceDcm "CREATIVE_AUTHORING_SOURCE_DBM" -> Right CreativeAuthoringSourceDBm "CREATIVE_AUTHORING_SOURCE_STUDIO" -> Right CreativeAuthoringSourceStudio "CREATIVE_AUTHORING_SOURCE_GWD" -> Right CreativeAuthoringSourceGwd x -> Left ("Unable to parse CreativeAuthoringSource from: " <> x) instance ToHttpApiData CreativeAuthoringSource where toQueryParam = \case CreativeAuthoringSourceDcm -> "CREATIVE_AUTHORING_SOURCE_DCM" CreativeAuthoringSourceDBm -> "CREATIVE_AUTHORING_SOURCE_DBM" CreativeAuthoringSourceStudio -> "CREATIVE_AUTHORING_SOURCE_STUDIO" CreativeAuthoringSourceGwd -> "CREATIVE_AUTHORING_SOURCE_GWD" instance FromJSON CreativeAuthoringSource where parseJSON = parseJSONText "CreativeAuthoringSource" instance ToJSON CreativeAuthoringSource where toJSON = toJSONText -- | Payment source for this placement. This is a required field that is -- read-only after insertion. data PlacementPaymentSource = PPSPlacementAgencyPaid -- ^ @PLACEMENT_AGENCY_PAID@ | PPSPlacementPublisherPaid -- ^ @PLACEMENT_PUBLISHER_PAID@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementPaymentSource instance FromHttpApiData PlacementPaymentSource where parseQueryParam = \case "PLACEMENT_AGENCY_PAID" -> Right PPSPlacementAgencyPaid "PLACEMENT_PUBLISHER_PAID" -> Right PPSPlacementPublisherPaid x -> Left ("Unable to parse PlacementPaymentSource from: " <> x) instance ToHttpApiData PlacementPaymentSource where toQueryParam = \case PPSPlacementAgencyPaid -> "PLACEMENT_AGENCY_PAID" PPSPlacementPublisherPaid -> "PLACEMENT_PUBLISHER_PAID" instance FromJSON PlacementPaymentSource where parseJSON = parseJSONText "PlacementPaymentSource" instance ToJSON PlacementPaymentSource where toJSON = toJSONText -- | Order of sorted results. data ReportsFilesListSortOrder = RFLSOAscending -- ^ @ASCENDING@ | RFLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportsFilesListSortOrder instance FromHttpApiData ReportsFilesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right RFLSOAscending "DESCENDING" -> Right RFLSODescending x -> Left ("Unable to parse ReportsFilesListSortOrder from: " <> x) instance ToHttpApiData ReportsFilesListSortOrder where toQueryParam = \case RFLSOAscending -> "ASCENDING" RFLSODescending -> "DESCENDING" instance FromJSON ReportsFilesListSortOrder where parseJSON = parseJSONText "ReportsFilesListSortOrder" instance ToJSON ReportsFilesListSortOrder where toJSON = toJSONText -- | Field by which to sort the list. data InventoryItemsListSortField = IILSFID -- ^ @ID@ | IILSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InventoryItemsListSortField instance FromHttpApiData InventoryItemsListSortField where parseQueryParam = \case "ID" -> Right IILSFID "NAME" -> Right IILSFName x -> Left ("Unable to parse InventoryItemsListSortField from: " <> x) instance ToHttpApiData InventoryItemsListSortField where toQueryParam = \case IILSFID -> "ID" IILSFName -> "NAME" instance FromJSON InventoryItemsListSortField where parseJSON = parseJSONText "InventoryItemsListSortField" instance ToJSON InventoryItemsListSortField where toJSON = toJSONText -- | Event tag type. Can be used to specify whether to use a third-party -- pixel, a third-party JavaScript URL, or a third-party click-through URL -- for either impression or click tracking. This is a required field. data EventTagType = ETTImpressionImageEventTag -- ^ @IMPRESSION_IMAGE_EVENT_TAG@ | ETTImpressionJavascriptEventTag -- ^ @IMPRESSION_JAVASCRIPT_EVENT_TAG@ | ETTClickThroughEventTag -- ^ @CLICK_THROUGH_EVENT_TAG@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EventTagType instance FromHttpApiData EventTagType where parseQueryParam = \case "IMPRESSION_IMAGE_EVENT_TAG" -> Right ETTImpressionImageEventTag "IMPRESSION_JAVASCRIPT_EVENT_TAG" -> Right ETTImpressionJavascriptEventTag "CLICK_THROUGH_EVENT_TAG" -> Right ETTClickThroughEventTag x -> Left ("Unable to parse EventTagType from: " <> x) instance ToHttpApiData EventTagType where toQueryParam = \case ETTImpressionImageEventTag -> "IMPRESSION_IMAGE_EVENT_TAG" ETTImpressionJavascriptEventTag -> "IMPRESSION_JAVASCRIPT_EVENT_TAG" ETTClickThroughEventTag -> "CLICK_THROUGH_EVENT_TAG" instance FromJSON EventTagType where parseJSON = parseJSONText "EventTagType" instance ToJSON EventTagType where toJSON = toJSONText -- | Order of sorted results. data CreativesListSortOrder = CAscending -- ^ @ASCENDING@ | CDescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativesListSortOrder instance FromHttpApiData CreativesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right CAscending "DESCENDING" -> Right CDescending x -> Left ("Unable to parse CreativesListSortOrder from: " <> x) instance ToHttpApiData CreativesListSortOrder where toQueryParam = \case CAscending -> "ASCENDING" CDescending -> "DESCENDING" instance FromJSON CreativesListSortOrder where parseJSON = parseJSONText "CreativesListSortOrder" instance ToJSON CreativesListSortOrder where toJSON = toJSONText -- | Measurement partner used for tag wrapping. data MeasurementPartnerCampaignLinkMeasurementPartner = MPCLMPNone -- ^ @NONE@ | MPCLMPIntegralAdScience -- ^ @INTEGRAL_AD_SCIENCE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MeasurementPartnerCampaignLinkMeasurementPartner instance FromHttpApiData MeasurementPartnerCampaignLinkMeasurementPartner where parseQueryParam = \case "NONE" -> Right MPCLMPNone "INTEGRAL_AD_SCIENCE" -> Right MPCLMPIntegralAdScience x -> Left ("Unable to parse MeasurementPartnerCampaignLinkMeasurementPartner from: " <> x) instance ToHttpApiData MeasurementPartnerCampaignLinkMeasurementPartner where toQueryParam = \case MPCLMPNone -> "NONE" MPCLMPIntegralAdScience -> "INTEGRAL_AD_SCIENCE" instance FromJSON MeasurementPartnerCampaignLinkMeasurementPartner where parseJSON = parseJSONText "MeasurementPartnerCampaignLinkMeasurementPartner" instance ToJSON MeasurementPartnerCampaignLinkMeasurementPartner where toJSON = toJSONText -- | Select only inventory items with this type. data InventoryItemsListType = PlanningPlacementTypeRegular -- ^ @PLANNING_PLACEMENT_TYPE_REGULAR@ | PlanningPlacementTypeCredit -- ^ @PLANNING_PLACEMENT_TYPE_CREDIT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InventoryItemsListType instance FromHttpApiData InventoryItemsListType where parseQueryParam = \case "PLANNING_PLACEMENT_TYPE_REGULAR" -> Right PlanningPlacementTypeRegular "PLANNING_PLACEMENT_TYPE_CREDIT" -> Right PlanningPlacementTypeCredit x -> Left ("Unable to parse InventoryItemsListType from: " <> x) instance ToHttpApiData InventoryItemsListType where toQueryParam = \case PlanningPlacementTypeRegular -> "PLANNING_PLACEMENT_TYPE_REGULAR" PlanningPlacementTypeCredit -> "PLANNING_PLACEMENT_TYPE_CREDIT" instance FromJSON InventoryItemsListType where parseJSON = parseJSONText "InventoryItemsListType" instance ToJSON InventoryItemsListType where toJSON = toJSONText -- | Popup window position either centered or at specific coordinate. data PopupWindowPropertiesPositionType = Center -- ^ @CENTER@ | Coordinates -- ^ @COORDINATES@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PopupWindowPropertiesPositionType instance FromHttpApiData PopupWindowPropertiesPositionType where parseQueryParam = \case "CENTER" -> Right Center "COORDINATES" -> Right Coordinates x -> Left ("Unable to parse PopupWindowPropertiesPositionType from: " <> x) instance ToHttpApiData PopupWindowPropertiesPositionType where toQueryParam = \case Center -> "CENTER" Coordinates -> "COORDINATES" instance FromJSON PopupWindowPropertiesPositionType where parseJSON = parseJSONText "PopupWindowPropertiesPositionType" instance ToJSON PopupWindowPropertiesPositionType where toJSON = toJSONText -- | Option specifying how keywords are embedded in ad tags. This setting can -- be used to specify whether keyword placeholders are inserted in -- placement tags for this site. Publishers can then add keywords to those -- placeholders. data TagSettingKeywordOption = PlaceholderWithListOfKeywords -- ^ @PLACEHOLDER_WITH_LIST_OF_KEYWORDS@ | Ignore -- ^ @IGNORE@ | GenerateSeparateTagForEachKeyword -- ^ @GENERATE_SEPARATE_TAG_FOR_EACH_KEYWORD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TagSettingKeywordOption instance FromHttpApiData TagSettingKeywordOption where parseQueryParam = \case "PLACEHOLDER_WITH_LIST_OF_KEYWORDS" -> Right PlaceholderWithListOfKeywords "IGNORE" -> Right Ignore "GENERATE_SEPARATE_TAG_FOR_EACH_KEYWORD" -> Right GenerateSeparateTagForEachKeyword x -> Left ("Unable to parse TagSettingKeywordOption from: " <> x) instance ToHttpApiData TagSettingKeywordOption where toQueryParam = \case PlaceholderWithListOfKeywords -> "PLACEHOLDER_WITH_LIST_OF_KEYWORDS" Ignore -> "IGNORE" GenerateSeparateTagForEachKeyword -> "GENERATE_SEPARATE_TAG_FOR_EACH_KEYWORD" instance FromJSON TagSettingKeywordOption where parseJSON = parseJSONText "TagSettingKeywordOption" instance ToJSON TagSettingKeywordOption where toJSON = toJSONText -- | Authoring tool for HTML5 banner creatives. This is a read-only field. -- Applicable to the following creative types: HTML5_BANNER. data CreativeAuthoringTool = Ninja -- ^ @NINJA@ | Swiffy -- ^ @SWIFFY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAuthoringTool instance FromHttpApiData CreativeAuthoringTool where parseQueryParam = \case "NINJA" -> Right Ninja "SWIFFY" -> Right Swiffy x -> Left ("Unable to parse CreativeAuthoringTool from: " <> x) instance ToHttpApiData CreativeAuthoringTool where toQueryParam = \case Ninja -> "NINJA" Swiffy -> "SWIFFY" instance FromJSON CreativeAuthoringTool where parseJSON = parseJSONText "CreativeAuthoringTool" instance ToJSON CreativeAuthoringTool where toJSON = toJSONText -- | Type of this contact. data OrderContactContactType = PlanningOrderContactBuyerContact -- ^ @PLANNING_ORDER_CONTACT_BUYER_CONTACT@ | PlanningOrderContactBuyerBillingContact -- ^ @PLANNING_ORDER_CONTACT_BUYER_BILLING_CONTACT@ | PlanningOrderContactSellerContact -- ^ @PLANNING_ORDER_CONTACT_SELLER_CONTACT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OrderContactContactType instance FromHttpApiData OrderContactContactType where parseQueryParam = \case "PLANNING_ORDER_CONTACT_BUYER_CONTACT" -> Right PlanningOrderContactBuyerContact "PLANNING_ORDER_CONTACT_BUYER_BILLING_CONTACT" -> Right PlanningOrderContactBuyerBillingContact "PLANNING_ORDER_CONTACT_SELLER_CONTACT" -> Right PlanningOrderContactSellerContact x -> Left ("Unable to parse OrderContactContactType from: " <> x) instance ToHttpApiData OrderContactContactType where toQueryParam = \case PlanningOrderContactBuyerContact -> "PLANNING_ORDER_CONTACT_BUYER_CONTACT" PlanningOrderContactBuyerBillingContact -> "PLANNING_ORDER_CONTACT_BUYER_BILLING_CONTACT" PlanningOrderContactSellerContact -> "PLANNING_ORDER_CONTACT_SELLER_CONTACT" instance FromJSON OrderContactContactType where parseJSON = parseJSONText "OrderContactContactType" instance ToJSON OrderContactContactType where toJSON = toJSONText -- | Type of asset to upload. This is a required field. FLASH and IMAGE are -- no longer supported for new uploads. All image assets should use -- HTML_IMAGE. data CreativeAssetIdType = CAITImage -- ^ @IMAGE@ | CAITFlash -- ^ @FLASH@ | CAITVideo -- ^ @VIDEO@ | CAITHTML -- ^ @HTML@ | CAITHTMLImage -- ^ @HTML_IMAGE@ | CAITAudio -- ^ @AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetIdType instance FromHttpApiData CreativeAssetIdType where parseQueryParam = \case "IMAGE" -> Right CAITImage "FLASH" -> Right CAITFlash "VIDEO" -> Right CAITVideo "HTML" -> Right CAITHTML "HTML_IMAGE" -> Right CAITHTMLImage "AUDIO" -> Right CAITAudio x -> Left ("Unable to parse CreativeAssetIdType from: " <> x) instance ToHttpApiData CreativeAssetIdType where toQueryParam = \case CAITImage -> "IMAGE" CAITFlash -> "FLASH" CAITVideo -> "VIDEO" CAITHTML -> "HTML" CAITHTMLImage -> "HTML_IMAGE" CAITAudio -> "AUDIO" instance FromJSON CreativeAssetIdType where parseJSON = parseJSONText "CreativeAssetIdType" instance ToJSON CreativeAssetIdType where toJSON = toJSONText -- | Order of sorted results. data AccountUserProFilesListSortOrder = AUPFLSOAscending -- ^ @ASCENDING@ | AUPFLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountUserProFilesListSortOrder instance FromHttpApiData AccountUserProFilesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right AUPFLSOAscending "DESCENDING" -> Right AUPFLSODescending x -> Left ("Unable to parse AccountUserProFilesListSortOrder from: " <> x) instance ToHttpApiData AccountUserProFilesListSortOrder where toQueryParam = \case AUPFLSOAscending -> "ASCENDING" AUPFLSODescending -> "DESCENDING" instance FromJSON AccountUserProFilesListSortOrder where parseJSON = parseJSONText "AccountUserProFilesListSortOrder" instance ToJSON AccountUserProFilesListSortOrder where toJSON = toJSONText -- | Product from which this remarketing list was originated. data RemarketingListListSource = RLLSRemarketingListSourceOther -- ^ @REMARKETING_LIST_SOURCE_OTHER@ | RLLSRemarketingListSourceAdx -- ^ @REMARKETING_LIST_SOURCE_ADX@ | RLLSRemarketingListSourceDfp -- ^ @REMARKETING_LIST_SOURCE_DFP@ | RLLSRemarketingListSourceXfp -- ^ @REMARKETING_LIST_SOURCE_XFP@ | RLLSRemarketingListSourceDfa -- ^ @REMARKETING_LIST_SOURCE_DFA@ | RLLSRemarketingListSourceGa -- ^ @REMARKETING_LIST_SOURCE_GA@ | RLLSRemarketingListSourceYouTube -- ^ @REMARKETING_LIST_SOURCE_YOUTUBE@ | RLLSRemarketingListSourceDBm -- ^ @REMARKETING_LIST_SOURCE_DBM@ | RLLSRemarketingListSourceGplus -- ^ @REMARKETING_LIST_SOURCE_GPLUS@ | RLLSRemarketingListSourceDmp -- ^ @REMARKETING_LIST_SOURCE_DMP@ | RLLSRemarketingListSourcePlayStore -- ^ @REMARKETING_LIST_SOURCE_PLAY_STORE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RemarketingListListSource instance FromHttpApiData RemarketingListListSource where parseQueryParam = \case "REMARKETING_LIST_SOURCE_OTHER" -> Right RLLSRemarketingListSourceOther "REMARKETING_LIST_SOURCE_ADX" -> Right RLLSRemarketingListSourceAdx "REMARKETING_LIST_SOURCE_DFP" -> Right RLLSRemarketingListSourceDfp "REMARKETING_LIST_SOURCE_XFP" -> Right RLLSRemarketingListSourceXfp "REMARKETING_LIST_SOURCE_DFA" -> Right RLLSRemarketingListSourceDfa "REMARKETING_LIST_SOURCE_GA" -> Right RLLSRemarketingListSourceGa "REMARKETING_LIST_SOURCE_YOUTUBE" -> Right RLLSRemarketingListSourceYouTube "REMARKETING_LIST_SOURCE_DBM" -> Right RLLSRemarketingListSourceDBm "REMARKETING_LIST_SOURCE_GPLUS" -> Right RLLSRemarketingListSourceGplus "REMARKETING_LIST_SOURCE_DMP" -> Right RLLSRemarketingListSourceDmp "REMARKETING_LIST_SOURCE_PLAY_STORE" -> Right RLLSRemarketingListSourcePlayStore x -> Left ("Unable to parse RemarketingListListSource from: " <> x) instance ToHttpApiData RemarketingListListSource where toQueryParam = \case RLLSRemarketingListSourceOther -> "REMARKETING_LIST_SOURCE_OTHER" RLLSRemarketingListSourceAdx -> "REMARKETING_LIST_SOURCE_ADX" RLLSRemarketingListSourceDfp -> "REMARKETING_LIST_SOURCE_DFP" RLLSRemarketingListSourceXfp -> "REMARKETING_LIST_SOURCE_XFP" RLLSRemarketingListSourceDfa -> "REMARKETING_LIST_SOURCE_DFA" RLLSRemarketingListSourceGa -> "REMARKETING_LIST_SOURCE_GA" RLLSRemarketingListSourceYouTube -> "REMARKETING_LIST_SOURCE_YOUTUBE" RLLSRemarketingListSourceDBm -> "REMARKETING_LIST_SOURCE_DBM" RLLSRemarketingListSourceGplus -> "REMARKETING_LIST_SOURCE_GPLUS" RLLSRemarketingListSourceDmp -> "REMARKETING_LIST_SOURCE_DMP" RLLSRemarketingListSourcePlayStore -> "REMARKETING_LIST_SOURCE_PLAY_STORE" instance FromJSON RemarketingListListSource where parseJSON = parseJSONText "RemarketingListListSource" instance ToJSON RemarketingListListSource where toJSON = toJSONText -- | . data MeasurementPartnerCampaignLinkLinkStatus = MeasurementPartnerUnlinked -- ^ @MEASUREMENT_PARTNER_UNLINKED@ | MeasurementPartnerLinked -- ^ @MEASUREMENT_PARTNER_LINKED@ | MeasurementPartnerLinkPending -- ^ @MEASUREMENT_PARTNER_LINK_PENDING@ | MeasurementPartnerLinkFailure -- ^ @MEASUREMENT_PARTNER_LINK_FAILURE@ | MeasurementPartnerLinkOptOut -- ^ @MEASUREMENT_PARTNER_LINK_OPT_OUT@ | MeasurementPartnerLinkOptOutPending -- ^ @MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING@ | MeasurementPartnerLinkWrAppingPending -- ^ @MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING@ | MeasurementPartnerModeChangePending -- ^ @MEASUREMENT_PARTNER_MODE_CHANGE_PENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MeasurementPartnerCampaignLinkLinkStatus instance FromHttpApiData MeasurementPartnerCampaignLinkLinkStatus where parseQueryParam = \case "MEASUREMENT_PARTNER_UNLINKED" -> Right MeasurementPartnerUnlinked "MEASUREMENT_PARTNER_LINKED" -> Right MeasurementPartnerLinked "MEASUREMENT_PARTNER_LINK_PENDING" -> Right MeasurementPartnerLinkPending "MEASUREMENT_PARTNER_LINK_FAILURE" -> Right MeasurementPartnerLinkFailure "MEASUREMENT_PARTNER_LINK_OPT_OUT" -> Right MeasurementPartnerLinkOptOut "MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING" -> Right MeasurementPartnerLinkOptOutPending "MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING" -> Right MeasurementPartnerLinkWrAppingPending "MEASUREMENT_PARTNER_MODE_CHANGE_PENDING" -> Right MeasurementPartnerModeChangePending x -> Left ("Unable to parse MeasurementPartnerCampaignLinkLinkStatus from: " <> x) instance ToHttpApiData MeasurementPartnerCampaignLinkLinkStatus where toQueryParam = \case MeasurementPartnerUnlinked -> "MEASUREMENT_PARTNER_UNLINKED" MeasurementPartnerLinked -> "MEASUREMENT_PARTNER_LINKED" MeasurementPartnerLinkPending -> "MEASUREMENT_PARTNER_LINK_PENDING" MeasurementPartnerLinkFailure -> "MEASUREMENT_PARTNER_LINK_FAILURE" MeasurementPartnerLinkOptOut -> "MEASUREMENT_PARTNER_LINK_OPT_OUT" MeasurementPartnerLinkOptOutPending -> "MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING" MeasurementPartnerLinkWrAppingPending -> "MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING" MeasurementPartnerModeChangePending -> "MEASUREMENT_PARTNER_MODE_CHANGE_PENDING" instance FromJSON MeasurementPartnerCampaignLinkLinkStatus where parseJSON = parseJSONText "MeasurementPartnerCampaignLinkLinkStatus" instance ToJSON MeasurementPartnerCampaignLinkLinkStatus where toJSON = toJSONText -- | User type of the user profile. This is a read-only field that can be -- left blank. data AccountUserProFileUserAccessType = NormalUser -- ^ @NORMAL_USER@ | SuperUser -- ^ @SUPER_USER@ | InternalAdministrator -- ^ @INTERNAL_ADMINISTRATOR@ | ReadOnlySuperUser -- ^ @READ_ONLY_SUPER_USER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountUserProFileUserAccessType instance FromHttpApiData AccountUserProFileUserAccessType where parseQueryParam = \case "NORMAL_USER" -> Right NormalUser "SUPER_USER" -> Right SuperUser "INTERNAL_ADMINISTRATOR" -> Right InternalAdministrator "READ_ONLY_SUPER_USER" -> Right ReadOnlySuperUser x -> Left ("Unable to parse AccountUserProFileUserAccessType from: " <> x) instance ToHttpApiData AccountUserProFileUserAccessType where toQueryParam = \case NormalUser -> "NORMAL_USER" SuperUser -> "SUPER_USER" InternalAdministrator -> "INTERNAL_ADMINISTRATOR" ReadOnlySuperUser -> "READ_ONLY_SUPER_USER" instance FromJSON AccountUserProFileUserAccessType where parseJSON = parseJSONText "AccountUserProFileUserAccessType" instance ToJSON AccountUserProFileUserAccessType where toJSON = toJSONText -- | Initial wait time type before making the asset visible. Applicable to -- the following creative types: all RICH_MEDIA. data CreativeAssetStartTimeType = AssetStartTimeTypeNone -- ^ @ASSET_START_TIME_TYPE_NONE@ | AssetStartTimeTypeCustom -- ^ @ASSET_START_TIME_TYPE_CUSTOM@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetStartTimeType instance FromHttpApiData CreativeAssetStartTimeType where parseQueryParam = \case "ASSET_START_TIME_TYPE_NONE" -> Right AssetStartTimeTypeNone "ASSET_START_TIME_TYPE_CUSTOM" -> Right AssetStartTimeTypeCustom x -> Left ("Unable to parse CreativeAssetStartTimeType from: " <> x) instance ToHttpApiData CreativeAssetStartTimeType where toQueryParam = \case AssetStartTimeTypeNone -> "ASSET_START_TIME_TYPE_NONE" AssetStartTimeTypeCustom -> "ASSET_START_TIME_TYPE_CUSTOM" instance FromJSON CreativeAssetStartTimeType where parseJSON = parseJSONText "CreativeAssetStartTimeType" instance ToJSON CreativeAssetStartTimeType where toJSON = toJSONText -- | Audience gender of this project. data ProjectAudienceGender = PlanningAudienceGenderMale -- ^ @PLANNING_AUDIENCE_GENDER_MALE@ | PlanningAudienceGenderFemale -- ^ @PLANNING_AUDIENCE_GENDER_FEMALE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ProjectAudienceGender instance FromHttpApiData ProjectAudienceGender where parseQueryParam = \case "PLANNING_AUDIENCE_GENDER_MALE" -> Right PlanningAudienceGenderMale "PLANNING_AUDIENCE_GENDER_FEMALE" -> Right PlanningAudienceGenderFemale x -> Left ("Unable to parse ProjectAudienceGender from: " <> x) instance ToHttpApiData ProjectAudienceGender where toQueryParam = \case PlanningAudienceGenderMale -> "PLANNING_AUDIENCE_GENDER_MALE" PlanningAudienceGenderFemale -> "PLANNING_AUDIENCE_GENDER_FEMALE" instance FromJSON ProjectAudienceGender where parseJSON = parseJSONText "ProjectAudienceGender" instance ToJSON ProjectAudienceGender where toJSON = toJSONText -- | Field by which to sort the list. data PlacementStrategiesListSortField = PSLSFID -- ^ @ID@ | PSLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementStrategiesListSortField instance FromHttpApiData PlacementStrategiesListSortField where parseQueryParam = \case "ID" -> Right PSLSFID "NAME" -> Right PSLSFName x -> Left ("Unable to parse PlacementStrategiesListSortField from: " <> x) instance ToHttpApiData PlacementStrategiesListSortField where toQueryParam = \case PSLSFID -> "ID" PSLSFName -> "NAME" instance FromJSON PlacementStrategiesListSortField where parseJSON = parseJSONText "PlacementStrategiesListSortField" instance ToJSON PlacementStrategiesListSortField where toJSON = toJSONText -- | Data type for the variable. This is a required field. data UserDefinedVariableConfigurationDataType = String -- ^ @STRING@ | Number -- ^ @NUMBER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable UserDefinedVariableConfigurationDataType instance FromHttpApiData UserDefinedVariableConfigurationDataType where parseQueryParam = \case "STRING" -> Right String "NUMBER" -> Right Number x -> Left ("Unable to parse UserDefinedVariableConfigurationDataType from: " <> x) instance ToHttpApiData UserDefinedVariableConfigurationDataType where toQueryParam = \case String -> "STRING" Number -> "NUMBER" instance FromJSON UserDefinedVariableConfigurationDataType where parseJSON = parseJSONText "UserDefinedVariableConfigurationDataType" instance ToJSON UserDefinedVariableConfigurationDataType where toJSON = toJSONText -- | Code type used for cache busting in the generated tag. Applicable only -- when floodlightActivityGroupType is COUNTER and countingMethod is -- STANDARD_COUNTING or UNIQUE_COUNTING. data FloodlightActivityCacheBustingType = Javascript -- ^ @JAVASCRIPT@ | ActiveServerPage -- ^ @ACTIVE_SERVER_PAGE@ | Jsp -- ^ @JSP@ | Php -- ^ @PHP@ | ColdFusion -- ^ @COLD_FUSION@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityCacheBustingType instance FromHttpApiData FloodlightActivityCacheBustingType where parseQueryParam = \case "JAVASCRIPT" -> Right Javascript "ACTIVE_SERVER_PAGE" -> Right ActiveServerPage "JSP" -> Right Jsp "PHP" -> Right Php "COLD_FUSION" -> Right ColdFusion x -> Left ("Unable to parse FloodlightActivityCacheBustingType from: " <> x) instance ToHttpApiData FloodlightActivityCacheBustingType where toQueryParam = \case Javascript -> "JAVASCRIPT" ActiveServerPage -> "ACTIVE_SERVER_PAGE" Jsp -> "JSP" Php -> "PHP" ColdFusion -> "COLD_FUSION" instance FromJSON FloodlightActivityCacheBustingType where parseJSON = parseJSONText "FloodlightActivityCacheBustingType" instance ToJSON FloodlightActivityCacheBustingType where toJSON = toJSONText -- | Order of sorted results. data CreativeGroupsListSortOrder = CGLSOAscending -- ^ @ASCENDING@ | CGLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeGroupsListSortOrder instance FromHttpApiData CreativeGroupsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right CGLSOAscending "DESCENDING" -> Right CGLSODescending x -> Left ("Unable to parse CreativeGroupsListSortOrder from: " <> x) instance ToHttpApiData CreativeGroupsListSortOrder where toQueryParam = \case CGLSOAscending -> "ASCENDING" CGLSODescending -> "DESCENDING" instance FromJSON CreativeGroupsListSortOrder where parseJSON = parseJSONText "CreativeGroupsListSortOrder" instance ToJSON CreativeGroupsListSortOrder where toJSON = toJSONText -- | Type of this order document data OrderDocumentType = PlanningOrderTypeInsertionOrder -- ^ @PLANNING_ORDER_TYPE_INSERTION_ORDER@ | PlanningOrderTypeChangeOrder -- ^ @PLANNING_ORDER_TYPE_CHANGE_ORDER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OrderDocumentType instance FromHttpApiData OrderDocumentType where parseQueryParam = \case "PLANNING_ORDER_TYPE_INSERTION_ORDER" -> Right PlanningOrderTypeInsertionOrder "PLANNING_ORDER_TYPE_CHANGE_ORDER" -> Right PlanningOrderTypeChangeOrder x -> Left ("Unable to parse OrderDocumentType from: " <> x) instance ToHttpApiData OrderDocumentType where toQueryParam = \case PlanningOrderTypeInsertionOrder -> "PLANNING_ORDER_TYPE_INSERTION_ORDER" PlanningOrderTypeChangeOrder -> "PLANNING_ORDER_TYPE_CHANGE_ORDER" instance FromJSON OrderDocumentType where parseJSON = parseJSONText "OrderDocumentType" instance ToJSON OrderDocumentType where toJSON = toJSONText -- | TagData tag format of this tag. data TagDataFormat = PlacementTagStandard -- ^ @PLACEMENT_TAG_STANDARD@ | PlacementTagIframeJavascript -- ^ @PLACEMENT_TAG_IFRAME_JAVASCRIPT@ | PlacementTagIframeIlayer -- ^ @PLACEMENT_TAG_IFRAME_ILAYER@ | PlacementTagInternalRedirect -- ^ @PLACEMENT_TAG_INTERNAL_REDIRECT@ | PlacementTagJavascript -- ^ @PLACEMENT_TAG_JAVASCRIPT@ | PlacementTagInterstitialIframeJavascript -- ^ @PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT@ | PlacementTagInterstitialInternalRedirect -- ^ @PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT@ | PlacementTagInterstitialJavascript -- ^ @PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT@ | PlacementTagClickCommands -- ^ @PLACEMENT_TAG_CLICK_COMMANDS@ | PlacementTagInstreamVideoPrefetch -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH@ | PlacementTagTracking -- ^ @PLACEMENT_TAG_TRACKING@ | PlacementTagTrackingIframe -- ^ @PLACEMENT_TAG_TRACKING_IFRAME@ | PlacementTagTrackingJavascript -- ^ @PLACEMENT_TAG_TRACKING_JAVASCRIPT@ | PlacementTagInstreamVideoPrefetchVast3 -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3@ | PlacementTagIframeJavascriptLegacy -- ^ @PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY@ | PlacementTagJavascriptLegacy -- ^ @PLACEMENT_TAG_JAVASCRIPT_LEGACY@ | PlacementTagInterstitialIframeJavascriptLegacy -- ^ @PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY@ | PlacementTagInterstitialJavascriptLegacy -- ^ @PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY@ | PlacementTagInstreamVideoPrefetchVast4 -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TagDataFormat instance FromHttpApiData TagDataFormat where parseQueryParam = \case "PLACEMENT_TAG_STANDARD" -> Right PlacementTagStandard "PLACEMENT_TAG_IFRAME_JAVASCRIPT" -> Right PlacementTagIframeJavascript "PLACEMENT_TAG_IFRAME_ILAYER" -> Right PlacementTagIframeIlayer "PLACEMENT_TAG_INTERNAL_REDIRECT" -> Right PlacementTagInternalRedirect "PLACEMENT_TAG_JAVASCRIPT" -> Right PlacementTagJavascript "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT" -> Right PlacementTagInterstitialIframeJavascript "PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT" -> Right PlacementTagInterstitialInternalRedirect "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT" -> Right PlacementTagInterstitialJavascript "PLACEMENT_TAG_CLICK_COMMANDS" -> Right PlacementTagClickCommands "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH" -> Right PlacementTagInstreamVideoPrefetch "PLACEMENT_TAG_TRACKING" -> Right PlacementTagTracking "PLACEMENT_TAG_TRACKING_IFRAME" -> Right PlacementTagTrackingIframe "PLACEMENT_TAG_TRACKING_JAVASCRIPT" -> Right PlacementTagTrackingJavascript "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3" -> Right PlacementTagInstreamVideoPrefetchVast3 "PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY" -> Right PlacementTagIframeJavascriptLegacy "PLACEMENT_TAG_JAVASCRIPT_LEGACY" -> Right PlacementTagJavascriptLegacy "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY" -> Right PlacementTagInterstitialIframeJavascriptLegacy "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY" -> Right PlacementTagInterstitialJavascriptLegacy "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4" -> Right PlacementTagInstreamVideoPrefetchVast4 x -> Left ("Unable to parse TagDataFormat from: " <> x) instance ToHttpApiData TagDataFormat where toQueryParam = \case PlacementTagStandard -> "PLACEMENT_TAG_STANDARD" PlacementTagIframeJavascript -> "PLACEMENT_TAG_IFRAME_JAVASCRIPT" PlacementTagIframeIlayer -> "PLACEMENT_TAG_IFRAME_ILAYER" PlacementTagInternalRedirect -> "PLACEMENT_TAG_INTERNAL_REDIRECT" PlacementTagJavascript -> "PLACEMENT_TAG_JAVASCRIPT" PlacementTagInterstitialIframeJavascript -> "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT" PlacementTagInterstitialInternalRedirect -> "PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT" PlacementTagInterstitialJavascript -> "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT" PlacementTagClickCommands -> "PLACEMENT_TAG_CLICK_COMMANDS" PlacementTagInstreamVideoPrefetch -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH" PlacementTagTracking -> "PLACEMENT_TAG_TRACKING" PlacementTagTrackingIframe -> "PLACEMENT_TAG_TRACKING_IFRAME" PlacementTagTrackingJavascript -> "PLACEMENT_TAG_TRACKING_JAVASCRIPT" PlacementTagInstreamVideoPrefetchVast3 -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3" PlacementTagIframeJavascriptLegacy -> "PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY" PlacementTagJavascriptLegacy -> "PLACEMENT_TAG_JAVASCRIPT_LEGACY" PlacementTagInterstitialIframeJavascriptLegacy -> "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY" PlacementTagInterstitialJavascriptLegacy -> "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY" PlacementTagInstreamVideoPrefetchVast4 -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4" instance FromJSON TagDataFormat where parseJSON = parseJSONText "TagDataFormat" instance ToJSON TagDataFormat where toJSON = toJSONText -- | Maximum number of active ads allowed for the account. data AccountActiveAdSummaryActiveAdsLimitTier = ActiveAdsTier40K -- ^ @ACTIVE_ADS_TIER_40K@ | ActiveAdsTier75K -- ^ @ACTIVE_ADS_TIER_75K@ | ActiveAdsTier100K -- ^ @ACTIVE_ADS_TIER_100K@ | ActiveAdsTier200K -- ^ @ACTIVE_ADS_TIER_200K@ | ActiveAdsTier300K -- ^ @ACTIVE_ADS_TIER_300K@ | ActiveAdsTier500K -- ^ @ACTIVE_ADS_TIER_500K@ | ActiveAdsTier750K -- ^ @ACTIVE_ADS_TIER_750K@ | ActiveAdsTier1M -- ^ @ACTIVE_ADS_TIER_1M@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountActiveAdSummaryActiveAdsLimitTier instance FromHttpApiData AccountActiveAdSummaryActiveAdsLimitTier where parseQueryParam = \case "ACTIVE_ADS_TIER_40K" -> Right ActiveAdsTier40K "ACTIVE_ADS_TIER_75K" -> Right ActiveAdsTier75K "ACTIVE_ADS_TIER_100K" -> Right ActiveAdsTier100K "ACTIVE_ADS_TIER_200K" -> Right ActiveAdsTier200K "ACTIVE_ADS_TIER_300K" -> Right ActiveAdsTier300K "ACTIVE_ADS_TIER_500K" -> Right ActiveAdsTier500K "ACTIVE_ADS_TIER_750K" -> Right ActiveAdsTier750K "ACTIVE_ADS_TIER_1M" -> Right ActiveAdsTier1M x -> Left ("Unable to parse AccountActiveAdSummaryActiveAdsLimitTier from: " <> x) instance ToHttpApiData AccountActiveAdSummaryActiveAdsLimitTier where toQueryParam = \case ActiveAdsTier40K -> "ACTIVE_ADS_TIER_40K" ActiveAdsTier75K -> "ACTIVE_ADS_TIER_75K" ActiveAdsTier100K -> "ACTIVE_ADS_TIER_100K" ActiveAdsTier200K -> "ACTIVE_ADS_TIER_200K" ActiveAdsTier300K -> "ACTIVE_ADS_TIER_300K" ActiveAdsTier500K -> "ACTIVE_ADS_TIER_500K" ActiveAdsTier750K -> "ACTIVE_ADS_TIER_750K" ActiveAdsTier1M -> "ACTIVE_ADS_TIER_1M" instance FromJSON AccountActiveAdSummaryActiveAdsLimitTier where parseJSON = parseJSONText "AccountActiveAdSummaryActiveAdsLimitTier" instance ToJSON AccountActiveAdSummaryActiveAdsLimitTier where toJSON = toJSONText -- | Rich media child asset type. This is a read-only field. Applicable to -- the following creative types: all VPAID. data CreativeAssetChildAssetType = ChildAssetTypeFlash -- ^ @CHILD_ASSET_TYPE_FLASH@ | ChildAssetTypeVideo -- ^ @CHILD_ASSET_TYPE_VIDEO@ | ChildAssetTypeImage -- ^ @CHILD_ASSET_TYPE_IMAGE@ | ChildAssetTypeData -- ^ @CHILD_ASSET_TYPE_DATA@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetChildAssetType instance FromHttpApiData CreativeAssetChildAssetType where parseQueryParam = \case "CHILD_ASSET_TYPE_FLASH" -> Right ChildAssetTypeFlash "CHILD_ASSET_TYPE_VIDEO" -> Right ChildAssetTypeVideo "CHILD_ASSET_TYPE_IMAGE" -> Right ChildAssetTypeImage "CHILD_ASSET_TYPE_DATA" -> Right ChildAssetTypeData x -> Left ("Unable to parse CreativeAssetChildAssetType from: " <> x) instance ToHttpApiData CreativeAssetChildAssetType where toQueryParam = \case ChildAssetTypeFlash -> "CHILD_ASSET_TYPE_FLASH" ChildAssetTypeVideo -> "CHILD_ASSET_TYPE_VIDEO" ChildAssetTypeImage -> "CHILD_ASSET_TYPE_IMAGE" ChildAssetTypeData -> "CHILD_ASSET_TYPE_DATA" instance FromJSON CreativeAssetChildAssetType where parseJSON = parseJSONText "CreativeAssetChildAssetType" instance ToJSON CreativeAssetChildAssetType where toJSON = toJSONText -- | Select only placement groups belonging with this group type. A package -- is a simple group of placements that acts as a single pricing point for -- a group of tags. A roadblock is a group of placements that not only acts -- as a single pricing point but also assumes that all the tags in it will -- be served at the same time. A roadblock requires one of its assigned -- placements to be marked as primary for reporting. data PlacementGroupsListPlacementGroupType = PlacementPackage -- ^ @PLACEMENT_PACKAGE@ | PlacementRoadblock -- ^ @PLACEMENT_ROADBLOCK@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementGroupsListPlacementGroupType instance FromHttpApiData PlacementGroupsListPlacementGroupType where parseQueryParam = \case "PLACEMENT_PACKAGE" -> Right PlacementPackage "PLACEMENT_ROADBLOCK" -> Right PlacementRoadblock x -> Left ("Unable to parse PlacementGroupsListPlacementGroupType from: " <> x) instance ToHttpApiData PlacementGroupsListPlacementGroupType where toQueryParam = \case PlacementPackage -> "PLACEMENT_PACKAGE" PlacementRoadblock -> "PLACEMENT_ROADBLOCK" instance FromJSON PlacementGroupsListPlacementGroupType where parseJSON = parseJSONText "PlacementGroupsListPlacementGroupType" instance ToJSON PlacementGroupsListPlacementGroupType where toJSON = toJSONText -- | Status of the filter. NONE means the user has access to none of the -- objects. ALL means the user has access to all objects. ASSIGNED means -- the user has access to the objects with IDs in the objectIds list. data ObjectFilterStatus = OFSNone -- ^ @NONE@ | OFSAssigned -- ^ @ASSIGNED@ | OFSAll -- ^ @ALL@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ObjectFilterStatus instance FromHttpApiData ObjectFilterStatus where parseQueryParam = \case "NONE" -> Right OFSNone "ASSIGNED" -> Right OFSAssigned "ALL" -> Right OFSAll x -> Left ("Unable to parse ObjectFilterStatus from: " <> x) instance ToHttpApiData ObjectFilterStatus where toQueryParam = \case OFSNone -> "NONE" OFSAssigned -> "ASSIGNED" OFSAll -> "ALL" instance FromJSON ObjectFilterStatus where parseJSON = parseJSONText "ObjectFilterStatus" instance ToJSON ObjectFilterStatus where toJSON = toJSONText -- | Order of sorted results. data CampaignCreativeAssociationsListSortOrder = CCALSOAscending -- ^ @ASCENDING@ | CCALSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CampaignCreativeAssociationsListSortOrder instance FromHttpApiData CampaignCreativeAssociationsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right CCALSOAscending "DESCENDING" -> Right CCALSODescending x -> Left ("Unable to parse CampaignCreativeAssociationsListSortOrder from: " <> x) instance ToHttpApiData CampaignCreativeAssociationsListSortOrder where toQueryParam = \case CCALSOAscending -> "ASCENDING" CCALSODescending -> "DESCENDING" instance FromJSON CampaignCreativeAssociationsListSortOrder where parseJSON = parseJSONText "CampaignCreativeAssociationsListSortOrder" instance ToJSON CampaignCreativeAssociationsListSortOrder where toJSON = toJSONText -- | Field by which to sort the list. data FloodlightActivitiesListSortField = FALSFID -- ^ @ID@ | FALSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivitiesListSortField instance FromHttpApiData FloodlightActivitiesListSortField where parseQueryParam = \case "ID" -> Right FALSFID "NAME" -> Right FALSFName x -> Left ("Unable to parse FloodlightActivitiesListSortField from: " <> x) instance ToHttpApiData FloodlightActivitiesListSortField where toQueryParam = \case FALSFID -> "ID" FALSFName -> "NAME" instance FromJSON FloodlightActivitiesListSortField where parseJSON = parseJSONText "FloodlightActivitiesListSortField" instance ToJSON FloodlightActivitiesListSortField where toJSON = toJSONText -- | Select only creatives with these creative types. data CreativesListTypes = CLTImage -- ^ @IMAGE@ | CLTDisplayRedirect -- ^ @DISPLAY_REDIRECT@ | CLTCustomDisplay -- ^ @CUSTOM_DISPLAY@ | CLTInternalRedirect -- ^ @INTERNAL_REDIRECT@ | CLTCustomDisplayInterstitial -- ^ @CUSTOM_DISPLAY_INTERSTITIAL@ | CLTInterstitialInternalRedirect -- ^ @INTERSTITIAL_INTERNAL_REDIRECT@ | CLTTrackingText -- ^ @TRACKING_TEXT@ | CLTRichMediaDisplayBanner -- ^ @RICH_MEDIA_DISPLAY_BANNER@ | CLTRichMediaInpageFloating -- ^ @RICH_MEDIA_INPAGE_FLOATING@ | CLTRichMediaImExpand -- ^ @RICH_MEDIA_IM_EXPAND@ | CLTRichMediaDisplayExpanding -- ^ @RICH_MEDIA_DISPLAY_EXPANDING@ | CLTRichMediaDisplayInterstitial -- ^ @RICH_MEDIA_DISPLAY_INTERSTITIAL@ | CLTRichMediaDisplayMultiFloatingInterstitial -- ^ @RICH_MEDIA_DISPLAY_MULTI_FLOATING_INTERSTITIAL@ | CLTRichMediaMobileInApp -- ^ @RICH_MEDIA_MOBILE_IN_APP@ | CLTFlashInpage -- ^ @FLASH_INPAGE@ | CLTInstreamVideo -- ^ @INSTREAM_VIDEO@ | CLTVpaidLinearVideo -- ^ @VPAID_LINEAR_VIDEO@ | CLTVpaidNonLinearVideo -- ^ @VPAID_NON_LINEAR_VIDEO@ | CLTInstreamVideoRedirect -- ^ @INSTREAM_VIDEO_REDIRECT@ | CLTRichMediaPeelDown -- ^ @RICH_MEDIA_PEEL_DOWN@ | CLTHTML5Banner -- ^ @HTML5_BANNER@ | CLTDisplay -- ^ @DISPLAY@ | CLTDisplayImageGallery -- ^ @DISPLAY_IMAGE_GALLERY@ | CLTBrandSafeDefaultInstreamVideo -- ^ @BRAND_SAFE_DEFAULT_INSTREAM_VIDEO@ | CLTInstreamAudio -- ^ @INSTREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativesListTypes instance FromHttpApiData CreativesListTypes where parseQueryParam = \case "IMAGE" -> Right CLTImage "DISPLAY_REDIRECT" -> Right CLTDisplayRedirect "CUSTOM_DISPLAY" -> Right CLTCustomDisplay "INTERNAL_REDIRECT" -> Right CLTInternalRedirect "CUSTOM_DISPLAY_INTERSTITIAL" -> Right CLTCustomDisplayInterstitial "INTERSTITIAL_INTERNAL_REDIRECT" -> Right CLTInterstitialInternalRedirect "TRACKING_TEXT" -> Right CLTTrackingText "RICH_MEDIA_DISPLAY_BANNER" -> Right CLTRichMediaDisplayBanner "RICH_MEDIA_INPAGE_FLOATING" -> Right CLTRichMediaInpageFloating "RICH_MEDIA_IM_EXPAND" -> Right CLTRichMediaImExpand "RICH_MEDIA_DISPLAY_EXPANDING" -> Right CLTRichMediaDisplayExpanding "RICH_MEDIA_DISPLAY_INTERSTITIAL" -> Right CLTRichMediaDisplayInterstitial "RICH_MEDIA_DISPLAY_MULTI_FLOATING_INTERSTITIAL" -> Right CLTRichMediaDisplayMultiFloatingInterstitial "RICH_MEDIA_MOBILE_IN_APP" -> Right CLTRichMediaMobileInApp "FLASH_INPAGE" -> Right CLTFlashInpage "INSTREAM_VIDEO" -> Right CLTInstreamVideo "VPAID_LINEAR_VIDEO" -> Right CLTVpaidLinearVideo "VPAID_NON_LINEAR_VIDEO" -> Right CLTVpaidNonLinearVideo "INSTREAM_VIDEO_REDIRECT" -> Right CLTInstreamVideoRedirect "RICH_MEDIA_PEEL_DOWN" -> Right CLTRichMediaPeelDown "HTML5_BANNER" -> Right CLTHTML5Banner "DISPLAY" -> Right CLTDisplay "DISPLAY_IMAGE_GALLERY" -> Right CLTDisplayImageGallery "BRAND_SAFE_DEFAULT_INSTREAM_VIDEO" -> Right CLTBrandSafeDefaultInstreamVideo "INSTREAM_AUDIO" -> Right CLTInstreamAudio x -> Left ("Unable to parse CreativesListTypes from: " <> x) instance ToHttpApiData CreativesListTypes where toQueryParam = \case CLTImage -> "IMAGE" CLTDisplayRedirect -> "DISPLAY_REDIRECT" CLTCustomDisplay -> "CUSTOM_DISPLAY" CLTInternalRedirect -> "INTERNAL_REDIRECT" CLTCustomDisplayInterstitial -> "CUSTOM_DISPLAY_INTERSTITIAL" CLTInterstitialInternalRedirect -> "INTERSTITIAL_INTERNAL_REDIRECT" CLTTrackingText -> "TRACKING_TEXT" CLTRichMediaDisplayBanner -> "RICH_MEDIA_DISPLAY_BANNER" CLTRichMediaInpageFloating -> "RICH_MEDIA_INPAGE_FLOATING" CLTRichMediaImExpand -> "RICH_MEDIA_IM_EXPAND" CLTRichMediaDisplayExpanding -> "RICH_MEDIA_DISPLAY_EXPANDING" CLTRichMediaDisplayInterstitial -> "RICH_MEDIA_DISPLAY_INTERSTITIAL" CLTRichMediaDisplayMultiFloatingInterstitial -> "RICH_MEDIA_DISPLAY_MULTI_FLOATING_INTERSTITIAL" CLTRichMediaMobileInApp -> "RICH_MEDIA_MOBILE_IN_APP" CLTFlashInpage -> "FLASH_INPAGE" CLTInstreamVideo -> "INSTREAM_VIDEO" CLTVpaidLinearVideo -> "VPAID_LINEAR_VIDEO" CLTVpaidNonLinearVideo -> "VPAID_NON_LINEAR_VIDEO" CLTInstreamVideoRedirect -> "INSTREAM_VIDEO_REDIRECT" CLTRichMediaPeelDown -> "RICH_MEDIA_PEEL_DOWN" CLTHTML5Banner -> "HTML5_BANNER" CLTDisplay -> "DISPLAY" CLTDisplayImageGallery -> "DISPLAY_IMAGE_GALLERY" CLTBrandSafeDefaultInstreamVideo -> "BRAND_SAFE_DEFAULT_INSTREAM_VIDEO" CLTInstreamAudio -> "INSTREAM_AUDIO" instance FromJSON CreativesListTypes where parseJSON = parseJSONText "CreativesListTypes" instance ToJSON CreativesListTypes where toJSON = toJSONText data DirectorySiteInpageTagFormatsItem = Standard -- ^ @STANDARD@ | IframeJavascriptInpage -- ^ @IFRAME_JAVASCRIPT_INPAGE@ | InternalRedirectInpage -- ^ @INTERNAL_REDIRECT_INPAGE@ | JavascriptInpage -- ^ @JAVASCRIPT_INPAGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DirectorySiteInpageTagFormatsItem instance FromHttpApiData DirectorySiteInpageTagFormatsItem where parseQueryParam = \case "STANDARD" -> Right Standard "IFRAME_JAVASCRIPT_INPAGE" -> Right IframeJavascriptInpage "INTERNAL_REDIRECT_INPAGE" -> Right InternalRedirectInpage "JAVASCRIPT_INPAGE" -> Right JavascriptInpage x -> Left ("Unable to parse DirectorySiteInpageTagFormatsItem from: " <> x) instance ToHttpApiData DirectorySiteInpageTagFormatsItem where toQueryParam = \case Standard -> "STANDARD" IframeJavascriptInpage -> "IFRAME_JAVASCRIPT_INPAGE" InternalRedirectInpage -> "INTERNAL_REDIRECT_INPAGE" JavascriptInpage -> "JAVASCRIPT_INPAGE" instance FromJSON DirectorySiteInpageTagFormatsItem where parseJSON = parseJSONText "DirectorySiteInpageTagFormatsItem" instance ToJSON DirectorySiteInpageTagFormatsItem where toJSON = toJSONText -- | Window mode options for flash assets. Applicable to the following -- creative types: FLASH_INPAGE, RICH_MEDIA_DISPLAY_EXPANDING, -- RICH_MEDIA_IM_EXPAND, RICH_MEDIA_DISPLAY_BANNER, and -- RICH_MEDIA_INPAGE_FLOATING. data CreativeAssetWindowMode = Opaque -- ^ @OPAQUE@ | Window -- ^ @WINDOW@ | Transparent -- ^ @TRANSPARENT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetWindowMode instance FromHttpApiData CreativeAssetWindowMode where parseQueryParam = \case "OPAQUE" -> Right Opaque "WINDOW" -> Right Window "TRANSPARENT" -> Right Transparent x -> Left ("Unable to parse CreativeAssetWindowMode from: " <> x) instance ToHttpApiData CreativeAssetWindowMode where toQueryParam = \case Opaque -> "OPAQUE" Window -> "WINDOW" Transparent -> "TRANSPARENT" instance FromJSON CreativeAssetWindowMode where parseJSON = parseJSONText "CreativeAssetWindowMode" instance ToJSON CreativeAssetWindowMode where toJSON = toJSONText -- | Possible alignments for an asset. This is a read-only field. Applicable -- to the following creative types: -- RICH_MEDIA_DISPLAY_MULTI_FLOATING_INTERSTITIAL . data CreativeAssetAlignment = AlignmentTop -- ^ @ALIGNMENT_TOP@ | AlignmentRight -- ^ @ALIGNMENT_RIGHT@ | AlignmentBottom -- ^ @ALIGNMENT_BOTTOM@ | AlignmentLeft -- ^ @ALIGNMENT_LEFT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetAlignment instance FromHttpApiData CreativeAssetAlignment where parseQueryParam = \case "ALIGNMENT_TOP" -> Right AlignmentTop "ALIGNMENT_RIGHT" -> Right AlignmentRight "ALIGNMENT_BOTTOM" -> Right AlignmentBottom "ALIGNMENT_LEFT" -> Right AlignmentLeft x -> Left ("Unable to parse CreativeAssetAlignment from: " <> x) instance ToHttpApiData CreativeAssetAlignment where toQueryParam = \case AlignmentTop -> "ALIGNMENT_TOP" AlignmentRight -> "ALIGNMENT_RIGHT" AlignmentBottom -> "ALIGNMENT_BOTTOM" AlignmentLeft -> "ALIGNMENT_LEFT" instance FromJSON CreativeAssetAlignment where parseJSON = parseJSONText "CreativeAssetAlignment" instance ToJSON CreativeAssetAlignment where toJSON = toJSONText -- | Order of sorted results. data RemarketingListsListSortOrder = RLLSOAscending -- ^ @ASCENDING@ | RLLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RemarketingListsListSortOrder instance FromHttpApiData RemarketingListsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right RLLSOAscending "DESCENDING" -> Right RLLSODescending x -> Left ("Unable to parse RemarketingListsListSortOrder from: " <> x) instance ToHttpApiData RemarketingListsListSortOrder where toQueryParam = \case RLLSOAscending -> "ASCENDING" RLLSODescending -> "DESCENDING" instance FromJSON RemarketingListsListSortOrder where parseJSON = parseJSONText "RemarketingListsListSortOrder" instance ToJSON RemarketingListsListSortOrder where toJSON = toJSONText -- | Placement wrapping status. data MeasurementPartnerWrAppingDataLinkStatus = MPWADLSMeasurementPartnerUnlinked -- ^ @MEASUREMENT_PARTNER_UNLINKED@ | MPWADLSMeasurementPartnerLinked -- ^ @MEASUREMENT_PARTNER_LINKED@ | MPWADLSMeasurementPartnerLinkPending -- ^ @MEASUREMENT_PARTNER_LINK_PENDING@ | MPWADLSMeasurementPartnerLinkFailure -- ^ @MEASUREMENT_PARTNER_LINK_FAILURE@ | MPWADLSMeasurementPartnerLinkOptOut -- ^ @MEASUREMENT_PARTNER_LINK_OPT_OUT@ | MPWADLSMeasurementPartnerLinkOptOutPending -- ^ @MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING@ | MPWADLSMeasurementPartnerLinkWrAppingPending -- ^ @MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING@ | MPWADLSMeasurementPartnerModeChangePending -- ^ @MEASUREMENT_PARTNER_MODE_CHANGE_PENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MeasurementPartnerWrAppingDataLinkStatus instance FromHttpApiData MeasurementPartnerWrAppingDataLinkStatus where parseQueryParam = \case "MEASUREMENT_PARTNER_UNLINKED" -> Right MPWADLSMeasurementPartnerUnlinked "MEASUREMENT_PARTNER_LINKED" -> Right MPWADLSMeasurementPartnerLinked "MEASUREMENT_PARTNER_LINK_PENDING" -> Right MPWADLSMeasurementPartnerLinkPending "MEASUREMENT_PARTNER_LINK_FAILURE" -> Right MPWADLSMeasurementPartnerLinkFailure "MEASUREMENT_PARTNER_LINK_OPT_OUT" -> Right MPWADLSMeasurementPartnerLinkOptOut "MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING" -> Right MPWADLSMeasurementPartnerLinkOptOutPending "MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING" -> Right MPWADLSMeasurementPartnerLinkWrAppingPending "MEASUREMENT_PARTNER_MODE_CHANGE_PENDING" -> Right MPWADLSMeasurementPartnerModeChangePending x -> Left ("Unable to parse MeasurementPartnerWrAppingDataLinkStatus from: " <> x) instance ToHttpApiData MeasurementPartnerWrAppingDataLinkStatus where toQueryParam = \case MPWADLSMeasurementPartnerUnlinked -> "MEASUREMENT_PARTNER_UNLINKED" MPWADLSMeasurementPartnerLinked -> "MEASUREMENT_PARTNER_LINKED" MPWADLSMeasurementPartnerLinkPending -> "MEASUREMENT_PARTNER_LINK_PENDING" MPWADLSMeasurementPartnerLinkFailure -> "MEASUREMENT_PARTNER_LINK_FAILURE" MPWADLSMeasurementPartnerLinkOptOut -> "MEASUREMENT_PARTNER_LINK_OPT_OUT" MPWADLSMeasurementPartnerLinkOptOutPending -> "MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING" MPWADLSMeasurementPartnerLinkWrAppingPending -> "MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING" MPWADLSMeasurementPartnerModeChangePending -> "MEASUREMENT_PARTNER_MODE_CHANGE_PENDING" instance FromJSON MeasurementPartnerWrAppingDataLinkStatus where parseJSON = parseJSONText "MeasurementPartnerWrAppingDataLinkStatus" instance ToJSON MeasurementPartnerWrAppingDataLinkStatus where toJSON = toJSONText -- | Select only placement groups with these pricing types. data PlacementGroupsListPricingTypes = PGLPTPricingTypeCpm -- ^ @PRICING_TYPE_CPM@ | PGLPTPricingTypeCpc -- ^ @PRICING_TYPE_CPC@ | PGLPTPricingTypeCpa -- ^ @PRICING_TYPE_CPA@ | PGLPTPricingTypeFlatRateImpressions -- ^ @PRICING_TYPE_FLAT_RATE_IMPRESSIONS@ | PGLPTPricingTypeFlatRateClicks -- ^ @PRICING_TYPE_FLAT_RATE_CLICKS@ | PGLPTPricingTypeCpmActiveview -- ^ @PRICING_TYPE_CPM_ACTIVEVIEW@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementGroupsListPricingTypes instance FromHttpApiData PlacementGroupsListPricingTypes where parseQueryParam = \case "PRICING_TYPE_CPM" -> Right PGLPTPricingTypeCpm "PRICING_TYPE_CPC" -> Right PGLPTPricingTypeCpc "PRICING_TYPE_CPA" -> Right PGLPTPricingTypeCpa "PRICING_TYPE_FLAT_RATE_IMPRESSIONS" -> Right PGLPTPricingTypeFlatRateImpressions "PRICING_TYPE_FLAT_RATE_CLICKS" -> Right PGLPTPricingTypeFlatRateClicks "PRICING_TYPE_CPM_ACTIVEVIEW" -> Right PGLPTPricingTypeCpmActiveview x -> Left ("Unable to parse PlacementGroupsListPricingTypes from: " <> x) instance ToHttpApiData PlacementGroupsListPricingTypes where toQueryParam = \case PGLPTPricingTypeCpm -> "PRICING_TYPE_CPM" PGLPTPricingTypeCpc -> "PRICING_TYPE_CPC" PGLPTPricingTypeCpa -> "PRICING_TYPE_CPA" PGLPTPricingTypeFlatRateImpressions -> "PRICING_TYPE_FLAT_RATE_IMPRESSIONS" PGLPTPricingTypeFlatRateClicks -> "PRICING_TYPE_FLAT_RATE_CLICKS" PGLPTPricingTypeCpmActiveview -> "PRICING_TYPE_CPM_ACTIVEVIEW" instance FromJSON PlacementGroupsListPricingTypes where parseJSON = parseJSONText "PlacementGroupsListPricingTypes" instance ToJSON PlacementGroupsListPricingTypes where toJSON = toJSONText -- | Type of the object of this dynamic targeting key. This is a required -- field. data DynamicTargetingKeysDeleteObjectType = DTKDOTObjectAdvertiser -- ^ @OBJECT_ADVERTISER@ | DTKDOTObjectAd -- ^ @OBJECT_AD@ | DTKDOTObjectCreative -- ^ @OBJECT_CREATIVE@ | DTKDOTObjectPlacement -- ^ @OBJECT_PLACEMENT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DynamicTargetingKeysDeleteObjectType instance FromHttpApiData DynamicTargetingKeysDeleteObjectType where parseQueryParam = \case "OBJECT_ADVERTISER" -> Right DTKDOTObjectAdvertiser "OBJECT_AD" -> Right DTKDOTObjectAd "OBJECT_CREATIVE" -> Right DTKDOTObjectCreative "OBJECT_PLACEMENT" -> Right DTKDOTObjectPlacement x -> Left ("Unable to parse DynamicTargetingKeysDeleteObjectType from: " <> x) instance ToHttpApiData DynamicTargetingKeysDeleteObjectType where toQueryParam = \case DTKDOTObjectAdvertiser -> "OBJECT_ADVERTISER" DTKDOTObjectAd -> "OBJECT_AD" DTKDOTObjectCreative -> "OBJECT_CREATIVE" DTKDOTObjectPlacement -> "OBJECT_PLACEMENT" instance FromJSON DynamicTargetingKeysDeleteObjectType where parseJSON = parseJSONText "DynamicTargetingKeysDeleteObjectType" instance ToJSON DynamicTargetingKeysDeleteObjectType where toJSON = toJSONText -- | Maximum number of active ads allowed for this account. data AccountActiveAdsLimitTier = AAALTActiveAdsTier40K -- ^ @ACTIVE_ADS_TIER_40K@ | AAALTActiveAdsTier75K -- ^ @ACTIVE_ADS_TIER_75K@ | AAALTActiveAdsTier100K -- ^ @ACTIVE_ADS_TIER_100K@ | AAALTActiveAdsTier200K -- ^ @ACTIVE_ADS_TIER_200K@ | AAALTActiveAdsTier300K -- ^ @ACTIVE_ADS_TIER_300K@ | AAALTActiveAdsTier500K -- ^ @ACTIVE_ADS_TIER_500K@ | AAALTActiveAdsTier750K -- ^ @ACTIVE_ADS_TIER_750K@ | AAALTActiveAdsTier1M -- ^ @ACTIVE_ADS_TIER_1M@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountActiveAdsLimitTier instance FromHttpApiData AccountActiveAdsLimitTier where parseQueryParam = \case "ACTIVE_ADS_TIER_40K" -> Right AAALTActiveAdsTier40K "ACTIVE_ADS_TIER_75K" -> Right AAALTActiveAdsTier75K "ACTIVE_ADS_TIER_100K" -> Right AAALTActiveAdsTier100K "ACTIVE_ADS_TIER_200K" -> Right AAALTActiveAdsTier200K "ACTIVE_ADS_TIER_300K" -> Right AAALTActiveAdsTier300K "ACTIVE_ADS_TIER_500K" -> Right AAALTActiveAdsTier500K "ACTIVE_ADS_TIER_750K" -> Right AAALTActiveAdsTier750K "ACTIVE_ADS_TIER_1M" -> Right AAALTActiveAdsTier1M x -> Left ("Unable to parse AccountActiveAdsLimitTier from: " <> x) instance ToHttpApiData AccountActiveAdsLimitTier where toQueryParam = \case AAALTActiveAdsTier40K -> "ACTIVE_ADS_TIER_40K" AAALTActiveAdsTier75K -> "ACTIVE_ADS_TIER_75K" AAALTActiveAdsTier100K -> "ACTIVE_ADS_TIER_100K" AAALTActiveAdsTier200K -> "ACTIVE_ADS_TIER_200K" AAALTActiveAdsTier300K -> "ACTIVE_ADS_TIER_300K" AAALTActiveAdsTier500K -> "ACTIVE_ADS_TIER_500K" AAALTActiveAdsTier750K -> "ACTIVE_ADS_TIER_750K" AAALTActiveAdsTier1M -> "ACTIVE_ADS_TIER_1M" instance FromJSON AccountActiveAdsLimitTier where parseJSON = parseJSONText "AccountActiveAdsLimitTier" instance ToJSON AccountActiveAdsLimitTier where toJSON = toJSONText -- | Order of sorted results. data AccountsListSortOrder = AAscending -- ^ @ASCENDING@ | ADescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountsListSortOrder instance FromHttpApiData AccountsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right AAscending "DESCENDING" -> Right ADescending x -> Left ("Unable to parse AccountsListSortOrder from: " <> x) instance ToHttpApiData AccountsListSortOrder where toQueryParam = \case AAscending -> "ASCENDING" ADescending -> "DESCENDING" instance FromJSON AccountsListSortOrder where parseJSON = parseJSONText "AccountsListSortOrder" instance ToJSON AccountsListSortOrder where toJSON = toJSONText -- | Measurement partner used for wrapping the placement. data MeasurementPartnerWrAppingDataMeasurementPartner = MPWADMPNone -- ^ @NONE@ | MPWADMPIntegralAdScience -- ^ @INTEGRAL_AD_SCIENCE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MeasurementPartnerWrAppingDataMeasurementPartner instance FromHttpApiData MeasurementPartnerWrAppingDataMeasurementPartner where parseQueryParam = \case "NONE" -> Right MPWADMPNone "INTEGRAL_AD_SCIENCE" -> Right MPWADMPIntegralAdScience x -> Left ("Unable to parse MeasurementPartnerWrAppingDataMeasurementPartner from: " <> x) instance ToHttpApiData MeasurementPartnerWrAppingDataMeasurementPartner where toQueryParam = \case MPWADMPNone -> "NONE" MPWADMPIntegralAdScience -> "INTEGRAL_AD_SCIENCE" instance FromJSON MeasurementPartnerWrAppingDataMeasurementPartner where parseJSON = parseJSONText "MeasurementPartnerWrAppingDataMeasurementPartner" instance ToJSON MeasurementPartnerWrAppingDataMeasurementPartner where toJSON = toJSONText -- | Field by which to sort the list. data SubAccountsListSortField = SALSFID -- ^ @ID@ | SALSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SubAccountsListSortField instance FromHttpApiData SubAccountsListSortField where parseQueryParam = \case "ID" -> Right SALSFID "NAME" -> Right SALSFName x -> Left ("Unable to parse SubAccountsListSortField from: " <> x) instance ToHttpApiData SubAccountsListSortField where toQueryParam = \case SALSFID -> "ID" SALSFName -> "NAME" instance FromJSON SubAccountsListSortField where parseJSON = parseJSONText "SubAccountsListSortField" instance ToJSON SubAccountsListSortField where toJSON = toJSONText -- | File type of the video format. data VideoFormatFileType = Flv -- ^ @FLV@ | Threegpp -- ^ @THREEGPP@ | MP4 -- ^ @MP4@ | Webm -- ^ @WEBM@ | M3U8 -- ^ @M3U8@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable VideoFormatFileType instance FromHttpApiData VideoFormatFileType where parseQueryParam = \case "FLV" -> Right Flv "THREEGPP" -> Right Threegpp "MP4" -> Right MP4 "WEBM" -> Right Webm "M3U8" -> Right M3U8 x -> Left ("Unable to parse VideoFormatFileType from: " <> x) instance ToHttpApiData VideoFormatFileType where toQueryParam = \case Flv -> "FLV" Threegpp -> "THREEGPP" MP4 -> "MP4" Webm -> "WEBM" M3U8 -> "M3U8" instance FromJSON VideoFormatFileType where parseJSON = parseJSONText "VideoFormatFileType" instance ToJSON VideoFormatFileType where toJSON = toJSONText -- | Field by which to sort the list. data AdsListSortField = ALSFID -- ^ @ID@ | ALSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdsListSortField instance FromHttpApiData AdsListSortField where parseQueryParam = \case "ID" -> Right ALSFID "NAME" -> Right ALSFName x -> Left ("Unable to parse AdsListSortField from: " <> x) instance ToHttpApiData AdsListSortField where toQueryParam = \case ALSFID -> "ID" ALSFName -> "NAME" instance FromJSON AdsListSortField where parseJSON = parseJSONText "AdsListSortField" instance ToJSON AdsListSortField where toJSON = toJSONText -- | Field by which to sort the list. data ProjectsListSortField = PID -- ^ @ID@ | PName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ProjectsListSortField instance FromHttpApiData ProjectsListSortField where parseQueryParam = \case "ID" -> Right PID "NAME" -> Right PName x -> Left ("Unable to parse ProjectsListSortField from: " <> x) instance ToHttpApiData ProjectsListSortField where toQueryParam = \case PID -> "ID" PName -> "NAME" instance FromJSON ProjectsListSortField where parseJSON = parseJSONText "ProjectsListSortField" instance ToJSON ProjectsListSortField where toJSON = toJSONText -- | Select only ads with these types. data AdsListType = AdServingStandardAd -- ^ @AD_SERVING_STANDARD_AD@ | AdServingDefaultAd -- ^ @AD_SERVING_DEFAULT_AD@ | AdServingClickTracker -- ^ @AD_SERVING_CLICK_TRACKER@ | AdServingTracking -- ^ @AD_SERVING_TRACKING@ | AdServingBrandSafeAd -- ^ @AD_SERVING_BRAND_SAFE_AD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdsListType instance FromHttpApiData AdsListType where parseQueryParam = \case "AD_SERVING_STANDARD_AD" -> Right AdServingStandardAd "AD_SERVING_DEFAULT_AD" -> Right AdServingDefaultAd "AD_SERVING_CLICK_TRACKER" -> Right AdServingClickTracker "AD_SERVING_TRACKING" -> Right AdServingTracking "AD_SERVING_BRAND_SAFE_AD" -> Right AdServingBrandSafeAd x -> Left ("Unable to parse AdsListType from: " <> x) instance ToHttpApiData AdsListType where toQueryParam = \case AdServingStandardAd -> "AD_SERVING_STANDARD_AD" AdServingDefaultAd -> "AD_SERVING_DEFAULT_AD" AdServingClickTracker -> "AD_SERVING_CLICK_TRACKER" AdServingTracking -> "AD_SERVING_TRACKING" AdServingBrandSafeAd -> "AD_SERVING_BRAND_SAFE_AD" instance FromJSON AdsListType where parseJSON = parseJSONText "AdsListType" instance ToJSON AdsListType where toJSON = toJSONText -- | Optimization model for this configuration. data CreativeOptimizationConfigurationOptimizationModel = Click -- ^ @CLICK@ | PostClick -- ^ @POST_CLICK@ | PostImpression -- ^ @POST_IMPRESSION@ | PostClickAndImpression -- ^ @POST_CLICK_AND_IMPRESSION@ | VideoCompletion -- ^ @VIDEO_COMPLETION@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeOptimizationConfigurationOptimizationModel instance FromHttpApiData CreativeOptimizationConfigurationOptimizationModel where parseQueryParam = \case "CLICK" -> Right Click "POST_CLICK" -> Right PostClick "POST_IMPRESSION" -> Right PostImpression "POST_CLICK_AND_IMPRESSION" -> Right PostClickAndImpression "VIDEO_COMPLETION" -> Right VideoCompletion x -> Left ("Unable to parse CreativeOptimizationConfigurationOptimizationModel from: " <> x) instance ToHttpApiData CreativeOptimizationConfigurationOptimizationModel where toQueryParam = \case Click -> "CLICK" PostClick -> "POST_CLICK" PostImpression -> "POST_IMPRESSION" PostClickAndImpression -> "POST_CLICK_AND_IMPRESSION" VideoCompletion -> "VIDEO_COMPLETION" instance FromJSON CreativeOptimizationConfigurationOptimizationModel where parseJSON = parseJSONText "CreativeOptimizationConfigurationOptimizationModel" instance ToJSON CreativeOptimizationConfigurationOptimizationModel where toJSON = toJSONText -- | Administrative level required to enable this account permission. data AccountPermissionLevel = User -- ^ @USER@ | Administrator -- ^ @ADMINISTRATOR@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountPermissionLevel instance FromHttpApiData AccountPermissionLevel where parseQueryParam = \case "USER" -> Right User "ADMINISTRATOR" -> Right Administrator x -> Left ("Unable to parse AccountPermissionLevel from: " <> x) instance ToHttpApiData AccountPermissionLevel where toQueryParam = \case User -> "USER" Administrator -> "ADMINISTRATOR" instance FromJSON AccountPermissionLevel where parseJSON = parseJSONText "AccountPermissionLevel" instance ToJSON AccountPermissionLevel where toJSON = toJSONText -- | List population term type determines the applicable fields in this -- object. If left unset or set to CUSTOM_VARIABLE_TERM, then variableName, -- variableFriendlyName, operator, value, and negation are applicable. If -- set to LIST_MEMBERSHIP_TERM then remarketingListId and contains are -- applicable. If set to REFERRER_TERM then operator, value, and negation -- are applicable. data ListPopulationTermType = CustomVariableTerm -- ^ @CUSTOM_VARIABLE_TERM@ | ListMembershipTerm -- ^ @LIST_MEMBERSHIP_TERM@ | ReferrerTerm -- ^ @REFERRER_TERM@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ListPopulationTermType instance FromHttpApiData ListPopulationTermType where parseQueryParam = \case "CUSTOM_VARIABLE_TERM" -> Right CustomVariableTerm "LIST_MEMBERSHIP_TERM" -> Right ListMembershipTerm "REFERRER_TERM" -> Right ReferrerTerm x -> Left ("Unable to parse ListPopulationTermType from: " <> x) instance ToHttpApiData ListPopulationTermType where toQueryParam = \case CustomVariableTerm -> "CUSTOM_VARIABLE_TERM" ListMembershipTerm -> "LIST_MEMBERSHIP_TERM" ReferrerTerm -> "REFERRER_TERM" instance FromJSON ListPopulationTermType where parseJSON = parseJSONText "ListPopulationTermType" instance ToJSON ListPopulationTermType where toJSON = toJSONText -- | Order of sorted results. data AdvertiserGroupsListSortOrder = AGLSOAscending -- ^ @ASCENDING@ | AGLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertiserGroupsListSortOrder instance FromHttpApiData AdvertiserGroupsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right AGLSOAscending "DESCENDING" -> Right AGLSODescending x -> Left ("Unable to parse AdvertiserGroupsListSortOrder from: " <> x) instance ToHttpApiData AdvertiserGroupsListSortOrder where toQueryParam = \case AGLSOAscending -> "ASCENDING" AGLSODescending -> "DESCENDING" instance FromJSON AdvertiserGroupsListSortOrder where parseJSON = parseJSONText "AdvertiserGroupsListSortOrder" instance ToJSON AdvertiserGroupsListSortOrder where toJSON = toJSONText -- | Order of sorted results. data CreativeFieldValuesListSortOrder = CFVLSOAscending -- ^ @ASCENDING@ | CFVLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeFieldValuesListSortOrder instance FromHttpApiData CreativeFieldValuesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right CFVLSOAscending "DESCENDING" -> Right CFVLSODescending x -> Left ("Unable to parse CreativeFieldValuesListSortOrder from: " <> x) instance ToHttpApiData CreativeFieldValuesListSortOrder where toQueryParam = \case CFVLSOAscending -> "ASCENDING" CFVLSODescending -> "DESCENDING" instance FromJSON CreativeFieldValuesListSortOrder where parseJSON = parseJSONText "CreativeFieldValuesListSortOrder" instance ToJSON CreativeFieldValuesListSortOrder where toJSON = toJSONText -- | An optional sort order for the dimension column. data SortedDimensionSortOrder = SDSOAscending -- ^ @ASCENDING@ | SDSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SortedDimensionSortOrder instance FromHttpApiData SortedDimensionSortOrder where parseQueryParam = \case "ASCENDING" -> Right SDSOAscending "DESCENDING" -> Right SDSODescending x -> Left ("Unable to parse SortedDimensionSortOrder from: " <> x) instance ToHttpApiData SortedDimensionSortOrder where toQueryParam = \case SDSOAscending -> "ASCENDING" SDSODescending -> "DESCENDING" instance FromJSON SortedDimensionSortOrder where parseJSON = parseJSONText "SortedDimensionSortOrder" instance ToJSON SortedDimensionSortOrder where toJSON = toJSONText -- | Select only apps from these directories. data MobileAppsListDirectories = Unknown -- ^ @UNKNOWN@ | AppleAppStore -- ^ @APPLE_APP_STORE@ | GooglePlayStore -- ^ @GOOGLE_PLAY_STORE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MobileAppsListDirectories instance FromHttpApiData MobileAppsListDirectories where parseQueryParam = \case "UNKNOWN" -> Right Unknown "APPLE_APP_STORE" -> Right AppleAppStore "GOOGLE_PLAY_STORE" -> Right GooglePlayStore x -> Left ("Unable to parse MobileAppsListDirectories from: " <> x) instance ToHttpApiData MobileAppsListDirectories where toQueryParam = \case Unknown -> "UNKNOWN" AppleAppStore -> "APPLE_APP_STORE" GooglePlayStore -> "GOOGLE_PLAY_STORE" instance FromJSON MobileAppsListDirectories where parseJSON = parseJSONText "MobileAppsListDirectories" instance ToJSON MobileAppsListDirectories where toJSON = toJSONText -- | The field by which to sort the list. data FilesListSortField = FLSFID -- ^ @ID@ -- Sort by file ID. | FLSFLastModifiedTime -- ^ @LAST_MODIFIED_TIME@ -- Sort by \'lastmodifiedAt\' field. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FilesListSortField instance FromHttpApiData FilesListSortField where parseQueryParam = \case "ID" -> Right FLSFID "LAST_MODIFIED_TIME" -> Right FLSFLastModifiedTime x -> Left ("Unable to parse FilesListSortField from: " <> x) instance ToHttpApiData FilesListSortField where toQueryParam = \case FLSFID -> "ID" FLSFLastModifiedTime -> "LAST_MODIFIED_TIME" instance FromJSON FilesListSortField where parseJSON = parseJSONText "FilesListSortField" instance ToJSON FilesListSortField where toJSON = toJSONText data DirectorySiteInterstitialTagFormatsItem = IframeJavascriptInterstitial -- ^ @IFRAME_JAVASCRIPT_INTERSTITIAL@ | InternalRedirectInterstitial -- ^ @INTERNAL_REDIRECT_INTERSTITIAL@ | JavascriptInterstitial -- ^ @JAVASCRIPT_INTERSTITIAL@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DirectorySiteInterstitialTagFormatsItem instance FromHttpApiData DirectorySiteInterstitialTagFormatsItem where parseQueryParam = \case "IFRAME_JAVASCRIPT_INTERSTITIAL" -> Right IframeJavascriptInterstitial "INTERNAL_REDIRECT_INTERSTITIAL" -> Right InternalRedirectInterstitial "JAVASCRIPT_INTERSTITIAL" -> Right JavascriptInterstitial x -> Left ("Unable to parse DirectorySiteInterstitialTagFormatsItem from: " <> x) instance ToHttpApiData DirectorySiteInterstitialTagFormatsItem where toQueryParam = \case IframeJavascriptInterstitial -> "IFRAME_JAVASCRIPT_INTERSTITIAL" InternalRedirectInterstitial -> "INTERNAL_REDIRECT_INTERSTITIAL" JavascriptInterstitial -> "JAVASCRIPT_INTERSTITIAL" instance FromJSON DirectorySiteInterstitialTagFormatsItem where parseJSON = parseJSONText "DirectorySiteInterstitialTagFormatsItem" instance ToJSON DirectorySiteInterstitialTagFormatsItem where toJSON = toJSONText -- | Field by which to sort the list. data EventTagsListSortField = ETLSFID -- ^ @ID@ | ETLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EventTagsListSortField instance FromHttpApiData EventTagsListSortField where parseQueryParam = \case "ID" -> Right ETLSFID "NAME" -> Right ETLSFName x -> Left ("Unable to parse EventTagsListSortField from: " <> x) instance ToHttpApiData EventTagsListSortField where toQueryParam = \case ETLSFID -> "ID" ETLSFName -> "NAME" instance FromJSON EventTagsListSortField where parseJSON = parseJSONText "EventTagsListSortField" instance ToJSON EventTagsListSortField where toJSON = toJSONText -- | Type of inventory item. data InventoryItemType = IITPlanningPlacementTypeRegular -- ^ @PLANNING_PLACEMENT_TYPE_REGULAR@ | IITPlanningPlacementTypeCredit -- ^ @PLANNING_PLACEMENT_TYPE_CREDIT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InventoryItemType instance FromHttpApiData InventoryItemType where parseQueryParam = \case "PLANNING_PLACEMENT_TYPE_REGULAR" -> Right IITPlanningPlacementTypeRegular "PLANNING_PLACEMENT_TYPE_CREDIT" -> Right IITPlanningPlacementTypeCredit x -> Left ("Unable to parse InventoryItemType from: " <> x) instance ToHttpApiData InventoryItemType where toQueryParam = \case IITPlanningPlacementTypeRegular -> "PLANNING_PLACEMENT_TYPE_REGULAR" IITPlanningPlacementTypeCredit -> "PLANNING_PLACEMENT_TYPE_CREDIT" instance FromJSON InventoryItemType where parseJSON = parseJSONText "InventoryItemType" instance ToJSON InventoryItemType where toJSON = toJSONText -- | Offset top unit for an asset. This is a read-only field if the asset -- displayType is ASSET_DISPLAY_TYPE_OVERLAY. Applicable to the following -- creative types: all RICH_MEDIA. data CreativeAssetPositionTopUnit = CAPTUOffSetUnitPixel -- ^ @OFFSET_UNIT_PIXEL@ | CAPTUOffSetUnitPercent -- ^ @OFFSET_UNIT_PERCENT@ | CAPTUOffSetUnitPixelFromCenter -- ^ @OFFSET_UNIT_PIXEL_FROM_CENTER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetPositionTopUnit instance FromHttpApiData CreativeAssetPositionTopUnit where parseQueryParam = \case "OFFSET_UNIT_PIXEL" -> Right CAPTUOffSetUnitPixel "OFFSET_UNIT_PERCENT" -> Right CAPTUOffSetUnitPercent "OFFSET_UNIT_PIXEL_FROM_CENTER" -> Right CAPTUOffSetUnitPixelFromCenter x -> Left ("Unable to parse CreativeAssetPositionTopUnit from: " <> x) instance ToHttpApiData CreativeAssetPositionTopUnit where toQueryParam = \case CAPTUOffSetUnitPixel -> "OFFSET_UNIT_PIXEL" CAPTUOffSetUnitPercent -> "OFFSET_UNIT_PERCENT" CAPTUOffSetUnitPixelFromCenter -> "OFFSET_UNIT_PIXEL_FROM_CENTER" instance FromJSON CreativeAssetPositionTopUnit where parseJSON = parseJSONText "CreativeAssetPositionTopUnit" instance ToJSON CreativeAssetPositionTopUnit where toJSON = toJSONText -- | Type of the associated floodlight activity group. This is a read-only -- field. data FloodlightActivityFloodlightActivityGroupType = FAFAGTCounter -- ^ @COUNTER@ | FAFAGTSale -- ^ @SALE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityFloodlightActivityGroupType instance FromHttpApiData FloodlightActivityFloodlightActivityGroupType where parseQueryParam = \case "COUNTER" -> Right FAFAGTCounter "SALE" -> Right FAFAGTSale x -> Left ("Unable to parse FloodlightActivityFloodlightActivityGroupType from: " <> x) instance ToHttpApiData FloodlightActivityFloodlightActivityGroupType where toQueryParam = \case FAFAGTCounter -> "COUNTER" FAFAGTSale -> "SALE" instance FromJSON FloodlightActivityFloodlightActivityGroupType where parseJSON = parseJSONText "FloodlightActivityFloodlightActivityGroupType" instance ToJSON FloodlightActivityFloodlightActivityGroupType where toJSON = toJSONText -- | Group type of this inventory item if it represents a placement group. Is -- null otherwise. There are two type of placement groups: -- PLANNING_PLACEMENT_GROUP_TYPE_PACKAGE is a simple group of inventory -- items that acts as a single pricing point for a group of tags. -- PLANNING_PLACEMENT_GROUP_TYPE_ROADBLOCK is a group of inventory items -- that not only acts as a single pricing point, but also assumes that all -- the tags in it will be served at the same time. A roadblock requires one -- of its assigned inventory items to be marked as primary. data PricingGroupType = PlanningPlacementGroupTypePackage -- ^ @PLANNING_PLACEMENT_GROUP_TYPE_PACKAGE@ | PlanningPlacementGroupTypeRoadblock -- ^ @PLANNING_PLACEMENT_GROUP_TYPE_ROADBLOCK@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PricingGroupType instance FromHttpApiData PricingGroupType where parseQueryParam = \case "PLANNING_PLACEMENT_GROUP_TYPE_PACKAGE" -> Right PlanningPlacementGroupTypePackage "PLANNING_PLACEMENT_GROUP_TYPE_ROADBLOCK" -> Right PlanningPlacementGroupTypeRoadblock x -> Left ("Unable to parse PricingGroupType from: " <> x) instance ToHttpApiData PricingGroupType where toQueryParam = \case PlanningPlacementGroupTypePackage -> "PLANNING_PLACEMENT_GROUP_TYPE_PACKAGE" PlanningPlacementGroupTypeRoadblock -> "PLANNING_PLACEMENT_GROUP_TYPE_ROADBLOCK" instance FromJSON PricingGroupType where parseJSON = parseJSONText "PricingGroupType" instance ToJSON PricingGroupType where toJSON = toJSONText -- | The type of Floodlight tag this activity will generate. This is a -- required field. data FloodlightActivityFloodlightTagType = Iframe -- ^ @IFRAME@ | Image -- ^ @IMAGE@ | GlobalSiteTag -- ^ @GLOBAL_SITE_TAG@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityFloodlightTagType instance FromHttpApiData FloodlightActivityFloodlightTagType where parseQueryParam = \case "IFRAME" -> Right Iframe "IMAGE" -> Right Image "GLOBAL_SITE_TAG" -> Right GlobalSiteTag x -> Left ("Unable to parse FloodlightActivityFloodlightTagType from: " <> x) instance ToHttpApiData FloodlightActivityFloodlightTagType where toQueryParam = \case Iframe -> "IFRAME" Image -> "IMAGE" GlobalSiteTag -> "GLOBAL_SITE_TAG" instance FromJSON FloodlightActivityFloodlightTagType where parseJSON = parseJSONText "FloodlightActivityFloodlightTagType" instance ToJSON FloodlightActivityFloodlightTagType where toJSON = toJSONText -- | Order of sorted results. data FloodlightActivityGroupsListSortOrder = FAGLSOAscending -- ^ @ASCENDING@ | FAGLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityGroupsListSortOrder instance FromHttpApiData FloodlightActivityGroupsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right FAGLSOAscending "DESCENDING" -> Right FAGLSODescending x -> Left ("Unable to parse FloodlightActivityGroupsListSortOrder from: " <> x) instance ToHttpApiData FloodlightActivityGroupsListSortOrder where toQueryParam = \case FAGLSOAscending -> "ASCENDING" FAGLSODescending -> "DESCENDING" instance FromJSON FloodlightActivityGroupsListSortOrder where parseJSON = parseJSONText "FloodlightActivityGroupsListSortOrder" instance ToJSON FloodlightActivityGroupsListSortOrder where toJSON = toJSONText -- | Type of creative rotation. Can be used to specify whether to use -- sequential or random rotation. data CreativeRotationType = CreativeRotationTypeSequential -- ^ @CREATIVE_ROTATION_TYPE_SEQUENTIAL@ | CreativeRotationTypeRandom -- ^ @CREATIVE_ROTATION_TYPE_RANDOM@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeRotationType instance FromHttpApiData CreativeRotationType where parseQueryParam = \case "CREATIVE_ROTATION_TYPE_SEQUENTIAL" -> Right CreativeRotationTypeSequential "CREATIVE_ROTATION_TYPE_RANDOM" -> Right CreativeRotationTypeRandom x -> Left ("Unable to parse CreativeRotationType from: " <> x) instance ToHttpApiData CreativeRotationType where toQueryParam = \case CreativeRotationTypeSequential -> "CREATIVE_ROTATION_TYPE_SEQUENTIAL" CreativeRotationTypeRandom -> "CREATIVE_ROTATION_TYPE_RANDOM" instance FromJSON CreativeRotationType where parseJSON = parseJSONText "CreativeRotationType" instance ToJSON CreativeRotationType where toJSON = toJSONText -- | Field by which to sort the list. data OrdersListSortField = OLSFID -- ^ @ID@ | OLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OrdersListSortField instance FromHttpApiData OrdersListSortField where parseQueryParam = \case "ID" -> Right OLSFID "NAME" -> Right OLSFName x -> Left ("Unable to parse OrdersListSortField from: " <> x) instance ToHttpApiData OrdersListSortField where toQueryParam = \case OLSFID -> "ID" OLSFName -> "NAME" instance FromJSON OrdersListSortField where parseJSON = parseJSONText "OrdersListSortField" instance ToJSON OrdersListSortField where toJSON = toJSONText -- | Field by which to sort the list. data PlacementGroupsListSortField = PGLSFID -- ^ @ID@ | PGLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementGroupsListSortField instance FromHttpApiData PlacementGroupsListSortField where parseQueryParam = \case "ID" -> Right PGLSFID "NAME" -> Right PGLSFName x -> Left ("Unable to parse PlacementGroupsListSortField from: " <> x) instance ToHttpApiData PlacementGroupsListSortField where toQueryParam = \case PGLSFID -> "ID" PGLSFName -> "NAME" instance FromJSON PlacementGroupsListSortField where parseJSON = parseJSONText "PlacementGroupsListSortField" instance ToJSON PlacementGroupsListSortField where toJSON = toJSONText -- | Order of sorted results. data DirectorySitesListSortOrder = DSLSOAscending -- ^ @ASCENDING@ | DSLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DirectorySitesListSortOrder instance FromHttpApiData DirectorySitesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right DSLSOAscending "DESCENDING" -> Right DSLSODescending x -> Left ("Unable to parse DirectorySitesListSortOrder from: " <> x) instance ToHttpApiData DirectorySitesListSortOrder where toQueryParam = \case DSLSOAscending -> "ASCENDING" DSLSODescending -> "DESCENDING" instance FromJSON DirectorySitesListSortOrder where parseJSON = parseJSONText "DirectorySitesListSortOrder" instance ToJSON DirectorySitesListSortOrder where toJSON = toJSONText data CreativeAssetDetectedFeaturesItem = CADFICssFontFace -- ^ @CSS_FONT_FACE@ | CADFICssBackgRoundSize -- ^ @CSS_BACKGROUND_SIZE@ | CADFICssBOrderImage -- ^ @CSS_BORDER_IMAGE@ | CADFICssBOrderRadius -- ^ @CSS_BORDER_RADIUS@ | CADFICssBoxShadow -- ^ @CSS_BOX_SHADOW@ | CADFICssFlexBox -- ^ @CSS_FLEX_BOX@ | CADFICssHsla -- ^ @CSS_HSLA@ | CADFICssMultipleBgs -- ^ @CSS_MULTIPLE_BGS@ | CADFICssOpacity -- ^ @CSS_OPACITY@ | CADFICssRgba -- ^ @CSS_RGBA@ | CADFICssTextShadow -- ^ @CSS_TEXT_SHADOW@ | CADFICssAnimations -- ^ @CSS_ANIMATIONS@ | CADFICssColumns -- ^ @CSS_COLUMNS@ | CADFICssGeneratedContent -- ^ @CSS_GENERATED_CONTENT@ | CADFICssGradients -- ^ @CSS_GRADIENTS@ | CADFICssReflections -- ^ @CSS_REFLECTIONS@ | CADFICssTransforms -- ^ @CSS_TRANSFORMS@ | CADFICssTRANSFORMS3D -- ^ @CSS_TRANSFORMS3D@ | CADFICssTransitions -- ^ @CSS_TRANSITIONS@ | CADFIApplicationCache -- ^ @APPLICATION_CACHE@ | CADFICanvas -- ^ @CANVAS@ | CADFICanvasText -- ^ @CANVAS_TEXT@ | CADFIDragAndDrop -- ^ @DRAG_AND_DROP@ | CADFIHashChange -- ^ @HASH_CHANGE@ | CADFIHistory -- ^ @HISTORY@ | CADFIAudio -- ^ @AUDIO@ | CADFIVideo -- ^ @VIDEO@ | CADFIIndexedDB -- ^ @INDEXED_DB@ | CADFIInputAttrAutocomplete -- ^ @INPUT_ATTR_AUTOCOMPLETE@ | CADFIInputAttrAutofocus -- ^ @INPUT_ATTR_AUTOFOCUS@ | CADFIInputAttrList -- ^ @INPUT_ATTR_LIST@ | CADFIInputAttrPlaceholder -- ^ @INPUT_ATTR_PLACEHOLDER@ | CADFIInputAttrMax -- ^ @INPUT_ATTR_MAX@ | CADFIInputAttrMin -- ^ @INPUT_ATTR_MIN@ | CADFIInputAttrMultiple -- ^ @INPUT_ATTR_MULTIPLE@ | CADFIInputAttrPattern -- ^ @INPUT_ATTR_PATTERN@ | CADFIInputAttrRequired -- ^ @INPUT_ATTR_REQUIRED@ | CADFIInputAttrStep -- ^ @INPUT_ATTR_STEP@ | CADFIInputTypeSearch -- ^ @INPUT_TYPE_SEARCH@ | CADFIInputTypeTel -- ^ @INPUT_TYPE_TEL@ | CADFIInputTypeURL -- ^ @INPUT_TYPE_URL@ | CADFIInputTypeEmail -- ^ @INPUT_TYPE_EMAIL@ | CADFIInputTypeDatetime -- ^ @INPUT_TYPE_DATETIME@ | CADFIInputTypeDate -- ^ @INPUT_TYPE_DATE@ | CADFIInputTypeMonth -- ^ @INPUT_TYPE_MONTH@ | CADFIInputTypeWeek -- ^ @INPUT_TYPE_WEEK@ | CADFIInputTypeTime -- ^ @INPUT_TYPE_TIME@ | CADFIInputTypeDatetimeLocal -- ^ @INPUT_TYPE_DATETIME_LOCAL@ | CADFIInputTypeNumber -- ^ @INPUT_TYPE_NUMBER@ | CADFIInputTypeRange -- ^ @INPUT_TYPE_RANGE@ | CADFIInputTypeColor -- ^ @INPUT_TYPE_COLOR@ | CADFILocalStorage -- ^ @LOCAL_STORAGE@ | CADFIPostMessage -- ^ @POST_MESSAGE@ | CADFISessionStorage -- ^ @SESSION_STORAGE@ | CADFIWebSockets -- ^ @WEB_SOCKETS@ | CADFIWebSQLDatabase -- ^ @WEB_SQL_DATABASE@ | CADFIWebWorkers -- ^ @WEB_WORKERS@ | CADFIGeoLocation -- ^ @GEO_LOCATION@ | CADFIInlineSvg -- ^ @INLINE_SVG@ | CADFISmil -- ^ @SMIL@ | CADFISvgHref -- ^ @SVG_HREF@ | CADFISvgClipPaths -- ^ @SVG_CLIP_PATHS@ | CADFITouch -- ^ @TOUCH@ | CADFIWebgl -- ^ @WEBGL@ | CADFISvgFilters -- ^ @SVG_FILTERS@ | CADFISvgFeImage -- ^ @SVG_FE_IMAGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetDetectedFeaturesItem instance FromHttpApiData CreativeAssetDetectedFeaturesItem where parseQueryParam = \case "CSS_FONT_FACE" -> Right CADFICssFontFace "CSS_BACKGROUND_SIZE" -> Right CADFICssBackgRoundSize "CSS_BORDER_IMAGE" -> Right CADFICssBOrderImage "CSS_BORDER_RADIUS" -> Right CADFICssBOrderRadius "CSS_BOX_SHADOW" -> Right CADFICssBoxShadow "CSS_FLEX_BOX" -> Right CADFICssFlexBox "CSS_HSLA" -> Right CADFICssHsla "CSS_MULTIPLE_BGS" -> Right CADFICssMultipleBgs "CSS_OPACITY" -> Right CADFICssOpacity "CSS_RGBA" -> Right CADFICssRgba "CSS_TEXT_SHADOW" -> Right CADFICssTextShadow "CSS_ANIMATIONS" -> Right CADFICssAnimations "CSS_COLUMNS" -> Right CADFICssColumns "CSS_GENERATED_CONTENT" -> Right CADFICssGeneratedContent "CSS_GRADIENTS" -> Right CADFICssGradients "CSS_REFLECTIONS" -> Right CADFICssReflections "CSS_TRANSFORMS" -> Right CADFICssTransforms "CSS_TRANSFORMS3D" -> Right CADFICssTRANSFORMS3D "CSS_TRANSITIONS" -> Right CADFICssTransitions "APPLICATION_CACHE" -> Right CADFIApplicationCache "CANVAS" -> Right CADFICanvas "CANVAS_TEXT" -> Right CADFICanvasText "DRAG_AND_DROP" -> Right CADFIDragAndDrop "HASH_CHANGE" -> Right CADFIHashChange "HISTORY" -> Right CADFIHistory "AUDIO" -> Right CADFIAudio "VIDEO" -> Right CADFIVideo "INDEXED_DB" -> Right CADFIIndexedDB "INPUT_ATTR_AUTOCOMPLETE" -> Right CADFIInputAttrAutocomplete "INPUT_ATTR_AUTOFOCUS" -> Right CADFIInputAttrAutofocus "INPUT_ATTR_LIST" -> Right CADFIInputAttrList "INPUT_ATTR_PLACEHOLDER" -> Right CADFIInputAttrPlaceholder "INPUT_ATTR_MAX" -> Right CADFIInputAttrMax "INPUT_ATTR_MIN" -> Right CADFIInputAttrMin "INPUT_ATTR_MULTIPLE" -> Right CADFIInputAttrMultiple "INPUT_ATTR_PATTERN" -> Right CADFIInputAttrPattern "INPUT_ATTR_REQUIRED" -> Right CADFIInputAttrRequired "INPUT_ATTR_STEP" -> Right CADFIInputAttrStep "INPUT_TYPE_SEARCH" -> Right CADFIInputTypeSearch "INPUT_TYPE_TEL" -> Right CADFIInputTypeTel "INPUT_TYPE_URL" -> Right CADFIInputTypeURL "INPUT_TYPE_EMAIL" -> Right CADFIInputTypeEmail "INPUT_TYPE_DATETIME" -> Right CADFIInputTypeDatetime "INPUT_TYPE_DATE" -> Right CADFIInputTypeDate "INPUT_TYPE_MONTH" -> Right CADFIInputTypeMonth "INPUT_TYPE_WEEK" -> Right CADFIInputTypeWeek "INPUT_TYPE_TIME" -> Right CADFIInputTypeTime "INPUT_TYPE_DATETIME_LOCAL" -> Right CADFIInputTypeDatetimeLocal "INPUT_TYPE_NUMBER" -> Right CADFIInputTypeNumber "INPUT_TYPE_RANGE" -> Right CADFIInputTypeRange "INPUT_TYPE_COLOR" -> Right CADFIInputTypeColor "LOCAL_STORAGE" -> Right CADFILocalStorage "POST_MESSAGE" -> Right CADFIPostMessage "SESSION_STORAGE" -> Right CADFISessionStorage "WEB_SOCKETS" -> Right CADFIWebSockets "WEB_SQL_DATABASE" -> Right CADFIWebSQLDatabase "WEB_WORKERS" -> Right CADFIWebWorkers "GEO_LOCATION" -> Right CADFIGeoLocation "INLINE_SVG" -> Right CADFIInlineSvg "SMIL" -> Right CADFISmil "SVG_HREF" -> Right CADFISvgHref "SVG_CLIP_PATHS" -> Right CADFISvgClipPaths "TOUCH" -> Right CADFITouch "WEBGL" -> Right CADFIWebgl "SVG_FILTERS" -> Right CADFISvgFilters "SVG_FE_IMAGE" -> Right CADFISvgFeImage x -> Left ("Unable to parse CreativeAssetDetectedFeaturesItem from: " <> x) instance ToHttpApiData CreativeAssetDetectedFeaturesItem where toQueryParam = \case CADFICssFontFace -> "CSS_FONT_FACE" CADFICssBackgRoundSize -> "CSS_BACKGROUND_SIZE" CADFICssBOrderImage -> "CSS_BORDER_IMAGE" CADFICssBOrderRadius -> "CSS_BORDER_RADIUS" CADFICssBoxShadow -> "CSS_BOX_SHADOW" CADFICssFlexBox -> "CSS_FLEX_BOX" CADFICssHsla -> "CSS_HSLA" CADFICssMultipleBgs -> "CSS_MULTIPLE_BGS" CADFICssOpacity -> "CSS_OPACITY" CADFICssRgba -> "CSS_RGBA" CADFICssTextShadow -> "CSS_TEXT_SHADOW" CADFICssAnimations -> "CSS_ANIMATIONS" CADFICssColumns -> "CSS_COLUMNS" CADFICssGeneratedContent -> "CSS_GENERATED_CONTENT" CADFICssGradients -> "CSS_GRADIENTS" CADFICssReflections -> "CSS_REFLECTIONS" CADFICssTransforms -> "CSS_TRANSFORMS" CADFICssTRANSFORMS3D -> "CSS_TRANSFORMS3D" CADFICssTransitions -> "CSS_TRANSITIONS" CADFIApplicationCache -> "APPLICATION_CACHE" CADFICanvas -> "CANVAS" CADFICanvasText -> "CANVAS_TEXT" CADFIDragAndDrop -> "DRAG_AND_DROP" CADFIHashChange -> "HASH_CHANGE" CADFIHistory -> "HISTORY" CADFIAudio -> "AUDIO" CADFIVideo -> "VIDEO" CADFIIndexedDB -> "INDEXED_DB" CADFIInputAttrAutocomplete -> "INPUT_ATTR_AUTOCOMPLETE" CADFIInputAttrAutofocus -> "INPUT_ATTR_AUTOFOCUS" CADFIInputAttrList -> "INPUT_ATTR_LIST" CADFIInputAttrPlaceholder -> "INPUT_ATTR_PLACEHOLDER" CADFIInputAttrMax -> "INPUT_ATTR_MAX" CADFIInputAttrMin -> "INPUT_ATTR_MIN" CADFIInputAttrMultiple -> "INPUT_ATTR_MULTIPLE" CADFIInputAttrPattern -> "INPUT_ATTR_PATTERN" CADFIInputAttrRequired -> "INPUT_ATTR_REQUIRED" CADFIInputAttrStep -> "INPUT_ATTR_STEP" CADFIInputTypeSearch -> "INPUT_TYPE_SEARCH" CADFIInputTypeTel -> "INPUT_TYPE_TEL" CADFIInputTypeURL -> "INPUT_TYPE_URL" CADFIInputTypeEmail -> "INPUT_TYPE_EMAIL" CADFIInputTypeDatetime -> "INPUT_TYPE_DATETIME" CADFIInputTypeDate -> "INPUT_TYPE_DATE" CADFIInputTypeMonth -> "INPUT_TYPE_MONTH" CADFIInputTypeWeek -> "INPUT_TYPE_WEEK" CADFIInputTypeTime -> "INPUT_TYPE_TIME" CADFIInputTypeDatetimeLocal -> "INPUT_TYPE_DATETIME_LOCAL" CADFIInputTypeNumber -> "INPUT_TYPE_NUMBER" CADFIInputTypeRange -> "INPUT_TYPE_RANGE" CADFIInputTypeColor -> "INPUT_TYPE_COLOR" CADFILocalStorage -> "LOCAL_STORAGE" CADFIPostMessage -> "POST_MESSAGE" CADFISessionStorage -> "SESSION_STORAGE" CADFIWebSockets -> "WEB_SOCKETS" CADFIWebSQLDatabase -> "WEB_SQL_DATABASE" CADFIWebWorkers -> "WEB_WORKERS" CADFIGeoLocation -> "GEO_LOCATION" CADFIInlineSvg -> "INLINE_SVG" CADFISmil -> "SMIL" CADFISvgHref -> "SVG_HREF" CADFISvgClipPaths -> "SVG_CLIP_PATHS" CADFITouch -> "TOUCH" CADFIWebgl -> "WEBGL" CADFISvgFilters -> "SVG_FILTERS" CADFISvgFeImage -> "SVG_FE_IMAGE" instance FromJSON CreativeAssetDetectedFeaturesItem where parseJSON = parseJSONText "CreativeAssetDetectedFeaturesItem" instance ToJSON CreativeAssetDetectedFeaturesItem where toJSON = toJSONText -- | Type of the floodlight activity group. This is a required field that is -- read-only after insertion. data FloodlightActivityGroupType = FAGTCounter -- ^ @COUNTER@ | FAGTSale -- ^ @SALE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityGroupType instance FromHttpApiData FloodlightActivityGroupType where parseQueryParam = \case "COUNTER" -> Right FAGTCounter "SALE" -> Right FAGTSale x -> Left ("Unable to parse FloodlightActivityGroupType from: " <> x) instance ToHttpApiData FloodlightActivityGroupType where toQueryParam = \case FAGTCounter -> "COUNTER" FAGTSale -> "SALE" instance FromJSON FloodlightActivityGroupType where parseJSON = parseJSONText "FloodlightActivityGroupType" instance ToJSON FloodlightActivityGroupType where toJSON = toJSONText -- | Tag formats to generate for these placements. *Note:* -- PLACEMENT_TAG_STANDARD can only be generated for 1x1 placements. data PlacementsGeneratetagsTagFormats = PGTFPlacementTagStandard -- ^ @PLACEMENT_TAG_STANDARD@ | PGTFPlacementTagIframeJavascript -- ^ @PLACEMENT_TAG_IFRAME_JAVASCRIPT@ | PGTFPlacementTagIframeIlayer -- ^ @PLACEMENT_TAG_IFRAME_ILAYER@ | PGTFPlacementTagInternalRedirect -- ^ @PLACEMENT_TAG_INTERNAL_REDIRECT@ | PGTFPlacementTagJavascript -- ^ @PLACEMENT_TAG_JAVASCRIPT@ | PGTFPlacementTagInterstitialIframeJavascript -- ^ @PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT@ | PGTFPlacementTagInterstitialInternalRedirect -- ^ @PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT@ | PGTFPlacementTagInterstitialJavascript -- ^ @PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT@ | PGTFPlacementTagClickCommands -- ^ @PLACEMENT_TAG_CLICK_COMMANDS@ | PGTFPlacementTagInstreamVideoPrefetch -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH@ | PGTFPlacementTagTracking -- ^ @PLACEMENT_TAG_TRACKING@ | PGTFPlacementTagTrackingIframe -- ^ @PLACEMENT_TAG_TRACKING_IFRAME@ | PGTFPlacementTagTrackingJavascript -- ^ @PLACEMENT_TAG_TRACKING_JAVASCRIPT@ | PGTFPlacementTagInstreamVideoPrefetchVast3 -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3@ | PGTFPlacementTagIframeJavascriptLegacy -- ^ @PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY@ | PGTFPlacementTagJavascriptLegacy -- ^ @PLACEMENT_TAG_JAVASCRIPT_LEGACY@ | PGTFPlacementTagInterstitialIframeJavascriptLegacy -- ^ @PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY@ | PGTFPlacementTagInterstitialJavascriptLegacy -- ^ @PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY@ | PGTFPlacementTagInstreamVideoPrefetchVast4 -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementsGeneratetagsTagFormats instance FromHttpApiData PlacementsGeneratetagsTagFormats where parseQueryParam = \case "PLACEMENT_TAG_STANDARD" -> Right PGTFPlacementTagStandard "PLACEMENT_TAG_IFRAME_JAVASCRIPT" -> Right PGTFPlacementTagIframeJavascript "PLACEMENT_TAG_IFRAME_ILAYER" -> Right PGTFPlacementTagIframeIlayer "PLACEMENT_TAG_INTERNAL_REDIRECT" -> Right PGTFPlacementTagInternalRedirect "PLACEMENT_TAG_JAVASCRIPT" -> Right PGTFPlacementTagJavascript "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT" -> Right PGTFPlacementTagInterstitialIframeJavascript "PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT" -> Right PGTFPlacementTagInterstitialInternalRedirect "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT" -> Right PGTFPlacementTagInterstitialJavascript "PLACEMENT_TAG_CLICK_COMMANDS" -> Right PGTFPlacementTagClickCommands "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH" -> Right PGTFPlacementTagInstreamVideoPrefetch "PLACEMENT_TAG_TRACKING" -> Right PGTFPlacementTagTracking "PLACEMENT_TAG_TRACKING_IFRAME" -> Right PGTFPlacementTagTrackingIframe "PLACEMENT_TAG_TRACKING_JAVASCRIPT" -> Right PGTFPlacementTagTrackingJavascript "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3" -> Right PGTFPlacementTagInstreamVideoPrefetchVast3 "PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY" -> Right PGTFPlacementTagIframeJavascriptLegacy "PLACEMENT_TAG_JAVASCRIPT_LEGACY" -> Right PGTFPlacementTagJavascriptLegacy "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY" -> Right PGTFPlacementTagInterstitialIframeJavascriptLegacy "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY" -> Right PGTFPlacementTagInterstitialJavascriptLegacy "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4" -> Right PGTFPlacementTagInstreamVideoPrefetchVast4 x -> Left ("Unable to parse PlacementsGeneratetagsTagFormats from: " <> x) instance ToHttpApiData PlacementsGeneratetagsTagFormats where toQueryParam = \case PGTFPlacementTagStandard -> "PLACEMENT_TAG_STANDARD" PGTFPlacementTagIframeJavascript -> "PLACEMENT_TAG_IFRAME_JAVASCRIPT" PGTFPlacementTagIframeIlayer -> "PLACEMENT_TAG_IFRAME_ILAYER" PGTFPlacementTagInternalRedirect -> "PLACEMENT_TAG_INTERNAL_REDIRECT" PGTFPlacementTagJavascript -> "PLACEMENT_TAG_JAVASCRIPT" PGTFPlacementTagInterstitialIframeJavascript -> "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT" PGTFPlacementTagInterstitialInternalRedirect -> "PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT" PGTFPlacementTagInterstitialJavascript -> "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT" PGTFPlacementTagClickCommands -> "PLACEMENT_TAG_CLICK_COMMANDS" PGTFPlacementTagInstreamVideoPrefetch -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH" PGTFPlacementTagTracking -> "PLACEMENT_TAG_TRACKING" PGTFPlacementTagTrackingIframe -> "PLACEMENT_TAG_TRACKING_IFRAME" PGTFPlacementTagTrackingJavascript -> "PLACEMENT_TAG_TRACKING_JAVASCRIPT" PGTFPlacementTagInstreamVideoPrefetchVast3 -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3" PGTFPlacementTagIframeJavascriptLegacy -> "PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY" PGTFPlacementTagJavascriptLegacy -> "PLACEMENT_TAG_JAVASCRIPT_LEGACY" PGTFPlacementTagInterstitialIframeJavascriptLegacy -> "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY" PGTFPlacementTagInterstitialJavascriptLegacy -> "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY" PGTFPlacementTagInstreamVideoPrefetchVast4 -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4" instance FromJSON PlacementsGeneratetagsTagFormats where parseJSON = parseJSONText "PlacementsGeneratetagsTagFormats" instance ToJSON PlacementsGeneratetagsTagFormats where toJSON = toJSONText -- | Field by which to sort the list. data AccountUserProFilesListSortField = AUPFLSFID -- ^ @ID@ | AUPFLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountUserProFilesListSortField instance FromHttpApiData AccountUserProFilesListSortField where parseQueryParam = \case "ID" -> Right AUPFLSFID "NAME" -> Right AUPFLSFName x -> Left ("Unable to parse AccountUserProFilesListSortField from: " <> x) instance ToHttpApiData AccountUserProFilesListSortField where toQueryParam = \case AUPFLSFID -> "ID" AUPFLSFName -> "NAME" instance FromJSON AccountUserProFilesListSortField where parseJSON = parseJSONText "AccountUserProFilesListSortField" instance ToJSON AccountUserProFilesListSortField where toJSON = toJSONText -- | V1 error format. data Xgafv = X1 -- ^ @1@ -- v1 error format | X2 -- ^ @2@ -- v2 error format deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable Xgafv instance FromHttpApiData Xgafv where parseQueryParam = \case "1" -> Right X1 "2" -> Right X2 x -> Left ("Unable to parse Xgafv from: " <> x) instance ToHttpApiData Xgafv where toQueryParam = \case X1 -> "1" X2 -> "2" instance FromJSON Xgafv where parseJSON = parseJSONText "Xgafv" instance ToJSON Xgafv where toJSON = toJSONText -- | Determines how the \'value\' field is matched when filtering. If not -- specified, defaults to EXACT. If set to WILDCARD_EXPRESSION, \'*\' is -- allowed as a placeholder for variable length character sequences, and it -- can be escaped with a backslash. Note, only paid search dimensions -- (\'dfa:paidSearch*\') allow a matchType other than EXACT. data PathFilterPathMatchPosition = PFPMPPathMatchPositionUnspecified -- ^ @PATH_MATCH_POSITION_UNSPECIFIED@ | PFPMPAny -- ^ @ANY@ | PFPMPFirst -- ^ @FIRST@ | PFPMPLast -- ^ @LAST@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PathFilterPathMatchPosition instance FromHttpApiData PathFilterPathMatchPosition where parseQueryParam = \case "PATH_MATCH_POSITION_UNSPECIFIED" -> Right PFPMPPathMatchPositionUnspecified "ANY" -> Right PFPMPAny "FIRST" -> Right PFPMPFirst "LAST" -> Right PFPMPLast x -> Left ("Unable to parse PathFilterPathMatchPosition from: " <> x) instance ToHttpApiData PathFilterPathMatchPosition where toQueryParam = \case PFPMPPathMatchPositionUnspecified -> "PATH_MATCH_POSITION_UNSPECIFIED" PFPMPAny -> "ANY" PFPMPFirst -> "FIRST" PFPMPLast -> "LAST" instance FromJSON PathFilterPathMatchPosition where parseJSON = parseJSONText "PathFilterPathMatchPosition" instance ToJSON PathFilterPathMatchPosition where toJSON = toJSONText -- | Order of sorted results. data InventoryItemsListSortOrder = IILSOAscending -- ^ @ASCENDING@ | IILSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable InventoryItemsListSortOrder instance FromHttpApiData InventoryItemsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right IILSOAscending "DESCENDING" -> Right IILSODescending x -> Left ("Unable to parse InventoryItemsListSortOrder from: " <> x) instance ToHttpApiData InventoryItemsListSortOrder where toQueryParam = \case IILSOAscending -> "ASCENDING" IILSODescending -> "DESCENDING" instance FromJSON InventoryItemsListSortOrder where parseJSON = parseJSONText "InventoryItemsListSortOrder" instance ToJSON InventoryItemsListSortOrder where toJSON = toJSONText -- | Order of sorted results. data PlacementStrategiesListSortOrder = PSLSOAscending -- ^ @ASCENDING@ | PSLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementStrategiesListSortOrder instance FromHttpApiData PlacementStrategiesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right PSLSOAscending "DESCENDING" -> Right PSLSODescending x -> Left ("Unable to parse PlacementStrategiesListSortOrder from: " <> x) instance ToHttpApiData PlacementStrategiesListSortOrder where toQueryParam = \case PSLSOAscending -> "ASCENDING" PSLSODescending -> "DESCENDING" instance FromJSON PlacementStrategiesListSortOrder where parseJSON = parseJSONText "PlacementStrategiesListSortOrder" instance ToJSON PlacementStrategiesListSortOrder where toJSON = toJSONText -- | The field by which to sort the list. data ReportsFilesListSortField = RFLSFID -- ^ @ID@ | RFLSFLastModifiedTime -- ^ @LAST_MODIFIED_TIME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportsFilesListSortField instance FromHttpApiData ReportsFilesListSortField where parseQueryParam = \case "ID" -> Right RFLSFID "LAST_MODIFIED_TIME" -> Right RFLSFLastModifiedTime x -> Left ("Unable to parse ReportsFilesListSortField from: " <> x) instance ToHttpApiData ReportsFilesListSortField where toQueryParam = \case RFLSFID -> "ID" RFLSFLastModifiedTime -> "LAST_MODIFIED_TIME" instance FromJSON ReportsFilesListSortField where parseJSON = parseJSONText "ReportsFilesListSortField" instance ToJSON ReportsFilesListSortField where toJSON = toJSONText -- | Field by which to sort the list. data CreativesListSortField = CID -- ^ @ID@ | CName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativesListSortField instance FromHttpApiData CreativesListSortField where parseQueryParam = \case "ID" -> Right CID "NAME" -> Right CName x -> Left ("Unable to parse CreativesListSortField from: " <> x) instance ToHttpApiData CreativesListSortField where toQueryParam = \case CID -> "ID" CName -> "NAME" instance FromJSON CreativesListSortField where parseJSON = parseJSONText "CreativesListSortField" instance ToJSON CreativesListSortField where toJSON = toJSONText data DayPartTargetingDaysOfWeekItem = DPTDOWIMonday -- ^ @MONDAY@ | DPTDOWITuesday -- ^ @TUESDAY@ | DPTDOWIWednesday -- ^ @WEDNESDAY@ | DPTDOWIThursday -- ^ @THURSDAY@ | DPTDOWIFriday -- ^ @FRIDAY@ | DPTDOWISaturday -- ^ @SATURDAY@ | DPTDOWISunday -- ^ @SUNDAY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DayPartTargetingDaysOfWeekItem instance FromHttpApiData DayPartTargetingDaysOfWeekItem where parseQueryParam = \case "MONDAY" -> Right DPTDOWIMonday "TUESDAY" -> Right DPTDOWITuesday "WEDNESDAY" -> Right DPTDOWIWednesday "THURSDAY" -> Right DPTDOWIThursday "FRIDAY" -> Right DPTDOWIFriday "SATURDAY" -> Right DPTDOWISaturday "SUNDAY" -> Right DPTDOWISunday x -> Left ("Unable to parse DayPartTargetingDaysOfWeekItem from: " <> x) instance ToHttpApiData DayPartTargetingDaysOfWeekItem where toQueryParam = \case DPTDOWIMonday -> "MONDAY" DPTDOWITuesday -> "TUESDAY" DPTDOWIWednesday -> "WEDNESDAY" DPTDOWIThursday -> "THURSDAY" DPTDOWIFriday -> "FRIDAY" DPTDOWISaturday -> "SATURDAY" DPTDOWISunday -> "SUNDAY" instance FromJSON DayPartTargetingDaysOfWeekItem where parseJSON = parseJSONText "DayPartTargetingDaysOfWeekItem" instance ToJSON DayPartTargetingDaysOfWeekItem where toJSON = toJSONText -- | Strategy for calculating weights. Used with -- CREATIVE_ROTATION_TYPE_RANDOM. data CreativeRotationWeightCalculationStrategy = WeightStrategyEqual -- ^ @WEIGHT_STRATEGY_EQUAL@ | WeightStrategyCustom -- ^ @WEIGHT_STRATEGY_CUSTOM@ | WeightStrategyHighestCtr -- ^ @WEIGHT_STRATEGY_HIGHEST_CTR@ | WeightStrategyOptimized -- ^ @WEIGHT_STRATEGY_OPTIMIZED@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeRotationWeightCalculationStrategy instance FromHttpApiData CreativeRotationWeightCalculationStrategy where parseQueryParam = \case "WEIGHT_STRATEGY_EQUAL" -> Right WeightStrategyEqual "WEIGHT_STRATEGY_CUSTOM" -> Right WeightStrategyCustom "WEIGHT_STRATEGY_HIGHEST_CTR" -> Right WeightStrategyHighestCtr "WEIGHT_STRATEGY_OPTIMIZED" -> Right WeightStrategyOptimized x -> Left ("Unable to parse CreativeRotationWeightCalculationStrategy from: " <> x) instance ToHttpApiData CreativeRotationWeightCalculationStrategy where toQueryParam = \case WeightStrategyEqual -> "WEIGHT_STRATEGY_EQUAL" WeightStrategyCustom -> "WEIGHT_STRATEGY_CUSTOM" WeightStrategyHighestCtr -> "WEIGHT_STRATEGY_HIGHEST_CTR" WeightStrategyOptimized -> "WEIGHT_STRATEGY_OPTIMIZED" instance FromJSON CreativeRotationWeightCalculationStrategy where parseJSON = parseJSONText "CreativeRotationWeightCalculationStrategy" instance ToJSON CreativeRotationWeightCalculationStrategy where toJSON = toJSONText -- | The scope that defines which results are returned. data FilesListScope = FLSAll -- ^ @ALL@ -- All files in account. | FLSMine -- ^ @MINE@ -- My files. | FLSSharedWithMe -- ^ @SHARED_WITH_ME@ -- Files shared with me. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FilesListScope instance FromHttpApiData FilesListScope where parseQueryParam = \case "ALL" -> Right FLSAll "MINE" -> Right FLSMine "SHARED_WITH_ME" -> Right FLSSharedWithMe x -> Left ("Unable to parse FilesListScope from: " <> x) instance ToHttpApiData FilesListScope where toQueryParam = \case FLSAll -> "ALL" FLSMine -> "MINE" FLSSharedWithMe -> "SHARED_WITH_ME" instance FromJSON FilesListScope where parseJSON = parseJSONText "FilesListScope" instance ToJSON FilesListScope where toJSON = toJSONText -- | Field by which to sort the list. data ContentCategoriesListSortField = CCLSFID -- ^ @ID@ | CCLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ContentCategoriesListSortField instance FromHttpApiData ContentCategoriesListSortField where parseQueryParam = \case "ID" -> Right CCLSFID "NAME" -> Right CCLSFName x -> Left ("Unable to parse ContentCategoriesListSortField from: " <> x) instance ToHttpApiData ContentCategoriesListSortField where toQueryParam = \case CCLSFID -> "ID" CCLSFName -> "NAME" instance FromJSON ContentCategoriesListSortField where parseJSON = parseJSONText "ContentCategoriesListSortField" instance ToJSON ContentCategoriesListSortField where toJSON = toJSONText -- | Audience age group of this project. data ProjectAudienceAgeGroup = PlanningAudienceAge1824 -- ^ @PLANNING_AUDIENCE_AGE_18_24@ | PlanningAudienceAge2534 -- ^ @PLANNING_AUDIENCE_AGE_25_34@ | PlanningAudienceAge3544 -- ^ @PLANNING_AUDIENCE_AGE_35_44@ | PlanningAudienceAge4554 -- ^ @PLANNING_AUDIENCE_AGE_45_54@ | PlanningAudienceAge5564 -- ^ @PLANNING_AUDIENCE_AGE_55_64@ | PlanningAudienceAge65OrMore -- ^ @PLANNING_AUDIENCE_AGE_65_OR_MORE@ | PlanningAudienceAgeUnknown -- ^ @PLANNING_AUDIENCE_AGE_UNKNOWN@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ProjectAudienceAgeGroup instance FromHttpApiData ProjectAudienceAgeGroup where parseQueryParam = \case "PLANNING_AUDIENCE_AGE_18_24" -> Right PlanningAudienceAge1824 "PLANNING_AUDIENCE_AGE_25_34" -> Right PlanningAudienceAge2534 "PLANNING_AUDIENCE_AGE_35_44" -> Right PlanningAudienceAge3544 "PLANNING_AUDIENCE_AGE_45_54" -> Right PlanningAudienceAge4554 "PLANNING_AUDIENCE_AGE_55_64" -> Right PlanningAudienceAge5564 "PLANNING_AUDIENCE_AGE_65_OR_MORE" -> Right PlanningAudienceAge65OrMore "PLANNING_AUDIENCE_AGE_UNKNOWN" -> Right PlanningAudienceAgeUnknown x -> Left ("Unable to parse ProjectAudienceAgeGroup from: " <> x) instance ToHttpApiData ProjectAudienceAgeGroup where toQueryParam = \case PlanningAudienceAge1824 -> "PLANNING_AUDIENCE_AGE_18_24" PlanningAudienceAge2534 -> "PLANNING_AUDIENCE_AGE_25_34" PlanningAudienceAge3544 -> "PLANNING_AUDIENCE_AGE_35_44" PlanningAudienceAge4554 -> "PLANNING_AUDIENCE_AGE_45_54" PlanningAudienceAge5564 -> "PLANNING_AUDIENCE_AGE_55_64" PlanningAudienceAge65OrMore -> "PLANNING_AUDIENCE_AGE_65_OR_MORE" PlanningAudienceAgeUnknown -> "PLANNING_AUDIENCE_AGE_UNKNOWN" instance FromJSON ProjectAudienceAgeGroup where parseJSON = parseJSONText "ProjectAudienceAgeGroup" instance ToJSON ProjectAudienceAgeGroup where toJSON = toJSONText -- | Type of ad. This is a required field on insertion. Note that default ads -- ( AD_SERVING_DEFAULT_AD) cannot be created directly (see Creative -- resource). data AdType = ATAdServingStandardAd -- ^ @AD_SERVING_STANDARD_AD@ | ATAdServingDefaultAd -- ^ @AD_SERVING_DEFAULT_AD@ | ATAdServingClickTracker -- ^ @AD_SERVING_CLICK_TRACKER@ | ATAdServingTracking -- ^ @AD_SERVING_TRACKING@ | ATAdServingBrandSafeAd -- ^ @AD_SERVING_BRAND_SAFE_AD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdType instance FromHttpApiData AdType where parseQueryParam = \case "AD_SERVING_STANDARD_AD" -> Right ATAdServingStandardAd "AD_SERVING_DEFAULT_AD" -> Right ATAdServingDefaultAd "AD_SERVING_CLICK_TRACKER" -> Right ATAdServingClickTracker "AD_SERVING_TRACKING" -> Right ATAdServingTracking "AD_SERVING_BRAND_SAFE_AD" -> Right ATAdServingBrandSafeAd x -> Left ("Unable to parse AdType from: " <> x) instance ToHttpApiData AdType where toQueryParam = \case ATAdServingStandardAd -> "AD_SERVING_STANDARD_AD" ATAdServingDefaultAd -> "AD_SERVING_DEFAULT_AD" ATAdServingClickTracker -> "AD_SERVING_CLICK_TRACKER" ATAdServingTracking -> "AD_SERVING_TRACKING" ATAdServingBrandSafeAd -> "AD_SERVING_BRAND_SAFE_AD" instance FromJSON AdType where parseJSON = parseJSONText "AdType" instance ToJSON AdType where toJSON = toJSONText -- | . data MeasurementPartnerAdvertiserLinkLinkStatus = MPALLSMeasurementPartnerUnlinked -- ^ @MEASUREMENT_PARTNER_UNLINKED@ | MPALLSMeasurementPartnerLinked -- ^ @MEASUREMENT_PARTNER_LINKED@ | MPALLSMeasurementPartnerLinkPending -- ^ @MEASUREMENT_PARTNER_LINK_PENDING@ | MPALLSMeasurementPartnerLinkFailure -- ^ @MEASUREMENT_PARTNER_LINK_FAILURE@ | MPALLSMeasurementPartnerLinkOptOut -- ^ @MEASUREMENT_PARTNER_LINK_OPT_OUT@ | MPALLSMeasurementPartnerLinkOptOutPending -- ^ @MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING@ | MPALLSMeasurementPartnerLinkWrAppingPending -- ^ @MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING@ | MPALLSMeasurementPartnerModeChangePending -- ^ @MEASUREMENT_PARTNER_MODE_CHANGE_PENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MeasurementPartnerAdvertiserLinkLinkStatus instance FromHttpApiData MeasurementPartnerAdvertiserLinkLinkStatus where parseQueryParam = \case "MEASUREMENT_PARTNER_UNLINKED" -> Right MPALLSMeasurementPartnerUnlinked "MEASUREMENT_PARTNER_LINKED" -> Right MPALLSMeasurementPartnerLinked "MEASUREMENT_PARTNER_LINK_PENDING" -> Right MPALLSMeasurementPartnerLinkPending "MEASUREMENT_PARTNER_LINK_FAILURE" -> Right MPALLSMeasurementPartnerLinkFailure "MEASUREMENT_PARTNER_LINK_OPT_OUT" -> Right MPALLSMeasurementPartnerLinkOptOut "MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING" -> Right MPALLSMeasurementPartnerLinkOptOutPending "MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING" -> Right MPALLSMeasurementPartnerLinkWrAppingPending "MEASUREMENT_PARTNER_MODE_CHANGE_PENDING" -> Right MPALLSMeasurementPartnerModeChangePending x -> Left ("Unable to parse MeasurementPartnerAdvertiserLinkLinkStatus from: " <> x) instance ToHttpApiData MeasurementPartnerAdvertiserLinkLinkStatus where toQueryParam = \case MPALLSMeasurementPartnerUnlinked -> "MEASUREMENT_PARTNER_UNLINKED" MPALLSMeasurementPartnerLinked -> "MEASUREMENT_PARTNER_LINKED" MPALLSMeasurementPartnerLinkPending -> "MEASUREMENT_PARTNER_LINK_PENDING" MPALLSMeasurementPartnerLinkFailure -> "MEASUREMENT_PARTNER_LINK_FAILURE" MPALLSMeasurementPartnerLinkOptOut -> "MEASUREMENT_PARTNER_LINK_OPT_OUT" MPALLSMeasurementPartnerLinkOptOutPending -> "MEASUREMENT_PARTNER_LINK_OPT_OUT_PENDING" MPALLSMeasurementPartnerLinkWrAppingPending -> "MEASUREMENT_PARTNER_LINK_WRAPPING_PENDING" MPALLSMeasurementPartnerModeChangePending -> "MEASUREMENT_PARTNER_MODE_CHANGE_PENDING" instance FromJSON MeasurementPartnerAdvertiserLinkLinkStatus where parseJSON = parseJSONText "MeasurementPartnerAdvertiserLinkLinkStatus" instance ToJSON MeasurementPartnerAdvertiserLinkLinkStatus where toJSON = toJSONText -- | Select only change logs with the specified action. data ChangeLogsListAction = ActionCreate -- ^ @ACTION_CREATE@ | ActionUpdate -- ^ @ACTION_UPDATE@ | ActionDelete -- ^ @ACTION_DELETE@ | ActionEnable -- ^ @ACTION_ENABLE@ | ActionDisable -- ^ @ACTION_DISABLE@ | ActionAdd -- ^ @ACTION_ADD@ | ActionRemove -- ^ @ACTION_REMOVE@ | ActionMarkAsDefault -- ^ @ACTION_MARK_AS_DEFAULT@ | ActionAssociate -- ^ @ACTION_ASSOCIATE@ | ActionAssign -- ^ @ACTION_ASSIGN@ | ActionUnassign -- ^ @ACTION_UNASSIGN@ | ActionSend -- ^ @ACTION_SEND@ | ActionLink -- ^ @ACTION_LINK@ | ActionUnlink -- ^ @ACTION_UNLINK@ | ActionPush -- ^ @ACTION_PUSH@ | ActionEmailTags -- ^ @ACTION_EMAIL_TAGS@ | ActionShare -- ^ @ACTION_SHARE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ChangeLogsListAction instance FromHttpApiData ChangeLogsListAction where parseQueryParam = \case "ACTION_CREATE" -> Right ActionCreate "ACTION_UPDATE" -> Right ActionUpdate "ACTION_DELETE" -> Right ActionDelete "ACTION_ENABLE" -> Right ActionEnable "ACTION_DISABLE" -> Right ActionDisable "ACTION_ADD" -> Right ActionAdd "ACTION_REMOVE" -> Right ActionRemove "ACTION_MARK_AS_DEFAULT" -> Right ActionMarkAsDefault "ACTION_ASSOCIATE" -> Right ActionAssociate "ACTION_ASSIGN" -> Right ActionAssign "ACTION_UNASSIGN" -> Right ActionUnassign "ACTION_SEND" -> Right ActionSend "ACTION_LINK" -> Right ActionLink "ACTION_UNLINK" -> Right ActionUnlink "ACTION_PUSH" -> Right ActionPush "ACTION_EMAIL_TAGS" -> Right ActionEmailTags "ACTION_SHARE" -> Right ActionShare x -> Left ("Unable to parse ChangeLogsListAction from: " <> x) instance ToHttpApiData ChangeLogsListAction where toQueryParam = \case ActionCreate -> "ACTION_CREATE" ActionUpdate -> "ACTION_UPDATE" ActionDelete -> "ACTION_DELETE" ActionEnable -> "ACTION_ENABLE" ActionDisable -> "ACTION_DISABLE" ActionAdd -> "ACTION_ADD" ActionRemove -> "ACTION_REMOVE" ActionMarkAsDefault -> "ACTION_MARK_AS_DEFAULT" ActionAssociate -> "ACTION_ASSOCIATE" ActionAssign -> "ACTION_ASSIGN" ActionUnassign -> "ACTION_UNASSIGN" ActionSend -> "ACTION_SEND" ActionLink -> "ACTION_LINK" ActionUnlink -> "ACTION_UNLINK" ActionPush -> "ACTION_PUSH" ActionEmailTags -> "ACTION_EMAIL_TAGS" ActionShare -> "ACTION_SHARE" instance FromJSON ChangeLogsListAction where parseJSON = parseJSONText "ChangeLogsListAction" instance ToJSON ChangeLogsListAction where toJSON = toJSONText -- | Type of artwork used for the creative. This is a read-only field. -- Applicable to the following creative types: all RICH_MEDIA, and all -- VPAID. data CreativeArtworkType = CATArtworkTypeFlash -- ^ @ARTWORK_TYPE_FLASH@ | CATArtworkTypeHTML5 -- ^ @ARTWORK_TYPE_HTML5@ | CATArtworkTypeMixed -- ^ @ARTWORK_TYPE_MIXED@ | CATArtworkTypeImage -- ^ @ARTWORK_TYPE_IMAGE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeArtworkType instance FromHttpApiData CreativeArtworkType where parseQueryParam = \case "ARTWORK_TYPE_FLASH" -> Right CATArtworkTypeFlash "ARTWORK_TYPE_HTML5" -> Right CATArtworkTypeHTML5 "ARTWORK_TYPE_MIXED" -> Right CATArtworkTypeMixed "ARTWORK_TYPE_IMAGE" -> Right CATArtworkTypeImage x -> Left ("Unable to parse CreativeArtworkType from: " <> x) instance ToHttpApiData CreativeArtworkType where toQueryParam = \case CATArtworkTypeFlash -> "ARTWORK_TYPE_FLASH" CATArtworkTypeHTML5 -> "ARTWORK_TYPE_HTML5" CATArtworkTypeMixed -> "ARTWORK_TYPE_MIXED" CATArtworkTypeImage -> "ARTWORK_TYPE_IMAGE" instance FromJSON CreativeArtworkType where parseJSON = parseJSONText "CreativeArtworkType" instance ToJSON CreativeArtworkType where toJSON = toJSONText -- | Third-party placement status. data PlacementStatus = PendingReview -- ^ @PENDING_REVIEW@ | PaymentAccepted -- ^ @PAYMENT_ACCEPTED@ | PaymentRejected -- ^ @PAYMENT_REJECTED@ | AcknowledgeRejection -- ^ @ACKNOWLEDGE_REJECTION@ | AcknowledgeAcceptance -- ^ @ACKNOWLEDGE_ACCEPTANCE@ | Draft -- ^ @DRAFT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementStatus instance FromHttpApiData PlacementStatus where parseQueryParam = \case "PENDING_REVIEW" -> Right PendingReview "PAYMENT_ACCEPTED" -> Right PaymentAccepted "PAYMENT_REJECTED" -> Right PaymentRejected "ACKNOWLEDGE_REJECTION" -> Right AcknowledgeRejection "ACKNOWLEDGE_ACCEPTANCE" -> Right AcknowledgeAcceptance "DRAFT" -> Right Draft x -> Left ("Unable to parse PlacementStatus from: " <> x) instance ToHttpApiData PlacementStatus where toQueryParam = \case PendingReview -> "PENDING_REVIEW" PaymentAccepted -> "PAYMENT_ACCEPTED" PaymentRejected -> "PAYMENT_REJECTED" AcknowledgeRejection -> "ACKNOWLEDGE_REJECTION" AcknowledgeAcceptance -> "ACKNOWLEDGE_ACCEPTANCE" Draft -> "DRAFT" instance FromJSON PlacementStatus where parseJSON = parseJSONText "PlacementStatus" instance ToJSON PlacementStatus where toJSON = toJSONText -- | Enum to define for \"MONTHLY\" scheduled reports whether reports should -- be repeated on the same day of the month as \"startDate\" or the same -- day of the week of the month. Example: If \'startDate\' is Monday, April -- 2nd 2012 (2012-04-02), \"DAY_OF_MONTH\" would run subsequent reports on -- the 2nd of every Month, and \"WEEK_OF_MONTH\" would run subsequent -- reports on the first Monday of the month. data ReportScheduleRunsOnDayOfMonth = DayOfMonth -- ^ @DAY_OF_MONTH@ | WeekOfMonth -- ^ @WEEK_OF_MONTH@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportScheduleRunsOnDayOfMonth instance FromHttpApiData ReportScheduleRunsOnDayOfMonth where parseQueryParam = \case "DAY_OF_MONTH" -> Right DayOfMonth "WEEK_OF_MONTH" -> Right WeekOfMonth x -> Left ("Unable to parse ReportScheduleRunsOnDayOfMonth from: " <> x) instance ToHttpApiData ReportScheduleRunsOnDayOfMonth where toQueryParam = \case DayOfMonth -> "DAY_OF_MONTH" WeekOfMonth -> "WEEK_OF_MONTH" instance FromJSON ReportScheduleRunsOnDayOfMonth where parseJSON = parseJSONText "ReportScheduleRunsOnDayOfMonth" instance ToJSON ReportScheduleRunsOnDayOfMonth where toJSON = toJSONText -- | Measurement partner used for tag wrapping. data MeasurementPartnerAdvertiserLinkMeasurementPartner = MPALMPNone -- ^ @NONE@ | MPALMPIntegralAdScience -- ^ @INTEGRAL_AD_SCIENCE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MeasurementPartnerAdvertiserLinkMeasurementPartner instance FromHttpApiData MeasurementPartnerAdvertiserLinkMeasurementPartner where parseQueryParam = \case "NONE" -> Right MPALMPNone "INTEGRAL_AD_SCIENCE" -> Right MPALMPIntegralAdScience x -> Left ("Unable to parse MeasurementPartnerAdvertiserLinkMeasurementPartner from: " <> x) instance ToHttpApiData MeasurementPartnerAdvertiserLinkMeasurementPartner where toQueryParam = \case MPALMPNone -> "NONE" MPALMPIntegralAdScience -> "INTEGRAL_AD_SCIENCE" instance FromJSON MeasurementPartnerAdvertiserLinkMeasurementPartner where parseJSON = parseJSONText "MeasurementPartnerAdvertiserLinkMeasurementPartner" instance ToJSON MeasurementPartnerAdvertiserLinkMeasurementPartner where toJSON = toJSONText data FloodlightActivityUserDefinedVariableTypesItem = FAUDVTIU1 -- ^ @U1@ | FAUDVTIU2 -- ^ @U2@ | FAUDVTIU3 -- ^ @U3@ | FAUDVTIU4 -- ^ @U4@ | FAUDVTIU5 -- ^ @U5@ | FAUDVTIU6 -- ^ @U6@ | FAUDVTIU7 -- ^ @U7@ | FAUDVTIU8 -- ^ @U8@ | FAUDVTIU9 -- ^ @U9@ | FAUDVTIU10 -- ^ @U10@ | FAUDVTIU11 -- ^ @U11@ | FAUDVTIU12 -- ^ @U12@ | FAUDVTIU13 -- ^ @U13@ | FAUDVTIU14 -- ^ @U14@ | FAUDVTIU15 -- ^ @U15@ | FAUDVTIU16 -- ^ @U16@ | FAUDVTIU17 -- ^ @U17@ | FAUDVTIU18 -- ^ @U18@ | FAUDVTIU19 -- ^ @U19@ | FAUDVTIU20 -- ^ @U20@ | FAUDVTIU21 -- ^ @U21@ | FAUDVTIU22 -- ^ @U22@ | FAUDVTIU23 -- ^ @U23@ | FAUDVTIU24 -- ^ @U24@ | FAUDVTIU25 -- ^ @U25@ | FAUDVTIU26 -- ^ @U26@ | FAUDVTIU27 -- ^ @U27@ | FAUDVTIU28 -- ^ @U28@ | FAUDVTIU29 -- ^ @U29@ | FAUDVTIU30 -- ^ @U30@ | FAUDVTIU31 -- ^ @U31@ | FAUDVTIU32 -- ^ @U32@ | FAUDVTIU33 -- ^ @U33@ | FAUDVTIU34 -- ^ @U34@ | FAUDVTIU35 -- ^ @U35@ | FAUDVTIU36 -- ^ @U36@ | FAUDVTIU37 -- ^ @U37@ | FAUDVTIU38 -- ^ @U38@ | FAUDVTIU39 -- ^ @U39@ | FAUDVTIU40 -- ^ @U40@ | FAUDVTIU41 -- ^ @U41@ | FAUDVTIU42 -- ^ @U42@ | FAUDVTIU43 -- ^ @U43@ | FAUDVTIU44 -- ^ @U44@ | FAUDVTIU45 -- ^ @U45@ | FAUDVTIU46 -- ^ @U46@ | FAUDVTIU47 -- ^ @U47@ | FAUDVTIU48 -- ^ @U48@ | FAUDVTIU49 -- ^ @U49@ | FAUDVTIU50 -- ^ @U50@ | FAUDVTIU51 -- ^ @U51@ | FAUDVTIU52 -- ^ @U52@ | FAUDVTIU53 -- ^ @U53@ | FAUDVTIU54 -- ^ @U54@ | FAUDVTIU55 -- ^ @U55@ | FAUDVTIU56 -- ^ @U56@ | FAUDVTIU57 -- ^ @U57@ | FAUDVTIU58 -- ^ @U58@ | FAUDVTIU59 -- ^ @U59@ | FAUDVTIU60 -- ^ @U60@ | FAUDVTIU61 -- ^ @U61@ | FAUDVTIU62 -- ^ @U62@ | FAUDVTIU63 -- ^ @U63@ | FAUDVTIU64 -- ^ @U64@ | FAUDVTIU65 -- ^ @U65@ | FAUDVTIU66 -- ^ @U66@ | FAUDVTIU67 -- ^ @U67@ | FAUDVTIU68 -- ^ @U68@ | FAUDVTIU69 -- ^ @U69@ | FAUDVTIU70 -- ^ @U70@ | FAUDVTIU71 -- ^ @U71@ | FAUDVTIU72 -- ^ @U72@ | FAUDVTIU73 -- ^ @U73@ | FAUDVTIU74 -- ^ @U74@ | FAUDVTIU75 -- ^ @U75@ | FAUDVTIU76 -- ^ @U76@ | FAUDVTIU77 -- ^ @U77@ | FAUDVTIU78 -- ^ @U78@ | FAUDVTIU79 -- ^ @U79@ | FAUDVTIU80 -- ^ @U80@ | FAUDVTIU81 -- ^ @U81@ | FAUDVTIU82 -- ^ @U82@ | FAUDVTIU83 -- ^ @U83@ | FAUDVTIU84 -- ^ @U84@ | FAUDVTIU85 -- ^ @U85@ | FAUDVTIU86 -- ^ @U86@ | FAUDVTIU87 -- ^ @U87@ | FAUDVTIU88 -- ^ @U88@ | FAUDVTIU89 -- ^ @U89@ | FAUDVTIU90 -- ^ @U90@ | FAUDVTIU91 -- ^ @U91@ | FAUDVTIU92 -- ^ @U92@ | FAUDVTIU93 -- ^ @U93@ | FAUDVTIU94 -- ^ @U94@ | FAUDVTIU95 -- ^ @U95@ | FAUDVTIU96 -- ^ @U96@ | FAUDVTIU97 -- ^ @U97@ | FAUDVTIU98 -- ^ @U98@ | FAUDVTIU99 -- ^ @U99@ | FAUDVTIU100 -- ^ @U100@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityUserDefinedVariableTypesItem instance FromHttpApiData FloodlightActivityUserDefinedVariableTypesItem where parseQueryParam = \case "U1" -> Right FAUDVTIU1 "U2" -> Right FAUDVTIU2 "U3" -> Right FAUDVTIU3 "U4" -> Right FAUDVTIU4 "U5" -> Right FAUDVTIU5 "U6" -> Right FAUDVTIU6 "U7" -> Right FAUDVTIU7 "U8" -> Right FAUDVTIU8 "U9" -> Right FAUDVTIU9 "U10" -> Right FAUDVTIU10 "U11" -> Right FAUDVTIU11 "U12" -> Right FAUDVTIU12 "U13" -> Right FAUDVTIU13 "U14" -> Right FAUDVTIU14 "U15" -> Right FAUDVTIU15 "U16" -> Right FAUDVTIU16 "U17" -> Right FAUDVTIU17 "U18" -> Right FAUDVTIU18 "U19" -> Right FAUDVTIU19 "U20" -> Right FAUDVTIU20 "U21" -> Right FAUDVTIU21 "U22" -> Right FAUDVTIU22 "U23" -> Right FAUDVTIU23 "U24" -> Right FAUDVTIU24 "U25" -> Right FAUDVTIU25 "U26" -> Right FAUDVTIU26 "U27" -> Right FAUDVTIU27 "U28" -> Right FAUDVTIU28 "U29" -> Right FAUDVTIU29 "U30" -> Right FAUDVTIU30 "U31" -> Right FAUDVTIU31 "U32" -> Right FAUDVTIU32 "U33" -> Right FAUDVTIU33 "U34" -> Right FAUDVTIU34 "U35" -> Right FAUDVTIU35 "U36" -> Right FAUDVTIU36 "U37" -> Right FAUDVTIU37 "U38" -> Right FAUDVTIU38 "U39" -> Right FAUDVTIU39 "U40" -> Right FAUDVTIU40 "U41" -> Right FAUDVTIU41 "U42" -> Right FAUDVTIU42 "U43" -> Right FAUDVTIU43 "U44" -> Right FAUDVTIU44 "U45" -> Right FAUDVTIU45 "U46" -> Right FAUDVTIU46 "U47" -> Right FAUDVTIU47 "U48" -> Right FAUDVTIU48 "U49" -> Right FAUDVTIU49 "U50" -> Right FAUDVTIU50 "U51" -> Right FAUDVTIU51 "U52" -> Right FAUDVTIU52 "U53" -> Right FAUDVTIU53 "U54" -> Right FAUDVTIU54 "U55" -> Right FAUDVTIU55 "U56" -> Right FAUDVTIU56 "U57" -> Right FAUDVTIU57 "U58" -> Right FAUDVTIU58 "U59" -> Right FAUDVTIU59 "U60" -> Right FAUDVTIU60 "U61" -> Right FAUDVTIU61 "U62" -> Right FAUDVTIU62 "U63" -> Right FAUDVTIU63 "U64" -> Right FAUDVTIU64 "U65" -> Right FAUDVTIU65 "U66" -> Right FAUDVTIU66 "U67" -> Right FAUDVTIU67 "U68" -> Right FAUDVTIU68 "U69" -> Right FAUDVTIU69 "U70" -> Right FAUDVTIU70 "U71" -> Right FAUDVTIU71 "U72" -> Right FAUDVTIU72 "U73" -> Right FAUDVTIU73 "U74" -> Right FAUDVTIU74 "U75" -> Right FAUDVTIU75 "U76" -> Right FAUDVTIU76 "U77" -> Right FAUDVTIU77 "U78" -> Right FAUDVTIU78 "U79" -> Right FAUDVTIU79 "U80" -> Right FAUDVTIU80 "U81" -> Right FAUDVTIU81 "U82" -> Right FAUDVTIU82 "U83" -> Right FAUDVTIU83 "U84" -> Right FAUDVTIU84 "U85" -> Right FAUDVTIU85 "U86" -> Right FAUDVTIU86 "U87" -> Right FAUDVTIU87 "U88" -> Right FAUDVTIU88 "U89" -> Right FAUDVTIU89 "U90" -> Right FAUDVTIU90 "U91" -> Right FAUDVTIU91 "U92" -> Right FAUDVTIU92 "U93" -> Right FAUDVTIU93 "U94" -> Right FAUDVTIU94 "U95" -> Right FAUDVTIU95 "U96" -> Right FAUDVTIU96 "U97" -> Right FAUDVTIU97 "U98" -> Right FAUDVTIU98 "U99" -> Right FAUDVTIU99 "U100" -> Right FAUDVTIU100 x -> Left ("Unable to parse FloodlightActivityUserDefinedVariableTypesItem from: " <> x) instance ToHttpApiData FloodlightActivityUserDefinedVariableTypesItem where toQueryParam = \case FAUDVTIU1 -> "U1" FAUDVTIU2 -> "U2" FAUDVTIU3 -> "U3" FAUDVTIU4 -> "U4" FAUDVTIU5 -> "U5" FAUDVTIU6 -> "U6" FAUDVTIU7 -> "U7" FAUDVTIU8 -> "U8" FAUDVTIU9 -> "U9" FAUDVTIU10 -> "U10" FAUDVTIU11 -> "U11" FAUDVTIU12 -> "U12" FAUDVTIU13 -> "U13" FAUDVTIU14 -> "U14" FAUDVTIU15 -> "U15" FAUDVTIU16 -> "U16" FAUDVTIU17 -> "U17" FAUDVTIU18 -> "U18" FAUDVTIU19 -> "U19" FAUDVTIU20 -> "U20" FAUDVTIU21 -> "U21" FAUDVTIU22 -> "U22" FAUDVTIU23 -> "U23" FAUDVTIU24 -> "U24" FAUDVTIU25 -> "U25" FAUDVTIU26 -> "U26" FAUDVTIU27 -> "U27" FAUDVTIU28 -> "U28" FAUDVTIU29 -> "U29" FAUDVTIU30 -> "U30" FAUDVTIU31 -> "U31" FAUDVTIU32 -> "U32" FAUDVTIU33 -> "U33" FAUDVTIU34 -> "U34" FAUDVTIU35 -> "U35" FAUDVTIU36 -> "U36" FAUDVTIU37 -> "U37" FAUDVTIU38 -> "U38" FAUDVTIU39 -> "U39" FAUDVTIU40 -> "U40" FAUDVTIU41 -> "U41" FAUDVTIU42 -> "U42" FAUDVTIU43 -> "U43" FAUDVTIU44 -> "U44" FAUDVTIU45 -> "U45" FAUDVTIU46 -> "U46" FAUDVTIU47 -> "U47" FAUDVTIU48 -> "U48" FAUDVTIU49 -> "U49" FAUDVTIU50 -> "U50" FAUDVTIU51 -> "U51" FAUDVTIU52 -> "U52" FAUDVTIU53 -> "U53" FAUDVTIU54 -> "U54" FAUDVTIU55 -> "U55" FAUDVTIU56 -> "U56" FAUDVTIU57 -> "U57" FAUDVTIU58 -> "U58" FAUDVTIU59 -> "U59" FAUDVTIU60 -> "U60" FAUDVTIU61 -> "U61" FAUDVTIU62 -> "U62" FAUDVTIU63 -> "U63" FAUDVTIU64 -> "U64" FAUDVTIU65 -> "U65" FAUDVTIU66 -> "U66" FAUDVTIU67 -> "U67" FAUDVTIU68 -> "U68" FAUDVTIU69 -> "U69" FAUDVTIU70 -> "U70" FAUDVTIU71 -> "U71" FAUDVTIU72 -> "U72" FAUDVTIU73 -> "U73" FAUDVTIU74 -> "U74" FAUDVTIU75 -> "U75" FAUDVTIU76 -> "U76" FAUDVTIU77 -> "U77" FAUDVTIU78 -> "U78" FAUDVTIU79 -> "U79" FAUDVTIU80 -> "U80" FAUDVTIU81 -> "U81" FAUDVTIU82 -> "U82" FAUDVTIU83 -> "U83" FAUDVTIU84 -> "U84" FAUDVTIU85 -> "U85" FAUDVTIU86 -> "U86" FAUDVTIU87 -> "U87" FAUDVTIU88 -> "U88" FAUDVTIU89 -> "U89" FAUDVTIU90 -> "U90" FAUDVTIU91 -> "U91" FAUDVTIU92 -> "U92" FAUDVTIU93 -> "U93" FAUDVTIU94 -> "U94" FAUDVTIU95 -> "U95" FAUDVTIU96 -> "U96" FAUDVTIU97 -> "U97" FAUDVTIU98 -> "U98" FAUDVTIU99 -> "U99" FAUDVTIU100 -> "U100" instance FromJSON FloodlightActivityUserDefinedVariableTypesItem where parseJSON = parseJSONText "FloodlightActivityUserDefinedVariableTypesItem" instance ToJSON FloodlightActivityUserDefinedVariableTypesItem where toJSON = toJSONText -- | Site filter type for this event tag. If no type is specified then the -- event tag will be applied to all sites. data EventTagSiteFilterType = AllowList -- ^ @ALLOWLIST@ | BlockList -- ^ @BLOCKLIST@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EventTagSiteFilterType instance FromHttpApiData EventTagSiteFilterType where parseQueryParam = \case "ALLOWLIST" -> Right AllowList "BLOCKLIST" -> Right BlockList x -> Left ("Unable to parse EventTagSiteFilterType from: " <> x) instance ToHttpApiData EventTagSiteFilterType where toQueryParam = \case AllowList -> "ALLOWLIST" BlockList -> "BLOCKLIST" instance FromJSON EventTagSiteFilterType where parseJSON = parseJSONText "EventTagSiteFilterType" instance ToJSON EventTagSiteFilterType where toJSON = toJSONText -- | The output format of the report. If not specified, default format is -- \"CSV\". Note that the actual format in the completed report file might -- differ if for instance the report\'s size exceeds the format\'s -- capabilities. \"CSV\" will then be the fallback format. data ReportFormat = RFCSV -- ^ @CSV@ | RFExcel -- ^ @EXCEL@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportFormat instance FromHttpApiData ReportFormat where parseQueryParam = \case "CSV" -> Right RFCSV "EXCEL" -> Right RFExcel x -> Left ("Unable to parse ReportFormat from: " <> x) instance ToHttpApiData ReportFormat where toQueryParam = \case RFCSV -> "CSV" RFExcel -> "EXCEL" instance FromJSON ReportFormat where parseJSON = parseJSONText "ReportFormat" instance ToJSON ReportFormat where toJSON = toJSONText -- | Type of this placement group. A package is a simple group of placements -- that acts as a single pricing point for a group of tags. A roadblock is -- a group of placements that not only acts as a single pricing point, but -- also assumes that all the tags in it will be served at the same time. A -- roadblock requires one of its assigned placements to be marked as -- primary for reporting. This field is required on insertion. data PlacementGroupPlacementGroupType = PGPGTPlacementPackage -- ^ @PLACEMENT_PACKAGE@ | PGPGTPlacementRoadblock -- ^ @PLACEMENT_ROADBLOCK@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementGroupPlacementGroupType instance FromHttpApiData PlacementGroupPlacementGroupType where parseQueryParam = \case "PLACEMENT_PACKAGE" -> Right PGPGTPlacementPackage "PLACEMENT_ROADBLOCK" -> Right PGPGTPlacementRoadblock x -> Left ("Unable to parse PlacementGroupPlacementGroupType from: " <> x) instance ToHttpApiData PlacementGroupPlacementGroupType where toQueryParam = \case PGPGTPlacementPackage -> "PLACEMENT_PACKAGE" PGPGTPlacementRoadblock -> "PLACEMENT_ROADBLOCK" instance FromJSON PlacementGroupPlacementGroupType where parseJSON = parseJSONText "PlacementGroupPlacementGroupType" instance ToJSON PlacementGroupPlacementGroupType where toJSON = toJSONText -- | Pricing type of this inventory item. data PricingPricingType = PlanningPlacementPricingTypeImpressions -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_IMPRESSIONS@ | PlanningPlacementPricingTypeCpm -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_CPM@ | PlanningPlacementPricingTypeClicks -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_CLICKS@ | PlanningPlacementPricingTypeCpc -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_CPC@ | PlanningPlacementPricingTypeCpa -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_CPA@ | PlanningPlacementPricingTypeFlatRateImpressions -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_FLAT_RATE_IMPRESSIONS@ | PlanningPlacementPricingTypeFlatRateClicks -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_FLAT_RATE_CLICKS@ | PlanningPlacementPricingTypeCpmActiveview -- ^ @PLANNING_PLACEMENT_PRICING_TYPE_CPM_ACTIVEVIEW@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PricingPricingType instance FromHttpApiData PricingPricingType where parseQueryParam = \case "PLANNING_PLACEMENT_PRICING_TYPE_IMPRESSIONS" -> Right PlanningPlacementPricingTypeImpressions "PLANNING_PLACEMENT_PRICING_TYPE_CPM" -> Right PlanningPlacementPricingTypeCpm "PLANNING_PLACEMENT_PRICING_TYPE_CLICKS" -> Right PlanningPlacementPricingTypeClicks "PLANNING_PLACEMENT_PRICING_TYPE_CPC" -> Right PlanningPlacementPricingTypeCpc "PLANNING_PLACEMENT_PRICING_TYPE_CPA" -> Right PlanningPlacementPricingTypeCpa "PLANNING_PLACEMENT_PRICING_TYPE_FLAT_RATE_IMPRESSIONS" -> Right PlanningPlacementPricingTypeFlatRateImpressions "PLANNING_PLACEMENT_PRICING_TYPE_FLAT_RATE_CLICKS" -> Right PlanningPlacementPricingTypeFlatRateClicks "PLANNING_PLACEMENT_PRICING_TYPE_CPM_ACTIVEVIEW" -> Right PlanningPlacementPricingTypeCpmActiveview x -> Left ("Unable to parse PricingPricingType from: " <> x) instance ToHttpApiData PricingPricingType where toQueryParam = \case PlanningPlacementPricingTypeImpressions -> "PLANNING_PLACEMENT_PRICING_TYPE_IMPRESSIONS" PlanningPlacementPricingTypeCpm -> "PLANNING_PLACEMENT_PRICING_TYPE_CPM" PlanningPlacementPricingTypeClicks -> "PLANNING_PLACEMENT_PRICING_TYPE_CLICKS" PlanningPlacementPricingTypeCpc -> "PLANNING_PLACEMENT_PRICING_TYPE_CPC" PlanningPlacementPricingTypeCpa -> "PLANNING_PLACEMENT_PRICING_TYPE_CPA" PlanningPlacementPricingTypeFlatRateImpressions -> "PLANNING_PLACEMENT_PRICING_TYPE_FLAT_RATE_IMPRESSIONS" PlanningPlacementPricingTypeFlatRateClicks -> "PLANNING_PLACEMENT_PRICING_TYPE_FLAT_RATE_CLICKS" PlanningPlacementPricingTypeCpmActiveview -> "PLANNING_PLACEMENT_PRICING_TYPE_CPM_ACTIVEVIEW" instance FromJSON PricingPricingType where parseJSON = parseJSONText "PricingPricingType" instance ToJSON PricingPricingType where toJSON = toJSONText -- | Order of sorted results. data SubAccountsListSortOrder = SALSOAscending -- ^ @ASCENDING@ | SALSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SubAccountsListSortOrder instance FromHttpApiData SubAccountsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right SALSOAscending "DESCENDING" -> Right SALSODescending x -> Left ("Unable to parse SubAccountsListSortOrder from: " <> x) instance ToHttpApiData SubAccountsListSortOrder where toQueryParam = \case SALSOAscending -> "ASCENDING" SALSODescending -> "DESCENDING" instance FromJSON SubAccountsListSortOrder where parseJSON = parseJSONText "SubAccountsListSortOrder" instance ToJSON SubAccountsListSortOrder where toJSON = toJSONText -- | Registry used for the Ad ID value. data UniversalAdIdRegistry = UAIROther -- ^ @OTHER@ | UAIRAdIdOfficial -- ^ @AD_ID_OFFICIAL@ | UAIRClearcast -- ^ @CLEARCAST@ | UAIRDcm -- ^ @DCM@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable UniversalAdIdRegistry instance FromHttpApiData UniversalAdIdRegistry where parseQueryParam = \case "OTHER" -> Right UAIROther "AD_ID_OFFICIAL" -> Right UAIRAdIdOfficial "CLEARCAST" -> Right UAIRClearcast "DCM" -> Right UAIRDcm x -> Left ("Unable to parse UniversalAdIdRegistry from: " <> x) instance ToHttpApiData UniversalAdIdRegistry where toQueryParam = \case UAIROther -> "OTHER" UAIRAdIdOfficial -> "AD_ID_OFFICIAL" UAIRClearcast -> "CLEARCAST" UAIRDcm -> "DCM" instance FromJSON UniversalAdIdRegistry where parseJSON = parseJSONText "UniversalAdIdRegistry" instance ToJSON UniversalAdIdRegistry where toJSON = toJSONText -- | Order of sorted results. data AdsListSortOrder = ADSAscending -- ^ @ASCENDING@ | ADSDescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdsListSortOrder instance FromHttpApiData AdsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right ADSAscending "DESCENDING" -> Right ADSDescending x -> Left ("Unable to parse AdsListSortOrder from: " <> x) instance ToHttpApiData AdsListSortOrder where toQueryParam = \case ADSAscending -> "ASCENDING" ADSDescending -> "DESCENDING" instance FromJSON AdsListSortOrder where parseJSON = parseJSONText "AdsListSortOrder" instance ToJSON AdsListSortOrder where toJSON = toJSONText -- | Order of sorted results. data ProjectsListSortOrder = PLSOAscending -- ^ @ASCENDING@ | PLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ProjectsListSortOrder instance FromHttpApiData ProjectsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right PLSOAscending "DESCENDING" -> Right PLSODescending x -> Left ("Unable to parse ProjectsListSortOrder from: " <> x) instance ToHttpApiData ProjectsListSortOrder where toQueryParam = \case PLSOAscending -> "ASCENDING" PLSODescending -> "DESCENDING" instance FromJSON ProjectsListSortOrder where parseJSON = parseJSONText "ProjectsListSortOrder" instance ToJSON ProjectsListSortOrder where toJSON = toJSONText -- | Field by which to sort the list. data RemarketingListsListSortField = RLLSFID -- ^ @ID@ | RLLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable RemarketingListsListSortField instance FromHttpApiData RemarketingListsListSortField where parseQueryParam = \case "ID" -> Right RLLSFID "NAME" -> Right RLLSFName x -> Left ("Unable to parse RemarketingListsListSortField from: " <> x) instance ToHttpApiData RemarketingListsListSortField where toQueryParam = \case RLLSFID -> "ID" RLLSFName -> "NAME" instance FromJSON RemarketingListsListSortField where parseJSON = parseJSONText "RemarketingListsListSortField" instance ToJSON RemarketingListsListSortField where toJSON = toJSONText -- | Mobile app directory. data MobileAppDirectory = MADUnknown -- ^ @UNKNOWN@ | MADAppleAppStore -- ^ @APPLE_APP_STORE@ | MADGooglePlayStore -- ^ @GOOGLE_PLAY_STORE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable MobileAppDirectory instance FromHttpApiData MobileAppDirectory where parseQueryParam = \case "UNKNOWN" -> Right MADUnknown "APPLE_APP_STORE" -> Right MADAppleAppStore "GOOGLE_PLAY_STORE" -> Right MADGooglePlayStore x -> Left ("Unable to parse MobileAppDirectory from: " <> x) instance ToHttpApiData MobileAppDirectory where toQueryParam = \case MADUnknown -> "UNKNOWN" MADAppleAppStore -> "APPLE_APP_STORE" MADGooglePlayStore -> "GOOGLE_PLAY_STORE" instance FromJSON MobileAppDirectory where parseJSON = parseJSONText "MobileAppDirectory" instance ToJSON MobileAppDirectory where toJSON = toJSONText data ReportScheduleRepeatsOnWeekDaysItem = RSROWDISunday -- ^ @SUNDAY@ | RSROWDIMonday -- ^ @MONDAY@ | RSROWDITuesday -- ^ @TUESDAY@ | RSROWDIWednesday -- ^ @WEDNESDAY@ | RSROWDIThursday -- ^ @THURSDAY@ | RSROWDIFriday -- ^ @FRIDAY@ | RSROWDISaturday -- ^ @SATURDAY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportScheduleRepeatsOnWeekDaysItem instance FromHttpApiData ReportScheduleRepeatsOnWeekDaysItem where parseQueryParam = \case "SUNDAY" -> Right RSROWDISunday "MONDAY" -> Right RSROWDIMonday "TUESDAY" -> Right RSROWDITuesday "WEDNESDAY" -> Right RSROWDIWednesday "THURSDAY" -> Right RSROWDIThursday "FRIDAY" -> Right RSROWDIFriday "SATURDAY" -> Right RSROWDISaturday x -> Left ("Unable to parse ReportScheduleRepeatsOnWeekDaysItem from: " <> x) instance ToHttpApiData ReportScheduleRepeatsOnWeekDaysItem where toQueryParam = \case RSROWDISunday -> "SUNDAY" RSROWDIMonday -> "MONDAY" RSROWDITuesday -> "TUESDAY" RSROWDIWednesday -> "WEDNESDAY" RSROWDIThursday -> "THURSDAY" RSROWDIFriday -> "FRIDAY" RSROWDISaturday -> "SATURDAY" instance FromJSON ReportScheduleRepeatsOnWeekDaysItem where parseJSON = parseJSONText "ReportScheduleRepeatsOnWeekDaysItem" instance ToJSON ReportScheduleRepeatsOnWeekDaysItem where toJSON = toJSONText -- | Creative group number of the creative group assignment. data CreativeGroupAssignmentCreativeGroupNumber = CreativeGroupOne -- ^ @CREATIVE_GROUP_ONE@ | CreativeGroupTwo -- ^ @CREATIVE_GROUP_TWO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeGroupAssignmentCreativeGroupNumber instance FromHttpApiData CreativeGroupAssignmentCreativeGroupNumber where parseQueryParam = \case "CREATIVE_GROUP_ONE" -> Right CreativeGroupOne "CREATIVE_GROUP_TWO" -> Right CreativeGroupTwo x -> Left ("Unable to parse CreativeGroupAssignmentCreativeGroupNumber from: " <> x) instance ToHttpApiData CreativeGroupAssignmentCreativeGroupNumber where toQueryParam = \case CreativeGroupOne -> "CREATIVE_GROUP_ONE" CreativeGroupTwo -> "CREATIVE_GROUP_TWO" instance FromJSON CreativeGroupAssignmentCreativeGroupNumber where parseJSON = parseJSONText "CreativeGroupAssignmentCreativeGroupNumber" instance ToJSON CreativeGroupAssignmentCreativeGroupNumber where toJSON = toJSONText -- | Default VPAID adapter setting for new placements created under this -- site. This value will be used to populate the -- placements.vpaidAdapterChoice field, when no value is specified for the -- new placement. Controls which VPAID format the measurement adapter will -- use for in-stream video creatives assigned to the placement. The -- publisher\'s specifications will typically determine this setting. For -- VPAID creatives, the adapter format will match the VPAID format (HTML5 -- VPAID creatives use the HTML5 adapter). *Note:* Flash is no longer -- supported. This field now defaults to HTML5 when the following values -- are provided: FLASH, BOTH. data SiteSettingsVpaidAdapterChoiceTemplate = SSVACTDefault -- ^ @DEFAULT@ | SSVACTFlash -- ^ @FLASH@ | SSVACTHTML5 -- ^ @HTML5@ | SSVACTBoth -- ^ @BOTH@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SiteSettingsVpaidAdapterChoiceTemplate instance FromHttpApiData SiteSettingsVpaidAdapterChoiceTemplate where parseQueryParam = \case "DEFAULT" -> Right SSVACTDefault "FLASH" -> Right SSVACTFlash "HTML5" -> Right SSVACTHTML5 "BOTH" -> Right SSVACTBoth x -> Left ("Unable to parse SiteSettingsVpaidAdapterChoiceTemplate from: " <> x) instance ToHttpApiData SiteSettingsVpaidAdapterChoiceTemplate where toQueryParam = \case SSVACTDefault -> "DEFAULT" SSVACTFlash -> "FLASH" SSVACTHTML5 -> "HTML5" SSVACTBoth -> "BOTH" instance FromJSON SiteSettingsVpaidAdapterChoiceTemplate where parseJSON = parseJSONText "SiteSettingsVpaidAdapterChoiceTemplate" instance ToJSON SiteSettingsVpaidAdapterChoiceTemplate where toJSON = toJSONText -- | Field by which to sort the list. data AccountsListSortField = AID -- ^ @ID@ | AName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountsListSortField instance FromHttpApiData AccountsListSortField where parseQueryParam = \case "ID" -> Right AID "NAME" -> Right AName x -> Left ("Unable to parse AccountsListSortField from: " <> x) instance ToHttpApiData AccountsListSortField where toQueryParam = \case AID -> "ID" AName -> "NAME" instance FromJSON AccountsListSortField where parseJSON = parseJSONText "AccountsListSortField" instance ToJSON AccountsListSortField where toJSON = toJSONText -- | Select only advertisers with the specified status. data AdvertisersListStatus = Approved -- ^ @APPROVED@ | OnHold -- ^ @ON_HOLD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertisersListStatus instance FromHttpApiData AdvertisersListStatus where parseQueryParam = \case "APPROVED" -> Right Approved "ON_HOLD" -> Right OnHold x -> Left ("Unable to parse AdvertisersListStatus from: " <> x) instance ToHttpApiData AdvertisersListStatus where toQueryParam = \case Approved -> "APPROVED" OnHold -> "ON_HOLD" instance FromJSON AdvertisersListStatus where parseJSON = parseJSONText "AdvertisersListStatus" instance ToJSON AdvertisersListStatus where toJSON = toJSONText -- | Determines how the \'value\' field is matched when filtering. If not -- specified, defaults to EXACT. If set to WILDCARD_EXPRESSION, \'*\' is -- allowed as a placeholder for variable length character sequences, and it -- can be escaped with a backslash. Note, only paid search dimensions -- (\'dfa:paidSearch*\') allow a matchType other than EXACT. data DimensionValueMatchType = Exact -- ^ @EXACT@ | BeginsWith -- ^ @BEGINS_WITH@ | Contains -- ^ @CONTAINS@ | WildcardExpression -- ^ @WILDCARD_EXPRESSION@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DimensionValueMatchType instance FromHttpApiData DimensionValueMatchType where parseQueryParam = \case "EXACT" -> Right Exact "BEGINS_WITH" -> Right BeginsWith "CONTAINS" -> Right Contains "WILDCARD_EXPRESSION" -> Right WildcardExpression x -> Left ("Unable to parse DimensionValueMatchType from: " <> x) instance ToHttpApiData DimensionValueMatchType where toQueryParam = \case Exact -> "EXACT" BeginsWith -> "BEGINS_WITH" Contains -> "CONTAINS" WildcardExpression -> "WILDCARD_EXPRESSION" instance FromJSON DimensionValueMatchType where parseJSON = parseJSONText "DimensionValueMatchType" instance ToJSON DimensionValueMatchType where toJSON = toJSONText -- | Determines how the \'value\' field is matched when filtering. If not -- specified, defaults to EXACT. If set to WILDCARD_EXPRESSION, \'*\' is -- allowed as a placeholder for variable length character sequences, and it -- can be escaped with a backslash. Note, only paid search dimensions -- (\'dfa:paidSearch*\') allow a matchType other than EXACT. data PathReportDimensionValueMatchType = PRDVMTExact -- ^ @EXACT@ | PRDVMTBeginsWith -- ^ @BEGINS_WITH@ | PRDVMTContains -- ^ @CONTAINS@ | PRDVMTWildcardExpression -- ^ @WILDCARD_EXPRESSION@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PathReportDimensionValueMatchType instance FromHttpApiData PathReportDimensionValueMatchType where parseQueryParam = \case "EXACT" -> Right PRDVMTExact "BEGINS_WITH" -> Right PRDVMTBeginsWith "CONTAINS" -> Right PRDVMTContains "WILDCARD_EXPRESSION" -> Right PRDVMTWildcardExpression x -> Left ("Unable to parse PathReportDimensionValueMatchType from: " <> x) instance ToHttpApiData PathReportDimensionValueMatchType where toQueryParam = \case PRDVMTExact -> "EXACT" PRDVMTBeginsWith -> "BEGINS_WITH" PRDVMTContains -> "CONTAINS" PRDVMTWildcardExpression -> "WILDCARD_EXPRESSION" instance FromJSON PathReportDimensionValueMatchType where parseJSON = parseJSONText "PathReportDimensionValueMatchType" instance ToJSON PathReportDimensionValueMatchType where toJSON = toJSONText -- | Order of sorted results. data PlacementGroupsListSortOrder = PGLSOAscending -- ^ @ASCENDING@ | PGLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementGroupsListSortOrder instance FromHttpApiData PlacementGroupsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right PGLSOAscending "DESCENDING" -> Right PGLSODescending x -> Left ("Unable to parse PlacementGroupsListSortOrder from: " <> x) instance ToHttpApiData PlacementGroupsListSortOrder where toQueryParam = \case PGLSOAscending -> "ASCENDING" PGLSODescending -> "DESCENDING" instance FromJSON PlacementGroupsListSortOrder where parseJSON = parseJSONText "PlacementGroupsListSortOrder" instance ToJSON PlacementGroupsListSortOrder where toJSON = toJSONText -- | Compatibility of this ad. Applicable when type is AD_SERVING_DEFAULT_AD. -- DISPLAY and DISPLAY_INTERSTITIAL refer to either rendering on desktop or -- on mobile devices or in mobile apps for regular or interstitial ads, -- respectively. APP and APP_INTERSTITIAL are only used for existing -- default ads. New mobile placements must be assigned DISPLAY or -- DISPLAY_INTERSTITIAL and default ads created for those placements will -- be limited to those compatibility types. IN_STREAM_VIDEO refers to -- rendering in-stream video ads developed with the VAST standard. data AdCompatibility = ACDisplay -- ^ @DISPLAY@ | ACDisplayInterstitial -- ^ @DISPLAY_INTERSTITIAL@ | ACApp -- ^ @APP@ | ACAppInterstitial -- ^ @APP_INTERSTITIAL@ | ACInStreamVideo -- ^ @IN_STREAM_VIDEO@ | ACInStreamAudio -- ^ @IN_STREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdCompatibility instance FromHttpApiData AdCompatibility where parseQueryParam = \case "DISPLAY" -> Right ACDisplay "DISPLAY_INTERSTITIAL" -> Right ACDisplayInterstitial "APP" -> Right ACApp "APP_INTERSTITIAL" -> Right ACAppInterstitial "IN_STREAM_VIDEO" -> Right ACInStreamVideo "IN_STREAM_AUDIO" -> Right ACInStreamAudio x -> Left ("Unable to parse AdCompatibility from: " <> x) instance ToHttpApiData AdCompatibility where toQueryParam = \case ACDisplay -> "DISPLAY" ACDisplayInterstitial -> "DISPLAY_INTERSTITIAL" ACApp -> "APP" ACAppInterstitial -> "APP_INTERSTITIAL" ACInStreamVideo -> "IN_STREAM_VIDEO" ACInStreamAudio -> "IN_STREAM_AUDIO" instance FromJSON AdCompatibility where parseJSON = parseJSONText "AdCompatibility" instance ToJSON AdCompatibility where toJSON = toJSONText -- | Field by which to sort the list. data CreativeFieldValuesListSortField = CFVLSFID -- ^ @ID@ | CFVLSFValue -- ^ @VALUE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeFieldValuesListSortField instance FromHttpApiData CreativeFieldValuesListSortField where parseQueryParam = \case "ID" -> Right CFVLSFID "VALUE" -> Right CFVLSFValue x -> Left ("Unable to parse CreativeFieldValuesListSortField from: " <> x) instance ToHttpApiData CreativeFieldValuesListSortField where toQueryParam = \case CFVLSFID -> "ID" CFVLSFValue -> "VALUE" instance FromJSON CreativeFieldValuesListSortField where parseJSON = parseJSONText "CreativeFieldValuesListSortField" instance ToJSON CreativeFieldValuesListSortField where toJSON = toJSONText -- | Field by which to sort the list. data FloodlightActivityGroupsListSortField = FAGLSFID -- ^ @ID@ | FAGLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityGroupsListSortField instance FromHttpApiData FloodlightActivityGroupsListSortField where parseQueryParam = \case "ID" -> Right FAGLSFID "NAME" -> Right FAGLSFName x -> Left ("Unable to parse FloodlightActivityGroupsListSortField from: " <> x) instance ToHttpApiData FloodlightActivityGroupsListSortField where toQueryParam = \case FAGLSFID -> "ID" FAGLSFName -> "NAME" instance FromJSON FloodlightActivityGroupsListSortField where parseJSON = parseJSONText "FloodlightActivityGroupsListSortField" instance ToJSON FloodlightActivityGroupsListSortField where toJSON = toJSONText -- | Order of sorted results. data OrdersListSortOrder = OLSOAscending -- ^ @ASCENDING@ | OLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable OrdersListSortOrder instance FromHttpApiData OrdersListSortOrder where parseQueryParam = \case "ASCENDING" -> Right OLSOAscending "DESCENDING" -> Right OLSODescending x -> Left ("Unable to parse OrdersListSortOrder from: " <> x) instance ToHttpApiData OrdersListSortOrder where toQueryParam = \case OLSOAscending -> "ASCENDING" OLSODescending -> "DESCENDING" instance FromJSON OrdersListSortOrder where parseJSON = parseJSONText "OrdersListSortOrder" instance ToJSON OrdersListSortOrder where toJSON = toJSONText -- | Profile for this account. This is a read-only field that can be left -- blank. data AccountAccountProFile = AccountProFileBasic -- ^ @ACCOUNT_PROFILE_BASIC@ | AccountProFileStandard -- ^ @ACCOUNT_PROFILE_STANDARD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountAccountProFile instance FromHttpApiData AccountAccountProFile where parseQueryParam = \case "ACCOUNT_PROFILE_BASIC" -> Right AccountProFileBasic "ACCOUNT_PROFILE_STANDARD" -> Right AccountProFileStandard x -> Left ("Unable to parse AccountAccountProFile from: " <> x) instance ToHttpApiData AccountAccountProFile where toQueryParam = \case AccountProFileBasic -> "ACCOUNT_PROFILE_BASIC" AccountProFileStandard -> "ACCOUNT_PROFILE_STANDARD" instance FromJSON AccountAccountProFile where parseJSON = parseJSONText "AccountAccountProFile" instance ToJSON AccountAccountProFile where toJSON = toJSONText -- | Type of this creative. This is a required field. Applicable to all -- creative types. *Note:* FLASH_INPAGE, HTML5_BANNER, and IMAGE are only -- used for existing creatives. New creatives should use DISPLAY as a -- replacement for these types. data CreativeType = CTImage -- ^ @IMAGE@ | CTDisplayRedirect -- ^ @DISPLAY_REDIRECT@ | CTCustomDisplay -- ^ @CUSTOM_DISPLAY@ | CTInternalRedirect -- ^ @INTERNAL_REDIRECT@ | CTCustomDisplayInterstitial -- ^ @CUSTOM_DISPLAY_INTERSTITIAL@ | CTInterstitialInternalRedirect -- ^ @INTERSTITIAL_INTERNAL_REDIRECT@ | CTTrackingText -- ^ @TRACKING_TEXT@ | CTRichMediaDisplayBanner -- ^ @RICH_MEDIA_DISPLAY_BANNER@ | CTRichMediaInpageFloating -- ^ @RICH_MEDIA_INPAGE_FLOATING@ | CTRichMediaImExpand -- ^ @RICH_MEDIA_IM_EXPAND@ | CTRichMediaDisplayExpanding -- ^ @RICH_MEDIA_DISPLAY_EXPANDING@ | CTRichMediaDisplayInterstitial -- ^ @RICH_MEDIA_DISPLAY_INTERSTITIAL@ | CTRichMediaDisplayMultiFloatingInterstitial -- ^ @RICH_MEDIA_DISPLAY_MULTI_FLOATING_INTERSTITIAL@ | CTRichMediaMobileInApp -- ^ @RICH_MEDIA_MOBILE_IN_APP@ | CTFlashInpage -- ^ @FLASH_INPAGE@ | CTInstreamVideo -- ^ @INSTREAM_VIDEO@ | CTVpaidLinearVideo -- ^ @VPAID_LINEAR_VIDEO@ | CTVpaidNonLinearVideo -- ^ @VPAID_NON_LINEAR_VIDEO@ | CTInstreamVideoRedirect -- ^ @INSTREAM_VIDEO_REDIRECT@ | CTRichMediaPeelDown -- ^ @RICH_MEDIA_PEEL_DOWN@ | CTHTML5Banner -- ^ @HTML5_BANNER@ | CTDisplay -- ^ @DISPLAY@ | CTDisplayImageGallery -- ^ @DISPLAY_IMAGE_GALLERY@ | CTBrandSafeDefaultInstreamVideo -- ^ @BRAND_SAFE_DEFAULT_INSTREAM_VIDEO@ | CTInstreamAudio -- ^ @INSTREAM_AUDIO@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeType instance FromHttpApiData CreativeType where parseQueryParam = \case "IMAGE" -> Right CTImage "DISPLAY_REDIRECT" -> Right CTDisplayRedirect "CUSTOM_DISPLAY" -> Right CTCustomDisplay "INTERNAL_REDIRECT" -> Right CTInternalRedirect "CUSTOM_DISPLAY_INTERSTITIAL" -> Right CTCustomDisplayInterstitial "INTERSTITIAL_INTERNAL_REDIRECT" -> Right CTInterstitialInternalRedirect "TRACKING_TEXT" -> Right CTTrackingText "RICH_MEDIA_DISPLAY_BANNER" -> Right CTRichMediaDisplayBanner "RICH_MEDIA_INPAGE_FLOATING" -> Right CTRichMediaInpageFloating "RICH_MEDIA_IM_EXPAND" -> Right CTRichMediaImExpand "RICH_MEDIA_DISPLAY_EXPANDING" -> Right CTRichMediaDisplayExpanding "RICH_MEDIA_DISPLAY_INTERSTITIAL" -> Right CTRichMediaDisplayInterstitial "RICH_MEDIA_DISPLAY_MULTI_FLOATING_INTERSTITIAL" -> Right CTRichMediaDisplayMultiFloatingInterstitial "RICH_MEDIA_MOBILE_IN_APP" -> Right CTRichMediaMobileInApp "FLASH_INPAGE" -> Right CTFlashInpage "INSTREAM_VIDEO" -> Right CTInstreamVideo "VPAID_LINEAR_VIDEO" -> Right CTVpaidLinearVideo "VPAID_NON_LINEAR_VIDEO" -> Right CTVpaidNonLinearVideo "INSTREAM_VIDEO_REDIRECT" -> Right CTInstreamVideoRedirect "RICH_MEDIA_PEEL_DOWN" -> Right CTRichMediaPeelDown "HTML5_BANNER" -> Right CTHTML5Banner "DISPLAY" -> Right CTDisplay "DISPLAY_IMAGE_GALLERY" -> Right CTDisplayImageGallery "BRAND_SAFE_DEFAULT_INSTREAM_VIDEO" -> Right CTBrandSafeDefaultInstreamVideo "INSTREAM_AUDIO" -> Right CTInstreamAudio x -> Left ("Unable to parse CreativeType from: " <> x) instance ToHttpApiData CreativeType where toQueryParam = \case CTImage -> "IMAGE" CTDisplayRedirect -> "DISPLAY_REDIRECT" CTCustomDisplay -> "CUSTOM_DISPLAY" CTInternalRedirect -> "INTERNAL_REDIRECT" CTCustomDisplayInterstitial -> "CUSTOM_DISPLAY_INTERSTITIAL" CTInterstitialInternalRedirect -> "INTERSTITIAL_INTERNAL_REDIRECT" CTTrackingText -> "TRACKING_TEXT" CTRichMediaDisplayBanner -> "RICH_MEDIA_DISPLAY_BANNER" CTRichMediaInpageFloating -> "RICH_MEDIA_INPAGE_FLOATING" CTRichMediaImExpand -> "RICH_MEDIA_IM_EXPAND" CTRichMediaDisplayExpanding -> "RICH_MEDIA_DISPLAY_EXPANDING" CTRichMediaDisplayInterstitial -> "RICH_MEDIA_DISPLAY_INTERSTITIAL" CTRichMediaDisplayMultiFloatingInterstitial -> "RICH_MEDIA_DISPLAY_MULTI_FLOATING_INTERSTITIAL" CTRichMediaMobileInApp -> "RICH_MEDIA_MOBILE_IN_APP" CTFlashInpage -> "FLASH_INPAGE" CTInstreamVideo -> "INSTREAM_VIDEO" CTVpaidLinearVideo -> "VPAID_LINEAR_VIDEO" CTVpaidNonLinearVideo -> "VPAID_NON_LINEAR_VIDEO" CTInstreamVideoRedirect -> "INSTREAM_VIDEO_REDIRECT" CTRichMediaPeelDown -> "RICH_MEDIA_PEEL_DOWN" CTHTML5Banner -> "HTML5_BANNER" CTDisplay -> "DISPLAY" CTDisplayImageGallery -> "DISPLAY_IMAGE_GALLERY" CTBrandSafeDefaultInstreamVideo -> "BRAND_SAFE_DEFAULT_INSTREAM_VIDEO" CTInstreamAudio -> "INSTREAM_AUDIO" instance FromJSON CreativeType where parseJSON = parseJSONText "CreativeType" instance ToJSON CreativeType where toJSON = toJSONText -- | Order of sorted results. data FilesListSortOrder = FLSOAscending -- ^ @ASCENDING@ -- Ascending order. | FLSODescending -- ^ @DESCENDING@ -- Descending order. deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FilesListSortOrder instance FromHttpApiData FilesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right FLSOAscending "DESCENDING" -> Right FLSODescending x -> Left ("Unable to parse FilesListSortOrder from: " <> x) instance ToHttpApiData FilesListSortOrder where toQueryParam = \case FLSOAscending -> "ASCENDING" FLSODescending -> "DESCENDING" instance FromJSON FilesListSortOrder where parseJSON = parseJSONText "FilesListSortOrder" instance ToJSON FilesListSortOrder where toJSON = toJSONText -- | Field by which to sort the list. data AdvertiserGroupsListSortField = AGLSFID -- ^ @ID@ | AGLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertiserGroupsListSortField instance FromHttpApiData AdvertiserGroupsListSortField where parseQueryParam = \case "ID" -> Right AGLSFID "NAME" -> Right AGLSFName x -> Left ("Unable to parse AdvertiserGroupsListSortField from: " <> x) instance ToHttpApiData AdvertiserGroupsListSortField where toQueryParam = \case AGLSFID -> "ID" AGLSFName -> "NAME" instance FromJSON AdvertiserGroupsListSortField where parseJSON = parseJSONText "AdvertiserGroupsListSortField" instance ToJSON AdvertiserGroupsListSortField where toJSON = toJSONText -- | Type of browser window for which the backup image of the flash creative -- can be displayed. data TargetWindowTargetWindowOption = NewWindow -- ^ @NEW_WINDOW@ | CurrentWindow -- ^ @CURRENT_WINDOW@ | Custom -- ^ @CUSTOM@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable TargetWindowTargetWindowOption instance FromHttpApiData TargetWindowTargetWindowOption where parseQueryParam = \case "NEW_WINDOW" -> Right NewWindow "CURRENT_WINDOW" -> Right CurrentWindow "CUSTOM" -> Right Custom x -> Left ("Unable to parse TargetWindowTargetWindowOption from: " <> x) instance ToHttpApiData TargetWindowTargetWindowOption where toQueryParam = \case NewWindow -> "NEW_WINDOW" CurrentWindow -> "CURRENT_WINDOW" Custom -> "CUSTOM" instance FromJSON TargetWindowTargetWindowOption where parseJSON = parseJSONText "TargetWindowTargetWindowOption" instance ToJSON TargetWindowTargetWindowOption where toJSON = toJSONText -- | Select only placements with these pricing types. data PlacementsListPricingTypes = PLPTPricingTypeCpm -- ^ @PRICING_TYPE_CPM@ | PLPTPricingTypeCpc -- ^ @PRICING_TYPE_CPC@ | PLPTPricingTypeCpa -- ^ @PRICING_TYPE_CPA@ | PLPTPricingTypeFlatRateImpressions -- ^ @PRICING_TYPE_FLAT_RATE_IMPRESSIONS@ | PLPTPricingTypeFlatRateClicks -- ^ @PRICING_TYPE_FLAT_RATE_CLICKS@ | PLPTPricingTypeCpmActiveview -- ^ @PRICING_TYPE_CPM_ACTIVEVIEW@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementsListPricingTypes instance FromHttpApiData PlacementsListPricingTypes where parseQueryParam = \case "PRICING_TYPE_CPM" -> Right PLPTPricingTypeCpm "PRICING_TYPE_CPC" -> Right PLPTPricingTypeCpc "PRICING_TYPE_CPA" -> Right PLPTPricingTypeCpa "PRICING_TYPE_FLAT_RATE_IMPRESSIONS" -> Right PLPTPricingTypeFlatRateImpressions "PRICING_TYPE_FLAT_RATE_CLICKS" -> Right PLPTPricingTypeFlatRateClicks "PRICING_TYPE_CPM_ACTIVEVIEW" -> Right PLPTPricingTypeCpmActiveview x -> Left ("Unable to parse PlacementsListPricingTypes from: " <> x) instance ToHttpApiData PlacementsListPricingTypes where toQueryParam = \case PLPTPricingTypeCpm -> "PRICING_TYPE_CPM" PLPTPricingTypeCpc -> "PRICING_TYPE_CPC" PLPTPricingTypeCpa -> "PRICING_TYPE_CPA" PLPTPricingTypeFlatRateImpressions -> "PRICING_TYPE_FLAT_RATE_IMPRESSIONS" PLPTPricingTypeFlatRateClicks -> "PRICING_TYPE_FLAT_RATE_CLICKS" PLPTPricingTypeCpmActiveview -> "PRICING_TYPE_CPM_ACTIVEVIEW" instance FromJSON PlacementsListPricingTypes where parseJSON = parseJSONText "PlacementsListPricingTypes" instance ToJSON PlacementsListPricingTypes where toJSON = toJSONText -- | Order of sorted results. data EventTagsListSortOrder = ETLSOAscending -- ^ @ASCENDING@ | ETLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EventTagsListSortOrder instance FromHttpApiData EventTagsListSortOrder where parseQueryParam = \case "ASCENDING" -> Right ETLSOAscending "DESCENDING" -> Right ETLSODescending x -> Left ("Unable to parse EventTagsListSortOrder from: " <> x) instance ToHttpApiData EventTagsListSortOrder where toQueryParam = \case ETLSOAscending -> "ASCENDING" ETLSODescending -> "DESCENDING" instance FromJSON EventTagsListSortOrder where parseJSON = parseJSONText "EventTagsListSortOrder" instance ToJSON EventTagsListSortOrder where toJSON = toJSONText -- | Describes whether the encrypted cookie was received from ad serving (the -- %m macro) or from Data Transfer. data EncryptionInfoEncryptionSource = EncryptionScopeUnknown -- ^ @ENCRYPTION_SCOPE_UNKNOWN@ | AdServing -- ^ @AD_SERVING@ | DataTransfer -- ^ @DATA_TRANSFER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable EncryptionInfoEncryptionSource instance FromHttpApiData EncryptionInfoEncryptionSource where parseQueryParam = \case "ENCRYPTION_SCOPE_UNKNOWN" -> Right EncryptionScopeUnknown "AD_SERVING" -> Right AdServing "DATA_TRANSFER" -> Right DataTransfer x -> Left ("Unable to parse EncryptionInfoEncryptionSource from: " <> x) instance ToHttpApiData EncryptionInfoEncryptionSource where toQueryParam = \case EncryptionScopeUnknown -> "ENCRYPTION_SCOPE_UNKNOWN" AdServing -> "AD_SERVING" DataTransfer -> "DATA_TRANSFER" instance FromJSON EncryptionInfoEncryptionSource where parseJSON = parseJSONText "EncryptionInfoEncryptionSource" instance ToJSON EncryptionInfoEncryptionSource where toJSON = toJSONText -- | Field by which to sort the list. data DirectorySitesListSortField = DSLSFID -- ^ @ID@ | DSLSFName -- ^ @NAME@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DirectorySitesListSortField instance FromHttpApiData DirectorySitesListSortField where parseQueryParam = \case "ID" -> Right DSLSFID "NAME" -> Right DSLSFName x -> Left ("Unable to parse DirectorySitesListSortField from: " <> x) instance ToHttpApiData DirectorySitesListSortField where toQueryParam = \case DSLSFID -> "ID" DSLSFName -> "NAME" instance FromJSON DirectorySitesListSortField where parseJSON = parseJSONText "DirectorySitesListSortField" instance ToJSON DirectorySitesListSortField where toJSON = toJSONText -- | The dimension option. data ReportCrossDimensionReachCriteriaDimension = RCDRCDAdvertiser -- ^ @ADVERTISER@ | RCDRCDCampaign -- ^ @CAMPAIGN@ | RCDRCDSiteByAdvertiser -- ^ @SITE_BY_ADVERTISER@ | RCDRCDSiteByCampaign -- ^ @SITE_BY_CAMPAIGN@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportCrossDimensionReachCriteriaDimension instance FromHttpApiData ReportCrossDimensionReachCriteriaDimension where parseQueryParam = \case "ADVERTISER" -> Right RCDRCDAdvertiser "CAMPAIGN" -> Right RCDRCDCampaign "SITE_BY_ADVERTISER" -> Right RCDRCDSiteByAdvertiser "SITE_BY_CAMPAIGN" -> Right RCDRCDSiteByCampaign x -> Left ("Unable to parse ReportCrossDimensionReachCriteriaDimension from: " <> x) instance ToHttpApiData ReportCrossDimensionReachCriteriaDimension where toQueryParam = \case RCDRCDAdvertiser -> "ADVERTISER" RCDRCDCampaign -> "CAMPAIGN" RCDRCDSiteByAdvertiser -> "SITE_BY_ADVERTISER" RCDRCDSiteByCampaign -> "SITE_BY_CAMPAIGN" instance FromJSON ReportCrossDimensionReachCriteriaDimension where parseJSON = parseJSONText "ReportCrossDimensionReachCriteriaDimension" instance ToJSON ReportCrossDimensionReachCriteriaDimension where toJSON = toJSONText -- | Order of sorted results. data SitesListSortOrder = SLSOAscending -- ^ @ASCENDING@ | SLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SitesListSortOrder instance FromHttpApiData SitesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right SLSOAscending "DESCENDING" -> Right SLSODescending x -> Left ("Unable to parse SitesListSortOrder from: " <> x) instance ToHttpApiData SitesListSortOrder where toQueryParam = \case SLSOAscending -> "ASCENDING" SLSODescending -> "DESCENDING" instance FromJSON SitesListSortOrder where parseJSON = parseJSONText "SitesListSortOrder" instance ToJSON SitesListSortOrder where toJSON = toJSONText data PlacementTagFormatsItem = PTFIPlacementTagStandard -- ^ @PLACEMENT_TAG_STANDARD@ | PTFIPlacementTagIframeJavascript -- ^ @PLACEMENT_TAG_IFRAME_JAVASCRIPT@ | PTFIPlacementTagIframeIlayer -- ^ @PLACEMENT_TAG_IFRAME_ILAYER@ | PTFIPlacementTagInternalRedirect -- ^ @PLACEMENT_TAG_INTERNAL_REDIRECT@ | PTFIPlacementTagJavascript -- ^ @PLACEMENT_TAG_JAVASCRIPT@ | PTFIPlacementTagInterstitialIframeJavascript -- ^ @PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT@ | PTFIPlacementTagInterstitialInternalRedirect -- ^ @PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT@ | PTFIPlacementTagInterstitialJavascript -- ^ @PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT@ | PTFIPlacementTagClickCommands -- ^ @PLACEMENT_TAG_CLICK_COMMANDS@ | PTFIPlacementTagInstreamVideoPrefetch -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH@ | PTFIPlacementTagTracking -- ^ @PLACEMENT_TAG_TRACKING@ | PTFIPlacementTagTrackingIframe -- ^ @PLACEMENT_TAG_TRACKING_IFRAME@ | PTFIPlacementTagTrackingJavascript -- ^ @PLACEMENT_TAG_TRACKING_JAVASCRIPT@ | PTFIPlacementTagInstreamVideoPrefetchVast3 -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3@ | PTFIPlacementTagIframeJavascriptLegacy -- ^ @PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY@ | PTFIPlacementTagJavascriptLegacy -- ^ @PLACEMENT_TAG_JAVASCRIPT_LEGACY@ | PTFIPlacementTagInterstitialIframeJavascriptLegacy -- ^ @PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY@ | PTFIPlacementTagInterstitialJavascriptLegacy -- ^ @PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY@ | PTFIPlacementTagInstreamVideoPrefetchVast4 -- ^ @PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PlacementTagFormatsItem instance FromHttpApiData PlacementTagFormatsItem where parseQueryParam = \case "PLACEMENT_TAG_STANDARD" -> Right PTFIPlacementTagStandard "PLACEMENT_TAG_IFRAME_JAVASCRIPT" -> Right PTFIPlacementTagIframeJavascript "PLACEMENT_TAG_IFRAME_ILAYER" -> Right PTFIPlacementTagIframeIlayer "PLACEMENT_TAG_INTERNAL_REDIRECT" -> Right PTFIPlacementTagInternalRedirect "PLACEMENT_TAG_JAVASCRIPT" -> Right PTFIPlacementTagJavascript "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT" -> Right PTFIPlacementTagInterstitialIframeJavascript "PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT" -> Right PTFIPlacementTagInterstitialInternalRedirect "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT" -> Right PTFIPlacementTagInterstitialJavascript "PLACEMENT_TAG_CLICK_COMMANDS" -> Right PTFIPlacementTagClickCommands "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH" -> Right PTFIPlacementTagInstreamVideoPrefetch "PLACEMENT_TAG_TRACKING" -> Right PTFIPlacementTagTracking "PLACEMENT_TAG_TRACKING_IFRAME" -> Right PTFIPlacementTagTrackingIframe "PLACEMENT_TAG_TRACKING_JAVASCRIPT" -> Right PTFIPlacementTagTrackingJavascript "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3" -> Right PTFIPlacementTagInstreamVideoPrefetchVast3 "PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY" -> Right PTFIPlacementTagIframeJavascriptLegacy "PLACEMENT_TAG_JAVASCRIPT_LEGACY" -> Right PTFIPlacementTagJavascriptLegacy "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY" -> Right PTFIPlacementTagInterstitialIframeJavascriptLegacy "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY" -> Right PTFIPlacementTagInterstitialJavascriptLegacy "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4" -> Right PTFIPlacementTagInstreamVideoPrefetchVast4 x -> Left ("Unable to parse PlacementTagFormatsItem from: " <> x) instance ToHttpApiData PlacementTagFormatsItem where toQueryParam = \case PTFIPlacementTagStandard -> "PLACEMENT_TAG_STANDARD" PTFIPlacementTagIframeJavascript -> "PLACEMENT_TAG_IFRAME_JAVASCRIPT" PTFIPlacementTagIframeIlayer -> "PLACEMENT_TAG_IFRAME_ILAYER" PTFIPlacementTagInternalRedirect -> "PLACEMENT_TAG_INTERNAL_REDIRECT" PTFIPlacementTagJavascript -> "PLACEMENT_TAG_JAVASCRIPT" PTFIPlacementTagInterstitialIframeJavascript -> "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT" PTFIPlacementTagInterstitialInternalRedirect -> "PLACEMENT_TAG_INTERSTITIAL_INTERNAL_REDIRECT" PTFIPlacementTagInterstitialJavascript -> "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT" PTFIPlacementTagClickCommands -> "PLACEMENT_TAG_CLICK_COMMANDS" PTFIPlacementTagInstreamVideoPrefetch -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH" PTFIPlacementTagTracking -> "PLACEMENT_TAG_TRACKING" PTFIPlacementTagTrackingIframe -> "PLACEMENT_TAG_TRACKING_IFRAME" PTFIPlacementTagTrackingJavascript -> "PLACEMENT_TAG_TRACKING_JAVASCRIPT" PTFIPlacementTagInstreamVideoPrefetchVast3 -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_3" PTFIPlacementTagIframeJavascriptLegacy -> "PLACEMENT_TAG_IFRAME_JAVASCRIPT_LEGACY" PTFIPlacementTagJavascriptLegacy -> "PLACEMENT_TAG_JAVASCRIPT_LEGACY" PTFIPlacementTagInterstitialIframeJavascriptLegacy -> "PLACEMENT_TAG_INTERSTITIAL_IFRAME_JAVASCRIPT_LEGACY" PTFIPlacementTagInterstitialJavascriptLegacy -> "PLACEMENT_TAG_INTERSTITIAL_JAVASCRIPT_LEGACY" PTFIPlacementTagInstreamVideoPrefetchVast4 -> "PLACEMENT_TAG_INSTREAM_VIDEO_PREFETCH_VAST_4" instance FromJSON PlacementTagFormatsItem where parseJSON = parseJSONText "PlacementTagFormatsItem" instance ToJSON PlacementTagFormatsItem where toJSON = toJSONText -- | Type of the object of this dynamic targeting key. This is a required -- field. data DynamicTargetingKeyObjectType = DTKOTObjectAdvertiser -- ^ @OBJECT_ADVERTISER@ | DTKOTObjectAd -- ^ @OBJECT_AD@ | DTKOTObjectCreative -- ^ @OBJECT_CREATIVE@ | DTKOTObjectPlacement -- ^ @OBJECT_PLACEMENT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable DynamicTargetingKeyObjectType instance FromHttpApiData DynamicTargetingKeyObjectType where parseQueryParam = \case "OBJECT_ADVERTISER" -> Right DTKOTObjectAdvertiser "OBJECT_AD" -> Right DTKOTObjectAd "OBJECT_CREATIVE" -> Right DTKOTObjectCreative "OBJECT_PLACEMENT" -> Right DTKOTObjectPlacement x -> Left ("Unable to parse DynamicTargetingKeyObjectType from: " <> x) instance ToHttpApiData DynamicTargetingKeyObjectType where toQueryParam = \case DTKOTObjectAdvertiser -> "OBJECT_ADVERTISER" DTKOTObjectAd -> "OBJECT_AD" DTKOTObjectCreative -> "OBJECT_CREATIVE" DTKOTObjectPlacement -> "OBJECT_PLACEMENT" instance FromJSON DynamicTargetingKeyObjectType where parseJSON = parseJSONText "DynamicTargetingKeyObjectType" instance ToJSON DynamicTargetingKeyObjectType where toJSON = toJSONText -- | The type of the report. data ReportType = RTStandard -- ^ @STANDARD@ | RTReach -- ^ @REACH@ | RTPathToConversion -- ^ @PATH_TO_CONVERSION@ | RTCrossDimensionReach -- ^ @CROSS_DIMENSION_REACH@ | RTFloodlight -- ^ @FLOODLIGHT@ | RTPath -- ^ @PATH@ | RTPathAttribution -- ^ @PATH_ATTRIBUTION@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ReportType instance FromHttpApiData ReportType where parseQueryParam = \case "STANDARD" -> Right RTStandard "REACH" -> Right RTReach "PATH_TO_CONVERSION" -> Right RTPathToConversion "CROSS_DIMENSION_REACH" -> Right RTCrossDimensionReach "FLOODLIGHT" -> Right RTFloodlight "PATH" -> Right RTPath "PATH_ATTRIBUTION" -> Right RTPathAttribution x -> Left ("Unable to parse ReportType from: " <> x) instance ToHttpApiData ReportType where toQueryParam = \case RTStandard -> "STANDARD" RTReach -> "REACH" RTPathToConversion -> "PATH_TO_CONVERSION" RTCrossDimensionReach -> "CROSS_DIMENSION_REACH" RTFloodlight -> "FLOODLIGHT" RTPath -> "PATH" RTPathAttribution -> "PATH_ATTRIBUTION" instance FromJSON ReportType where parseJSON = parseJSONText "ReportType" instance ToJSON ReportType where toJSON = toJSONText data CreativeAssetMetadataWarnedValidationRulesItem = ClickTagNonTopLevel -- ^ @CLICK_TAG_NON_TOP_LEVEL@ | ClickTagMissing -- ^ @CLICK_TAG_MISSING@ | ClickTagMoreThanOne -- ^ @CLICK_TAG_MORE_THAN_ONE@ | ClickTagInvalid -- ^ @CLICK_TAG_INVALID@ | OrphanedAsset -- ^ @ORPHANED_ASSET@ | PrimaryHTMLMissing -- ^ @PRIMARY_HTML_MISSING@ | ExternalFileReferenced -- ^ @EXTERNAL_FILE_REFERENCED@ | MraidReferenced -- ^ @MRAID_REFERENCED@ | ADMobReferenced -- ^ @ADMOB_REFERENCED@ | FileTypeInvalid -- ^ @FILE_TYPE_INVALID@ | ZipInvalid -- ^ @ZIP_INVALID@ | LinkedFileNotFound -- ^ @LINKED_FILE_NOT_FOUND@ | MaxFlashVersion11 -- ^ @MAX_FLASH_VERSION_11@ | NotSSLCompliant -- ^ @NOT_SSL_COMPLIANT@ | FileDetailEmpty -- ^ @FILE_DETAIL_EMPTY@ | AssetInvalid -- ^ @ASSET_INVALID@ | GwdPropertiesInvalid -- ^ @GWD_PROPERTIES_INVALID@ | EnablerUnsupportedMethodDcm -- ^ @ENABLER_UNSUPPORTED_METHOD_DCM@ | AssetFormatUnsupportedDcm -- ^ @ASSET_FORMAT_UNSUPPORTED_DCM@ | ComponentUnsupportedDcm -- ^ @COMPONENT_UNSUPPORTED_DCM@ | HTML5FeatureUnsupported -- ^ @HTML5_FEATURE_UNSUPPORTED@ | ClickTagInGwd -- ^ @CLICK_TAG_IN_GWD@ | ClickTagHardCoded -- ^ @CLICK_TAG_HARD_CODED@ | SvgInvalid -- ^ @SVG_INVALID@ | ClickTagInRichMedia -- ^ @CLICK_TAG_IN_RICH_MEDIA@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetMetadataWarnedValidationRulesItem instance FromHttpApiData CreativeAssetMetadataWarnedValidationRulesItem where parseQueryParam = \case "CLICK_TAG_NON_TOP_LEVEL" -> Right ClickTagNonTopLevel "CLICK_TAG_MISSING" -> Right ClickTagMissing "CLICK_TAG_MORE_THAN_ONE" -> Right ClickTagMoreThanOne "CLICK_TAG_INVALID" -> Right ClickTagInvalid "ORPHANED_ASSET" -> Right OrphanedAsset "PRIMARY_HTML_MISSING" -> Right PrimaryHTMLMissing "EXTERNAL_FILE_REFERENCED" -> Right ExternalFileReferenced "MRAID_REFERENCED" -> Right MraidReferenced "ADMOB_REFERENCED" -> Right ADMobReferenced "FILE_TYPE_INVALID" -> Right FileTypeInvalid "ZIP_INVALID" -> Right ZipInvalid "LINKED_FILE_NOT_FOUND" -> Right LinkedFileNotFound "MAX_FLASH_VERSION_11" -> Right MaxFlashVersion11 "NOT_SSL_COMPLIANT" -> Right NotSSLCompliant "FILE_DETAIL_EMPTY" -> Right FileDetailEmpty "ASSET_INVALID" -> Right AssetInvalid "GWD_PROPERTIES_INVALID" -> Right GwdPropertiesInvalid "ENABLER_UNSUPPORTED_METHOD_DCM" -> Right EnablerUnsupportedMethodDcm "ASSET_FORMAT_UNSUPPORTED_DCM" -> Right AssetFormatUnsupportedDcm "COMPONENT_UNSUPPORTED_DCM" -> Right ComponentUnsupportedDcm "HTML5_FEATURE_UNSUPPORTED" -> Right HTML5FeatureUnsupported "CLICK_TAG_IN_GWD" -> Right ClickTagInGwd "CLICK_TAG_HARD_CODED" -> Right ClickTagHardCoded "SVG_INVALID" -> Right SvgInvalid "CLICK_TAG_IN_RICH_MEDIA" -> Right ClickTagInRichMedia x -> Left ("Unable to parse CreativeAssetMetadataWarnedValidationRulesItem from: " <> x) instance ToHttpApiData CreativeAssetMetadataWarnedValidationRulesItem where toQueryParam = \case ClickTagNonTopLevel -> "CLICK_TAG_NON_TOP_LEVEL" ClickTagMissing -> "CLICK_TAG_MISSING" ClickTagMoreThanOne -> "CLICK_TAG_MORE_THAN_ONE" ClickTagInvalid -> "CLICK_TAG_INVALID" OrphanedAsset -> "ORPHANED_ASSET" PrimaryHTMLMissing -> "PRIMARY_HTML_MISSING" ExternalFileReferenced -> "EXTERNAL_FILE_REFERENCED" MraidReferenced -> "MRAID_REFERENCED" ADMobReferenced -> "ADMOB_REFERENCED" FileTypeInvalid -> "FILE_TYPE_INVALID" ZipInvalid -> "ZIP_INVALID" LinkedFileNotFound -> "LINKED_FILE_NOT_FOUND" MaxFlashVersion11 -> "MAX_FLASH_VERSION_11" NotSSLCompliant -> "NOT_SSL_COMPLIANT" FileDetailEmpty -> "FILE_DETAIL_EMPTY" AssetInvalid -> "ASSET_INVALID" GwdPropertiesInvalid -> "GWD_PROPERTIES_INVALID" EnablerUnsupportedMethodDcm -> "ENABLER_UNSUPPORTED_METHOD_DCM" AssetFormatUnsupportedDcm -> "ASSET_FORMAT_UNSUPPORTED_DCM" ComponentUnsupportedDcm -> "COMPONENT_UNSUPPORTED_DCM" HTML5FeatureUnsupported -> "HTML5_FEATURE_UNSUPPORTED" ClickTagInGwd -> "CLICK_TAG_IN_GWD" ClickTagHardCoded -> "CLICK_TAG_HARD_CODED" SvgInvalid -> "SVG_INVALID" ClickTagInRichMedia -> "CLICK_TAG_IN_RICH_MEDIA" instance FromJSON CreativeAssetMetadataWarnedValidationRulesItem where parseJSON = parseJSONText "CreativeAssetMetadataWarnedValidationRulesItem" instance ToJSON CreativeAssetMetadataWarnedValidationRulesItem where toJSON = toJSONText -- | Payment source type of this ad slot. data AdSlotPaymentSourceType = PlanningPaymentSourceTypeAgencyPaid -- ^ @PLANNING_PAYMENT_SOURCE_TYPE_AGENCY_PAID@ | PlanningPaymentSourceTypePublisherPaid -- ^ @PLANNING_PAYMENT_SOURCE_TYPE_PUBLISHER_PAID@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdSlotPaymentSourceType instance FromHttpApiData AdSlotPaymentSourceType where parseQueryParam = \case "PLANNING_PAYMENT_SOURCE_TYPE_AGENCY_PAID" -> Right PlanningPaymentSourceTypeAgencyPaid "PLANNING_PAYMENT_SOURCE_TYPE_PUBLISHER_PAID" -> Right PlanningPaymentSourceTypePublisherPaid x -> Left ("Unable to parse AdSlotPaymentSourceType from: " <> x) instance ToHttpApiData AdSlotPaymentSourceType where toQueryParam = \case PlanningPaymentSourceTypeAgencyPaid -> "PLANNING_PAYMENT_SOURCE_TYPE_AGENCY_PAID" PlanningPaymentSourceTypePublisherPaid -> "PLANNING_PAYMENT_SOURCE_TYPE_PUBLISHER_PAID" instance FromJSON AdSlotPaymentSourceType where parseJSON = parseJSONText "AdSlotPaymentSourceType" instance ToJSON AdSlotPaymentSourceType where toJSON = toJSONText data AccountPermissionAccountProFilesItem = APAPFIAccountProFileBasic -- ^ @ACCOUNT_PROFILE_BASIC@ | APAPFIAccountProFileStandard -- ^ @ACCOUNT_PROFILE_STANDARD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AccountPermissionAccountProFilesItem instance FromHttpApiData AccountPermissionAccountProFilesItem where parseQueryParam = \case "ACCOUNT_PROFILE_BASIC" -> Right APAPFIAccountProFileBasic "ACCOUNT_PROFILE_STANDARD" -> Right APAPFIAccountProFileStandard x -> Left ("Unable to parse AccountPermissionAccountProFilesItem from: " <> x) instance ToHttpApiData AccountPermissionAccountProFilesItem where toQueryParam = \case APAPFIAccountProFileBasic -> "ACCOUNT_PROFILE_BASIC" APAPFIAccountProFileStandard -> "ACCOUNT_PROFILE_STANDARD" instance FromJSON AccountPermissionAccountProFilesItem where parseJSON = parseJSONText "AccountPermissionAccountProFilesItem" instance ToJSON AccountPermissionAccountProFilesItem where toJSON = toJSONText -- | Type of the event. This is a read-only field. data CreativeCustomEventAdvertiserCustomEventType = AdvertiserEventTimer -- ^ @ADVERTISER_EVENT_TIMER@ | AdvertiserEventExit -- ^ @ADVERTISER_EVENT_EXIT@ | AdvertiserEventCounter -- ^ @ADVERTISER_EVENT_COUNTER@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeCustomEventAdvertiserCustomEventType instance FromHttpApiData CreativeCustomEventAdvertiserCustomEventType where parseQueryParam = \case "ADVERTISER_EVENT_TIMER" -> Right AdvertiserEventTimer "ADVERTISER_EVENT_EXIT" -> Right AdvertiserEventExit "ADVERTISER_EVENT_COUNTER" -> Right AdvertiserEventCounter x -> Left ("Unable to parse CreativeCustomEventAdvertiserCustomEventType from: " <> x) instance ToHttpApiData CreativeCustomEventAdvertiserCustomEventType where toQueryParam = \case AdvertiserEventTimer -> "ADVERTISER_EVENT_TIMER" AdvertiserEventExit -> "ADVERTISER_EVENT_EXIT" AdvertiserEventCounter -> "ADVERTISER_EVENT_COUNTER" instance FromJSON CreativeCustomEventAdvertiserCustomEventType where parseJSON = parseJSONText "CreativeCustomEventAdvertiserCustomEventType" instance ToJSON CreativeCustomEventAdvertiserCustomEventType where toJSON = toJSONText -- | Select only change logs with the specified object type. data ChangeLogsListObjectType = CLLOTObjectAdvertiser -- ^ @OBJECT_ADVERTISER@ | CLLOTObjectFloodlightConfiguration -- ^ @OBJECT_FLOODLIGHT_CONFIGURATION@ | CLLOTObjectAd -- ^ @OBJECT_AD@ | CLLOTObjectFloodlightActvity -- ^ @OBJECT_FLOODLIGHT_ACTVITY@ | CLLOTObjectCampaign -- ^ @OBJECT_CAMPAIGN@ | CLLOTObjectFloodlightActivityGroup -- ^ @OBJECT_FLOODLIGHT_ACTIVITY_GROUP@ | CLLOTObjectCreative -- ^ @OBJECT_CREATIVE@ | CLLOTObjectPlacement -- ^ @OBJECT_PLACEMENT@ | CLLOTObjectDfaSite -- ^ @OBJECT_DFA_SITE@ | CLLOTObjectUserRole -- ^ @OBJECT_USER_ROLE@ | CLLOTObjectUserProFile -- ^ @OBJECT_USER_PROFILE@ | CLLOTObjectAdvertiserGroup -- ^ @OBJECT_ADVERTISER_GROUP@ | CLLOTObjectAccount -- ^ @OBJECT_ACCOUNT@ | CLLOTObjectSubAccount -- ^ @OBJECT_SUBACCOUNT@ | CLLOTObjectRichmediaCreative -- ^ @OBJECT_RICHMEDIA_CREATIVE@ | CLLOTObjectInstreamCreative -- ^ @OBJECT_INSTREAM_CREATIVE@ | CLLOTObjectMediaOrder -- ^ @OBJECT_MEDIA_ORDER@ | CLLOTObjectContentCategory -- ^ @OBJECT_CONTENT_CATEGORY@ | CLLOTObjectPlacementStrategy -- ^ @OBJECT_PLACEMENT_STRATEGY@ | CLLOTObjectSdSite -- ^ @OBJECT_SD_SITE@ | CLLOTObjectSize -- ^ @OBJECT_SIZE@ | CLLOTObjectCreativeGroup -- ^ @OBJECT_CREATIVE_GROUP@ | CLLOTObjectCreativeAsset -- ^ @OBJECT_CREATIVE_ASSET@ | CLLOTObjectUserProFileFilter -- ^ @OBJECT_USER_PROFILE_FILTER@ | CLLOTObjectLandingPage -- ^ @OBJECT_LANDING_PAGE@ | CLLOTObjectCreativeField -- ^ @OBJECT_CREATIVE_FIELD@ | CLLOTObjectRemarketingList -- ^ @OBJECT_REMARKETING_LIST@ | CLLOTObjectProvidedListClient -- ^ @OBJECT_PROVIDED_LIST_CLIENT@ | CLLOTObjectEventTag -- ^ @OBJECT_EVENT_TAG@ | CLLOTObjectCreativeBundle -- ^ @OBJECT_CREATIVE_BUNDLE@ | CLLOTObjectBillingAccountGroup -- ^ @OBJECT_BILLING_ACCOUNT_GROUP@ | CLLOTObjectBillingFeature -- ^ @OBJECT_BILLING_FEATURE@ | CLLOTObjectRateCard -- ^ @OBJECT_RATE_CARD@ | CLLOTObjectAccountBillingFeature -- ^ @OBJECT_ACCOUNT_BILLING_FEATURE@ | CLLOTObjectBillingMinimumFee -- ^ @OBJECT_BILLING_MINIMUM_FEE@ | CLLOTObjectBillingProFile -- ^ @OBJECT_BILLING_PROFILE@ | CLLOTObjectPlaystoreLink -- ^ @OBJECT_PLAYSTORE_LINK@ | CLLOTObjectTargetingTemplate -- ^ @OBJECT_TARGETING_TEMPLATE@ | CLLOTObjectSearchLiftStudy -- ^ @OBJECT_SEARCH_LIFT_STUDY@ | CLLOTObjectFloodlightDV360Link -- ^ @OBJECT_FLOODLIGHT_DV360_LINK@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ChangeLogsListObjectType instance FromHttpApiData ChangeLogsListObjectType where parseQueryParam = \case "OBJECT_ADVERTISER" -> Right CLLOTObjectAdvertiser "OBJECT_FLOODLIGHT_CONFIGURATION" -> Right CLLOTObjectFloodlightConfiguration "OBJECT_AD" -> Right CLLOTObjectAd "OBJECT_FLOODLIGHT_ACTVITY" -> Right CLLOTObjectFloodlightActvity "OBJECT_CAMPAIGN" -> Right CLLOTObjectCampaign "OBJECT_FLOODLIGHT_ACTIVITY_GROUP" -> Right CLLOTObjectFloodlightActivityGroup "OBJECT_CREATIVE" -> Right CLLOTObjectCreative "OBJECT_PLACEMENT" -> Right CLLOTObjectPlacement "OBJECT_DFA_SITE" -> Right CLLOTObjectDfaSite "OBJECT_USER_ROLE" -> Right CLLOTObjectUserRole "OBJECT_USER_PROFILE" -> Right CLLOTObjectUserProFile "OBJECT_ADVERTISER_GROUP" -> Right CLLOTObjectAdvertiserGroup "OBJECT_ACCOUNT" -> Right CLLOTObjectAccount "OBJECT_SUBACCOUNT" -> Right CLLOTObjectSubAccount "OBJECT_RICHMEDIA_CREATIVE" -> Right CLLOTObjectRichmediaCreative "OBJECT_INSTREAM_CREATIVE" -> Right CLLOTObjectInstreamCreative "OBJECT_MEDIA_ORDER" -> Right CLLOTObjectMediaOrder "OBJECT_CONTENT_CATEGORY" -> Right CLLOTObjectContentCategory "OBJECT_PLACEMENT_STRATEGY" -> Right CLLOTObjectPlacementStrategy "OBJECT_SD_SITE" -> Right CLLOTObjectSdSite "OBJECT_SIZE" -> Right CLLOTObjectSize "OBJECT_CREATIVE_GROUP" -> Right CLLOTObjectCreativeGroup "OBJECT_CREATIVE_ASSET" -> Right CLLOTObjectCreativeAsset "OBJECT_USER_PROFILE_FILTER" -> Right CLLOTObjectUserProFileFilter "OBJECT_LANDING_PAGE" -> Right CLLOTObjectLandingPage "OBJECT_CREATIVE_FIELD" -> Right CLLOTObjectCreativeField "OBJECT_REMARKETING_LIST" -> Right CLLOTObjectRemarketingList "OBJECT_PROVIDED_LIST_CLIENT" -> Right CLLOTObjectProvidedListClient "OBJECT_EVENT_TAG" -> Right CLLOTObjectEventTag "OBJECT_CREATIVE_BUNDLE" -> Right CLLOTObjectCreativeBundle "OBJECT_BILLING_ACCOUNT_GROUP" -> Right CLLOTObjectBillingAccountGroup "OBJECT_BILLING_FEATURE" -> Right CLLOTObjectBillingFeature "OBJECT_RATE_CARD" -> Right CLLOTObjectRateCard "OBJECT_ACCOUNT_BILLING_FEATURE" -> Right CLLOTObjectAccountBillingFeature "OBJECT_BILLING_MINIMUM_FEE" -> Right CLLOTObjectBillingMinimumFee "OBJECT_BILLING_PROFILE" -> Right CLLOTObjectBillingProFile "OBJECT_PLAYSTORE_LINK" -> Right CLLOTObjectPlaystoreLink "OBJECT_TARGETING_TEMPLATE" -> Right CLLOTObjectTargetingTemplate "OBJECT_SEARCH_LIFT_STUDY" -> Right CLLOTObjectSearchLiftStudy "OBJECT_FLOODLIGHT_DV360_LINK" -> Right CLLOTObjectFloodlightDV360Link x -> Left ("Unable to parse ChangeLogsListObjectType from: " <> x) instance ToHttpApiData ChangeLogsListObjectType where toQueryParam = \case CLLOTObjectAdvertiser -> "OBJECT_ADVERTISER" CLLOTObjectFloodlightConfiguration -> "OBJECT_FLOODLIGHT_CONFIGURATION" CLLOTObjectAd -> "OBJECT_AD" CLLOTObjectFloodlightActvity -> "OBJECT_FLOODLIGHT_ACTVITY" CLLOTObjectCampaign -> "OBJECT_CAMPAIGN" CLLOTObjectFloodlightActivityGroup -> "OBJECT_FLOODLIGHT_ACTIVITY_GROUP" CLLOTObjectCreative -> "OBJECT_CREATIVE" CLLOTObjectPlacement -> "OBJECT_PLACEMENT" CLLOTObjectDfaSite -> "OBJECT_DFA_SITE" CLLOTObjectUserRole -> "OBJECT_USER_ROLE" CLLOTObjectUserProFile -> "OBJECT_USER_PROFILE" CLLOTObjectAdvertiserGroup -> "OBJECT_ADVERTISER_GROUP" CLLOTObjectAccount -> "OBJECT_ACCOUNT" CLLOTObjectSubAccount -> "OBJECT_SUBACCOUNT" CLLOTObjectRichmediaCreative -> "OBJECT_RICHMEDIA_CREATIVE" CLLOTObjectInstreamCreative -> "OBJECT_INSTREAM_CREATIVE" CLLOTObjectMediaOrder -> "OBJECT_MEDIA_ORDER" CLLOTObjectContentCategory -> "OBJECT_CONTENT_CATEGORY" CLLOTObjectPlacementStrategy -> "OBJECT_PLACEMENT_STRATEGY" CLLOTObjectSdSite -> "OBJECT_SD_SITE" CLLOTObjectSize -> "OBJECT_SIZE" CLLOTObjectCreativeGroup -> "OBJECT_CREATIVE_GROUP" CLLOTObjectCreativeAsset -> "OBJECT_CREATIVE_ASSET" CLLOTObjectUserProFileFilter -> "OBJECT_USER_PROFILE_FILTER" CLLOTObjectLandingPage -> "OBJECT_LANDING_PAGE" CLLOTObjectCreativeField -> "OBJECT_CREATIVE_FIELD" CLLOTObjectRemarketingList -> "OBJECT_REMARKETING_LIST" CLLOTObjectProvidedListClient -> "OBJECT_PROVIDED_LIST_CLIENT" CLLOTObjectEventTag -> "OBJECT_EVENT_TAG" CLLOTObjectCreativeBundle -> "OBJECT_CREATIVE_BUNDLE" CLLOTObjectBillingAccountGroup -> "OBJECT_BILLING_ACCOUNT_GROUP" CLLOTObjectBillingFeature -> "OBJECT_BILLING_FEATURE" CLLOTObjectRateCard -> "OBJECT_RATE_CARD" CLLOTObjectAccountBillingFeature -> "OBJECT_ACCOUNT_BILLING_FEATURE" CLLOTObjectBillingMinimumFee -> "OBJECT_BILLING_MINIMUM_FEE" CLLOTObjectBillingProFile -> "OBJECT_BILLING_PROFILE" CLLOTObjectPlaystoreLink -> "OBJECT_PLAYSTORE_LINK" CLLOTObjectTargetingTemplate -> "OBJECT_TARGETING_TEMPLATE" CLLOTObjectSearchLiftStudy -> "OBJECT_SEARCH_LIFT_STUDY" CLLOTObjectFloodlightDV360Link -> "OBJECT_FLOODLIGHT_DV360_LINK" instance FromJSON ChangeLogsListObjectType where parseJSON = parseJSONText "ChangeLogsListObjectType" instance ToJSON ChangeLogsListObjectType where toJSON = toJSONText -- | The status of the activity. This can only be set to ACTIVE or -- ARCHIVED_AND_DISABLED. The ARCHIVED status is no longer supported and -- cannot be set for Floodlight activities. The DISABLED_POLICY status -- indicates that a Floodlight activity is violating Google policy. Contact -- your account manager for more information. data FloodlightActivityStatus = Active -- ^ @ACTIVE@ | ArchivedAndDisabled -- ^ @ARCHIVED_AND_DISABLED@ | Archived -- ^ @ARCHIVED@ | DisabledPolicy -- ^ @DISABLED_POLICY@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityStatus instance FromHttpApiData FloodlightActivityStatus where parseQueryParam = \case "ACTIVE" -> Right Active "ARCHIVED_AND_DISABLED" -> Right ArchivedAndDisabled "ARCHIVED" -> Right Archived "DISABLED_POLICY" -> Right DisabledPolicy x -> Left ("Unable to parse FloodlightActivityStatus from: " <> x) instance ToHttpApiData FloodlightActivityStatus where toQueryParam = \case Active -> "ACTIVE" ArchivedAndDisabled -> "ARCHIVED_AND_DISABLED" Archived -> "ARCHIVED" DisabledPolicy -> "DISABLED_POLICY" instance FromJSON FloodlightActivityStatus where parseJSON = parseJSONText "FloodlightActivityStatus" instance ToJSON FloodlightActivityStatus where toJSON = toJSONText -- | Orientation of a site template used for video. This will act as default -- for new placements created under this site. data SiteVideoSettingsOrientation = SVSOAny -- ^ @ANY@ | SVSOLandscape -- ^ @LANDSCAPE@ | SVSOPortrait -- ^ @PORTRAIT@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable SiteVideoSettingsOrientation instance FromHttpApiData SiteVideoSettingsOrientation where parseQueryParam = \case "ANY" -> Right SVSOAny "LANDSCAPE" -> Right SVSOLandscape "PORTRAIT" -> Right SVSOPortrait x -> Left ("Unable to parse SiteVideoSettingsOrientation from: " <> x) instance ToHttpApiData SiteVideoSettingsOrientation where toQueryParam = \case SVSOAny -> "ANY" SVSOLandscape -> "LANDSCAPE" SVSOPortrait -> "PORTRAIT" instance FromJSON SiteVideoSettingsOrientation where parseJSON = parseJSONText "SiteVideoSettingsOrientation" instance ToJSON SiteVideoSettingsOrientation where toJSON = toJSONText -- | Cap cost type of this inventory item. data PricingCapCostType = PlanningPlacementCapCostTypeNone -- ^ @PLANNING_PLACEMENT_CAP_COST_TYPE_NONE@ | PlanningPlacementCapCostTypeMonthly -- ^ @PLANNING_PLACEMENT_CAP_COST_TYPE_MONTHLY@ | PlanningPlacementCapCostTypeCumulative -- ^ @PLANNING_PLACEMENT_CAP_COST_TYPE_CUMULATIVE@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable PricingCapCostType instance FromHttpApiData PricingCapCostType where parseQueryParam = \case "PLANNING_PLACEMENT_CAP_COST_TYPE_NONE" -> Right PlanningPlacementCapCostTypeNone "PLANNING_PLACEMENT_CAP_COST_TYPE_MONTHLY" -> Right PlanningPlacementCapCostTypeMonthly "PLANNING_PLACEMENT_CAP_COST_TYPE_CUMULATIVE" -> Right PlanningPlacementCapCostTypeCumulative x -> Left ("Unable to parse PricingCapCostType from: " <> x) instance ToHttpApiData PricingCapCostType where toQueryParam = \case PlanningPlacementCapCostTypeNone -> "PLANNING_PLACEMENT_CAP_COST_TYPE_NONE" PlanningPlacementCapCostTypeMonthly -> "PLANNING_PLACEMENT_CAP_COST_TYPE_MONTHLY" PlanningPlacementCapCostTypeCumulative -> "PLANNING_PLACEMENT_CAP_COST_TYPE_CUMULATIVE" instance FromJSON PricingCapCostType where parseJSON = parseJSONText "PricingCapCostType" instance ToJSON PricingCapCostType where toJSON = toJSONText -- | Type of rich media asset. This is a read-only field. Applicable to the -- following creative types: all RICH_MEDIA. data CreativeAssetDisplayType = AssetDisplayTypeInpage -- ^ @ASSET_DISPLAY_TYPE_INPAGE@ | AssetDisplayTypeFloating -- ^ @ASSET_DISPLAY_TYPE_FLOATING@ | AssetDisplayTypeOverlay -- ^ @ASSET_DISPLAY_TYPE_OVERLAY@ | AssetDisplayTypeExpanding -- ^ @ASSET_DISPLAY_TYPE_EXPANDING@ | AssetDisplayTypeFlashInFlash -- ^ @ASSET_DISPLAY_TYPE_FLASH_IN_FLASH@ | AssetDisplayTypeFlashInFlashExpanding -- ^ @ASSET_DISPLAY_TYPE_FLASH_IN_FLASH_EXPANDING@ | AssetDisplayTypePeelDown -- ^ @ASSET_DISPLAY_TYPE_PEEL_DOWN@ | AssetDisplayTypeVpaidLinear -- ^ @ASSET_DISPLAY_TYPE_VPAID_LINEAR@ | AssetDisplayTypeVpaidNonLinear -- ^ @ASSET_DISPLAY_TYPE_VPAID_NON_LINEAR@ | AssetDisplayTypeBackdrop -- ^ @ASSET_DISPLAY_TYPE_BACKDROP@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable CreativeAssetDisplayType instance FromHttpApiData CreativeAssetDisplayType where parseQueryParam = \case "ASSET_DISPLAY_TYPE_INPAGE" -> Right AssetDisplayTypeInpage "ASSET_DISPLAY_TYPE_FLOATING" -> Right AssetDisplayTypeFloating "ASSET_DISPLAY_TYPE_OVERLAY" -> Right AssetDisplayTypeOverlay "ASSET_DISPLAY_TYPE_EXPANDING" -> Right AssetDisplayTypeExpanding "ASSET_DISPLAY_TYPE_FLASH_IN_FLASH" -> Right AssetDisplayTypeFlashInFlash "ASSET_DISPLAY_TYPE_FLASH_IN_FLASH_EXPANDING" -> Right AssetDisplayTypeFlashInFlashExpanding "ASSET_DISPLAY_TYPE_PEEL_DOWN" -> Right AssetDisplayTypePeelDown "ASSET_DISPLAY_TYPE_VPAID_LINEAR" -> Right AssetDisplayTypeVpaidLinear "ASSET_DISPLAY_TYPE_VPAID_NON_LINEAR" -> Right AssetDisplayTypeVpaidNonLinear "ASSET_DISPLAY_TYPE_BACKDROP" -> Right AssetDisplayTypeBackdrop x -> Left ("Unable to parse CreativeAssetDisplayType from: " <> x) instance ToHttpApiData CreativeAssetDisplayType where toQueryParam = \case AssetDisplayTypeInpage -> "ASSET_DISPLAY_TYPE_INPAGE" AssetDisplayTypeFloating -> "ASSET_DISPLAY_TYPE_FLOATING" AssetDisplayTypeOverlay -> "ASSET_DISPLAY_TYPE_OVERLAY" AssetDisplayTypeExpanding -> "ASSET_DISPLAY_TYPE_EXPANDING" AssetDisplayTypeFlashInFlash -> "ASSET_DISPLAY_TYPE_FLASH_IN_FLASH" AssetDisplayTypeFlashInFlashExpanding -> "ASSET_DISPLAY_TYPE_FLASH_IN_FLASH_EXPANDING" AssetDisplayTypePeelDown -> "ASSET_DISPLAY_TYPE_PEEL_DOWN" AssetDisplayTypeVpaidLinear -> "ASSET_DISPLAY_TYPE_VPAID_LINEAR" AssetDisplayTypeVpaidNonLinear -> "ASSET_DISPLAY_TYPE_VPAID_NON_LINEAR" AssetDisplayTypeBackdrop -> "ASSET_DISPLAY_TYPE_BACKDROP" instance FromJSON CreativeAssetDisplayType where parseJSON = parseJSONText "CreativeAssetDisplayType" instance ToJSON CreativeAssetDisplayType where toJSON = toJSONText -- | Counting method for conversions for this floodlight activity. This is a -- required field. data FloodlightActivityCountingMethod = StandardCounting -- ^ @STANDARD_COUNTING@ | UniqueCounting -- ^ @UNIQUE_COUNTING@ | SessionCounting -- ^ @SESSION_COUNTING@ | TransactionsCounting -- ^ @TRANSACTIONS_COUNTING@ | ItemsSoldCounting -- ^ @ITEMS_SOLD_COUNTING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable FloodlightActivityCountingMethod instance FromHttpApiData FloodlightActivityCountingMethod where parseQueryParam = \case "STANDARD_COUNTING" -> Right StandardCounting "UNIQUE_COUNTING" -> Right UniqueCounting "SESSION_COUNTING" -> Right SessionCounting "TRANSACTIONS_COUNTING" -> Right TransactionsCounting "ITEMS_SOLD_COUNTING" -> Right ItemsSoldCounting x -> Left ("Unable to parse FloodlightActivityCountingMethod from: " <> x) instance ToHttpApiData FloodlightActivityCountingMethod where toQueryParam = \case StandardCounting -> "STANDARD_COUNTING" UniqueCounting -> "UNIQUE_COUNTING" SessionCounting -> "SESSION_COUNTING" TransactionsCounting -> "TRANSACTIONS_COUNTING" ItemsSoldCounting -> "ITEMS_SOLD_COUNTING" instance FromJSON FloodlightActivityCountingMethod where parseJSON = parseJSONText "FloodlightActivityCountingMethod" instance ToJSON FloodlightActivityCountingMethod where toJSON = toJSONText -- | Order of sorted results. data ContentCategoriesListSortOrder = CCLSOAscending -- ^ @ASCENDING@ | CCLSODescending -- ^ @DESCENDING@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable ContentCategoriesListSortOrder instance FromHttpApiData ContentCategoriesListSortOrder where parseQueryParam = \case "ASCENDING" -> Right CCLSOAscending "DESCENDING" -> Right CCLSODescending x -> Left ("Unable to parse ContentCategoriesListSortOrder from: " <> x) instance ToHttpApiData ContentCategoriesListSortOrder where toQueryParam = \case CCLSOAscending -> "ASCENDING" CCLSODescending -> "DESCENDING" instance FromJSON ContentCategoriesListSortOrder where parseJSON = parseJSONText "ContentCategoriesListSortOrder" instance ToJSON ContentCategoriesListSortOrder where toJSON = toJSONText -- | Status of this advertiser. data AdvertiserStatus = ASApproved -- ^ @APPROVED@ | ASOnHold -- ^ @ON_HOLD@ deriving (Eq, Ord, Enum, Read, Show, Data, Typeable, Generic) instance Hashable AdvertiserStatus instance FromHttpApiData AdvertiserStatus where parseQueryParam = \case "APPROVED" -> Right ASApproved "ON_HOLD" -> Right ASOnHold x -> Left ("Unable to parse AdvertiserStatus from: " <> x) instance ToHttpApiData AdvertiserStatus where toQueryParam = \case ASApproved -> "APPROVED" ASOnHold -> "ON_HOLD" instance FromJSON AdvertiserStatus where parseJSON = parseJSONText "AdvertiserStatus" instance ToJSON AdvertiserStatus where toJSON = toJSONText
brendanhay/gogol
gogol-dfareporting/gen/Network/Google/DFAReporting/Types/Sum.hs
mpl-2.0
338,182
0
11
74,176
51,345
26,868
24,477
6,578
0
{-# LANGUAGE CPP, Unsafe, UnliftedFFITypes, MagicHash, UnboxedTuples #-} module Graphics.OpenGLES.Base.Proc (glGetProcAddress) where import Foreign import Foreign.C.String import GHC.Base (realWorld#) import GHC.CString (unpackCString#) import GHC.IO (IO (IO)) import GHC.Ptr (Ptr(..)) import System.IO.Unsafe (unsafePerformIO) #if defined(EGL_GETPROC) foreign import ccall unsafe "eglGetProcAddress" getProcAddress :: CString -> IO (FunPtr a) #elif defined(WGL_GETPROC) foreign import ccall unsafe "wglGetProcAddress" getProcAddress :: CString -> IO (FunPtr a) #elif defined(GLX_GETPROC) foreign import ccall unsafe "glXGetProcAddress" getProcAddress :: CString -> IO (FunPtr a) #elif defined(DLSYM_GETPROC) -- | void *dlsym(void *handle, const char *symbol); foreign import ccall unsafe "dlfcn.h dlsym" dlsym :: Ptr () -> CString -> IO (FunPtr a) getProcAddress :: CString -> IO (FunPtr a) getProcAddress procname = dlsym runtime_loader_default procname where runtime_loader_default = nullPtr #else #error "Don't know how to retrieve OpenGL ES extension entries. try -DEGL_GETPROC" #endif -- * Retrieve OpenGL (ES) and EGL Extension Entries -- | Just like unsafePerformIO, but we inline it. Big performance gains as -- it exposes lots of things to further inlining. /Very unsafe/. In -- particular, you should do no memory allocation inside an -- 'inlinePerformIO' block. inlinePerformIO :: IO a -> a inlinePerformIO (IO m) = case m realWorld# of (# _, r #) -> r {-# INLINE inlinePerformIO #-} glGetProcAddress :: String -> FunPtr a glGetProcAddress procname = unsafePerformIO $ withCString procname getProcAddress {-# INLINE [0] glGetProcAddress #-} {-# RULES "glGetProcAddress/getProcAddress" forall s. glGetProcAddress (unpackCString# s) = inlinePerformIO (getProcAddress (Ptr s)) #-}
capsjac/opengles
src/Graphics/OpenGLES/Base/Proc.hs
lgpl-3.0
1,870
4
9
315
197
116
81
-1
-1
------------------------------------------------------------------------------ -- Copyright 2012 Microsoft Corporation. -- -- This is free software; you can redistribute it and/or modify it under the -- terms of the Apache License, Version 2.0. A copy of the License can be -- found in the file "license.txt" at the root of this distribution. ----------------------------------------------------------------------------- {- Responsibilities of the kind checker: - Kindcheck all types in the program - Translate user types to internal types - Collect lists of data types, synonyms and constructors - Expand all synonyms (i.e., replace @id(int)@ by @id(int) == int@) - Transate type definition groups and externals to Core. -} ----------------------------------------------------------------------------- module Kind.Infer (inferKinds) where import Lib.Trace -- import Type.Pretty import Data.Char(isAlphaNum) import Data.List(groupBy,intersperse) import Lib.PPrint import Common.Failure import Common.Unique( uniqueId ) import Common.Error import Common.ColorScheme( ColorScheme, colorType, colorSource ) import Common.Range import Common.Name import Common.NamePrim( nameTrue, nameFalse, nameEffectEmpty, nameEffectExtend, nameEffectAppend, nameCopy, namePatternMatchError ) import Common.Syntax import qualified Common.NameMap as M import Syntax.Syntax import qualified Core.Core as Core import Kind.ImportMap import Kind.Kind import Kind.Assumption import Kind.Constructors import Kind.Newtypes import Kind.Synonym import Type.Type import Type.Assumption import Type.TypeVar( tvsIsEmpty, ftv, subNew, (|->) ) import Kind.InferKind import Kind.InferMonad import Kind.Unify import Syntax.RangeMap {-------------------------------------------------------------------------- Kindcheck a program and calculate types --------------------------------------------------------------------------} -- | Kindcheck a program and calculate types inferKinds :: ColorScheme -- ^ Color scheme used for error messages -> Int -- ^ max struct fields option -> Maybe RangeMap -- ^ possible range map for tool integration -> ImportMap -- ^ Import aliases -> KGamma -- ^ Initial kind kgamma -> Synonyms -- ^ Initial list of synonyms -> Int -- ^ Unique -> Program UserType UserKind -- ^ Original program -> Error ( DefGroups Type -- Translated program (containing translated types) -- , Gamma -- Gamma containing generated functions, i.e type scheme for every constructor , KGamma -- updated kind gamma , Synonyms -- Updated synonyms , Newtypes -- Data type information , Constructors -- Constructor information -- , Core.TypeDefGroups -- Core type definition groups -- , Core.Externals -- Core externals , Core.Core -- Initial core program with type definition groups, externals, and some generated definitions for data types (like folds). , Int -- New unique , Maybe RangeMap ) inferKinds colors maxStructFields mbRangeMap imports kgamma0 syns0 unique0 (Program source modName nameRange tdgroups defs importdefs externals fixdefs doc) = let (errs1,warns1,rm1,unique1,(cgroups,kgamma1,syns1)) = runKindInfer colors mbRangeMap modName imports kgamma0 syns0 unique0 (infTypeDefGroups tdgroups) (errs2,warns2,rm2,unique2,externals1) = runKindInfer colors rm1 modName imports kgamma1 syns1 unique1 (infExternals externals) (errs3,warns3,rm3,unique3,defs1) = runKindInfer colors rm2 modName imports kgamma1 syns1 unique2 (infDefGroups defs) -- (errs4,warns4,unique4,cgroups) = runKindInfer colors modName imports kgamma1 syns1 unique3 (infCoreTDGroups cgroups) (synInfos,dataInfos) = unzipEither (extractInfos cgroups) conInfos = concatMap dataInfoConstrs dataInfos cons1 = constructorsFromList conInfos gamma1 = constructorGamma maxStructFields dataInfos errs4 = constructorCheckDuplicates colors conInfos errs = errs1 ++ errs2 ++ errs3 ++ errs4 warns = warns1 ++ warns2 ++ warns3 dgroups = concatMap (synTypeDefGroup modName) cgroups in addWarnings warns $ if (null errs) then return (dgroups ++ defs1 -- ,gamma1 ,kgamma1 ,syns1 ,newtypesNew dataInfos ,cons1 -- ,cgroups -- ,externals1 ,Core.Core modName [] [] cgroups [] externals1 doc ,unique3 ,rm3 ) else errorMsg (ErrorKind errs) unzipEither :: [Either a b] -> ([a],[b]) unzipEither xs = unz [] [] xs where unz left right (Left x:xs) = unz (x:left) right xs unz left right (Right x:xs) = unz left (x:right) xs unz left right [] = (reverse left, reverse right) extractInfos :: [Core.TypeDefGroup] -> [Either SynInfo DataInfo] extractInfos groups = concatMap extractGroupInfos groups where extractGroupInfos (Core.TypeDefGroup ctdefs) = map extractInfo ctdefs extractInfo (Core.Synonym synInfo vis) = Left synInfo extractInfo (Core.Data dataInfo vis convss) = Right dataInfo {--------------------------------------------------------------- ---------------------------------------------------------------} synTypeDefGroup :: Name -> Core.TypeDefGroup -> DefGroups Type synTypeDefGroup modName (Core.TypeDefGroup ctdefs) = concatMap (synTypeDef modName) ctdefs synTypeDef :: Name -> Core.TypeDef -> DefGroups Type synTypeDef modName (Core.Synonym synInfo vis) = [] synTypeDef modName (Core.Data dataInfo vis conviss) = synAccessors modName dataInfo vis conviss ++ (if (length (dataInfoConstrs dataInfo) == 1) then [synCopyCon modName dataInfo (head conviss) (head (dataInfoConstrs dataInfo))] else []) ++ (if (length (dataInfoConstrs dataInfo) > 1) then map (synTester dataInfo) (zip conviss (dataInfoConstrs dataInfo)) else []) synCopyCon :: Name -> DataInfo -> Visibility -> ConInfo -> DefGroup Type synCopyCon modName info vis con = let rc = conInfoRange con tp = typeApp (TCon (TypeCon (dataInfoName info) (dataInfoKind info))) [TVar (TypeVar id kind Meta) | TypeVar id kind _ <- (dataInfoParams info)] fullTp = let (vars,preds,rho) = splitPredType (conInfoType con) in case splitFunType rho of Just (args,eff,res) -> TForall vars preds (TFun ([(argName,res)] ++ [(name,if name==nameNil then t else makeOptional t) | (name,t) <- args]) eff res) Nothing -> TForall vars preds (TFun [(argName,rho)] typeTotal rho) -- for unary constructors, like unit var n = Var n False rc app x [] = x app x xs = App x [(Nothing,y) | y <- xs] rc argName = newName ".this" params = [ValueBinder name Nothing (if isFieldName name then Nothing else (Just (app (var name) [var argName]))) rc rc| (name,t) <- conInfoParams con] expr = Lam ([ValueBinder argName Nothing Nothing rc rc] ++ params) body rc body = app (var (conInfoName con)) [var name | (name,tp) <- conInfoParams con] def = DefNonRec (Def (ValueBinder nameCopy () (Ann expr fullTp rc) rc rc) rc vis DefFun "") in def synAccessors :: Name -> DataInfo -> Visibility -> [Visibility] -> [DefGroup Type] synAccessors modName info vis conviss = let params = concatMap (\conInfo -> zipWith (\(name,tp) rng -> (name,(tp,rng))) (conInfoParams conInfo) (conInfoParamRanges conInfo)) (dataInfoConstrs info) fields :: [(Name,(Type,Range))] fields = filter (\(nm,(tp,rng)) -> not (isFieldName nm) && tvsIsEmpty (ftv (TForall (dataInfoParams info) [] tp))) $ -- no existentials select [] params select acc [] = reverse acc select acc ((name,(tp,rng)):params) = case lookup name acc of Nothing -> select ((name,(tp,rng)):acc) params Just (t,r) -> if (t == tp) then select acc params else -- todo: give an error if duplicate names with different types exist? select (filter (\(n,_) -> n /= name) acc) params synAccessor :: (Name,(Type,Range)) -> DefGroup Type synAccessor (name,(tp,rng)) = let dataName = unqualify $ dataInfoName info arg = if (all isAlphaNum (show dataName)) then dataName else newName ".this" fld = newName ".x" fullTp = quantifyType (dataInfoParams info) $ typeFun [(arg,dataTp)] (if isPartial then typePartial else typeTotal) tp dataTp = typeApp (TCon (TypeCon (dataInfoName info) (dataInfoKind info))) (map TVar (dataInfoParams info)) expr = Ann (Lam [ValueBinder arg Nothing Nothing rng rng] caseExpr rng) fullTp rng caseExpr = Case (Var arg False rng) (map snd branches ++ defaultBranch) rng visibility = if (all (==Public) (map fst branches)) then Public else Private isPartial = (length branches < length (dataInfoConstrs info)) branches :: [(Visibility,Branch Type)] branches = concatMap makeBranch (zip conviss (dataInfoConstrs info)) makeBranch (vis,con) = let r = conInfoRange con in case lookup name (zip (map fst (conInfoParams con)) [0..]) of Just i -> let patterns = [(Nothing,PatWild r) | _ <- [0..i-1]] ++ [(Nothing,PatVar (ValueBinder fld Nothing (PatWild r) r r))] ++ [(Nothing,PatWild r) | _ <- [i+1..length (conInfoParams con)-1]] in [(vis,Branch (PatCon (conInfoName con) patterns r r) guardTrue (Var fld False r))] Nothing -> [] defaultBranch = if isPartial then [Branch (PatWild rng) guardTrue (App (Var namePatternMatchError False rng) [(Nothing,msg) | msg <- messages] rng)] else [] messages = [Lit (LitString (sourceName (posSource (rangeStart rng)) ++ show rng) rng), Lit (LitString (show name) rng)] doc = "// Automatically generated. Retrieves the `" ++ show name ++ "` constructor field of the \":" ++ nameId (dataInfoName info) ++ "\" type.\n" in DefNonRec (Def (ValueBinder name () expr rng rng) rng visibility DefFun doc) in map synAccessor fields synTester :: DataInfo -> (Visibility,ConInfo) -> DefGroup Type synTester info (vis,con) = let name = (newName ("is" ++ nameId (conInfoName con))) arg = unqualify $ dataInfoName info rc = conInfoRange con expr = Lam [ValueBinder arg Nothing Nothing rc rc] caseExpr rc caseExpr = Case (Var arg False rc) [branch1,branch2] rc branch1 = Branch (PatCon (conInfoName con) patterns rc rc) guardTrue (Var nameTrue False rc) branch2 = Branch (PatWild rc) guardTrue (Var nameFalse False rc) patterns = [(Nothing,PatWild rc) | _ <- conInfoParams con] doc = "// Automatically generated. Tests for the \"" ++ nameId (conInfoName con) ++ "\" constructor of the \":" ++ nameId (dataInfoName info) ++ "\" type.\n" in DefNonRec (Def (ValueBinder name () expr rc rc) rc vis DefFun doc) {--------------------------------------------------------------- Types for constructors ---------------------------------------------------------------} constructorGamma :: Int -> [DataInfo] -> Gamma constructorGamma maxStructFields dataInfos = conInfoGamma (concatMap (\info -> zip (dataInfoConstrs info) (snd (Core.getDataRepr maxStructFields info))) dataInfos) where conInfoGamma conInfos = gammaNew [(conInfoName conInfo,InfoCon (conInfoType conInfo) conRepr conInfo (conInfoRange conInfo)) | (conInfo,conRepr) <- conInfos] constructorCheckDuplicates :: ColorScheme -> [ConInfo] -> [(Range,Doc)] constructorCheckDuplicates cscheme conInfos = concatMap duplicate $ groupBy sameName conInfos where sameName ci1 ci2 = conInfoName ci1 == conInfoName ci2 duplicate (ci1:ci2:_) = [(conInfoRange ci2 ,text "Constructor" <+> color (colorSource cscheme) (pretty (conInfoName ci2)) <+> text "is already defined at" <+> text (show (conInfoRange ci1)))] duplicate _ = [] {--------------------------------------------------------------- Infer kinds for type definition groups ---------------------------------------------------------------} infTypeDefGroups :: [TypeDefGroup UserType UserKind] -> KInfer ([Core.TypeDefGroup],KGamma,Synonyms) infTypeDefGroups (tdgroup:tdgroups) = do (ctdgroup) <- infTypeDefGroup tdgroup (ctdgroups,kgamma,syns) <- extendKGamma (getRanges tdgroup) ctdgroup $ infTypeDefGroups tdgroups return (ctdgroup:ctdgroups,kgamma,syns) where getRanges (TypeDefRec tdefs) = map getRange tdefs getRanges (TypeDefNonRec tdef) = [getRange tdef] infTypeDefGroups [] = do kgamma <- getKGamma syns <- getSynonyms return ([],kgamma,syns) infTypeDefGroup :: TypeDefGroup UserType UserKind -> KInfer (Core.TypeDefGroup) infTypeDefGroup (TypeDefRec tdefs) = infTypeDefs True tdefs infTypeDefGroup (TypeDefNonRec tdef) = infTypeDefs False [tdef] infTypeDefs isRec tdefs = do infgamma <- mapM bindTypeDef tdefs -- set up recursion ctdefs <- extendInfGamma infgamma $ -- extend inference gamma, also checks for duplicates do let names = map tbinderName infgamma tdefs1 <- mapM infTypeDef (zip infgamma tdefs) mapM (resolveTypeDef isRec names) tdefs1 checkRecursion tdefs -- check for recursive type synonym definitions rather late so we spot duplicate definitions first return (Core.TypeDefGroup ctdefs) checkRecursion :: [TypeDef UserType UserType UserKind] -> KInfer () checkRecursion tdefs = if (length tdefs <= 1 || any isDataType tdefs) then return () else do addError (getRange tdefs) (text "Type synonyms cannot be recursive") return () where isDataType (DataType{}) = True isDataType _ = False {--------------------------------------------------------------- Setup type environment for recursive definitions ---------------------------------------------------------------} bindTypeDef :: TypeDef UserType UserType UserKind -> KInfer (TypeBinder InfKind) bindTypeDef tdef = do (TypeBinder name kind rngName rng) <- bindTypeBinder (typeDefBinder tdef) qname <- qualifyDef name return (TypeBinder qname kind rngName rng) bindTypeBinder :: TypeBinder UserKind -> KInfer (TypeBinder InfKind) bindTypeBinder (TypeBinder name userKind rngName rng) = do kind <- userKindToKind userKind return (TypeBinder name kind rngName rng) userKindToKind :: UserKind -> KInfer InfKind userKindToKind KindNone = freshKind userKindToKind userKind = return (KICon (convert userKind)) where convert userKind = case userKind of KindCon name rng -> KCon name KindArrow k1 k2 -> kindFun (convert k1) (convert k2) KindParens k rng -> convert k KindNone -> failure ("Kind.Infer.userKindToKind.convert: unexpected kindNone") {--------------------------------------------------------------- Infer kinds of external definitions ---------------------------------------------------------------} infExternals :: [External] -> KInfer Core.Externals infExternals externals = walk [] externals where walk names [] = return [] walk names (external:externals) = do (ext,names2) <- infExternal names external exts <- walk names2 externals return (ext:exts) infExternal :: [Name] -> External -> KInfer (Core.External,[Name]) infExternal names (External name tp nameRng rng calls vis doc) = do tp' <- infResolveType tp (Check "Externals must be values" rng) qname <- qualifyDef name let cname = let n = length (filter (==qname) names) in Core.canonicalName n qname if (isHiddenName name) then return () else do addRangeInfo nameRng (Id qname (NIValue tp') True) addRangeInfo rng (Decl "external" qname (mangle cname tp')) -- trace ("infExternal: " ++ show cname ++ ": " ++ show (pretty tp')) $ return (Core.External cname tp' (map (formatCall tp') calls) vis nameRng doc, qname:names) infExternal names (ExternalInclude include range) = return (Core.ExternalInclude include range, names) infExternal names (ExternalImport imports range) = return (Core.ExternalImport imports range, names) formatCall tp (target,ExternalInline inline) = (target,inline) formatCall tp (target,ExternalCall fname) = case target of CS -> (target,formatCS) JS -> (target,formatJS) Default -> (target,formatJS) where (foralls,preds,rho) = splitPredType tp argumentCount = case splitFunType rho of Just (args,eff,res) -> length args Nothing -> 0 arguments = "(" ++ concat (intersperse "," ["#" ++ show i | i <- [1..argumentCount]]) ++ ")" typeArguments = if null foralls then "" else ("<" ++ concat (intersperse "," ["##" ++ show i | i <- [1..length foralls]]) ++ ">") formatJS = fname ++ arguments formatCS = fname ++ typeArguments ++ arguments infResolveType :: UserType -> Context -> KInfer Type infResolveType tp ctx = do infTp <- infUserType infKindStar ctx tp resolveType M.empty False infTp {--------------------------------------------------------------- Infer kinds of definitions ---------------------------------------------------------------} infDefGroups :: [DefGroup UserType] -> KInfer [DefGroup Type] infDefGroups defgroups = mapM infDefGroup defgroups infDefGroup :: DefGroup UserType -> KInfer (DefGroup Type) infDefGroup (DefRec defs) = do defs' <- mapM infDef defs return (DefRec defs') infDefGroup (DefNonRec def) = do def' <- infDef def return (DefNonRec def') infDef :: (Def UserType) -> KInfer (Def Type) infDef (Def binder rng vis isVal doc) = do binder' <- infValueBinder binder return (Def binder' rng vis isVal doc) infValueBinder (ValueBinder name () expr nameRng rng) = do expr' <- infExpr expr return (ValueBinder name () expr' nameRng rng) infLamValueBinder (ValueBinder name mbTp mbExpr nameRng rng) = do mbTp' <- case mbTp of Nothing -> return Nothing Just tp -> do tp' <- infResolveType tp (Check "Function parameters must be values" rng) return (Just tp') mbExpr' <- case mbExpr of Nothing -> return Nothing Just expr -> do expr' <- infExpr expr return (Just expr') return (ValueBinder name mbTp' mbExpr' nameRng rng) infPatValueBinder (ValueBinder name mbTp pat nameRng rng) = do mbTp' <- case mbTp of Nothing -> return Nothing Just tp -> do tp' <- infResolveType tp (Check "Matched expressions must be values" rng) return (Just tp') pat' <- infPat pat return (ValueBinder name mbTp' pat' nameRng rng) infExpr :: Expr UserType -> KInfer (Expr Type) infExpr expr = case expr of Lam binds expr rng -> do binds' <- mapM infLamValueBinder binds expr' <- infExpr expr return (Lam binds' expr' rng) Let defs expr range -> do defs' <- infDefGroup defs expr' <- infExpr expr return (Let defs' expr' range) Bind def expr range -> do def' <- infDef def expr' <- infExpr expr return (Bind def' expr' range) App fun nargs range -> do fun' <- infExpr fun let (names,exprs) = unzip nargs exprs' <- mapM infExpr exprs return (App fun' (zip names exprs') range) Var name isOp range -> do name' <- infQualifiedName name range return (Var name' isOp range) Lit lit -> return (Lit lit) Ann expr tp range -> do expr' <- infExpr expr tp' <- infResolveType tp (Check "Expressions must be values" range) -- trace ("resolve ann: " ++ show (pretty tp')) $ return (Ann expr' tp' range) Case expr brs range -> do expr' <- infExpr expr brs' <- mapM infBranch brs return (Case expr' brs' range) Parens expr range -> do expr' <- infExpr expr return (Parens expr' range) infPat pat = case pat of PatWild range -> return (PatWild range) PatVar binder -> do binder' <- infPatValueBinder binder return (PatVar binder') PatAnn pat tp range -> do pat' <- infPat pat tp' <- infResolveType tp (Check "Patterns must be values" range) return (PatAnn pat' tp' range) PatCon name args r1 r2 -> do args' <- mapM (\(mbName,pat) -> do pat' <- infPat pat; return (mbName,pat')) args return (PatCon name args' r1 r2) PatParens pat range -> do pat' <- infPat pat return (PatParens pat' range) infBranch (Branch pattern guard body) = do pattern'<- infPat pattern guard' <- infExpr guard body' <- infExpr body return (Branch pattern' guard' body') {--------------------------------------------------------------- Infer the kinds for a type definition ---------------------------------------------------------------} infTypeDef :: (TypeBinder InfKind, TypeDef UserType UserType UserKind) -> KInfer (TypeDef (KUserType InfKind) UserType InfKind) infTypeDef (tbinder, Synonym syn args tp range vis doc) = do infgamma <- mapM bindTypeBinder args kind <- freshKind tp' <- extendInfGamma infgamma (infUserType kind (Infer range) tp) unifyBinder tbinder range infgamma kind return (Synonym tbinder infgamma tp' range vis doc) infTypeDef (tbinder, td@(DataType newtp args constructors range vis sort doc)) = do infgamma <- mapM bindTypeBinder args constructors' <- extendInfGamma infgamma (mapM infConstructor constructors) reskind <- freshKind unifyBinder tbinder range infgamma reskind return (DataType tbinder infgamma constructors' range vis sort doc) unifyBinder tbinder range infgamma reskind = do let kind = infKindFunN (map typeBinderKind infgamma) reskind unify (Infer range) range (typeBinderKind tbinder) kind typeBinderKind (TypeBinder name kind _ _) = kind infConstructor :: UserCon UserType UserType UserKind -> KInfer (UserCon (KUserType InfKind) UserType InfKind) infConstructor (UserCon name exist params rngName rng vis doc) = do infgamma <- mapM bindTypeBinder exist params' <- extendInfGamma infgamma (mapM infConValueBinder params) return (UserCon name infgamma params' rngName rng vis doc) infConValueBinder :: ValueBinder UserType (Maybe (Expr UserType)) -> KInfer (ValueBinder (KUserType InfKind) (Maybe (Expr UserType))) infConValueBinder (ValueBinder name tp mbExpr nameRng rng) = do tp' <- infUserType infKindStar (Check "Constructor parameters must be values" rng) tp return (ValueBinder name tp' mbExpr nameRng rng) infUserType :: InfKind -> Context -> UserType -> KInfer (KUserType InfKind) infUserType expected context userType = let range = getRange userType in case userType of TpQuan quant tname tp rng -> do unify context range expected infKindStar tname' <- bindTypeBinder tname tp' <- extendInfGamma [tname'] $ infUserType infKindStar (checkQuant range) tp return (TpQuan quant tname' tp' rng) TpQual preds tp -> do preds' <- mapM (infUserType (KICon kindPred) (checkPred range)) preds tp' <- infUserType expected context tp return (TpQual preds' tp') TpFun args effect tp rng -> do unify context range expected infKindStar args' <- mapM (infParam infKindStar (checkArg range)) args -- somewhat involved since we auto-wrap labels L into effects E here ekind <- freshKind etp <- infUserType ekind (checkEff range) effect skind <- subst ekind effect' <- case skind of KICon kind | kind == kindLabel -> return (makeEffectExtend etp makeEffectEmpty) _ -> do unify (checkEff range) range (KICon kindEffect) skind return etp tp' <- infUserType infKindStar (checkRes range) tp return (TpFun args' effect' tp' rng) TpApp tp@(TpCon name _) [lab,tl] rng | name == nameEffectExtend -> do tp' <- infUserType (infKindFunN [KICon kindLabel,KICon kindEffect] expected) (checkApp range) tp tl' <- infUserType (KICon kindEffect) (checkExtendTail range) tl -- somewhat involved since we allow fixed effects to be used as labels -- the append nodes are just used temporarily (see resolveApp in this file) lkind <- freshKind ltp <- infUserType lkind (Infer range) lab skind <- subst lkind case skind of KICon kind | kind == kindEffect -> return (makeEffectAppend ltp tl') _ -> do unify (checkExtendLabel range) range (KICon kindLabel) skind return (TpApp tp' [ltp,tl'] rng) TpApp tp args rng -> do kinds <- mapM (\arg -> freshKind) args tp' <- infUserType (infKindFunN kinds expected) (checkApp range) tp args' <- mapM (\(kind,arg) -> infUserType kind (Infer range) arg) (zip kinds args) return (TpApp tp' args' rng) TpVar name rng -> do (qname,kind) <- findInfKind name rng unify context range expected kind return (TpVar qname rng) TpCon name rng -> do (qname,kind) <- findInfKind name rng unify context range expected kind return (TpCon qname rng) TpParens tp rng -> do tp' <- infUserType expected context tp return (TpParens tp' rng) TpAnn tp userKind -> do kind <- userKindToKind userKind unify context range expected kind tp' <- infUserType kind (checkAnnot range) tp return (TpAnn tp' kind) infParam expected context (name,tp) = do tp' <- infUserType expected context tp return (name,tp') checkQuant range = Check "Can only quantify over types" range checkPred range = Check "The left-hand side of a \"=>\" can only contain predicates" range checkArg range = Check "The parameters of a function type must be types" range checkEff range = Check "The effect of a function type must be an effect type" range checkRes range = Check "The result of a function type must be a type" range checkAnnot range = Check "The inferred kind doesn't match the annotated kind" range checkApp range = Check "The type cannot be applied to those arguments" range checkExtendTail r = Check "The extension of an effect must be an effect type" r checkExtendLabel r= Check "The elements of an effect must be effect constants" r {--------------------------------------------------------------- Resolve kinds: from InfKind to Kind, and UserType to Type ---------------------------------------------------------------} resolveTypeDef :: Bool -> [Name] -> TypeDef (KUserType InfKind) UserType InfKind -> KInfer (Core.TypeDef) resolveTypeDef isRec recNames (Synonym syn params tp range vis doc) = do syn' <- resolveTypeBinderDef syn params' <- mapM resolveTypeBinder params typeVars <- mapM (\param -> freshTypeVar param Bound) params' let tvarMap = M.fromList (zip (map getName params') typeVars) tp' <- resolveType tvarMap True tp -- eta-expand type synonyms let kind = typeBinderKind syn' arity = kindArity kind etaKinds = drop (length typeVars) arity (etaTp,etaParams) <- if (null etaKinds) then return (tp',typeVars) else do etaVars <- mapM (\kind -> do id <- uniqueId "eta"; return (TypeVar id kind Bound)) etaKinds return (typeApp tp' (map TVar etaVars), typeVars ++ etaVars) -- trace (showTypeBinder syn') $ addRangeInfo range (Decl "alias" (getName syn') (mangleTypeName (getName syn'))) let synInfo = SynInfo (getName syn') (typeBinderKind syn') etaParams etaTp (maxSynonymRank etaTp + 1) range doc return (Core.Synonym synInfo vis) where kindArity (KApp (KApp kcon k1) k2) | kcon == kindArrow = k1 : kindArity k2 kindArity _ = [] resolveTypeDef isRec recNames (DataType newtp params constructors range vis sort doc) = do newtp' <- resolveTypeBinderDef newtp params' <- mapM resolveTypeBinder params let typeResult = TCon (TypeCon (getName newtp') (typeBinderKind newtp')) typeVars <- let (kargs,kres) = extractKindFun (typeBinderKind newtp') in if (null params' && not (null kargs)) then mapM (\karg -> do{ id <- uniqueId "k"; return (TypeVar id karg Bound) }) kargs -- invent parameters if they are not given (and it has an arrow kind) else mapM (\param -> freshTypeVar param Bound) params' let tvarMap = M.fromList (zip (map getName params') typeVars) consinfos <- mapM (resolveConstructor (getName newtp') sort (length constructors == 1) typeResult typeVars tvarMap) constructors let (constructors',infos) = unzip consinfos if (sort == Retractive) then return () else if (any (occursNegative recNames) (concatMap (map snd . conInfoParams) infos)) then do cs <- getColorScheme addError range (text "Type" <+> color (colorType cs) (pretty (unqualify (getName newtp'))) <+> text "is declared as being (co)inductive but it occurs" <$> text " recursively in a negative position." <$> text " hint: declare it as a 'rectype' to allow negative occurrences") else return () -- trace (showTypeBinder newtp') $ addRangeInfo range (Decl (show sort) (getName newtp') (mangleTypeName (getName newtp'))) let dataInfo = DataInfo sort (getName newtp') (typeBinderKind newtp') typeVars infos range isRec doc return (Core.Data dataInfo vis (map conVis constructors)) where conVis (UserCon name exist params rngName rng vis _) = vis occursNegative :: [Name] -> Type -> Bool occursNegative names tp = occurs names False tp occurs :: [Name] -> Bool -> Type -> Bool occurs names isNeg tp = case tp of TForall vars preds tp -> occurs names isNeg tp TFun args effect result -> any (occurs names (not isNeg)) (map snd args) || occurs names isNeg effect || occurs names isNeg result TCon tcon -> if (typeConName tcon `elem` names) then isNeg else False TVar tvar -> False TApp tp args -> any (occurs names isNeg) (tp:args) TSyn syn xs tp -> occurs names isNeg tp showTypeBinder :: TypeBinder Kind -> String showTypeBinder (TypeBinder name kind _ _) = show name ++ ": " ++ show kind resolveTypeBinderDef :: TypeBinder InfKind -> KInfer (TypeBinder Kind) resolveTypeBinderDef (TypeBinder name infkind rngName rng) = do infkind' <- resolveKind infkind qname <- qualifyDef name addRangeInfo rngName (Id qname (NITypeCon infkind') True) return (TypeBinder qname infkind' rngName rng) resolveTypeBinder :: TypeBinder InfKind -> KInfer (TypeBinder Kind) resolveTypeBinder (TypeBinder name infkind rngName rng) = do infkind' <- resolveKind infkind addRangeInfo rngName (Id name (NITypeCon infkind') True) return (TypeBinder name infkind' rngName rng) resolveKind :: InfKind -> KInfer Kind resolveKind infkind = do skind <- subst infkind return (resolve skind) where resolve (KIVar id) = kindStar -- default unconstrained parameter to kind star resolve (KICon kind) = kind resolve (KIApp k1 k2) = KApp (resolve k1) (resolve k2) resolveConstructor :: Name -> DataKind -> Bool -> Type -> [TypeVar] -> M.NameMap TypeVar -> UserCon (KUserType InfKind) UserType InfKind -> KInfer (UserCon Type Type Kind, ConInfo) resolveConstructor typeName typeSort isSingleton typeResult typeParams idmap (UserCon name exist params rngName rng vis doc) = do qname <- qualifyDef name exist' <- mapM resolveTypeBinder exist existVars <- mapM (\ename -> freshTypeVar ename Bound) exist' let idmap' = M.union (M.fromList (zip (map getName exist) existVars)) idmap -- ASSUME: left-biased union params' <- mapM (resolveConParam idmap') params -- mapM (resolveType idmap' False) params let result = typeApp typeResult (map TVar typeParams) scheme = quantifyType (typeParams ++ existVars) $ if (null params') then result else typeFun [(binderName p, binderType p) | p <- params'] typeTotal result addRangeInfo rngName (Id qname (NICon scheme) True) addRangeInfo rng (Decl "con" qname (mangleConName qname)) return (UserCon qname exist' params' rngName rng vis doc ,ConInfo qname typeName existVars (map (\(i,b) -> (if (nameIsNil (binderName b)) then newFieldName i else binderName b, binderType b)) (zip [1..] params')) scheme typeSort rngName (map binderNameRange params') isSingleton doc) resolveConParam :: M.NameMap TypeVar -> ValueBinder (KUserType InfKind) (Maybe (Expr UserType)) -> KInfer (ValueBinder Type (Maybe (Expr Type))) resolveConParam idmap vb = do tp <- resolveType idmap False (binderType vb) expr <- case (binderExpr vb) of Nothing -> return Nothing Just e -> {- do e' <- infExpr e return (Just e') -} return (Just (failure "Kind.Infer.resolveConParam: optional parameter expression in constructor")) addRangeInfo (binderNameRange vb) (Id (binderName vb) (NIValue tp) True) return (vb{ binderType = tp, binderExpr = expr }) -- | @resolveType@ takes: a map from locally quantified type name variables to types, -- a boolean that is 'True' if partially applied type synonyms are allowed (i.e. when -- these are arguments to type synonyms themselves), a user type with inference kinds, -- and it returns a fully resolved type. resolveType :: M.NameMap TypeVar -> Bool -> KUserType InfKind -> KInfer Type resolveType idmap partialSyn userType = case userType of TpQuan QForall tname tp rng -> do tname' <- resolveTypeBinder tname tvar <- freshTypeVar tname' Bound tp' <- resolveType (M.insert (getName tname) tvar idmap) False tp return (quantifyType [tvar] tp') TpQuan QSome tname tp rng -> do tname' <- resolveTypeBinder tname tvar <- freshTypeVar tname' Meta tp' <- resolveType (M.insert (getName tname) tvar idmap) False tp -- trace ("Kind.Infer.Some") $ return tp' TpQuan QExists tname tp rng -> todo "Kind.Infer.resolveType: existentials are not supported yet" TpQual preds tp -> do preds' <- mapM (resolvePredicate idmap) preds tp' <- resolveType idmap False tp return (qualifyType preds' tp') TpFun args effect tp rng -> do args' <- mapM resolveParam args effect' <- resolveType idmap False effect tp' <- resolveType idmap False tp return (TFun args' effect' tp') TpApp tp args rng -> resolveApp idmap partialSyn (collectArgs tp args) rng TpVar name rng -> resolveApp idmap partialSyn (userType,[]) rng TpCon name rng -> resolveApp idmap partialSyn (userType,[]) rng TpParens tp rng -> resolveType idmap partialSyn tp TpAnn tp userKind -> resolveType idmap partialSyn tp where resolveParam (name,tp) = do tp' <- resolveType idmap False tp return (name,tp') collectArgs tp args = case tp of TpApp tp' args' _ -> collectArgs tp' (args' ++ args) TpParens tp' _ -> collectArgs tp' args TpAnn tp' _ -> collectArgs tp' args _ -> (tp, args) resolvePredicate :: M.NameMap TypeVar -> KUserType InfKind -> KInfer Pred resolvePredicate idmap tp = do tp' <- resolveType idmap False tp case tp' of TApp (TCon tc) targs -> return (PredIFace (typeconName tc) targs) TCon tc -> return (PredIFace (typeconName tc) []) _ -> failure ("Kind.Infer.resolvePredicate: invalid predicate: " ++ show tp') resolveApp idmap partialSyn (TpVar name r,args) rng = do (tp',kind) <- case M.lookup name idmap of Nothing -> do cs <- getColorScheme -- failure ("Kind.Infer.ResolveApp: cannot find: " ++ show name ++ " at " ++ show rng) addError rng (text "Type variable" <+> color (colorType cs) (pretty name) <+> text "is undefined" <$> text " hint: bind the variable using" <+> color (colorType cs) (text "forall<" <> pretty name <> text ">")) id <- uniqueId (show name) return (TVar (TypeVar id kindStar Bound), kindStar) Just tvar -> return (TVar tvar, typevarKind tvar) if (not (isImplicitTypeVarName name)) then addRangeInfo r (Id name (NITypeVar kind) False) else return () args' <- mapM (resolveType idmap False) args return (typeApp tp' args') resolveApp idmap partialSyn (TpCon name r,[fixed,ext]) rng | name == nameEffectAppend = do fixed' <- resolveType idmap False fixed ext' <- resolveType idmap False ext let (ls,tl) = extractOrderedEffect fixed' if isEffectEmpty tl then return () else addError rng (text "Effects can only have one extension point") return (shallowEffectExtend fixed' ext') resolveApp idmap partialSyn (TpCon name r,args) rng = do (qname,ikind) <- findInfKind name rng kind <- resolveKind ikind addRangeInfo r (Id qname (NITypeCon kind) False) mbSyn <- lookupSynInfo name case mbSyn of Just syn@(SynInfo name kind params tp rank range doc) -> do -- check over/under application if (not partialSyn && length args < length params) then do cs <- getColorScheme addError rng (text "Type alias" <+> color (colorType cs) (pretty name) <+> text "has too few arguments") else if (length args > length params) then do cs <- getColorScheme addError rng (text "Type alias" <+> color (colorType cs) (pretty name) <+> text "has too many arguments") else return () args' <- mapM (resolveType idmap True) args -- partially applied synonyms are allowed in synonym applications let tsyn = (TSyn (TypeSyn name kind rank (Just syn)) args' (subNew (zip params args') |-> tp)) -- trace ("resolved type syn: " ++ show (pretty syn)) $ return tsyn -- NOTE: on partially applied type synonyms, we get a funky body type with free parameters but this -- is only inside synonyms arguments so we are ok. Nothing -> do args' <- mapM (resolveType idmap False) args return (typeApp (TCon (TypeCon name kind)) args') resolveApp idmap partialSyn _ rng = failure "Kind.Infer.resolveApp: this case should never occur after kind checking" makeEffectAppend fixed ext = TpApp (TpCon nameEffectAppend rangeNull) [fixed,ext] rangeNull makeEffectExtend (label) ext = TpApp (TpCon nameEffectExtend rangeNull) [label,ext] rangeNull makeEffectEmpty = TpCon nameEffectEmpty rangeNull
lpeterse/koka
src/Kind/Infer.hs
apache-2.0
42,775
0
30
12,996
12,103
5,938
6,165
666
13
{-# OPTIONS_GHC -fno-warn-unused-imports -fno-warn-missing-signatures -fno-warn-orphans -fno-warn-unused-imports -fno-warn-unused-binds -fno-warn-unused-do-bind #-} module Arbitrary.ModulePath where import Test.QuickCheck import Data.Char import Data.ModulePath import Control.Applicative hiding (empty) import Prelude hiding (FilePath) import qualified Data.List as L data Module = Module { str :: String } deriving Show instance Arbitrary Module where arbitrary = toModule $ choose ('a','p') toModule :: Gen Char -> Gen Module toModule subpath = do modLen <- choose (1, 2) uncased <- vectorOf modLen subpath return . Module $ L.map toUpper (take 1 uncased) ++ L.drop 1 uncased instance Arbitrary ModulePath where arbitrary = do pathLen <- choose (1, 3) ModulePath . map str <$> vectorOf pathLen arbitrary toModulePath :: Gen Char -> Gen ModulePath toModulePath subpath = do pathLen <- choose (1, 2) ModulePath . map str <$> vectorOf pathLen (toModule subpath)
jfeltz/tasty-integrate
tests/Arbitrary/ModulePath.hs
bsd-2-clause
1,004
0
11
173
294
152
142
24
1
{-# LANGUAGE Haskell2010 #-} {-# LANGUAGE DataKinds, GADTs, KindSignatures, PatternSynonyms, TypeOperators, ViewPatterns #-} module BundledPatterns2 (Vec((:>), Empty), RTree(..)) where import GHC.TypeLits import BundledPatterns pattern Empty :: Vec 0 a pattern Empty <- Nil
haskell/haddock
html-test/src/BundledPatterns2.hs
bsd-2-clause
290
0
6
49
54
35
19
11
0
{-# OPTIONS_GHC -w #-} {-# OPTIONS -fglasgow-exts -cpp #-} {-# OPTIONS_GHC -fno-warn-incomplete-patterns -fno-warn-overlapping-patterns #-} module ParTree where import AbsTree import LexTree import ErrM import qualified Data.Array as Happy_Data_Array import qualified GHC.Exts as Happy_GHC_Exts -- parser produced by Happy Version 1.18.10 newtype HappyAbsSyn = HappyAbsSyn HappyAny #if __GLASGOW_HASKELL__ >= 607 type HappyAny = Happy_GHC_Exts.Any #else type HappyAny = forall a . a #endif happyIn5 :: (Ident) -> (HappyAbsSyn ) happyIn5 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn5 #-} happyOut5 :: (HappyAbsSyn ) -> (Ident) happyOut5 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut5 #-} happyIn6 :: (String) -> (HappyAbsSyn ) happyIn6 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn6 #-} happyOut6 :: (HappyAbsSyn ) -> (String) happyOut6 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut6 #-} happyIn7 :: (Treebank) -> (HappyAbsSyn ) happyIn7 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn7 #-} happyOut7 :: (HappyAbsSyn ) -> (Treebank) happyOut7 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut7 #-} happyIn8 :: (AnnotGTree) -> (HappyAbsSyn ) happyIn8 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn8 #-} happyOut8 :: (HappyAbsSyn ) -> (AnnotGTree) happyOut8 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut8 #-} happyIn9 :: ([AnnotGTree]) -> (HappyAbsSyn ) happyIn9 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn9 #-} happyOut9 :: (HappyAbsSyn ) -> ([AnnotGTree]) happyOut9 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut9 #-} happyIn10 :: (GAnnot) -> (HappyAbsSyn ) happyIn10 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn10 #-} happyOut10 :: (HappyAbsSyn ) -> (GAnnot) happyOut10 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut10 #-} happyIn11 :: (GTree) -> (HappyAbsSyn ) happyIn11 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn11 #-} happyOut11 :: (HappyAbsSyn ) -> (GTree) happyOut11 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut11 #-} happyIn12 :: (GTree) -> (HappyAbsSyn ) happyIn12 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn12 #-} happyOut12 :: (HappyAbsSyn ) -> (GTree) happyOut12 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut12 #-} happyIn13 :: ([GTree]) -> (HappyAbsSyn ) happyIn13 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn13 #-} happyOut13 :: (HappyAbsSyn ) -> ([GTree]) happyOut13 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut13 #-} happyIn14 :: (GAtom) -> (HappyAbsSyn ) happyIn14 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyIn14 #-} happyOut14 :: (HappyAbsSyn ) -> (GAtom) happyOut14 x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOut14 #-} happyInTok :: (Token) -> (HappyAbsSyn ) happyInTok x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyInTok #-} happyOutTok :: (HappyAbsSyn ) -> (Token) happyOutTok x = Happy_GHC_Exts.unsafeCoerce# x {-# INLINE happyOutTok #-} happyActOffsets :: HappyAddr happyActOffsets = HappyA# "\x00\x00\x22\x00\xfd\xff\x00\x00\x00\x00\x00\x00\xf9\xff\x00\x00\x22\x00\x22\x00\x00\x00\x00\x00\xf9\xff\x2a\x00\x00\x00\x22\x00\x00\x00\x00\x00\x00\x00\x04\x00\x22\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"# happyGotoOffsets :: HappyAddr happyGotoOffsets = HappyA# "\x1d\x00\x1c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x12\x00\x0f\x00\x00\x00\x00\x00\x00\x00\x1b\x00\x00\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"# happyDefActions :: HappyAddr happyDefActions = HappyA# "\xf9\xff\x00\x00\x00\x00\xfd\xff\xee\xff\xec\xff\x00\x00\xf3\xff\xf2\xff\x00\x00\xed\xff\xfc\xff\x00\x00\xfb\xff\xf8\xff\x00\x00\xf5\xff\xf6\xff\xf7\xff\x00\x00\xf0\xff\xf4\xff\xf2\xff\xef\xff\xf1\xff\xfa\xff"# happyCheck :: HappyAddr happyCheck = HappyA# "\xff\xff\x00\x00\x01\x00\x0a\x00\x07\x00\x00\x00\x01\x00\x03\x00\x07\x00\x08\x00\x09\x00\x06\x00\x07\x00\xff\xff\x09\x00\x00\x00\x01\x00\xff\xff\x00\x00\x01\x00\xff\xff\x06\x00\x07\x00\xff\xff\x09\x00\x07\x00\x08\x00\x09\x00\x00\x00\x01\x00\x03\x00\x02\x00\x05\x00\x04\x00\x06\x00\x07\x00\x02\x00\x09\x00\xff\xff\xff\xff\x06\x00\x07\x00\x08\x00\x01\x00\xff\xff\xff\xff\x04\x00\x05\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff"# happyTable :: HappyAddr happyTable = HappyA# "\x00\x00\x04\x00\x05\x00\xff\xff\x04\x00\x04\x00\x05\x00\x19\x00\x14\x00\x17\x00\x16\x00\x19\x00\x07\x00\x00\x00\x08\x00\x04\x00\x05\x00\x00\x00\x04\x00\x05\x00\x00\x00\x13\x00\x07\x00\x00\x00\x08\x00\x14\x00\x15\x00\x16\x00\x04\x00\x05\x00\x0e\x00\x0c\x00\x0f\x00\x0d\x00\x06\x00\x07\x00\x0a\x00\x08\x00\x00\x00\x00\x00\x0b\x00\x04\x00\x0c\x00\x11\x00\x00\x00\x00\x00\x12\x00\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"# happyReduceArr = Happy_Data_Array.array (2, 19) [ (2 , happyReduce_2), (3 , happyReduce_3), (4 , happyReduce_4), (5 , happyReduce_5), (6 , happyReduce_6), (7 , happyReduce_7), (8 , happyReduce_8), (9 , happyReduce_9), (10 , happyReduce_10), (11 , happyReduce_11), (12 , happyReduce_12), (13 , happyReduce_13), (14 , happyReduce_14), (15 , happyReduce_15), (16 , happyReduce_16), (17 , happyReduce_17), (18 , happyReduce_18), (19 , happyReduce_19) ] happy_n_terms = 11 :: Int happy_n_nonterms = 10 :: Int happyReduce_2 = happySpecReduce_1 0# happyReduction_2 happyReduction_2 happy_x_1 = case happyOutTok happy_x_1 of { (PT _ (TV happy_var_1)) -> happyIn5 (Ident happy_var_1 )} happyReduce_3 = happySpecReduce_1 1# happyReduction_3 happyReduction_3 happy_x_1 = case happyOutTok happy_x_1 of { (PT _ (TL happy_var_1)) -> happyIn6 (happy_var_1 )} happyReduce_4 = happySpecReduce_1 2# happyReduction_4 happyReduction_4 happy_x_1 = case happyOut9 happy_x_1 of { happy_var_1 -> happyIn7 (GB (reverse happy_var_1) )} happyReduce_5 = happySpecReduce_2 3# happyReduction_5 happyReduction_5 happy_x_2 happy_x_1 = case happyOut10 happy_x_1 of { happy_var_1 -> case happyOut11 happy_x_2 of { happy_var_2 -> happyIn8 (AG happy_var_1 happy_var_2 )}} happyReduce_6 = happySpecReduce_0 4# happyReduction_6 happyReduction_6 = happyIn9 ([] ) happyReduce_7 = happySpecReduce_2 4# happyReduction_7 happyReduction_7 happy_x_2 happy_x_1 = case happyOut9 happy_x_1 of { happy_var_1 -> case happyOut8 happy_x_2 of { happy_var_2 -> happyIn9 (flip (:) happy_var_1 happy_var_2 )}} happyReduce_8 = happySpecReduce_1 5# happyReduction_8 happyReduction_8 happy_x_1 = happyIn10 (GAPlus ) happyReduce_9 = happySpecReduce_1 5# happyReduction_9 happyReduction_9 happy_x_1 = happyIn10 (GAStar ) happyReduce_10 = happySpecReduce_1 5# happyReduction_10 happyReduction_10 happy_x_1 = happyIn10 (GAHash ) happyReduce_11 = happySpecReduce_2 6# happyReduction_11 happyReduction_11 happy_x_2 happy_x_1 = case happyOut14 happy_x_1 of { happy_var_1 -> case happyOut13 happy_x_2 of { happy_var_2 -> happyIn11 (GTApp happy_var_1 happy_var_2 )}} happyReduce_12 = happySpecReduce_1 6# happyReduction_12 happyReduction_12 happy_x_1 = case happyOut12 happy_x_1 of { happy_var_1 -> happyIn11 (happy_var_1 )} happyReduce_13 = happySpecReduce_1 7# happyReduction_13 happyReduction_13 happy_x_1 = case happyOut14 happy_x_1 of { happy_var_1 -> happyIn12 (GTAtom happy_var_1 )} happyReduce_14 = happySpecReduce_3 7# happyReduction_14 happyReduction_14 happy_x_3 happy_x_2 happy_x_1 = case happyOut11 happy_x_2 of { happy_var_2 -> happyIn12 (happy_var_2 )} happyReduce_15 = happySpecReduce_1 8# happyReduction_15 happyReduction_15 happy_x_1 = case happyOut12 happy_x_1 of { happy_var_1 -> happyIn13 ((:[]) happy_var_1 )} happyReduce_16 = happySpecReduce_2 8# happyReduction_16 happyReduction_16 happy_x_2 happy_x_1 = case happyOut12 happy_x_1 of { happy_var_1 -> case happyOut13 happy_x_2 of { happy_var_2 -> happyIn13 ((:) happy_var_1 happy_var_2 )}} happyReduce_17 = happySpecReduce_1 9# happyReduction_17 happyReduction_17 happy_x_1 = case happyOut5 happy_x_1 of { happy_var_1 -> happyIn14 (GFun happy_var_1 )} happyReduce_18 = happySpecReduce_1 9# happyReduction_18 happyReduction_18 happy_x_1 = happyIn14 (GMeta ) happyReduce_19 = happySpecReduce_1 9# happyReduction_19 happyReduction_19 happy_x_1 = case happyOut6 happy_x_1 of { happy_var_1 -> happyIn14 (GStr happy_var_1 )} happyNewToken action sts stk [] = happyDoAction 10# notHappyAtAll action sts stk [] happyNewToken action sts stk (tk:tks) = let cont i = happyDoAction i tk action sts stk tks in case tk of { PT _ (TS _ 1) -> cont 1#; PT _ (TS _ 2) -> cont 2#; PT _ (TS _ 3) -> cont 3#; PT _ (TS _ 4) -> cont 4#; PT _ (TS _ 5) -> cont 5#; PT _ (TS _ 6) -> cont 6#; PT _ (TV happy_dollar_dollar) -> cont 7#; PT _ (TL happy_dollar_dollar) -> cont 8#; _ -> cont 9#; _ -> happyError' (tk:tks) } happyError_ 10# tk tks = happyError' tks happyError_ _ tk tks = happyError' (tk:tks) happyThen :: () => Err a -> (a -> Err b) -> Err b happyThen = (thenM) happyReturn :: () => a -> Err a happyReturn = (returnM) happyThen1 m k tks = (thenM) m (\a -> k a tks) happyReturn1 :: () => a -> b -> Err a happyReturn1 = \a tks -> (returnM) a happyError' :: () => [(Token)] -> Err a happyError' = happyError pTreebank tks = happySomeParser where happySomeParser = happyThen (happyParse 0# tks) (\x -> happyReturn (happyOut7 x)) pGTree tks = happySomeParser where happySomeParser = happyThen (happyParse 1# tks) (\x -> happyReturn (happyOut11 x)) happySeq = happyDontSeq returnM :: a -> Err a returnM = return thenM :: Err a -> (a -> Err b) -> Err b thenM = (>>=) happyError :: [Token] -> Err a happyError ts = Bad $ "syntax error at " ++ tokenPos ts ++ case ts of [] -> [] [Err _] -> " due to lexer error" _ -> " before " ++ unwords (map (id . prToken) (take 4 ts)) myLexer = tokens {-# LINE 1 "templates/GenericTemplate.hs" #-} {-# LINE 1 "templates/GenericTemplate.hs" #-} {-# LINE 1 "<built-in>" #-} {-# LINE 1 "<command-line>" #-} {-# LINE 1 "templates/GenericTemplate.hs" #-} -- Id: GenericTemplate.hs,v 1.26 2005/01/14 14:47:22 simonmar Exp {-# LINE 30 "templates/GenericTemplate.hs" #-} data Happy_IntList = HappyCons Happy_GHC_Exts.Int# Happy_IntList {-# LINE 51 "templates/GenericTemplate.hs" #-} {-# LINE 61 "templates/GenericTemplate.hs" #-} {-# LINE 70 "templates/GenericTemplate.hs" #-} infixr 9 `HappyStk` data HappyStk a = HappyStk a (HappyStk a) ----------------------------------------------------------------------------- -- starting the parse happyParse start_state = happyNewToken start_state notHappyAtAll notHappyAtAll ----------------------------------------------------------------------------- -- Accepting the parse -- If the current token is 0#, it means we've just accepted a partial -- parse (a %partial parser). We must ignore the saved token on the top of -- the stack in this case. happyAccept 0# tk st sts (_ `HappyStk` ans `HappyStk` _) = happyReturn1 ans happyAccept j tk st sts (HappyStk ans _) = (happyTcHack j (happyTcHack st)) (happyReturn1 ans) ----------------------------------------------------------------------------- -- Arrays only: do the next action happyDoAction i tk st = {- nothing -} case action of 0# -> {- nothing -} happyFail i tk st -1# -> {- nothing -} happyAccept i tk st n | (n Happy_GHC_Exts.<# (0# :: Happy_GHC_Exts.Int#)) -> {- nothing -} (happyReduceArr Happy_Data_Array.! rule) i tk st where rule = (Happy_GHC_Exts.I# ((Happy_GHC_Exts.negateInt# ((n Happy_GHC_Exts.+# (1# :: Happy_GHC_Exts.Int#)))))) n -> {- nothing -} happyShift new_state i tk st where (new_state) = (n Happy_GHC_Exts.-# (1# :: Happy_GHC_Exts.Int#)) where (off) = indexShortOffAddr happyActOffsets st (off_i) = (off Happy_GHC_Exts.+# i) check = if (off_i Happy_GHC_Exts.>=# (0# :: Happy_GHC_Exts.Int#)) then (indexShortOffAddr happyCheck off_i Happy_GHC_Exts.==# i) else False (action) | check = indexShortOffAddr happyTable off_i | otherwise = indexShortOffAddr happyDefActions st {-# LINE 130 "templates/GenericTemplate.hs" #-} indexShortOffAddr (HappyA# arr) off = Happy_GHC_Exts.narrow16Int# i where i = Happy_GHC_Exts.word2Int# (Happy_GHC_Exts.or# (Happy_GHC_Exts.uncheckedShiftL# high 8#) low) high = Happy_GHC_Exts.int2Word# (Happy_GHC_Exts.ord# (Happy_GHC_Exts.indexCharOffAddr# arr (off' Happy_GHC_Exts.+# 1#))) low = Happy_GHC_Exts.int2Word# (Happy_GHC_Exts.ord# (Happy_GHC_Exts.indexCharOffAddr# arr off')) off' = off Happy_GHC_Exts.*# 2# data HappyAddr = HappyA# Happy_GHC_Exts.Addr# ----------------------------------------------------------------------------- -- HappyState data type (not arrays) {-# LINE 163 "templates/GenericTemplate.hs" #-} ----------------------------------------------------------------------------- -- Shifting a token happyShift new_state 0# tk st sts stk@(x `HappyStk` _) = let (i) = (case Happy_GHC_Exts.unsafeCoerce# x of { (Happy_GHC_Exts.I# (i)) -> i }) in -- trace "shifting the error token" $ happyDoAction i tk new_state (HappyCons (st) (sts)) (stk) happyShift new_state i tk st sts stk = happyNewToken new_state (HappyCons (st) (sts)) ((happyInTok (tk))`HappyStk`stk) -- happyReduce is specialised for the common cases. happySpecReduce_0 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_0 nt fn j tk st@((action)) sts stk = happyGoto nt j tk st (HappyCons (st) (sts)) (fn `HappyStk` stk) happySpecReduce_1 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_1 nt fn j tk _ sts@((HappyCons (st@(action)) (_))) (v1`HappyStk`stk') = let r = fn v1 in happySeq r (happyGoto nt j tk st sts (r `HappyStk` stk')) happySpecReduce_2 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_2 nt fn j tk _ (HappyCons (_) (sts@((HappyCons (st@(action)) (_))))) (v1`HappyStk`v2`HappyStk`stk') = let r = fn v1 v2 in happySeq r (happyGoto nt j tk st sts (r `HappyStk` stk')) happySpecReduce_3 i fn 0# tk st sts stk = happyFail 0# tk st sts stk happySpecReduce_3 nt fn j tk _ (HappyCons (_) ((HappyCons (_) (sts@((HappyCons (st@(action)) (_))))))) (v1`HappyStk`v2`HappyStk`v3`HappyStk`stk') = let r = fn v1 v2 v3 in happySeq r (happyGoto nt j tk st sts (r `HappyStk` stk')) happyReduce k i fn 0# tk st sts stk = happyFail 0# tk st sts stk happyReduce k nt fn j tk st sts stk = case happyDrop (k Happy_GHC_Exts.-# (1# :: Happy_GHC_Exts.Int#)) sts of sts1@((HappyCons (st1@(action)) (_))) -> let r = fn stk in -- it doesn't hurt to always seq here... happyDoSeq r (happyGoto nt j tk st1 sts1 r) happyMonadReduce k nt fn 0# tk st sts stk = happyFail 0# tk st sts stk happyMonadReduce k nt fn j tk st sts stk = happyThen1 (fn stk tk) (\r -> happyGoto nt j tk st1 sts1 (r `HappyStk` drop_stk)) where (sts1@((HappyCons (st1@(action)) (_)))) = happyDrop k (HappyCons (st) (sts)) drop_stk = happyDropStk k stk happyMonad2Reduce k nt fn 0# tk st sts stk = happyFail 0# tk st sts stk happyMonad2Reduce k nt fn j tk st sts stk = happyThen1 (fn stk tk) (\r -> happyNewToken new_state sts1 (r `HappyStk` drop_stk)) where (sts1@((HappyCons (st1@(action)) (_)))) = happyDrop k (HappyCons (st) (sts)) drop_stk = happyDropStk k stk (off) = indexShortOffAddr happyGotoOffsets st1 (off_i) = (off Happy_GHC_Exts.+# nt) (new_state) = indexShortOffAddr happyTable off_i happyDrop 0# l = l happyDrop n (HappyCons (_) (t)) = happyDrop (n Happy_GHC_Exts.-# (1# :: Happy_GHC_Exts.Int#)) t happyDropStk 0# l = l happyDropStk n (x `HappyStk` xs) = happyDropStk (n Happy_GHC_Exts.-# (1#::Happy_GHC_Exts.Int#)) xs ----------------------------------------------------------------------------- -- Moving to a new state after a reduction happyGoto nt j tk st = {- nothing -} happyDoAction j tk new_state where (off) = indexShortOffAddr happyGotoOffsets st (off_i) = (off Happy_GHC_Exts.+# nt) (new_state) = indexShortOffAddr happyTable off_i ----------------------------------------------------------------------------- -- Error recovery (0# is the error token) -- parse error if we are in recovery and we fail again happyFail 0# tk old_st _ stk@(x `HappyStk` _) = let (i) = (case Happy_GHC_Exts.unsafeCoerce# x of { (Happy_GHC_Exts.I# (i)) -> i }) in -- trace "failing" $ happyError_ i tk {- We don't need state discarding for our restricted implementation of "error". In fact, it can cause some bogus parses, so I've disabled it for now --SDM -- discard a state happyFail 0# tk old_st (HappyCons ((action)) (sts)) (saved_tok `HappyStk` _ `HappyStk` stk) = -- trace ("discarding state, depth " ++ show (length stk)) $ happyDoAction 0# tk action sts ((saved_tok`HappyStk`stk)) -} -- Enter error recovery: generate an error token, -- save the old token and carry on. happyFail i tk (action) sts stk = -- trace "entering error recovery" $ happyDoAction 0# tk action sts ( (Happy_GHC_Exts.unsafeCoerce# (Happy_GHC_Exts.I# (i))) `HappyStk` stk) -- Internal happy errors: notHappyAtAll :: a notHappyAtAll = error "Internal Happy error\n" ----------------------------------------------------------------------------- -- Hack to get the typechecker to accept our action functions happyTcHack :: Happy_GHC_Exts.Int# -> a -> a happyTcHack x y = y {-# INLINE happyTcHack #-} ----------------------------------------------------------------------------- -- Seq-ing. If the --strict flag is given, then Happy emits -- happySeq = happyDoSeq -- otherwise it emits -- happySeq = happyDontSeq happyDoSeq, happyDontSeq :: a -> b -> b happyDoSeq a b = a `seq` b happyDontSeq a b = b ----------------------------------------------------------------------------- -- Don't inline any functions from the template. GHC has a nasty habit -- of deciding to inline happyGoto everywhere, which increases the size of -- the generated parser quite a bit. {-# NOINLINE happyDoAction #-} {-# NOINLINE happyTable #-} {-# NOINLINE happyCheck #-} {-# NOINLINE happyActOffsets #-} {-# NOINLINE happyGotoOffsets #-} {-# NOINLINE happyDefActions #-} {-# NOINLINE happyShift #-} {-# NOINLINE happySpecReduce_0 #-} {-# NOINLINE happySpecReduce_1 #-} {-# NOINLINE happySpecReduce_2 #-} {-# NOINLINE happySpecReduce_3 #-} {-# NOINLINE happyReduce #-} {-# NOINLINE happyMonadReduce #-} {-# NOINLINE happyGoto #-} {-# NOINLINE happyFail #-} -- end of Happy Template.
aarneranta/china
penn/ParTree.hs
bsd-2-clause
18,745
254
20
3,148
4,994
2,695
2,299
-1
-1
module Lib ( Operation, rpnRun, rpnRunEmpty, rpnParse, rpnParseRun, rpnParseRunEmpty ) where import Data.Char (isDigit) import Data.List (intercalate) import Data.Either (isRight, rights, lefts) import Control.Monad ((<=<)) data Operation = Push Int | Add | Sub | Mul | Div | Mod | Switch | Dup | Pop | Clear deriving Show rpnOp :: Operation -> [Int] -> Either String [Int] rpnOp (Push x) xs = Right (x:xs) rpnOp Add (x:y:xs) = Right ((x+y):xs) rpnOp Sub (x:y:xs) = Right ((y-x):xs) rpnOp Mul (x:y:xs) = Right ((x*y):xs) rpnOp Div (x:y:xs) = Right ((y`div`x):xs) rpnOp Mod (x:y:xs) = Right ((y`mod`x):xs) rpnOp Dup (x:xs) = Right (x:x:xs) rpnOp Switch (x:y:xs) = Right (y:x:xs) rpnOp Pop (x:xs) = Right xs rpnOp Clear _ = Right [] rpnOp o _ = Left ("not enough items on the stack for operation "++(show o)) -- applying operators in order rpnRun :: [Int] -> [Operation] -> Either String [Int] rpnRun stk ops = foldl (>>=) (return stk) $ (map rpnOp ops) rpnRunEmpty :: [Operation] -> Either String [Int] rpnRunEmpty = rpnRun [] -- getting operations from strings rpnParseOp :: String -> Either String Operation rpnParseOp s | all isDigit s = Right $ Push (read s :: Int) | s == "+" = Right Add | s == "-" = Right Sub | s == "*" = Right Mul | s == "/" = Right Div | s == "%" = Right Mod | s == ":" = Right Dup | s == "\\" = Right Switch | s == "$" = Right Pop | s == "C" = Right Clear | otherwise = Left $ "invalid token "++s rpnFixOps :: [Either String Operation] -> Either String [Operation] rpnFixOps ops | all isRight ops = Right $ rights ops | otherwise = Left $ "parse failed:\n\t"++(intercalate "\n\t" $ lefts ops) rpnParse :: String -> Either String [Operation] rpnParse s = rpnFixOps $ map rpnParseOp (words s) rpnParseRun :: [Int] -> String -> Either String [Int] rpnParseRun stk = (rpnRun stk) <=< rpnParse rpnParseRunEmpty :: String -> Either String [Int] rpnParseRunEmpty = rpnParseRun []
Kasran/RPNCalc
src/Lib.hs
bsd-3-clause
1,973
0
9
417
976
504
472
51
1
{-# LANGUAGE NoImplicitPrelude #-} -- | -- Module: TestCase -- Description: All test cases aggregated and exported as tests :: [Test]. -- Copyright: (c) 2015-2016, Ixperta Solutions s.r.o. -- License: BSD3 -- -- Stability: stable -- Portability: NoImplicitPrelude -- -- All test cases aggregated and exported as @'tests' :: ['Test']@. module TestCase (tests) where import Test.Framework (Test, testGroup) import qualified TestCase.Data.Streaming.NamedPipes as Data.Streaming.NamedPipes (tests) tests :: [Test] tests = [ testGroup "Data.Streaming.NamedPipes" Data.Streaming.NamedPipes.tests ]
IxpertaSolutions/windows-named-pipes
test/TestCase.hs
bsd-3-clause
627
0
7
109
76
53
23
8
1
-- | Left factoring of grammars. {-# LANGUAGE ScopedTypeVariables #-} module Data.Cfg.LeftFactor ( LF(..), hasLeftFactors, leftFactor ) where import Control.Monad.Writer(Writer, liftM, runWriter, tell) import Data.Cfg.Cfg(Cfg, ProductionMap, V(..), Vs, productionMap) import Data.Cfg.FreeCfg(FreeCfg, bimapCfg, withProductionMap) import Data.List(nub, partition) import qualified Data.Map as M import qualified Data.Set as S -- | 'True' if the grammar has multiple productions of the same -- nonterminal whose right-hand sides start with the same vocabulary -- element. hasLeftFactors :: (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> Bool hasLeftFactors cfg = any hasLeftFactorsRhss (M.elems $ productionMap cfg) hasLeftFactorsRhss :: forall nt t . (Ord nt, Ord t) => S.Set (Vs t nt) -> Bool hasLeftFactorsRhss rhsSet = S.size rhsSet /= S.size (S.map safeHead rhsSet) where safeHead :: [a] -> Maybe a safeHead as = case as of [] -> Nothing a : _ -> Just a -- | Nonterminal wrapper to introduce symbols for tails of -- left-factored productions. data LF t nt = LF nt | LFTail nt (Vs t (LF t nt)) deriving (Eq, Ord, Show) mkLFHead :: LF t nt -> Vs t (LF t nt) -> LF t nt mkLFHead (LF base) seen = if null seen then LF base else LFTail base seen mkLFHead (LFTail base vs) seen = LFTail base (vs ++ seen) type P t nt = (LF t nt, S.Set (Vs t (LF t nt))) type PT t nt = PatriciaTrie (V t (LF t nt)) () data Trie ke v = Trie (Maybe v) (M.Map ke (Trie ke v)) type PatriciaTrie ke v = Trie [ke] v isCap :: Trie k () -> Bool isCap (Trie (Just ()) m) = M.null m isCap _ = False -- | Factor out common leading prefixes to production right-hand sides. leftFactor :: forall cfg nt t . (Cfg cfg t nt, Ord nt, Ord t) => cfg t nt -> FreeCfg t (LF t nt) leftFactor = withProductionMap f . bimapCfg id LF where f :: ProductionMap t (LF t nt) -> ProductionMap t (LF t nt) f = M.fromList . concatMap f' . M.toList f' :: P t nt -> [P t nt] f' (hd, tls) = (hd, S.fromList alts) : ps where pt :: PatriciaTrie (V t (LF t nt)) () pt = patriciaTrieFromList [(vs, ()) | vs <- S.toList tls ] (alts, ps) = runWriter $ patriciaTrieToAlts hd pt type W t nt = Writer [P t nt] patriciaTrieToAlts :: (Ord nt, Ord t) => LF t nt -> PT t nt -> W t nt [Vs t (LF t nt)] patriciaTrieToAlts hd (Trie Nothing trieMap) = trieMapToAlts hd trieMap patriciaTrieToAlts hd (Trie (Just ()) trieMap) = liftM (++[[]]) $ trieMapToAlts hd trieMap trieMapToAlts :: (Ord nt, Ord t) => LF t nt -> M.Map (Vs t (LF t nt)) (Trie (Vs t (LF t nt)) ()) -> W t nt [Vs t (LF t nt)] trieMapToAlts hd trieMap = if M.null trieMap then return [] else mapM (segTrieToAlt hd) $ M.toList trieMap segTrieToAlt :: (Ord nt, Ord t) => LF t nt -> (Vs t (LF t nt), Trie (Vs t (LF t nt)) ()) -> W t nt (Vs t (LF t nt)) segTrieToAlt hd (seg, trie) = if isCap trie then return seg else do let hd' = mkLFHead hd seg alts <- patriciaTrieToAlts hd' trie tell [(hd', S.fromList alts)] return (seg ++ [NT hd']) ------------------------------------------------------------ patriciaTrieFromList :: Ord ke => [([ke], v)] -> PatriciaTrie ke v patriciaTrieFromList [] = Trie Nothing M.empty patriciaTrieFromList (kvs :: [([ke], v)]) = Trie mV subtries' where nulls, fulls :: [([ke], v)] (nulls, fulls) = partition (null . fst) kvs mV :: Maybe v mV = if null nulls then Nothing else Just (last $ map snd nulls) trieKeys :: Eq ke => [ke] trieKeys = nub $ map (head . fst) fulls groups :: [[([ke], v)]] groups = map f trieKeys where f ini = [ full | full <- fulls, head (fst full) == ini ] prefixGroups :: [([ke], [([ke], v)])] prefixGroups = map f groups where f :: [([ke], v)] -> ([ke], [([ke], v)]) f gp = (pref, [(suffix, v) | (ke, v) <- gp, let suffix = drop len ke ]) where pref = commonPrefix (map fst gp) len = length pref subtries' :: M.Map [ke] (PatriciaTrie ke v) subtries' = M.fromList ls where ls :: [([ke], PatriciaTrie ke v)] ls = map f prefixGroups f :: ([ke], [([ke], v)]) -> ([ke], PatriciaTrie ke v) f (ini, dat) = (ini, patriciaTrieFromList dat) commonPrefix :: Eq x => [[x]] -> [x] commonPrefix [] = error "commonPrefix: null list" commonPrefix xss = map head $ takeWhile allSame (zipN xss) where allSame [] = error "allSame: null list" allSame (x : xs) = all (==x) xs zipN :: [[x]] -> [[x]] zipN xss = if null xss || any null xss then [] else map head xss : zipN (map tail xss)
nedervold/context-free-grammar
src/Data/Cfg/LeftFactor.hs
bsd-3-clause
5,048
0
15
1,562
2,140
1,140
1,000
108
2
module PatternRecogn.Lina( Matrix, Vector, MatrixOf, VectorOf, module Lina ) where import Numeric.LinearAlgebra as Lina hiding( Matrix, Vector ) import qualified Numeric.LinearAlgebra as LinaIntern type Matrix = LinaIntern.Matrix Double type Vector = LinaIntern.Vector Double type MatrixOf = LinaIntern.Matrix type VectorOf = LinaIntern.Vector
EsGeh/pattern-recognition
src/PatternRecogn/Lina.hs
bsd-3-clause
351
6
6
48
92
58
34
10
0
{-# LANGUAGE RecordWildCards, PatternGuards #-} -- | A Ninja style environment, basically a linked-list of mutable hash tables. module Development.Ninja.Env( Env, newEnv, scopeEnv, addEnv, askEnv ) where import qualified Data.HashMap.Strict as Map import Data.Hashable import Data.IORef data Env k v = Env (IORef (Map.HashMap k v)) (Maybe (Env k v)) instance Show (Env k v) where show _ = "Env" newEnv :: IO (Env k v) newEnv = do ref <- newIORef Map.empty; return $ Env ref Nothing scopeEnv :: Env k v -> IO (Env k v) scopeEnv e = do ref <- newIORef Map.empty; return $ Env ref $ Just e addEnv :: (Eq k, Hashable k) => Env k v -> k -> v -> IO () addEnv (Env ref _) k v = modifyIORef ref $ Map.insert k v askEnv :: (Eq k, Hashable k) => Env k v -> k -> IO (Maybe v) askEnv (Env ref e) k = do mp <- readIORef ref case Map.lookup k mp of Just v -> return $ Just v Nothing | Just e <- e -> askEnv e k _ -> return Nothing
nh2/shake
Development/Ninja/Env.hs
bsd-3-clause
970
0
14
239
430
215
215
21
3
{-# LANGUAGE DeriveAnyClass #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TemplateHaskell #-} module Base.Context where import Base.Event import Base.Exception import Base.Import import Base.Logger import Base.Prop import Control.Concurrent (ThreadId) import qualified Control.Concurrent.Map as M import Control.Monad.Trans.State import qualified Data.Cache as C import Data.Dynamic import Data.Functor.Identity (Identity (..)) import qualified Data.Map as Map import Data.Proxy import Data.Swagger hiding (get) import Database.Persist.TH import Text.Read (readMaybe) import Web.HttpApiData data RoleType = RoleUser | RoleAdmin deriving (Eq,Show,Read,Generic,ToSchema,FromJSON,ToJSON) derivePersistField "RoleType" data TokenType = TokenUser | TokenAdmin | Ticket deriving (Eq,Show,Read,Generic,ToSchema,FromJSON,ToJSON) data TicketType = TicketUserInfo deriving (Eq,Show,Read,Generic,ToParamSchema,ToSchema,FromJSON,ToJSON) instance FromHttpApiData TicketType where parseQueryParam v = maybeToEither ("Param " <> v <> " in valid") $ readMaybe $ cs v validTime :: (Num a) => TokenType -> a validTime TokenUser = 3600 * 24 validTime TokenAdmin = 3600 validTime Ticket = 600 -- Determine token has with permission hasAuth :: Token -> TokenType -> Bool hasAuth token auth = let userAuth = tokenType token in userAuth == TokenAdmin || userAuth == auth isOnce :: TokenType -> Bool isOnce = (== Ticket) -- Determine which role can sign which permission canSign :: TokenType -> RoleType -> Bool canSign want role = role == RoleAdmin || want == TokenUser data Token = Token { tokenId :: Text , tokenType :: TokenType , tokenClaims :: [TicketType] , tokenUser :: ID , tokenSecret :: Text , tokenRefreshSecret :: Text } deriving (Eq,Show) type TokenCache = C.Cache Text Token type JobMap = Map.Map ThreadId Text type ExtensionMap = M.Map Text Dynamic data BaseContext = BaseContext { baseConnection :: BaseConnection , baseTokenCache :: TokenCache , baseJobs :: JobMap , baseExtension :: ExtensionMap , basePropSource :: PropertySource , baseLogger :: LogContext } extensionLockKey :: Text extensionLockKey = "Extension.Lock" getExtension :: (MonadIO m, MonadThrow m, Typeable a) => Text -> AppM m a getExtension key = gets baseExtension >>= liftIO . M.lookup key >>= get . (fromDynamic =<<) where get Nothing = throwM $ ServiceException_ $ key <> " not loaded" get (Just r) = return r tryExtension :: (MonadIO m, MonadThrow m, Typeable a) => a -> Text -> AppM m a tryExtension a key = (fromMaybe a . (fromDynamic =<<)) <$> (gets baseExtension >>= liftIO . M.lookup key) setExtension :: (MonadIO m, MonadThrow m, Typeable a) => Text -> a -> AppM m () setExtension key a = do checkLock when (extensionLockKey /= key) (debugLn $ "Register extension <<" <> key <> ">>") void $ gets baseExtension >>= liftIO . M.insert key (toDyn a) checkLock :: (MonadIO m, MonadThrow m) => AppM m () checkLock = tryExtension False extensionLockKey >>= go where go True = throwM ExtensionModificationRejectedException go _ = return () lockExtenstion :: (MonadIO m, MonadThrow m) => AppM m () lockExtenstion = setExtension extensionLockKey True type AppM = StateT BaseContext instance (MonadIO m) => MonadLogger (AppM m) where getLogContext = baseLogger <$> get instance (MonadIO m, MonadThrow m) => MonadEvent (AppM m) where getEventConsumer proxy = tryExtension [] $ "Event." <> cs (eventKey proxy) instance (MonadThrow m) => MonadProperty (AppM m) where propertySources = basePropSource <$> get addEventHandler :: (MonadIO m, MonadThrow m, Event e) => Proxy e -> (e -> AppM IO ()) -> AppM m () addEventHandler p = addEventHandler' p Nothing addEventHandler' :: (MonadIO m, MonadThrow m, Event e) => Proxy e -> Maybe Text -> (e -> AppM IO ()) -> AppM m () addEventHandler' p hname h = do hs <- getEventConsumer p context <- get let key = "Event." <> cs (eventKey p) h' = runAppM context . h name = fromMaybe (key <> "." <> showText (length hs + 1)) hname infoLn $ "Register eventHandler " <> name <> " for " <> key setExtension key (h':hs) defaultBaseContext :: IO BaseContext defaultBaseContext = do cache <- C.newCache Nothing :: IO TokenCache eMap <- M.empty BaseContext (Nothing,Nothing) cache Map.empty eMap emptyPropertySource <$> stdoutLog runAppM :: (Monad m) => BaseContext -> AppM m a -> m a runAppM = flip evalStateT evalPropOrDefault :: FromJSON a => a -> BaseContext -> Text -> a evalPropOrDefault d c key = fromMaybe d $ evalProp c key evalProp :: FromJSON a => BaseContext -> Text -> Maybe a evalProp c key = runIdentity $ runProp (snd $ basePropSource c) $ getProp key
leptonyu/mint
corn/src/Base/Context.hs
bsd-3-clause
5,314
0
16
1,303
1,638
860
778
116
2
module Lib ( answers ) where import qualified Day1 as Day1 import qualified Day2 as Day2 import qualified Day3 as Day3 import qualified Day4 as Day4 import qualified Day5 as Day5 import qualified Day6 as Day6 import qualified Day8 as Day8 import qualified Day10 as Day10 import qualified Day12 as Day12 answers :: IO () answers = do content <- readFile "day1.txt" Day1.answers content content <- readFile "day2.txt" Day2.answers content content <- readFile "day3.txt" Day3.answers content Day4.answers content <- readFile "day5.txt" Day5.answers content content <- readFile "day6.txt" Day6.answers content content <- readFile "day8.txt" Day8.answers content Day10.answers content <- readFile "day12.txt" Day12.answers content
hlmerscher/advent-of-code-2015
src/Lib.hs
bsd-3-clause
800
0
8
176
214
112
102
29
1
{-| Module : Data.Number.MPFR.Mutable.Special Description : Special functions Copyright : (c) Aleš Bizjak License : BSD3 Maintainer : ales.bizjak0@gmail.com Stability : experimental Portability : non-portable For documentation on particular functions see <http://www.mpfr.org/mpfr-current/mpfr.html#Special-Functions>. -} {-# INCLUDE <mpfr.h> #-} {-# INCLUDE <chsmpfr.h> #-} module Data.Number.MPFR.Mutable.Special where import Data.Number.MPFR.Mutable.Internal import Control.Monad.ST(ST) import Data.Word(Word) log :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int log = withMutableMPFRS mpfr_log log2 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int log2 = withMutableMPFRS mpfr_log2 log10 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int log10 = withMutableMPFRS mpfr_log10 exp :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int exp = withMutableMPFRS mpfr_exp exp2 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int exp2 = withMutableMPFRS mpfr_exp2 exp10 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int exp10 = withMutableMPFRS mpfr_exp10 sin :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int sin = withMutableMPFRS mpfr_sin cos :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int cos = withMutableMPFRS mpfr_cos tan :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int tan = withMutableMPFRS mpfr_tan sec :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int sec = withMutableMPFRS mpfr_sec csc :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int csc = withMutableMPFRS mpfr_csc cot :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int cot = withMutableMPFRS mpfr_cot sincos :: MMPFR s -> MMPFR s -> MMPFR s -> RoundMode -> ST s Int sincos = withMutableMPFRSC mpfr_sin_cos asin :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int asin = withMutableMPFRS mpfr_asin acos :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int acos = withMutableMPFRS mpfr_acos atan :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int atan = withMutableMPFRS mpfr_atan atan2 :: MMPFR s -> MMPFR s -> MMPFR s -> RoundMode -> ST s Int atan2 = withMutableMPFRBA mpfr_atan2 sinh :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int sinh = withMutableMPFRS mpfr_sinh cosh :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int cosh = withMutableMPFRS mpfr_cosh tanh :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int tanh = withMutableMPFRS mpfr_tanh sinhcosh :: MMPFR s -> MMPFR s -> MMPFR s -> RoundMode -> ST s Int sinhcosh = withMutableMPFRSC mpfr_sinh_cosh sech :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int sech = withMutableMPFRS mpfr_sech csch :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int csch = withMutableMPFRS mpfr_csch coth :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int coth = withMutableMPFRS mpfr_coth asinh :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int asinh = withMutableMPFRS mpfr_asinh acosh :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int acosh = withMutableMPFRS mpfr_acosh atanh :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int atanh = withMutableMPFRS mpfr_atanh facw :: MMPFR s -> Word -> RoundMode -> ST s Int facw = withMutableMPFRUI mpfr_fac_ui log1p :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int log1p = withMutableMPFRS mpfr_log1p expm1 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int expm1 = withMutableMPFRS mpfr_expm1 eint :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int eint = withMutableMPFRS mpfr_eint li2 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int li2 = withMutableMPFRS mpfr_li2 gamma :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int gamma = withMutableMPFRS mpfr_gamma lngamma :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int lngamma = withMutableMPFRS mpfr_lngamma {- TODO lgamma :: RoundMode -> Precision -> MPFR -> (MPFR, Int) lgamma r p d = case lgamma_ r p d of (a, b, _) -> (a,b) -} zeta :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int zeta = withMutableMPFRS mpfr_zeta zetaw :: MMPFR s -> Word -> RoundMode -> ST s Int zetaw = withMutableMPFRUI mpfr_zeta_ui erf :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int erf = withMutableMPFRS mpfr_erf erfc :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int erfc = withMutableMPFRS mpfr_erfc j0 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int j0 = withMutableMPFRS mpfr_j0 j1 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int j1 = withMutableMPFRS mpfr_j1 jn :: MMPFR s -> Word -> MMPFR s -> RoundMode -> ST s Int jn = withMutableMPFR2 mpfr_jn y0 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int y0 = withMutableMPFRS mpfr_y0 y1 :: MMPFR s -> MMPFR s -> RoundMode -> ST s Int y1 = withMutableMPFRS mpfr_y1 yn :: MMPFR s -> Word -> MMPFR s -> RoundMode -> ST s Int yn = withMutableMPFR2 mpfr_yn fma :: MMPFR s -> MMPFR s -> MMPFR s -> MMPFR s -> RoundMode -> ST s Int fma = withMutableMPFRBA3 mpfr_fma fms :: MMPFR s -> MMPFR s -> MMPFR s -> MMPFR s -> RoundMode -> ST s Int fms = withMutableMPFRBA3 mpfr_fms agm :: MMPFR s -> MMPFR s -> MMPFR s -> RoundMode -> ST s Int agm = withMutableMPFRBA mpfr_agm hypot :: MMPFR s -> MMPFR s -> MMPFR s -> RoundMode -> ST s Int hypot = withMutableMPFRBA mpfr_hypot {- INTERNAL CACHES, dangerous pi :: RoundMode -> Precision -> MPFR pi r = fst . pi_ r log2c :: RoundMode -> Precision -> MPFR log2c r = fst . pi_ r euler :: RoundMode -> Precision -> MPFR euler r = fst . pi_ r catalan :: RoundMode -> Precision -> MPFR catalan r = fst . pi_ r -}
ekmett/hmpfr
src/Data/Number/MPFR/Mutable/Special.hs
bsd-3-clause
5,297
0
10
1,127
1,836
876
960
100
1
{-# OPTIONS_GHC -fno-warn-unrecognised-pragmas #-} {-# LANGUAGE CPP #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE UndecidableInstances #-} {-# LANGUAGE FunctionalDependencies #-} #if __GLASGOW_HASKELL__ < 710 {-# LANGUAGE OverlappingInstances #-} #endif -- | See "Control.Monad.State.Class". module Control.Monad.Ether.State.Class ( MonadState(..) , modify , gets ) where #if __GLASGOW_HASKELL__ < 710 import Data.Monoid #endif import Control.Monad.Trans (lift) import Control.Monad.Trans.Ether.Reader (ReaderT) import Control.Monad.Trans.Ether.Writer (WriterT) import Control.Monad.Trans.Ether.Except (ExceptT) import qualified Control.Monad.Trans.Ether.State.Lazy as S.L import qualified Control.Monad.Trans.Ether.State.Strict as S.S import qualified Control.Ether.Util as Util -- for mtl instances import qualified Control.Monad.Trans.Cont as Trans (ContT) import qualified Control.Monad.Trans.Except as Trans (ExceptT) import qualified Control.Monad.Trans.Identity as Trans (IdentityT) import qualified Control.Monad.Trans.List as Trans (ListT) import qualified Control.Monad.Trans.Maybe as Trans (MaybeT) import qualified Control.Monad.Trans.Reader as Trans (ReaderT) import qualified Control.Monad.Trans.State.Lazy as Trans.Lazy (StateT) import qualified Control.Monad.Trans.State.Strict as Trans.Strict (StateT) import qualified Control.Monad.Trans.Writer.Lazy as Trans.Lazy (WriterT) import qualified Control.Monad.Trans.Writer.Strict as Trans.Strict (WriterT) -- | See 'Control.Monad.State.MonadState'. class Monad m => MonadState tag s m | m tag -> s where {-# MINIMAL state | get, put #-} -- | Return the state from the internals of the monad. get :: proxy tag -> m s get t = state t (\s -> (s, s)) -- | Replace the state inside the monad. put :: proxy tag -> s -> m () put t s = state t (\_ -> ((), s)) -- | Embed a simple state action into the monad. state :: proxy tag -> (s -> (a, s)) -> m a state t f = do s <- get t let ~(a, s') = f s put t s' return a -- | Modifies the state inside a state monad. modify :: MonadState tag s m => proxy tag -> (s -> s) -> m () modify t f = state t (\s -> ((), f s)) -- | Gets specific component of the state, using a projection function supplied. gets :: MonadState tag s m => proxy tag -> (s -> a) -> m a gets t f = Util.fmap f (get t) instance {-# OVERLAPPING #-} Monad m => MonadState tag s (S.L.StateT tag s m) where get = S.L.get put = S.L.put state = S.L.state instance MonadState tag s m => MonadState tag s (S.L.StateT tag' s' m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance {-# OVERLAPPING #-} Monad m => MonadState tag s (S.S.StateT tag s m) where get = S.S.get put = S.S.put state = S.S.state instance MonadState tag s m => MonadState tag s (S.S.StateT tag' s' m) where get t = lift (get t) put t = lift . put t state t = lift . state t -- Instances for other tagged transformers instance (MonadState tag s m) => MonadState tag s (ReaderT tag' r m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance (Monoid w, MonadState tag s m) => MonadState tag s (WriterT tag' w m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance (MonadState tag s m) => MonadState tag s (ExceptT tag' e m) where get t = lift (get t) put t = lift . put t state t = lift . state t -- Instances for mtl transformers instance MonadState tag s m => MonadState tag s (Trans.ContT r m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance MonadState tag s m => MonadState tag s (Trans.ExceptT e m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance MonadState tag s m => MonadState tag s (Trans.IdentityT m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance MonadState tag s m => MonadState tag s (Trans.ListT m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance MonadState tag s m => MonadState tag s (Trans.MaybeT m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance MonadState tag s m => MonadState tag s (Trans.ReaderT r m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance MonadState tag s m => MonadState tag s (Trans.Lazy.StateT s' m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance MonadState tag s m => MonadState tag s (Trans.Strict.StateT s' m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance (Monoid w, MonadState tag s m) => MonadState tag s (Trans.Lazy.WriterT w m) where get t = lift (get t) put t = lift . put t state t = lift . state t instance (Monoid w, MonadState tag s m) => MonadState tag s (Trans.Strict.WriterT w m) where get t = lift (get t) put t = lift . put t state t = lift . state t
bitemyapp/ether
src/Control/Monad/Ether/State/Class.hs
bsd-3-clause
5,268
0
13
1,326
1,986
1,050
936
113
1
{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE DeriveTraversable #-} {-# LANGUAGE DeriveFoldable #-} {-# LANGUAGE DeriveFunctor #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE QuasiQuotes #-} module Data.Type.Quote where import Control.Arrow import Language.Haskell.TH import qualified Data.List as L import Data.Maybe (maybeToList) import Type.Family.Nat import Text.Read (readMaybe) import Data.Char (isSpace) import qualified Language.Haskell.Meta.Parse as P import Control.Monad ((>=>),(<=<)) failFrom :: Monad m => String -> String -> m a failFrom src msg = fail $ src ++ ": " ++ msg stub :: String -> String -> a -> Q b stub qq fn _ = failFrom qq $ fn ++ " not provided" -- Parsers {{{ parseExp :: String -> String -> Q Exp parseExp qq = eitherM qq . P.parseExp parsePat :: String -> String -> Q Pat parsePat qq = eitherM qq . P.parsePat parseType :: String -> String -> Q Type parseType qq = eitherM qq . P.parseType parseDecs :: String -> String -> Q [Dec] parseDecs qq = eitherM qq . P.parseDecs -- }}} -- Nat Util {{{ parseN :: Monad m => String -> String -> m N parseN qq = maybe (failFrom qq "couldn't parse number") (notNeg qq) . readMaybe notNeg :: Monad m => String -> Int -> m N notNeg qq n = maybe (failFrom qq $ "negative number: " ++ show n) return $ fromInt n -- Remove with update of type-combinators fromInt :: Int -> Maybe N fromInt n = case compare n 0 of LT -> Nothing EQ -> Just Z GT -> S <$> fromInt (pred n) -- }}} eitherM :: Monad m => String -> Either String a -> m a eitherM qq = either (failFrom qq) return maybeM :: Monad m => String -> String -> Maybe a -> m a maybeM qq msg = maybe (failFrom qq msg) return -- List Util {{{ readMaybeList :: Read a => String -> [a] readMaybeList = maybeToList . readMaybe commaSep :: String -> [String] commaSep = map (strip isSpace) . breakOnAll "," strip :: (a -> Bool) -> [a] -> [a] strip pr = L.dropWhileEnd pr . dropWhile pr breakOnAll :: Eq a => [a] -> [a] -> [[a]] breakOnAll b as = b1 : case rest of [] -> [] _ -> breakOnAll b rest where (b1,rest) = breakOn b as breakOn :: Eq a => [a] -> [a] -> ([a],[a]) breakOn b = \case [] -> ([],[]) as@(a : as') -> case getPrefix b as of Just sf -> ([],sf) _ -> first (a:) $ breakOn b as' getPrefix :: Eq a => [a] -> [a] -> Maybe [a] getPrefix p as | L.isPrefixOf p as = Just $ drop (length p) as | otherwise = Nothing -- }}} -- AddTerm {{{ data AddTerm a = Simple a | Add String a deriving (Eq,Ord,Show,Functor,Foldable,Traversable) instance (a ~ Int) => Read (AddTerm a) where readsPrec d s0 = [ (Add x i,s3) | (x,s1) <- lex s0 , ("+",s2) <- lex s1 , (i,s3) <- reads s2 ] ++ [ (Simple i,s1) | (i,s1) <- reads s0 ] parseAddTerm :: Monad m => String -> String -> m (AddTerm N) parseAddTerm qq = traverse (notNeg qq) <=< maybeM qq "couldn't parse AddTerm" . readMaybe fromAddTerm :: b -> (String -> b) -> (b -> a -> Q c) -> AddTerm a -> Q c fromAddTerm simp var f = \case Simple a -> f simp a Add x a -> f (var x) a parseAsNatTerm :: forall a. String -> (Name -> Q a) -> Q a -> (Q a -> Q a) -> String -> Q a parseAsNatTerm qq v z s = parseAddTerm qq >=> fromAddTerm z (v . mkName) go where go :: Q a -> N -> Q a go x = \case Z -> x S n -> s $ go x n -- }}}
kylcarte/type-combinators-quote
src/Data/Type/Quote.hs
bsd-3-clause
3,465
0
13
880
1,497
771
726
-1
-1
{-# LANGUAGE DeriveGeneric #-} module Yng.Types where import Data.Aeson (ToJSON) import GHC.Generics data GithubUser = GithubUser { handle :: String, repositories :: [String] } deriving (Show, Eq, Generic) instance ToJSON GithubUser data GithubError = GithubError deriving (Show, Eq)
NorthParkSoftware/yournextgig-backend
src/Yng/Types.hs
bsd-3-clause
296
0
9
50
86
50
36
10
0
{-# LANGUAGE TupleSections, GADTs, StandaloneDeriving, DataKinds #-} ----------------------------------------------------------------------------- -- | -- Module : Language.Glambda.Token -- Copyright : (C) 2015 Richard Eisenberg -- License : BSD-style (see LICENSE) -- Maintainer : Richard Eisenberg (rae@cs.brynmawr.edu) -- Stability : experimental -- -- Defines a lexical token -- ---------------------------------------------------------------------------- module Language.Glambda.Token ( -- * Arithmetic operators ArithOp(..), UArithOp(..), eqArithOp, -- ** Unchecked synonyms for arithmetic operators uPlus, uMinus, uTimes, uDivide, uMod, uLess, uLessE, uGreater, uGreaterE, uEquals, -- * Tokens Token(..), LToken(..), unLoc, unArithOp, unInt, unBool, unName ) where import Language.Glambda.Type import Language.Glambda.Util import Text.PrettyPrint.ANSI.Leijen as Pretty import Text.Parsec.Pos ( SourcePos ) import Data.List as List -- | An @ArithOp ty@ is an operator on numbers that produces a result -- of type @ty@ data ArithOp ty where Plus, Minus, Times, Divide, Mod :: ArithOp Int Less, LessE, Greater, GreaterE, Equals :: ArithOp Bool -- | 'UArithOp' ("unchecked 'ArithOp'") is an existential package for -- an 'ArithOp' data UArithOp where UArithOp :: ITy ty => ArithOp ty -> UArithOp uPlus, uMinus, uTimes, uDivide, uMod, uLess, uLessE, uGreater, uGreaterE, uEquals :: UArithOp uPlus = UArithOp Plus uMinus = UArithOp Minus uTimes = UArithOp Times uDivide = UArithOp Divide uMod = UArithOp Mod uLess = UArithOp Less uLessE = UArithOp LessE uGreater = UArithOp Greater uGreaterE = UArithOp GreaterE uEquals = UArithOp Equals -- | Compare two 'ArithOp's (potentially of different types) for equality eqArithOp :: ArithOp ty1 -> ArithOp ty2 -> Bool eqArithOp Plus Plus = True eqArithOp Minus Minus = True eqArithOp Times Times = True eqArithOp Divide Divide = True eqArithOp Mod Mod = True eqArithOp Less Less = True eqArithOp LessE LessE = True eqArithOp Greater Greater = True eqArithOp GreaterE GreaterE = True eqArithOp Equals Equals = True eqArithOp _ _ = False instance Eq (ArithOp ty) where (==) = eqArithOp instance Eq UArithOp where UArithOp op1 == UArithOp op2 = op1 `eqArithOp` op2 -- | A lexed token data Token = LParen | RParen | Lambda | Dot | Arrow | Colon | ArithOp UArithOp | Int Int | Bool Bool | If | Then | Else | FixT | Assign | Semi | Name String deriving Eq -- | Perhaps extract a 'UArithOp' unArithOp :: Token -> Maybe UArithOp unArithOp (ArithOp x) = Just x unArithOp _ = Nothing -- | Perhaps extract an 'Int' unInt :: Token -> Maybe Int unInt (Int x) = Just x unInt _ = Nothing -- | Perhaps extract an 'Bool' unBool :: Token -> Maybe Bool unBool (Bool x) = Just x unBool _ = Nothing -- | Perhaps extract a 'String' unName :: Token -> Maybe String unName (Name x) = Just x unName _ = Nothing -- | A lexed token with location information attached data LToken = L SourcePos Token -- | Remove location information from an 'LToken' unLoc :: LToken -> Token unLoc (L _ t) = t instance Pretty (ArithOp ty) where pretty Plus = char '+' pretty Minus = char '-' pretty Times = char '*' pretty Divide = char '/' pretty Mod = char '%' pretty Less = char '<' pretty LessE = text "<=" pretty Greater = char '>' pretty GreaterE = text ">=" pretty Equals = text "==" instance Show (ArithOp ty) where show = render . pretty instance Pretty UArithOp where pretty (UArithOp op) = pretty op instance Show UArithOp where show = render . pretty instance Pretty Token where pretty = getDoc . printingInfo prettyList = printTogether . List.map printingInfo instance Show Token where show = render . pretty instance Pretty LToken where pretty = pretty . unLoc prettyList = prettyList . List.map unLoc instance Show LToken where show = render . pretty type PrintingInfo = (Doc, Bool, Bool) -- the bools say whether or not to include a space before or a space after alone :: Doc -> PrintingInfo alone = (, True, True) getDoc :: PrintingInfo -> Doc getDoc (doc, _, _) = doc printingInfo :: Token -> PrintingInfo printingInfo LParen = (char '(', True, False) printingInfo RParen = (char ')', False, True) printingInfo Lambda = (char '\\', True, False) printingInfo Dot = (char '.', False, True) printingInfo Arrow = alone $ text "->" printingInfo Colon = (char ':', False, False) printingInfo (ArithOp a) = alone $ pretty a printingInfo (Int i) = alone $ int i printingInfo (Bool True) = alone $ text "true" printingInfo (Bool False) = alone $ text "false" printingInfo If = alone $ text "if" printingInfo Then = alone $ text "then" printingInfo Else = alone $ text "else" printingInfo FixT = alone $ text "fix" printingInfo Assign = alone $ text "=" printingInfo Semi = (char ';', False, True) printingInfo (Name t) = alone $ text t printTogether :: [PrintingInfo] -> Doc printTogether [] = Pretty.empty printTogether pis = getDoc $ List.foldl1 combine pis where combine (doc1, before_space, inner_space1) (doc2, inner_space2, after_space) | inner_space1 && inner_space2 = (doc1 <+> doc2, before_space, after_space) | otherwise = (doc1 <> doc2, before_space, after_space)
goldfirere/glambda
src/Language/Glambda/Token.hs
bsd-3-clause
5,561
15
10
1,305
1,539
837
702
-1
-1
{-# OPTIONS_GHC -fno-warn-orphans #-} {-# LANGUAGE ExistentialQuantification #-} module Yesod.Auth.DeskCom ( YesodDeskCom(..) , deskComCreateCreds , DeskComCredentials , DeskComUser(..) , DeskComUserId(..) , DeskComCustomField , DeskCom , getDeskCom , deskComLoginRoute , deskComMaybeLoginRoute ) where import Control.Applicative ((<$>)) import Control.Monad.IO.Class (MonadIO, liftIO) import Data.Default (Default(..)) import Data.Monoid ((<>)) import Data.Text (Text) import Language.Haskell.TH.Syntax (Pred(ClassP), Type(VarT), mkName) import Network.HTTP.Types (renderSimpleQuery) import Yesod.Auth import Yesod.Core import qualified Crypto.Cipher.AES as AES import qualified Crypto.Classes as Crypto import qualified Crypto.Hash.SHA1 as SHA1 import qualified Crypto.HMAC as HMAC import qualified Crypto.Padding as Padding import qualified Data.Aeson as A import qualified Data.ByteString as B import qualified Data.ByteString.Lazy as BL import qualified Data.ByteString.Base64 as B64 import qualified Data.ByteString.Base64.URL as B64URL import qualified Data.Text as T import qualified Data.Text.Encoding as TE import qualified Data.Time as TI import Yesod.Auth.DeskCom.Data import Database.Persist (Key) import Crypto.Hash.CryptoAPI (SHA1) import Crypto.Classes (Hash) -- | Type class that you need to implement in order to support -- Desk.com remote authentication. -- -- /Minimal complete definition:/ everything except for 'deskComTokenTimeout'. class YesodAuthPersist master => YesodDeskCom master where -- | The credentials needed to use Multipass. Use -- 'deskComCreateCreds'. We recommend caching the resulting -- 'DeskComCredentials' value on your foundation data type -- since creating it is an expensive operation. deskComCredentials :: HandlerT master IO DeskComCredentials -- | Gather information that should be given to Desk.com about -- an user. Please see 'DeskComUser' for more information -- about what these fields mean. -- -- Simple example: -- -- @ -- deskComUserInfo uid = do -- user <- runDB $ get uid -- return 'def' { 'duName' = userName user -- , 'duEmail' = userEmail user } -- @ -- -- Advanced example: -- -- @ -- deskComUserInfo uid = do -- render <- 'getUrlRender' -- runDB $ do -- Just user <- get uid -- Just org <- get (userOrganization user) -- return 'def' { 'duName' = userName user -- , 'duEmail' = userEmail user -- , 'duOrganization' = Just (organizationName org) -- , 'duRemotePhotoURL' = Just (render $ UserPhotoR uid) -- } -- @ -- -- /Note:/ although I don't recomend this and I don't see any -- reason why you would do it, it /is/ possible to use -- 'maybeAuth' instead of 'requireAuth' and login on Desk.com -- with some sort of guest user should the user not be logged -- in. deskComUserInfo :: AuthId master -> HandlerT master IO DeskComUser -- | Get a random 16-byte @ByteString@ to use as the IV. deskComRandomIV :: HandlerT master IO B.ByteString -- | Each time we login an user on Desk.com, we create a token. -- This function defines how much time the token should be -- valid before expiring. Should be greater than 0. Defaults -- to 5 minutes. deskComTokenTimeout :: master -> TI.NominalDiffTime deskComTokenTimeout _ = 300 -- seconds instance YesodDeskCom master => YesodSubDispatch DeskCom (HandlerT master IO) where yesodSubDispatch = $(mkYesodSubDispatch resourcesDeskCom) -- | Create the credentials data type used by this library. This -- function is relatively expensive (uses SHA1 and AES), so -- you'll probably want to cache its result. deskComCreateCreds :: T.Text -- ^ The name of your site (e.g., @\"foo\"@ if your -- site is at @http://foo.desk.com/@). -> T.Text -- ^ The domain of your site -- (e.g. @\"foo.desk.com\"@). -> T.Text -- ^ The Multipass API key, a shared secret between -- Desk.com and your site. -> DeskComCredentials deskComCreateCreds site domain apiKey = DeskComCredentials site domain aesKey hmacKey where -- Yes, I know, Desk.com's crypto is messy. aesKey = AES.initKey . B.take 16 . SHA1.hash . TE.encodeUtf8 $ apiKey <> site hmacKey = MacKeyHelper $ HMAC.MacKey $ TE.encodeUtf8 apiKey data MacKeyHelper d = forall c. Hash c d => MacKeyHelper { unMacKeyHelper :: HMAC.MacKey c d } -- | Credentials used to access your Desk.com's Multipass. data DeskComCredentials = DeskComCredentials { dccSite :: !T.Text , dccDomain :: !T.Text , dccAesKey :: !AES.AES , dccHmacKey :: !(MacKeyHelper SHA1) } -- | Information about a user that is given to 'DeskCom'. Please -- see Desk.com's documentation -- (<http://dev.desk.com/docs/portal/multipass>) in order to see -- more details of how theses fields are interpreted. -- -- Only 'duName' and 'duEmail' are required. We suggest using -- 'def'. data DeskComUser = DeskComUser { duName :: Text -- ^ User name, at least two characters. (required) , duEmail :: Text -- ^ E-mail address. (required) , duUserId :: DeskComUserId -- ^ Desk.com expects an string to be used as the ID of the -- user on their system. Defaults to 'UseYesodAuthId'. , duCustomFields :: [DeskComCustomField] -- ^ Custom fields to be set. , duRedirectTo :: Maybe Text -- ^ When @Just url@, forces the user to be redirected to -- @url@ after being logged in. Otherwise, the user is -- redirected either to the page they were trying to view (if -- any) or to your portal page at Desk.com. } deriving (Eq, Ord, Show, Read) -- | Fields 'duName' and 'duEmail' are required, so 'def' will be -- 'undefined' for them. instance Default DeskComUser where def = DeskComUser { duName = req "duName" , duEmail = req "duEmail" , duUserId = def , duCustomFields = [] , duRedirectTo = Nothing } where req fi = error $ "DeskComUser's " ++ fi ++ " is a required field." -- | Which external ID should be given to Desk.com. data DeskComUserId = UseYesodAuthId -- ^ Use the user ID from @persistent@\'s database. This is -- the recommended and default value. | Explicit Text -- ^ Use this given value. deriving (Eq, Ord, Show, Read) -- | Default is 'UseYesodAuthId'. instance Default DeskComUserId where def = UseYesodAuthId -- | The value of a custom customer field as @(key, value)@. -- Note that you have prefix your @key@ with @\"custom_\"@. type DeskComCustomField = (Text, Text) ---------------------------------------------------------------------- -- | Create a new 'DeskCom', use this on your @config/routes@ file. getDeskCom :: a -> DeskCom getDeskCom = const DeskCom -- | Redirect the user to Desk.com such that they're already -- logged in when they arrive. For example, you may use -- @deskComLoginRoute@ as the login URL on Multipass config. deskComLoginRoute :: Route DeskCom deskComLoginRoute = DeskComLoginR -- | If the user is logged in, redirect them to Desk.com such -- that they're already logged in when they arrive (same as -- 'deskComLoginRoute'). Otherwise, redirect them to Desk.com -- without asking for credentials. For example, you may use -- @deskComMaybeLoginRoute@ when the user clicks on a \"Support\" -- item on a menu. deskComMaybeLoginRoute :: Route DeskCom deskComMaybeLoginRoute = DeskComMaybeLoginR -- | Route used by the Desk.com remote authentication. Works -- both when Desk.com call us and when we call them. Forces user -- to be logged in. getDeskComLoginR :: YesodDeskCom master => HandlerT DeskCom (HandlerT master IO) () getDeskComLoginR = lift $ requireAuthId >>= redirectToMultipass -- | Same as 'getDeskComLoginR' if the user is logged in, -- otherwise redirect to the Desk.com portal without asking for -- credentials. getDeskComMaybeLoginR :: YesodDeskCom master => HandlerT DeskCom (HandlerT master IO) () getDeskComMaybeLoginR = lift $ maybeAuthId >>= maybe redirectToPortal redirectToMultipass -- | Redirect the user to the main Desk.com portal. redirectToPortal :: YesodDeskCom master => HandlerT master IO () redirectToPortal = do DeskComCredentials {..} <- deskComCredentials redirect $ T.concat [ "http://", dccDomain, "/" ] -- | Redirect the user to the multipass login. redirectToMultipass :: YesodDeskCom master => AuthId master -> HandlerT master IO () redirectToMultipass uid = do -- Get generic info. y <- getYesod DeskComCredentials {..} <- deskComCredentials -- Get the expires timestamp. expires <- TI.addUTCTime (deskComTokenTimeout y) <$> liftIO TI.getCurrentTime -- Get information about the currently logged user. DeskComUser {..} <- deskComUserInfo uid userId <- case duUserId of UseYesodAuthId -> toPathPiece <$> requireAuthId Explicit x -> return x -- FIXME Desk.com now actually does have IV support. We should use it... but -- I'm tired. ivBS <- deskComRandomIV let iv = ivBS -- Create Multipass token. let toStrict = B.concat . BL.toChunks deskComEncode = fst . B.spanEnd (== 61) -- remove trailing '=' per Desk.com . B64URL.encode -- base64url encoding encrypt = deskComEncode -- encode as modified base64url . AES.encryptCBC dccAesKey iv -- encrypt with AES128-CBC . (ivBS <>) . Padding.padPKCS5 16 -- PKCS#5 padding . toStrict . A.encode . A.object -- encode as JSON sign = \bs -> case dccHmacKey of MacKeyHelper key -> B64.encode . Crypto.encode -- encode as normal base64 (why??? =[) . HMAC.hmac' key $ bs -- sign using HMAC-SHA1 multipass = encrypt $ "uid" A..= userId : "expires" A..= expires : "customer_email" A..= duEmail : "customer_name" A..= duName : [ "to" A..= to | Just to <- return duRedirectTo ] ++ [ ("customer_" <> k) A..= v | (k, v) <- duCustomFields ] signature = sign multipass query = [("multipass", multipass), ("signature", signature)] -- Redirect to Desk.com redirect $ T.concat [ "http://" , dccDomain , "/customer/authentication/multipass/callback?" , TE.decodeUtf8 (renderSimpleQuery False query) ]
fpco/yesod-auth-deskcom
src/Yesod/Auth/DeskCom.hs
bsd-3-clause
10,809
0
19
2,684
1,577
927
650
-1
-1
{-# LANGUAGE OverloadedStrings, GeneralizedNewtypeDeriving #-} module Clay.Border ( -- * Stroke type. Stroke , solid, dotted, dashed, double, wavy -- * Border properties. , border, borderTop, borderLeft, borderBottom, borderRight , borderColor, borderLeftColor, borderRightColor, borderTopColor, borderBottomColor , borderStyle, borderLeftStyle, borderRightStyle, borderTopStyle, borderBottomStyle , borderWidth, borderLeftWidth, borderRightWidth, borderTopWidth, borderBottomWidth -- * Border radius. , borderRadius , borderTopLeftRadius, borderTopRightRadius , borderBottomLeftRadius, borderBottomRightRadius ) where import Clay.Property import Clay.Stylesheet import Clay.Color import Clay.Common import Clay.Size newtype Stroke = Stroke Value deriving (Val, Other, Inherit, Auto, None) solid, dotted, dashed, double, wavy :: Stroke solid = Stroke "solid" dotted = Stroke "dotted" dashed = Stroke "dashed" double = Stroke "double" wavy = Stroke "Wavu" border, borderTop, borderLeft, borderBottom, borderRight :: Stroke -> Size Abs -> Color -> Css border a b c = key "border" (a ! b ! c) borderTop a b c = key "border-top" (a ! b ! c) borderLeft a b c = key "border-left" (a ! b ! c) borderBottom a b c = key "border-bottom" (a ! b ! c) borderRight a b c = key "border-right" (a ! b ! c) borderColor, borderLeftColor, borderRightColor, borderTopColor, borderBottomColor :: Color -> Css borderColor = key "border-color" borderLeftColor = key "border-left-color" borderRightColor = key "border-right-color" borderTopColor = key "border-top-color" borderBottomColor = key "border-bottom-color" borderStyle, borderLeftStyle, borderRightStyle, borderTopStyle, borderBottomStyle :: Stroke -> Css borderStyle = key "border-style" borderLeftStyle = key "border-left-style" borderRightStyle = key "border-right-style" borderTopStyle = key "border-top-style" borderBottomStyle = key "border-bottom-style" borderWidth, borderLeftWidth, borderRightWidth, borderTopWidth, borderBottomWidth :: Size Abs -> Css borderWidth = key "border-width" borderLeftWidth = key "border-left-width" borderRightWidth = key "border-right-width" borderTopWidth = key "border-top-width" borderBottomWidth = key "border-bottom-width" ------------------------------------------------------------------------------- borderRadius :: Size a -> Css borderRadius = key "border-radius" borderTopLeftRadius, borderTopRightRadius, borderBottomLeftRadius, borderBottomRightRadius :: Size a -> Size a -> Css borderTopLeftRadius a b = key "border-top-left-radius" (a ! b) borderTopRightRadius a b = key "border-top-right-radius" (a ! b) borderBottomLeftRadius a b = key "border-bottom-left-radius" (a ! b) borderBottomRightRadius a b = key "border-bottom-right-radius" (a ! b)
bergmark/clay
src/Clay/Border.hs
bsd-3-clause
2,846
0
8
442
690
392
298
57
1
-- | Stolen from rack: catches all exceptions raised from the app it wraps. module Hack2.Contrib.Middleware.ShowExceptions (show_exceptions) where import Data.Default import Data.Maybe import Hack2 import Hack2.Contrib.Middleware.Hub import Hack2.Contrib.Utils import Air.Light import Prelude hiding ((.), (^), (>), (-), log) import System.IO import System.IO.Error import qualified Data.ByteString.Char8 as B program :: String program = "ShowExceptions" show_exceptions :: Maybe HackErrors -> Middleware show_exceptions stream app = \env -> do let my_stream = unHackErrors - stream.fromMaybe (env.hack_errors) let log = simple_logger (\x -> my_stream (B.pack x)) program app env `catch` (handler log) where handler :: Logger -> IOError -> IO Response handler log e = do let message = e.show Error. log message return - def { status = 500, body = B.pack message }
nfjinjing/hack2-contrib
src/Hack2/Contrib/Middleware/ShowExceptions.hs
bsd-3-clause
909
0
17
166
280
159
121
23
1
{-# LANGUAGE QuasiQuotes #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE TemplateHaskell #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE DeriveDataTypeable #-} {-# LANGUAGE RecordWildCards #-} {-# LANGUAGE DeriveGeneric #-} {-# LANGUAGE StandaloneDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# OPTIONS_GHC -fno-warn-orphans #-} module Data.KeyStore.Types.Schema ( keystoreSchema , keystoreChangelog ) where import Data.API.Parse import Data.API.Types import Data.API.Changes keystoreSchema :: API keystoreChangelog :: APIChangelog (keystoreSchema, keystoreChangelog) = [apiWithChangelog| // // External Representation Only // // The builtin support for map-like types introduced in Aeson 1.0 has broken // the mechanism for representing Map in this schema. In order to minimise the // disruption and preserve the existing schema representation we have renamed // all of the types in the schema that contain Map types. In the model these // types are reconstructed just as they would have been in previous KeyStore // editions and mapping functions have been introduced to convert between the // two representations. The KeyStore gets read with this representation, // matching the representation of past keystore packages and gets converted // into the internal type representation (with the maps) that the rest of the // keystore code base expects. z_ks :: KeyStore_ // the keystore = record config :: Configuration_ keymap :: KeyMap_ z_cfg :: Configuration_ = record settings :: Settings triggers :: TriggerMap_ z_tmp :: TriggerMap_ = record map :: [Trigger] z_kmp :: KeyMap_ = record map :: [NameKeyAssoc_] z_nka :: NameKeyAssoc_ = record name :: Name key :: Key_ z_key :: Key_ = record name :: Name comment :: Comment identity :: Identity is_binary :: boolean env_var :: ? EnvVar hash :: ? Hash public :: ? PublicKey secret_copies :: EncrypedCopyMap_ clear_text :: ? ClearText clear_private :: ? PrivateKey created_at :: UTC z_ecm :: EncrypedCopyMap_ = record map :: [EncrypedCopy] // // Classic Schema Definitions // trg :: Trigger = record id :: TriggerID pattern :: Pattern settings :: Settings stgs :: Settings = record 'json' :: json with inj_settings, prj_settings hash :: Hash = record description :: HashDescription hash :: HashData hashd :: HashDescription = record comment :: Comment prf :: HashPRF iterations :: Iterations width_octets :: Octets salt_octets :: Octets salt :: Salt ec :: EncrypedCopy = record safeguard :: Safeguard cipher :: Cipher prf :: HashPRF iterations :: Iterations salt :: Salt secret_data :: EncrypedCopyData sg :: Safeguard = record names :: [Name] with inj_safeguard, prj_safeguard ecd :: EncrypedCopyData = union | rsa :: RSASecretData | aes :: AESSecretData | clear :: ClearText | no_data :: Void rsd :: RSASecretData = record encrypted_key :: RSAEncryptedKey aes_secret_data :: AESSecretData asd :: AESSecretData = record iv :: IV secret_data :: SecretData puk :: PublicKey = record size :: integer n :: Integer e :: Integer with inj_PublicKey, prj_PublicKey prk :: PrivateKey = record pub :: PublicKey d :: Integer p :: Integer q :: Integer dP :: Integer dQ :: Integer qinv :: Integer with inj_PrivateKey, prj_PrivateKey cph :: Cipher = enum | aes128 | aes192 | aes256 prf :: HashPRF = enum | sha1 | sha256 | sha512 ek :: EncryptionKey = union | public :: PublicKey | private :: PrivateKey | symmetric :: AESKey | none :: Void fid :: FragmentID // name of a settings fragment = basic string pat :: Pattern // a regular expression to match keynames = basic string with inj_pattern, prj_pattern its :: Iterations = basic integer octs :: Octets = basic integer nm :: Name = basic string with inj_name, prj_name idn :: Identity = basic string sid :: SettingID = basic string tid :: TriggerID = basic string cmt :: Comment = basic string ev :: EnvVar = basic string ct :: ClearText = basic binary slt :: Salt = basic binary iv :: IV = basic binary hd :: HashData = basic binary aek :: AESKey = basic binary sd :: SecretData = basic binary rek :: RSAEncryptedKey = basic binary rsb :: RSASecretBytes = basic binary rsg :: RSASignature = basic binary ep :: EncryptionPacket = basic binary sp :: SignaturePacket = basic binary void :: Void = basic integer changes // Initial version version "0.0.0.1" |]
cdornan/keystore
src/Data/KeyStore/Types/Schema.hs
bsd-3-clause
5,665
0
5
1,857
77
57
20
26
1
module Text.Highlighter.Lexers.Atomo (lexer) where import Data.List (intercalate) import Text.Printf import Text.Regex.PCRE.Light import Text.Highlighter.Types lexer :: Lexer lexer = Lexer { lName = "Atomo" , lAliases = ["atomo"] , lExtensions = [".atomo"] , lMimetypes = ["text/x-atomo"] , lStart = root , lFlags = [multiline] } ascii :: [String] ascii = ["NUL","SOH","[SE]TX","EOT","ENQ","ACK", "BEL","BS","HT","LF","VT","FF","CR","S[OI]","DLE", "DC[1-4]","NAK","SYN","ETB","CAN", "EM","SUB","ESC","[FGRU]S","SP","DEL"] reserved :: [String] reserved = ["operator", "macro", "for-macro", "this"] identifier :: String identifier = "[a-zA-Z0-9_!#%&\\*\\+\\.\\\\/<=>\\?@^\\|~\\-]" operator :: String operator = "[:!#%&\\*\\+\\.\\\\/<=>\\?@^\\|~\\-]" root :: TokenMatcher root = -- Comments [ tok "--.*?$" (Comment :. Single) , tokNext "{-" (Comment :. Multiline) (GoTo comment) -- Boolean , tok "True|False" (Keyword :. Constant) -- Numbers , tok "[\\+\\-]?\\d+[eE][\\+\\-]?\\d+" (Number :. Float) , tok "[\\+\\-]?\\d+\\.\\d+([eE][\\+\\-]?\\d+)?" (Number :. Float) , tok "[\\+\\-]?0[oO][0-7]+" (Number :. Oct) , tok "[\\+\\-]?0[xX][\\da-fA-F]+" (Number :. Hex) , tok "[\\+\\-]?\\d+/[\\+\\-]?\\d+" Number , tok "[\\+\\-]?\\d+" (Number :. Integer) -- Internal representations (TODO: these should get less ambiguous syntax.) , tokNext "<[a-z]" (Generic :. Output) (GoTo internal) -- Macro-Quote , tokNext ("(?![\"$|`;~@])(" ++ identifier ++ "+)([\"$|`'~@])") (String :. Other) (CapturesTo macroQuote) , tokNext ("(?![\"$|`;~@])(" ++ identifier ++ "+)\\(") (String :. Other) (GoTo (macroQuoteDelim "\\)")) , tokNext ("(?![\"$|`;~@])(" ++ identifier ++ "+)\\{") (String :. Other) (GoTo (macroQuoteDelim "\\}")) , tokNext ("(?![\"$|`;~@])(" ++ identifier ++ "+)\\[") (String :. Other) (GoTo (macroQuoteDelim "\\]")) -- Identifiers , tok (printf "\\b(%s)\\b(?!%s)" (intercalate "|" reserved) operator) (Keyword :. Reserved) , tok ("(?![@$~])(?!" ++ operator ++ "+(\\s|$))" ++ identifier ++ "+:") (Name :. Function) {-, tok ("[A-Z]" ++ identifier ++ "*") (Name :. Variable :. Global)-} , tok ("(?![@$~])(?!" ++ operator ++ "+(\\s|$))" ++ identifier ++ "+") Name -- Operators , tok ("(?![@$~])" ++ operator ++ "+") Operator -- Whitespace , tok "\\s+" Text -- Characters & Strings , tokNext "\\$" (String :. Char) (GoTo character) , tokNext "\"" String (GoTo string) -- Quoting , tok ("'" ++ identifier ++ "+") (String :. Symbol) , tok "'" (String :. Symbol) , tok ("`" ++ identifier ++ "+") (String :. Symbol) , tok "`" (String :. Symbol) , tok ("~" ++ identifier ++ "+") (String :. Interpol) , tok "~" (String :. Interpol) -- Particles , tok ("@(" ++ identifier ++ "+:)+") (Name :. Decorator) , tok ("@" ++ identifier ++ "+") (Name :. Decorator) , tok "@" (Name :. Decorator) -- Punctuation , tok "[][(),;{}|]" Punctuation ] internal :: TokenMatcher internal = [ tok "[^<>]+" (Generic :. Output) , tokNext "<" (Generic :. Output) Push , tokNext ">" (Generic :. Output) Pop ] comment :: TokenMatcher comment = [ tok "[^\\-\\{\\}]+" (Comment :. Multiline) , tokNext "{-" (Comment :. Multiline) Push , tokNext "-}" (Comment :. Multiline) Pop , tok "[-{}]" (Comment :. Multiline) ] character :: TokenMatcher character = [ tokNext "[^\\\\]" (String :. Char) Pop , tokNext "\\\\[^\\s]+" (String :. Escape) Pop ] string :: TokenMatcher string = [ tok "[^\\\\\"]+" String , tokNext "\\\\" (String :. Escape) (GoTo escape) , tokNext "\"" String Pop ] macroQuoteDelim :: String -> TokenMatcher macroQuoteDelim c = [ tok ("[^\\\\" ++ c ++ "]+") (String :. Other) , tokNext "\\\\." (String :. Other) Continue , tokNext (c ++ "([[:alpha:]]*)") (String :. Other) Pop ] macroQuote :: [String] -> TokenMatcher macroQuote cs = [ tok ("[^\\\\" ++ (cs !! 2) ++ "]+") (String :. Other) , tokNext "\\\\." (String :. Other) Continue , tokNext ((cs !! 2) ++ "([[:alpha:]]*)") (String :. Other) Pop ] escape :: TokenMatcher escape = [ tokNext "[abfnrtv\"&\\\\]" (String :. Escape) Pop , tokNext "\\^[\\]\\[A-Z@\\^_]" (String :. Escape) Pop , tokNext (intercalate "|" ascii) (String :. Escape) Pop , tokNext "o[0-7]+" (String :. Escape) Pop , tokNext "x[\\da-fA-F]+" (String :. Escape) Pop , tokNext "\\d+" (String :. Escape) Pop , tokNext "\\s+\\\\" (String :. Escape) Pop ]
chemist/highlighter
src/Text/Highlighter/Lexers/Atomo.hs
bsd-3-clause
4,631
0
11
1,002
1,481
823
658
98
1
module Main where import Network.Krist.Address import Network.Krist.Node import Network.Krist.Work import Network.Krist.Block import Data.Krist.PrivateKey import Data.Krist.Address main :: IO () main = do x <- getAddress defaultNode "khugepoopy" print x y <- getAddresses defaultNode 10 print y let pkey = makeKWPrivateKey "0000" putStrLn pkey putStrLn $ makeV2Address pkey work <- getWork defaultNode putStrLn $ "Work is: " ++ show work lastBlock <- getLastBlock defaultNode putStrLn $ "Last block is: " ++ show lastBlock block4 <- getBlock defaultNode 4 putStrLn $ "Block #4 is: " ++ show block4 let testNonce = "3431241" resp <- submitBlock defaultNode "khugepoopy" testNonce case resp of Left e -> print e Right s -> if s then putStrLn "Submitted block!" else putStrLn "Block rejected."
demhydraz/krisths
app/Main.hs
bsd-3-clause
1,001
0
11
327
258
120
138
27
3
{-# OPTIONS_GHC -F -pgmF htfpp #-} module Main where import Test.Framework import {-@ HTF_TESTS @-} MultiTrieTest main :: IO() main = htfMain htf_importedTests
vadimvinnik/multi-trie
tests/Spec.hs
mit
164
0
6
27
32
19
13
6
1
{-# LANGUAGE PolyKinds #-} module Database.Edis.Command.Scripting where import Database.Edis.Type import Data.ByteString (ByteString) import Database.Redis as Redis hiding (decode) -------------------------------------------------------------------------------- -- Scripting -------------------------------------------------------------------------------- eval :: (RedisResult a) => ByteString -> [ByteString] -> [ByteString] -> Edis xs xs (Either Reply a) eval script keys' args = Edis $ Redis.eval script keys' args evalsha :: (RedisResult a) => ByteString -> [ByteString] -> [ByteString] -> Edis xs xs (Either Reply a) evalsha script keys' args = Edis $ Redis.evalsha script keys' args scriptExists :: [ByteString] -> Edis xs xs (Either Reply [Bool]) scriptExists scripts = Edis $ Redis.scriptExists scripts scriptFlush :: Edis xs xs (Either Reply Status) scriptFlush = Edis $ Redis.scriptFlush scriptKill :: Edis xs xs (Either Reply Status) scriptKill = Edis $ Redis.scriptFlush scriptLoad :: ByteString -> Edis xs xs (Either Reply ByteString) scriptLoad script = Edis $ Redis.scriptLoad script
banacorn/tredis
src/Database/Edis/Command/Scripting.hs
mit
1,129
0
11
168
335
179
156
19
1
{- | Module : $Header$ Description : folding functions for CASL terms and formulas Copyright : (c) Christian Maeder, Uni Bremen 2005 License : GPLv2 or higher, see LICENSE.txt Maintainer : Christian.Maeder@dfki.de Stability : provisional Portability : portable folding functions for CASL terms and formulas -} module CASL.Fold where import Common.Id import CASL.AS_Basic_CASL data Record f a b = Record { foldQuantification :: FORMULA f -> QUANTIFIER -> [VAR_DECL] -> a -> Range -> a , foldJunction :: FORMULA f -> Junctor -> [a] -> Range -> a , foldRelation :: FORMULA f -> a -> Relation -> a -> Range -> a , foldNegation :: FORMULA f -> a -> Range -> a , foldAtom :: FORMULA f -> Bool -> Range -> a , foldPredication :: FORMULA f -> PRED_SYMB -> [b] -> Range -> a , foldDefinedness :: FORMULA f -> b -> Range -> a , foldEquation :: FORMULA f -> b -> Equality -> b -> Range -> a , foldMembership :: FORMULA f -> b -> SORT -> Range -> a , foldMixfix_formula :: FORMULA f -> b -> a , foldSort_gen_ax :: FORMULA f -> [Constraint] -> Bool -> a , foldQuantOp :: FORMULA f -> OP_NAME -> OP_TYPE -> a -> a , foldQuantPred :: FORMULA f -> PRED_NAME -> PRED_TYPE -> a -> a , foldExtFORMULA :: FORMULA f -> f -> a , foldQual_var :: TERM f -> VAR -> SORT -> Range -> b , foldApplication :: TERM f -> OP_SYMB -> [b] -> Range -> b , foldSorted_term :: TERM f -> b -> SORT -> Range -> b , foldCast :: TERM f -> b -> SORT -> Range -> b , foldConditional :: TERM f -> b -> a -> b -> Range -> b , foldMixfix_qual_pred :: TERM f -> PRED_SYMB -> b , foldMixfix_term :: TERM f -> [b] -> b , foldMixfix_token :: TERM f -> Token -> b , foldMixfix_sorted_term :: TERM f -> SORT -> Range -> b , foldMixfix_cast :: TERM f -> SORT -> Range -> b , foldMixfix_parenthesized :: TERM f -> [b] -> Range -> b , foldMixfix_bracketed :: TERM f -> [b] -> Range -> b , foldMixfix_braced :: TERM f -> [b] -> Range -> b , foldExtTERM :: TERM f -> f -> b } mapRecord :: (f -> g) -> Record f (FORMULA g) (TERM g) mapRecord mf = Record { foldQuantification = const Quantification , foldJunction = const Junction , foldRelation = const Relation , foldNegation = const Negation , foldAtom = const Atom , foldPredication = const Predication , foldDefinedness = const Definedness , foldEquation = const Equation , foldMembership = const Membership , foldMixfix_formula = const Mixfix_formula , foldSort_gen_ax = const mkSort_gen_ax , foldQuantOp = const QuantOp , foldQuantPred = const QuantPred , foldExtFORMULA = \ _ -> ExtFORMULA . mf , foldQual_var = const Qual_var , foldApplication = const Application , foldSorted_term = const Sorted_term , foldCast = const Cast , foldConditional = const Conditional , foldMixfix_qual_pred = const Mixfix_qual_pred , foldMixfix_term = const Mixfix_term , foldMixfix_token = const Mixfix_token , foldMixfix_sorted_term = const Mixfix_sorted_term , foldMixfix_cast = const Mixfix_cast , foldMixfix_parenthesized = const Mixfix_parenthesized , foldMixfix_bracketed = const Mixfix_bracketed , foldMixfix_braced = const Mixfix_braced , foldExtTERM = \ _ -> ExtTERM . mf } constRecord :: (f -> a) -> ([a] -> a) -> a -> Record f a a constRecord mf join c = Record { foldQuantification = \ _ _ _ r _ -> r , foldJunction = \ _ _ l _ -> join l , foldRelation = \ _ l _ r _ -> join [l, r] , foldNegation = \ _ r _ -> r , foldAtom = \ _ _ _ -> c , foldPredication = \ _ _ l _ -> join l , foldDefinedness = \ _ r _ -> r , foldEquation = \ _ l _ r _ -> join [l, r] , foldMembership = \ _ r _ _ -> r , foldMixfix_formula = \ _ r -> r , foldSort_gen_ax = \ _ _ _ -> c , foldQuantOp = \ _ _ _ a -> a , foldQuantPred = \ _ _ _ a -> a , foldExtFORMULA = const mf , foldQual_var = \ _ _ _ _ -> c , foldApplication = \ _ _ l _ -> join l , foldSorted_term = \ _ r _ _ -> r , foldCast = \ _ r _ _ -> r , foldConditional = \ _ l f r _ -> join [l, f, r] , foldMixfix_qual_pred = \ _ _ -> c , foldMixfix_term = const join , foldMixfix_token = \ _ _ -> c , foldMixfix_sorted_term = \ _ _ _ -> c , foldMixfix_cast = \ _ _ _ -> c , foldMixfix_parenthesized = \ _ l _ -> join l , foldMixfix_bracketed = \ _ l _ -> join l , foldMixfix_braced = \ _ l _ -> join l , foldExtTERM = const mf } foldFormula :: Record f a b -> FORMULA f -> a foldFormula r f = case f of Quantification q vs e ps -> foldQuantification r f q vs (foldFormula r e) ps Junction j fs ps -> foldJunction r f j (map (foldFormula r) fs) ps Relation f1 c f2 ps -> foldRelation r f (foldFormula r f1) c (foldFormula r f2) ps Negation e ps -> foldNegation r f (foldFormula r e) ps Atom b ps -> foldAtom r f b ps Predication p ts ps -> foldPredication r f p (map (foldTerm r) ts) ps Definedness t ps -> foldDefinedness r f (foldTerm r t) ps Equation t1 e t2 ps -> foldEquation r f (foldTerm r t1) e (foldTerm r t2) ps Membership t s ps -> foldMembership r f (foldTerm r t) s ps Mixfix_formula t -> foldMixfix_formula r f (foldTerm r t) Unparsed_formula s _ -> error $ "Fold.foldFormula.Unparsed" ++ s Sort_gen_ax cs b -> foldSort_gen_ax r f cs b QuantOp o t q -> foldQuantOp r f o t $ foldFormula r q QuantPred p t q -> foldQuantPred r f p t $ foldFormula r q ExtFORMULA e -> foldExtFORMULA r f e foldTerm :: Record f a b -> TERM f -> b foldTerm r = foldOnlyTerm (foldFormula r) r foldOnlyTerm :: (FORMULA f -> a) -> Record f a b -> TERM f -> b foldOnlyTerm ff r t = case t of Qual_var v s ps -> foldQual_var r t v s ps Application o ts ps -> foldApplication r t o (map (foldOnlyTerm ff r) ts) ps Sorted_term st s ps -> foldSorted_term r t (foldOnlyTerm ff r st) s ps Cast ct s ps -> foldCast r t (foldOnlyTerm ff r ct) s ps Conditional t1 f t2 ps -> foldConditional r t (foldOnlyTerm ff r t1) (ff f) (foldOnlyTerm ff r t2) ps Unparsed_term s _ -> error $ "Fold.Unparsed_term" ++ s Mixfix_qual_pred p -> foldMixfix_qual_pred r t p Mixfix_term ts -> foldMixfix_term r t (map (foldOnlyTerm ff r) ts) Mixfix_token s -> foldMixfix_token r t s Mixfix_sorted_term s ps -> foldMixfix_sorted_term r t s ps Mixfix_cast s ps -> foldMixfix_cast r t s ps Mixfix_parenthesized ts ps -> foldMixfix_parenthesized r t (map (foldOnlyTerm ff r) ts) ps Mixfix_bracketed ts ps -> foldMixfix_bracketed r t (map (foldOnlyTerm ff r) ts) ps Mixfix_braced ts ps -> foldMixfix_braced r t (map (foldOnlyTerm ff r) ts) ps ExtTERM e -> foldExtTERM r t e
keithodulaigh/Hets
CASL/Fold.hs
gpl-2.0
6,786
0
13
1,793
2,544
1,319
1,225
135
15
module HAHP.Data.Utils where import Data.Map (Map) import GHC.Generics import Numeric.LinearAlgebra.HMatrix import HAHP.Data.Core -- * Data retrieve functions getTreeLeaves :: AHPTree -- ^ Input tree -> [AHPTree] -- ^ List of the leaves getTreeLeaves ahpTree = case ahpTree of AHPTree {} -> concatMap getTreeLeaves (children ahpTree) AHPLeaf {} -> [ahpTree] getIndicatorCurrentLevelCount :: AHPTree -- ^ Input tree -> Int -- ^ Indicator (AHPLeaf) count. Current level only getIndicatorCurrentLevelCount ahpTree = length leaves where leaves = filter isLeaf (children ahpTree) getIndicatorRecursiveCount :: AHPTree -- ^ Input tree -> Int -- ^ Indicator (AHPLeaf) recursively counted getIndicatorRecursiveCount ahpTree = case ahpTree of AHPLeaf {} -> 1 AHPTree {} -> currentLevel + countSubLevel where trees = filter isTree (children ahpTree) currentLevel = getIndicatorCurrentLevelCount ahpTree countSubLevel = sum $ map getIndicatorRecursiveCount trees isLeaf :: AHPTree -> Bool isLeaf ahpTree = case ahpTree of AHPLeaf {} -> True AHPTree {} -> False isTree :: AHPTree -> Bool isTree = not . isLeaf
Taeradan/hahp
src/HAHP/Data/Utils.hs
gpl-3.0
1,341
0
10
399
281
152
129
31
2
{-# LANGUAGE OverloadedStrings #-} module HROOT.Data.IO.Class where import FFICXX.Generate.Code.Primitive ( cstring, int ) import FFICXX.Generate.Type.Cabal ( BuildType(..), Cabal(..), CabalName(..) ) import FFICXX.Generate.Type.Class ( Class(..) , Function(..) , ProtectedMethod(..) , TopLevel(..) ) import FFICXX.Generate.Type.Config ( ModuleUnit(..) , ModuleUnitImports(..) , modImports ) -- import HROOT.Data.Core.Class ( tDirectory ) iocabal :: Cabal iocabal = Cabal { cabal_pkgname = CabalName "HROOT-io" , cabal_version = "0.10.0.1" , cabal_cheaderprefix = "HROOTIO" , cabal_moduleprefix = "HROOT.IO" , cabal_additional_c_incs = [] , cabal_additional_c_srcs = [] , cabal_additional_pkgdeps = [ CabalName "stdcxx", CabalName "HROOT-core" ] , cabal_license = Nothing , cabal_licensefile = Nothing , cabal_extraincludedirs = [] , cabal_extralibdirs = [] , cabal_extrafiles = [] , cabal_pkg_config_depends = [] , cabal_buildType = Custom [CabalName "Cabal", CabalName "base", CabalName "process"] } ioclass :: String -> [Class] -> [Function] -> Class ioclass n ps fs = Class { class_cabal = iocabal , class_name = n , class_parents = ps , class_protected = Protected [] , class_alias = Nothing , class_funcs = fs , class_vars = [] , class_tmpl_funcs = [] , class_has_proxy = False } tDirectoryFile :: Class tDirectoryFile = ioclass "TDirectoryFile" [tDirectory] [ {- Virtual (cppclass_ "TList") "GetListOfKeys" [] -} ] tFile :: Class tFile = ioclass "TFile" [tDirectoryFile] [ Constructor [cstring "fname", cstring "option", cstring "ftitle", int "compress" ] Nothing ] tMemFile :: Class tMemFile = ioclass "TMemFile" [tFile] [ Constructor [cstring "path", cstring "option", cstring "ftitle", int "compress" ] Nothing ] io_classes :: [Class] io_classes = [ tDirectoryFile , tFile , tMemFile ] io_topfunctions :: [TopLevel] io_topfunctions = [] io_headers :: [(ModuleUnit,ModuleUnitImports)] io_headers = [ modImports "TDirectoryFile" ["ROOT"] ["TDirectoryFile.h"] , modImports "TFile" ["ROOT"] ["TFile.h"] , modImports "TMemFile" ["ROOT"] ["TMemFile.h"] ] io_extraLib :: [String] io_extraLib = [] io_extraDep :: [(String,[String])] io_extraDep = []
wavewave/HROOT
HROOT-generate/lib/HROOT/Data/IO/Class.hs
gpl-3.0
2,689
0
9
821
644
390
254
68
1
{-# LANGUAGE CPP #-} {-# LANGUAGE Trustworthy #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleContexts #-} ----------------------------------------------------------------------------- -- | -- Copyright : (C) 2013-15 Edward Kmett -- License : BSD-style (see the file LICENSE) -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable -- ----------------------------------------------------------------------------- module Succinct.Dictionary.Poppy ( Poppy(..) , poppy ) where #if __GLASGOW_HASKELL__ < 710 import Control.Applicative #endif import Control.Monad.ST import Data.Bits import qualified Data.Vector.Primitive as P import Data.Vector.Internal.Check as Ck import Data.Word import Succinct.Dictionary.Builder import Succinct.Dictionary.Class import Succinct.Internal.Bit as B import Succinct.Internal.PopCount #define BOUNDS_CHECK(f) Ck.f __FILE__ __LINE__ Ck.Bounds data Poppy = Poppy {-# UNPACK #-} !Int -- length in bit {-# UNPACK #-} !VectorInternal -- the bitvector !(P.Vector Word64) -- upper layer of the inventory !(P.Vector Word64) -- main layer of the inventory deriving (Eq,Ord,Show) instance Access Bool Poppy where size (Poppy n _ _ _) = n {-# INLINE size #-} (!) (Poppy n bs _ _) i = BOUNDS_CHECK(checkIndex) "Poppy.!" i n $ testBit (unsafeIndexInternal bs $ wd i) (bt i) {-# INLINE (!) #-} instance Bitwise Poppy B.Vector where bitwise (Poppy n v _ _) = V_Bit n $ vectorFromInternal v {-# INLINE bitwise #-} instance Dictionary Bool Poppy instance Select0 Poppy instance Select1 Poppy instance Ranked Poppy where rank1 t@(Poppy n _ _ _) i = BOUNDS_CHECK(checkIndex) "rank" i (n+1) $ unsafeRank1 t i {-# INLINE rank1 #-} unsafeRank1 (Poppy _ ws ups ps) i = fromIntegral result where upperBlock = i `shiftR` 32 upperCnt = fromIntegral $ P.unsafeIndex ups upperBlock block = i `shiftR` 9 -- TODO(klao): Is it better to read it as 2 Word32s? d4 = P.unsafeIndex ps (i `shiftR` 11) upto4BlockCnt = fromIntegral $ d4 `shiftR` 32 k4 = block .&. 3 m = d4 .&. (1 `unsafeShiftL` (10 * k4) - 1) blockCnts = fromIntegral $ m .&. 1023 + (m `shiftR` 10) .&. 1023 + (m `shiftR` 20) .&. 1023 blockStart = block `shiftL` 3 bitInBlock = i .&. 511 cnt = popCountBitSlice ws blockStart bitInBlock result = upto4BlockCnt + blockCnts + cnt + upperCnt {-# INLINE unsafeRank1 #-} poppy :: Bitwise t B.Vector => t -> Poppy poppy t = case bitwise t of V_Bit n ws0 -> Poppy n ws ups ps where ws = vectorToInternal ws0 psSize = 1 + (n + 512) `shiftR` 11 (ups, ps) = runST $ case poppyBlockBuilder $ vectorSized psSize of Builder (Building kp hp zp) -> zp >>= go 0 >>= kp where nWords = wd n go k s | k' <= nWords = hp s (popCount512Bits ws k) >>= go k' | otherwise = hp s (popCountBitSlice ws k remBits) where remBits = n - k `shiftL` 6 k' = k + 8 {-# INLINE [0] poppy #-} {-# RULES "poppy" poppy = id #-} data BuildPoppyBlock a b = BPB {-# UNPACK #-} !Int -- block count {-# UNPACK #-} !Word64 -- full popcount {-# UNPACK #-} !Word64 -- lower popcount {-# UNPACK #-} !Word64 -- 4 block popcounts !a -- upper vector builder !b -- lower vector builder poppyBlockBuilder :: Builder Word64 (P.Vector Word64) -> Builder Int (P.Vector Word64, P.Vector Word64) poppyBlockBuilder vectorBuilder = Builder $ case vector of Builder (Building ku hu zu) -> case vectorBuilder of Builder (Building kl hl zl) -> Building stop step start where uMask = 1 `shiftL` (32 - 9) - 1 start = BPB 0 0 0 0 <$> (zu >>= (`hu` 0)) <*> zl step (BPB n pc lpc cw us ls) p | n .&. uMask == uMask = BPB n' pc' 0 0 <$> hu us pc' <*> hl ls cw | n .&. 3 == 3 = BPB n' pc' lpc' cw'' us <$> hl ls cw | otherwise = return $ BPB n' pc' lpc' cw' us ls where n' = n + 1 pw = fromIntegral p pc' = pc + pw lpc' = lpc + pw cw'' = lpc' `shiftL` 32 i = n .&. 3 cw' = cw .|. (pw `unsafeShiftL` (i * 10)) stop (BPB _n _pc _lpc cw us ls) = do ls' <- hl ls cw ups <- ku us ps <- kl ls' return (ups, ps) {-# INLINE poppyBlockBuilder #-} data BuildPoppyWords a b = BPW {-# UNPACK #-} !Int -- word count {-# UNPACK #-} !Int -- block popcount !a -- poppy block builder !b -- vector builder poppyWordBuilder :: Builder Word64 Poppy poppyWordBuilder = Builder $ case vector of Builder (Building kw hw zw) -> case poppyBlockBuilder vector of Builder (Building kb hb zb) -> Building stop step start where start = BPW 0 0 <$> zb <*> zw step (BPW n pc bs ws) w | n .&. 7 == 7 = BPW n' 0 <$> hb bs pc' <*> hw ws w | otherwise = BPW n' pc' bs <$> hw ws w where n' = n + 1 pc' = pc + popCountWord64 w stop (BPW n pc bs ws) = do bs' <- hb bs pc vec <- kw ws (ups, ps) <- kb bs' return $ Poppy (n * 64) (vectorToInternal vec) ups ps {-# INLINE poppyWordBuilder #-} instance Buildable Bool Poppy where builder = Builder $ case poppyWordBuilder of Builder pwb -> wordToBitBuilding pwb fixSize where fixSize n (Poppy _ ws ups ps) = return $ Poppy n ws ups ps {-# INLINE builder #-}
Gabriel439/succinct
src/Succinct/Dictionary/Poppy.hs
bsd-2-clause
5,775
0
20
1,797
1,740
911
829
139
1
{-# LANGUAGE DeriveDataTypeable, TypeFamilies, TemplateHaskell, FlexibleInstances, FlexibleContexts, MultiParamTypeClasses, TypeOperators, TypeSynonymInstances #-} module Distribution.Server.Features.BuildReports.State where import Distribution.Server.Features.BuildReports.BuildReports (BuildReportId, BuildLog, BuildReport, BuildReports, PkgBuildReports) import qualified Distribution.Server.Features.BuildReports.BuildReports as BuildReports import Distribution.Package import qualified Data.Serialize as Serialize import Control.Monad.Reader import qualified Control.Monad.State as State import Data.Acid (Query, Update, makeAcidic) import Data.SafeCopy (SafeCopy(..), contain) -- BuildReportId instance SafeCopy BuildReportId where putCopy = contain . Serialize.put getCopy = contain Serialize.get -- BuildLog instance SafeCopy BuildLog where putCopy = contain . Serialize.put getCopy = contain Serialize.get -- BuildReport instance SafeCopy BuildReport where putCopy = contain . Serialize.put getCopy = contain Serialize.get -- PkgBuildReports instance SafeCopy PkgBuildReports where putCopy = contain . Serialize.put getCopy = contain Serialize.get -- BuildReports instance SafeCopy BuildReports where putCopy = contain . Serialize.put getCopy = contain Serialize.get initialBuildReports :: BuildReports initialBuildReports = BuildReports.emptyReports -- and defined methods addReport :: PackageId -> (BuildReport, Maybe BuildLog) -> Update BuildReports BuildReportId addReport pkgid report = do buildReports <- State.get let (reports, reportId) = BuildReports.addReport pkgid report buildReports State.put reports return reportId setBuildLog :: PackageId -> BuildReportId -> Maybe BuildLog -> Update BuildReports Bool setBuildLog pkgid reportId buildLog = do buildReports <- State.get case BuildReports.setBuildLog pkgid reportId buildLog buildReports of Nothing -> return False Just reports -> State.put reports >> return True deleteReport :: PackageId -> BuildReportId -> Update BuildReports Bool --Maybe BuildReports deleteReport pkgid reportId = do buildReports <- State.get case BuildReports.deleteReport pkgid reportId buildReports of Nothing -> return False Just reports -> State.put reports >> return True lookupReport :: PackageId -> BuildReportId -> Query BuildReports (Maybe (BuildReport, Maybe BuildLog)) lookupReport pkgid reportId = asks (BuildReports.lookupReport pkgid reportId) lookupPackageReports :: PackageId -> Query BuildReports [(BuildReportId, (BuildReport, Maybe BuildLog))] lookupPackageReports pkgid = asks (BuildReports.lookupPackageReports pkgid) getBuildReports :: Query BuildReports BuildReports getBuildReports = ask replaceBuildReports :: BuildReports -> Update BuildReports () replaceBuildReports = State.put $(makeAcidic ''BuildReports ['addReport ,'setBuildLog ,'deleteReport ,'lookupReport ,'lookupPackageReports ,'getBuildReports ,'replaceBuildReports ])
isomorphism/hackage2
Distribution/Server/Features/BuildReports/State.hs
bsd-3-clause
3,245
0
12
650
720
387
333
62
2
{- Copyright 2013-2015 Mario Blazevic License: BSD3 (see BSD3-LICENSE.txt file) -} -- | This module defines the 'FactorialMonoid' class and some of its instances. -- {-# LANGUAGE Haskell2010, Trustworthy #-} module Data.Monoid.Factorial ( -- * Classes FactorialMonoid(..), StableFactorialMonoid, -- * Monad function equivalents mapM, mapM_ ) where import Prelude hiding (break, drop, dropWhile, foldl, foldMap, foldr, last, length, map, mapM, mapM_, max, min, null, reverse, span, splitAt, take, takeWhile) import Control.Arrow (first) import qualified Control.Monad as Monad import Data.Monoid (Monoid (..), Dual(..), Sum(..), Product(..), Endo(Endo, appEndo)) import qualified Data.Foldable as Foldable import qualified Data.List as List import qualified Data.ByteString as ByteString import qualified Data.ByteString.Lazy as LazyByteString import qualified Data.Text as Text import qualified Data.Text.Lazy as LazyText import qualified Data.IntMap as IntMap import qualified Data.IntSet as IntSet import qualified Data.Map as Map import qualified Data.Sequence as Sequence import qualified Data.Set as Set import qualified Data.Vector as Vector import Data.Int (Int64) import Data.Numbers.Primes (primeFactors) import Data.Monoid.Null (MonoidNull(null), PositiveMonoid) -- | Class of monoids that can be split into irreducible (/i.e./, atomic or prime) 'factors' in a unique way. Factors of -- a 'Product' are literally its prime factors: -- -- prop> factors (Product 12) == [Product 2, Product 2, Product 3] -- -- Factors of a list are /not/ its elements but all its single-item sublists: -- -- prop> factors "abc" == ["a", "b", "c"] -- -- The methods of this class satisfy the following laws: -- -- > mconcat . factors == id -- > null == List.null . factors -- > List.all (\prime-> factors prime == [prime]) . factors -- > factors == unfoldr splitPrimePrefix == List.reverse . unfoldr (fmap swap . splitPrimeSuffix) -- > reverse == mconcat . List.reverse . factors -- > primePrefix == maybe mempty fst . splitPrimePrefix -- > primeSuffix == maybe mempty snd . splitPrimeSuffix -- > inits == List.map mconcat . List.tails . factors -- > tails == List.map mconcat . List.tails . factors -- > foldl f a == List.foldl f a . factors -- > foldl' f a == List.foldl' f a . factors -- > foldr f a == List.foldr f a . factors -- > span p m == (mconcat l, mconcat r) where (l, r) = List.span p (factors m) -- > List.all (List.all (not . pred) . factors) . split pred -- > mconcat . intersperse prime . split (== prime) == id -- > splitAt i m == (mconcat l, mconcat r) where (l, r) = List.splitAt i (factors m) -- > spanMaybe () (const $ bool Nothing (Maybe ()) . p) m == (takeWhile p m, dropWhile p m, ()) -- > spanMaybe s0 (\s m-> Just $ f s m) m0 == (m0, mempty, foldl f s0 m0) -- > let (prefix, suffix, s') = spanMaybe s f m -- > foldMaybe = foldl g (Just s) -- > g s m = s >>= flip f m -- > in all ((Nothing ==) . foldMaybe) (inits prefix) -- > && prefix == last (filter (isJust . foldMaybe) $ inits m) -- > && Just s' == foldMaybe prefix -- > && m == prefix <> suffix -- -- A minimal instance definition must implement 'factors' or 'splitPrimePrefix'. Other methods are provided and should -- be implemented only for performance reasons. class MonoidNull m => FactorialMonoid m where -- | Returns a list of all prime factors; inverse of mconcat. factors :: m -> [m] -- | The prime prefix, 'mempty' if none. primePrefix :: m -> m -- | The prime suffix, 'mempty' if none. primeSuffix :: m -> m -- | Splits the argument into its prime prefix and the remaining suffix. Returns 'Nothing' for 'mempty'. splitPrimePrefix :: m -> Maybe (m, m) -- | Splits the argument into its prime suffix and the remaining prefix. Returns 'Nothing' for 'mempty'. splitPrimeSuffix :: m -> Maybe (m, m) -- | Returns the list of all prefixes of the argument, 'mempty' first. inits :: m -> [m] -- | Returns the list of all suffixes of the argument, 'mempty' last. tails :: m -> [m] -- | Like 'List.foldl' from "Data.List" on the list of 'primes'. foldl :: (a -> m -> a) -> a -> m -> a -- | Like 'List.foldl'' from "Data.List" on the list of 'primes'. foldl' :: (a -> m -> a) -> a -> m -> a -- | Like 'List.foldr' from "Data.List" on the list of 'primes'. foldr :: (m -> a -> a) -> a -> m -> a -- | The 'length' of the list of 'primes'. length :: m -> Int -- | Generalizes 'foldMap' from "Data.Foldable", except the function arguments are prime factors rather than the -- structure elements. foldMap :: Monoid n => (m -> n) -> m -> n -- | Like 'List.span' from "Data.List" on the list of 'primes'. span :: (m -> Bool) -> m -> (m, m) -- | Equivalent to 'List.break' from "Data.List". break :: (m -> Bool) -> m -> (m, m) -- | Splits the monoid into components delimited by prime separators satisfying the given predicate. The primes -- satisfying the predicate are not a part of the result. split :: (m -> Bool) -> m -> [m] -- | Equivalent to 'List.takeWhile' from "Data.List". takeWhile :: (m -> Bool) -> m -> m -- | Equivalent to 'List.dropWhile' from "Data.List". dropWhile :: (m -> Bool) -> m -> m -- | A stateful variant of 'span', threading the result of the test function as long as it returns 'Just'. spanMaybe :: s -> (s -> m -> Maybe s) -> m -> (m, m, s) -- | Strict version of 'spanMaybe'. spanMaybe' :: s -> (s -> m -> Maybe s) -> m -> (m, m, s) -- | Like 'List.splitAt' from "Data.List" on the list of 'primes'. splitAt :: Int -> m -> (m, m) -- | Equivalent to 'List.drop' from "Data.List". drop :: Int -> m -> m -- | Equivalent to 'List.take' from "Data.List". take :: Int -> m -> m -- | Equivalent to 'List.reverse' from "Data.List". reverse :: m -> m factors = List.unfoldr splitPrimePrefix primePrefix = maybe mempty fst . splitPrimePrefix primeSuffix = maybe mempty snd . splitPrimeSuffix splitPrimePrefix x = case factors x of [] -> Nothing prefix : rest -> Just (prefix, mconcat rest) splitPrimeSuffix x = case factors x of [] -> Nothing fs -> Just (mconcat (List.init fs), List.last fs) inits = foldr (\m l-> mempty : List.map (mappend m) l) [mempty] tails m = m : maybe [] (tails . snd) (splitPrimePrefix m) foldl f f0 = List.foldl f f0 . factors foldl' f f0 = List.foldl' f f0 . factors foldr f f0 = List.foldr f f0 . factors length = List.length . factors foldMap f = foldr (mappend . f) mempty span p m0 = spanAfter id m0 where spanAfter f m = case splitPrimePrefix m of Just (prime, rest) | p prime -> spanAfter (f . mappend prime) rest _ -> (f mempty, m) break = span . (not .) spanMaybe s0 f m0 = spanAfter id s0 m0 where spanAfter g s m = case splitPrimePrefix m of Just (prime, rest) | Just s' <- f s prime -> spanAfter (g . mappend prime) s' rest | otherwise -> (g mempty, m, s) Nothing -> (m0, m, s) spanMaybe' s0 f m0 = spanAfter id s0 m0 where spanAfter g s m = seq s $ case splitPrimePrefix m of Just (prime, rest) | Just s' <- f s prime -> spanAfter (g . mappend prime) s' rest | otherwise -> (g mempty, m, s) Nothing -> (m0, m, s) split p m = prefix : splitRest where (prefix, rest) = break p m splitRest = case splitPrimePrefix rest of Nothing -> [] Just (_, tl) -> split p tl takeWhile p = fst . span p dropWhile p = snd . span p splitAt n0 m0 | n0 <= 0 = (mempty, m0) | otherwise = split' n0 id m0 where split' 0 f m = (f mempty, m) split' n f m = case splitPrimePrefix m of Nothing -> (f mempty, m) Just (prime, rest) -> split' (pred n) (f . mappend prime) rest drop n p = snd (splitAt n p) take n p = fst (splitAt n p) reverse = mconcat . List.reverse . factors {-# MINIMAL factors | splitPrimePrefix #-} -- | A subclass of 'FactorialMonoid' whose instances satisfy this additional law: -- -- > factors (a <> b) == factors a <> factors b class (FactorialMonoid m, PositiveMonoid m) => StableFactorialMonoid m instance FactorialMonoid () where factors () = [] primePrefix () = () primeSuffix () = () splitPrimePrefix () = Nothing splitPrimeSuffix () = Nothing length () = 0 reverse = id instance FactorialMonoid a => FactorialMonoid (Dual a) where factors (Dual a) = fmap Dual (reverse $ factors a) length (Dual a) = length a primePrefix (Dual a) = Dual (primeSuffix a) primeSuffix (Dual a) = Dual (primePrefix a) splitPrimePrefix (Dual a) = case splitPrimeSuffix a of Nothing -> Nothing Just (p, s) -> Just (Dual s, Dual p) splitPrimeSuffix (Dual a) = case splitPrimePrefix a of Nothing -> Nothing Just (p, s) -> Just (Dual s, Dual p) inits (Dual a) = fmap Dual (reverse $ tails a) tails (Dual a) = fmap Dual (reverse $ inits a) reverse (Dual a) = Dual (reverse a) instance (Integral a, Eq a) => FactorialMonoid (Sum a) where primePrefix (Sum a) = Sum (signum a ) primeSuffix = primePrefix splitPrimePrefix (Sum 0) = Nothing splitPrimePrefix (Sum a) = Just (Sum (signum a), Sum (a - signum a)) splitPrimeSuffix (Sum 0) = Nothing splitPrimeSuffix (Sum a) = Just (Sum (a - signum a), Sum (signum a)) length (Sum a) = abs (fromIntegral a) reverse = id instance Integral a => FactorialMonoid (Product a) where factors (Product a) = List.map Product (primeFactors a) reverse = id instance FactorialMonoid a => FactorialMonoid (Maybe a) where factors Nothing = [] factors (Just a) | null a = [Just a] | otherwise = List.map Just (factors a) length Nothing = 0 length (Just a) | null a = 1 | otherwise = length a reverse = fmap reverse instance (FactorialMonoid a, FactorialMonoid b) => FactorialMonoid (a, b) where factors (a, b) = List.map (\a1-> (a1, mempty)) (factors a) ++ List.map ((,) mempty) (factors b) primePrefix (a, b) | null a = (a, primePrefix b) | otherwise = (primePrefix a, mempty) primeSuffix (a, b) | null b = (primeSuffix a, b) | otherwise = (mempty, primeSuffix b) splitPrimePrefix (a, b) = case (splitPrimePrefix a, splitPrimePrefix b) of (Just (ap, as), _) -> Just ((ap, mempty), (as, b)) (Nothing, Just (bp, bs)) -> Just ((a, bp), (a, bs)) (Nothing, Nothing) -> Nothing splitPrimeSuffix (a, b) = case (splitPrimeSuffix a, splitPrimeSuffix b) of (_, Just (bp, bs)) -> Just ((a, bp), (mempty, bs)) (Just (ap, as), Nothing) -> Just ((ap, b), (as, b)) (Nothing, Nothing) -> Nothing inits (a, b) = List.map (flip (,) mempty) (inits a) ++ List.map ((,) a) (List.tail $ inits b) tails (a, b) = List.map (flip (,) b) (tails a) ++ List.map ((,) mempty) (List.tail $ tails b) foldl f a0 (x, y) = foldl f2 (foldl f1 a0 x) y where f1 a = f a . fromFst f2 a = f a . fromSnd foldl' f a0 (x, y) = a' `seq` foldl' f2 a' y where f1 a = f a . fromFst f2 a = f a . fromSnd a' = foldl' f1 a0 x foldr f a (x, y) = foldr (f . fromFst) (foldr (f . fromSnd) a y) x foldMap f (x, y) = foldMap (f . fromFst) x `mappend` foldMap (f . fromSnd) y length (a, b) = length a + length b span p (x, y) = ((xp, yp), (xs, ys)) where (xp, xs) = span (p . fromFst) x (yp, ys) | null xs = span (p . fromSnd) y | otherwise = (mempty, y) spanMaybe s0 f (x, y) | null xs = ((xp, yp), (xs, ys), s2) | otherwise = ((xp, mempty), (xs, y), s1) where (xp, xs, s1) = spanMaybe s0 (\s-> f s . fromFst) x (yp, ys, s2) = spanMaybe s1 (\s-> f s . fromSnd) y spanMaybe' s0 f (x, y) | null xs = ((xp, yp), (xs, ys), s2) | otherwise = ((xp, mempty), (xs, y), s1) where (xp, xs, s1) = spanMaybe' s0 (\s-> f s . fromFst) x (yp, ys, s2) = spanMaybe' s1 (\s-> f s . fromSnd) y split p (x0, y0) = fst $ List.foldr combine (ys, False) xs where xs = List.map fromFst $ split (p . fromFst) x0 ys = List.map fromSnd $ split (p . fromSnd) y0 combine x (~(y:rest), False) = (mappend x y : rest, True) combine x (rest, True) = (x:rest, True) splitAt n (x, y) = ((xp, yp), (xs, ys)) where (xp, xs) = splitAt n x (yp, ys) | null xs = splitAt (n - length x) y | otherwise = (mempty, y) reverse (a, b) = (reverse a, reverse b) {-# INLINE fromFst #-} fromFst :: Monoid b => a -> (a, b) fromFst a = (a, mempty) {-# INLINE fromSnd #-} fromSnd :: Monoid a => b -> (a, b) fromSnd b = (mempty, b) instance FactorialMonoid [x] where factors xs = List.map (:[]) xs primePrefix [] = [] primePrefix (x:_) = [x] primeSuffix [] = [] primeSuffix xs = [List.last xs] splitPrimePrefix [] = Nothing splitPrimePrefix (x:xs) = Just ([x], xs) splitPrimeSuffix [] = Nothing splitPrimeSuffix xs = Just (splitLast id xs) where splitLast f last@[_] = (f [], last) splitLast f ~(x:rest) = splitLast (f . (x:)) rest inits = List.inits tails = List.tails foldl _ a [] = a foldl f a (x:xs) = foldl f (f a [x]) xs foldl' _ a [] = a foldl' f a (x:xs) = let a' = f a [x] in a' `seq` foldl' f a' xs foldr _ f0 [] = f0 foldr f f0 (x:xs) = f [x] (foldr f f0 xs) length = List.length foldMap f = mconcat . List.map (f . (:[])) break f = List.break (f . (:[])) span f = List.span (f . (:[])) dropWhile f = List.dropWhile (f . (:[])) takeWhile f = List.takeWhile (f . (:[])) spanMaybe s0 f l = (prefix' [], suffix' [], s') where (prefix', suffix', s', _) = List.foldl' g (id, id, s0, True) l g (prefix, suffix, s1, live) x | live, Just s2 <- f s1 [x] = (prefix . (x:), id, s2, True) | otherwise = (prefix, suffix . (x:), s1, False) spanMaybe' s0 f l = (prefix' [], suffix' [], s') where (prefix', suffix', s', _) = List.foldl' g (id, id, s0, True) l g (prefix, suffix, s1, live) x | live, Just s2 <- f s1 [x] = seq s2 $ (prefix . (x:), id, s2, True) | otherwise = (prefix, suffix . (x:), s1, False) splitAt = List.splitAt drop = List.drop take = List.take reverse = List.reverse instance FactorialMonoid ByteString.ByteString where factors x = factorize (ByteString.length x) x where factorize 0 _ = [] factorize n xs = xs1 : factorize (pred n) xs' where (xs1, xs') = ByteString.splitAt 1 xs primePrefix = ByteString.take 1 primeSuffix x = ByteString.drop (ByteString.length x - 1) x splitPrimePrefix x = if ByteString.null x then Nothing else Just (ByteString.splitAt 1 x) splitPrimeSuffix x = if ByteString.null x then Nothing else Just (ByteString.splitAt (ByteString.length x - 1) x) inits = ByteString.inits tails = ByteString.tails foldl f = ByteString.foldl f' where f' a byte = f a (ByteString.singleton byte) foldl' f = ByteString.foldl' f' where f' a byte = f a (ByteString.singleton byte) foldr f = ByteString.foldr (f . ByteString.singleton) break f = ByteString.break (f . ByteString.singleton) span f = ByteString.span (f . ByteString.singleton) spanMaybe s0 f b = case ByteString.foldr g id b (0, s0) of (i, s') | (prefix, suffix) <- ByteString.splitAt i b -> (prefix, suffix, s') where g w cont (i, s) | Just s' <- f s (ByteString.singleton w) = let i' = succ i :: Int in seq i' $ cont (i', s') | otherwise = (i, s) spanMaybe' s0 f b = case ByteString.foldr g id b (0, s0) of (i, s') | (prefix, suffix) <- ByteString.splitAt i b -> (prefix, suffix, s') where g w cont (i, s) | Just s' <- f s (ByteString.singleton w) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s') | otherwise = (i, s) dropWhile f = ByteString.dropWhile (f . ByteString.singleton) takeWhile f = ByteString.takeWhile (f . ByteString.singleton) length = ByteString.length split f = ByteString.splitWith f' where f' = f . ByteString.singleton splitAt = ByteString.splitAt drop = ByteString.drop take = ByteString.take reverse = ByteString.reverse instance FactorialMonoid LazyByteString.ByteString where factors x = factorize (LazyByteString.length x) x where factorize 0 _ = [] factorize n xs = xs1 : factorize (pred n) xs' where (xs1, xs') = LazyByteString.splitAt 1 xs primePrefix = LazyByteString.take 1 primeSuffix x = LazyByteString.drop (LazyByteString.length x - 1) x splitPrimePrefix x = if LazyByteString.null x then Nothing else Just (LazyByteString.splitAt 1 x) splitPrimeSuffix x = if LazyByteString.null x then Nothing else Just (LazyByteString.splitAt (LazyByteString.length x - 1) x) inits = LazyByteString.inits tails = LazyByteString.tails foldl f = LazyByteString.foldl f' where f' a byte = f a (LazyByteString.singleton byte) foldl' f = LazyByteString.foldl' f' where f' a byte = f a (LazyByteString.singleton byte) foldr f = LazyByteString.foldr f' where f' byte a = f (LazyByteString.singleton byte) a length = fromIntegral . LazyByteString.length break f = LazyByteString.break (f . LazyByteString.singleton) span f = LazyByteString.span (f . LazyByteString.singleton) spanMaybe s0 f b = case LazyByteString.foldr g id b (0, s0) of (i, s') | (prefix, suffix) <- LazyByteString.splitAt i b -> (prefix, suffix, s') where g w cont (i, s) | Just s' <- f s (LazyByteString.singleton w) = let i' = succ i :: Int64 in seq i' $ cont (i', s') | otherwise = (i, s) spanMaybe' s0 f b = case LazyByteString.foldr g id b (0, s0) of (i, s') | (prefix, suffix) <- LazyByteString.splitAt i b -> (prefix, suffix, s') where g w cont (i, s) | Just s' <- f s (LazyByteString.singleton w) = let i' = succ i :: Int64 in seq i' $ seq s' $ cont (i', s') | otherwise = (i, s) dropWhile f = LazyByteString.dropWhile (f . LazyByteString.singleton) takeWhile f = LazyByteString.takeWhile (f . LazyByteString.singleton) split f = LazyByteString.splitWith f' where f' = f . LazyByteString.singleton splitAt = LazyByteString.splitAt . fromIntegral drop n = LazyByteString.drop (fromIntegral n) take n = LazyByteString.take (fromIntegral n) reverse = LazyByteString.reverse instance FactorialMonoid Text.Text where factors = Text.chunksOf 1 primePrefix = Text.take 1 primeSuffix x = if Text.null x then Text.empty else Text.singleton (Text.last x) splitPrimePrefix = fmap (first Text.singleton) . Text.uncons splitPrimeSuffix x = if Text.null x then Nothing else Just (Text.init x, Text.singleton (Text.last x)) inits = Text.inits tails = Text.tails foldl f = Text.foldl f' where f' a char = f a (Text.singleton char) foldl' f = Text.foldl' f' where f' a char = f a (Text.singleton char) foldr f = Text.foldr f' where f' char a = f (Text.singleton char) a length = Text.length span f = Text.span (f . Text.singleton) break f = Text.break (f . Text.singleton) dropWhile f = Text.dropWhile (f . Text.singleton) takeWhile f = Text.takeWhile (f . Text.singleton) spanMaybe s0 f t = case Text.foldr g id t (0, s0) of (i, s') | (prefix, suffix) <- Text.splitAt i t -> (prefix, suffix, s') where g c cont (i, s) | Just s' <- f s (Text.singleton c) = let i' = succ i :: Int in seq i' $ cont (i', s') | otherwise = (i, s) spanMaybe' s0 f t = case Text.foldr g id t (0, s0) of (i, s') | (prefix, suffix) <- Text.splitAt i t -> (prefix, suffix, s') where g c cont (i, s) | Just s' <- f s (Text.singleton c) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s') | otherwise = (i, s) split f = Text.split f' where f' = f . Text.singleton splitAt = Text.splitAt drop = Text.drop take = Text.take reverse = Text.reverse instance FactorialMonoid LazyText.Text where factors = LazyText.chunksOf 1 primePrefix = LazyText.take 1 primeSuffix x = if LazyText.null x then LazyText.empty else LazyText.singleton (LazyText.last x) splitPrimePrefix = fmap (first LazyText.singleton) . LazyText.uncons splitPrimeSuffix x = if LazyText.null x then Nothing else Just (LazyText.init x, LazyText.singleton (LazyText.last x)) inits = LazyText.inits tails = LazyText.tails foldl f = LazyText.foldl f' where f' a char = f a (LazyText.singleton char) foldl' f = LazyText.foldl' f' where f' a char = f a (LazyText.singleton char) foldr f = LazyText.foldr f' where f' char a = f (LazyText.singleton char) a length = fromIntegral . LazyText.length span f = LazyText.span (f . LazyText.singleton) break f = LazyText.break (f . LazyText.singleton) dropWhile f = LazyText.dropWhile (f . LazyText.singleton) takeWhile f = LazyText.takeWhile (f . LazyText.singleton) spanMaybe s0 f t = case LazyText.foldr g id t (0, s0) of (i, s') | (prefix, suffix) <- LazyText.splitAt i t -> (prefix, suffix, s') where g c cont (i, s) | Just s' <- f s (LazyText.singleton c) = let i' = succ i :: Int64 in seq i' $ cont (i', s') | otherwise = (i, s) spanMaybe' s0 f t = case LazyText.foldr g id t (0, s0) of (i, s') | (prefix, suffix) <- LazyText.splitAt i t -> (prefix, suffix, s') where g c cont (i, s) | Just s' <- f s (LazyText.singleton c) = let i' = succ i :: Int64 in seq i' $ seq s' $ cont (i', s') | otherwise = (i, s) split f = LazyText.split f' where f' = f . LazyText.singleton splitAt = LazyText.splitAt . fromIntegral drop n = LazyText.drop (fromIntegral n) take n = LazyText.take (fromIntegral n) reverse = LazyText.reverse instance Ord k => FactorialMonoid (Map.Map k v) where factors = List.map (uncurry Map.singleton) . Map.toAscList primePrefix map | Map.null map = map | otherwise = uncurry Map.singleton $ Map.findMin map primeSuffix map | Map.null map = map | otherwise = uncurry Map.singleton $ Map.findMax map splitPrimePrefix = fmap singularize . Map.minViewWithKey where singularize ((k, v), rest) = (Map.singleton k v, rest) splitPrimeSuffix = fmap singularize . Map.maxViewWithKey where singularize ((k, v), rest) = (rest, Map.singleton k v) foldl f = Map.foldlWithKey f' where f' a k v = f a (Map.singleton k v) foldl' f = Map.foldlWithKey' f' where f' a k v = f a (Map.singleton k v) foldr f = Map.foldrWithKey f' where f' k v a = f (Map.singleton k v) a length = Map.size reverse = id instance FactorialMonoid (IntMap.IntMap a) where factors = List.map (uncurry IntMap.singleton) . IntMap.toAscList primePrefix map | IntMap.null map = map | otherwise = uncurry IntMap.singleton $ IntMap.findMin map primeSuffix map | IntMap.null map = map | otherwise = uncurry IntMap.singleton $ IntMap.findMax map splitPrimePrefix = fmap singularize . IntMap.minViewWithKey where singularize ((k, v), rest) = (IntMap.singleton k v, rest) splitPrimeSuffix = fmap singularize . IntMap.maxViewWithKey where singularize ((k, v), rest) = (rest, IntMap.singleton k v) foldl f = IntMap.foldlWithKey f' where f' a k v = f a (IntMap.singleton k v) foldl' f = IntMap.foldlWithKey' f' where f' a k v = f a (IntMap.singleton k v) foldr f = IntMap.foldrWithKey f' where f' k v a = f (IntMap.singleton k v) a length = IntMap.size reverse = id instance FactorialMonoid IntSet.IntSet where factors = List.map IntSet.singleton . IntSet.toAscList primePrefix set | IntSet.null set = set | otherwise = IntSet.singleton $ IntSet.findMin set primeSuffix set | IntSet.null set = set | otherwise = IntSet.singleton $ IntSet.findMax set splitPrimePrefix = fmap singularize . IntSet.minView where singularize (min, rest) = (IntSet.singleton min, rest) splitPrimeSuffix = fmap singularize . IntSet.maxView where singularize (max, rest) = (rest, IntSet.singleton max) foldl f = IntSet.foldl f' where f' a b = f a (IntSet.singleton b) foldl' f = IntSet.foldl' f' where f' a b = f a (IntSet.singleton b) foldr f = IntSet.foldr f' where f' a b = f (IntSet.singleton a) b length = IntSet.size reverse = id instance FactorialMonoid (Sequence.Seq a) where factors = List.map Sequence.singleton . Foldable.toList primePrefix = Sequence.take 1 primeSuffix q = Sequence.drop (Sequence.length q - 1) q splitPrimePrefix q = case Sequence.viewl q of Sequence.EmptyL -> Nothing hd Sequence.:< rest -> Just (Sequence.singleton hd, rest) splitPrimeSuffix q = case Sequence.viewr q of Sequence.EmptyR -> Nothing rest Sequence.:> last -> Just (rest, Sequence.singleton last) inits = Foldable.toList . Sequence.inits tails = Foldable.toList . Sequence.tails foldl f = Foldable.foldl f' where f' a b = f a (Sequence.singleton b) foldl' f = Foldable.foldl' f' where f' a b = f a (Sequence.singleton b) foldr f = Foldable.foldr f' where f' a b = f (Sequence.singleton a) b span f = Sequence.spanl (f . Sequence.singleton) break f = Sequence.breakl (f . Sequence.singleton) dropWhile f = Sequence.dropWhileL (f . Sequence.singleton) takeWhile f = Sequence.takeWhileL (f . Sequence.singleton) spanMaybe s0 f b = case Foldable.foldr g id b (0, s0) of (i, s') | (prefix, suffix) <- Sequence.splitAt i b -> (prefix, suffix, s') where g x cont (i, s) | Just s' <- f s (Sequence.singleton x) = let i' = succ i :: Int in seq i' $ cont (i', s') | otherwise = (i, s) spanMaybe' s0 f b = case Foldable.foldr g id b (0, s0) of (i, s') | (prefix, suffix) <- Sequence.splitAt i b -> (prefix, suffix, s') where g x cont (i, s) | Just s' <- f s (Sequence.singleton x) = let i' = succ i :: Int in seq i' $ seq s' $ cont (i', s') | otherwise = (i, s) splitAt = Sequence.splitAt drop = Sequence.drop take = Sequence.take length = Sequence.length reverse = Sequence.reverse instance Ord a => FactorialMonoid (Set.Set a) where factors = List.map Set.singleton . Set.toAscList primePrefix set | Set.null set = set | otherwise = Set.singleton $ Set.findMin set primeSuffix set | Set.null set = set | otherwise = Set.singleton $ Set.findMax set splitPrimePrefix = fmap singularize . Set.minView where singularize (min, rest) = (Set.singleton min, rest) splitPrimeSuffix = fmap singularize . Set.maxView where singularize (max, rest) = (rest, Set.singleton max) foldl f = Foldable.foldl f' where f' a b = f a (Set.singleton b) foldl' f = Foldable.foldl' f' where f' a b = f a (Set.singleton b) foldr f = Foldable.foldr f' where f' a b = f (Set.singleton a) b length = Set.size reverse = id instance FactorialMonoid (Vector.Vector a) where factors x = factorize (Vector.length x) x where factorize 0 _ = [] factorize n xs = xs1 : factorize (pred n) xs' where (xs1, xs') = Vector.splitAt 1 xs primePrefix = Vector.take 1 primeSuffix x = Vector.drop (Vector.length x - 1) x splitPrimePrefix x = if Vector.null x then Nothing else Just (Vector.splitAt 1 x) splitPrimeSuffix x = if Vector.null x then Nothing else Just (Vector.splitAt (Vector.length x - 1) x) inits x0 = initsWith x0 [] where initsWith x rest | Vector.null x = x:rest | otherwise = initsWith (Vector.unsafeInit x) (x:rest) tails x = x : if Vector.null x then [] else tails (Vector.unsafeTail x) foldl f = Vector.foldl f' where f' a byte = f a (Vector.singleton byte) foldl' f = Vector.foldl' f' where f' a byte = f a (Vector.singleton byte) foldr f = Vector.foldr f' where f' byte a = f (Vector.singleton byte) a break f = Vector.break (f . Vector.singleton) span f = Vector.span (f . Vector.singleton) dropWhile f = Vector.dropWhile (f . Vector.singleton) takeWhile f = Vector.takeWhile (f . Vector.singleton) spanMaybe s0 f v = case Vector.ifoldr g Left v s0 of Left s' -> (v, Vector.empty, s') Right (i, s') | (prefix, suffix) <- Vector.splitAt i v -> (prefix, suffix, s') where g i x cont s | Just s' <- f s (Vector.singleton x) = cont s' | otherwise = Right (i, s) spanMaybe' s0 f v = case Vector.ifoldr' g Left v s0 of Left s' -> (v, Vector.empty, s') Right (i, s') | (prefix, suffix) <- Vector.splitAt i v -> (prefix, suffix, s') where g i x cont s | Just s' <- f s (Vector.singleton x) = seq s' (cont s') | otherwise = Right (i, s) splitAt = Vector.splitAt drop = Vector.drop take = Vector.take length = Vector.length reverse = Vector.reverse instance StableFactorialMonoid () instance StableFactorialMonoid a => StableFactorialMonoid (Dual a) instance StableFactorialMonoid [x] instance StableFactorialMonoid ByteString.ByteString instance StableFactorialMonoid LazyByteString.ByteString instance StableFactorialMonoid Text.Text instance StableFactorialMonoid LazyText.Text instance StableFactorialMonoid (Sequence.Seq a) instance StableFactorialMonoid (Vector.Vector a) -- | A 'Monad.mapM' equivalent. mapM :: (FactorialMonoid a, Monoid b, Monad m) => (a -> m b) -> a -> m b mapM f = ($ return mempty) . appEndo . foldMap (Endo . Monad.liftM2 mappend . f) -- | A 'Monad.mapM_' equivalent. mapM_ :: (FactorialMonoid a, Monad m) => (a -> m b) -> a -> m () mapM_ f = foldr ((>>) . f) (return ())
mpickering/ghc-exactprint
tests/examples/ghc710/Undefined10.hs
bsd-3-clause
31,158
0
17
8,756
11,679
6,030
5,649
-1
-1
{-# Language PatternGuards #-} module Blub ( blub , foo , bar ) where import Ugah.Foo import Control.Applicative import Control.Monad import Ugah.Blub ddd f :: Int -> Int f = (+ 3)
jystic/hsimport
tests/goldenFiles/ModuleTest20.hs
bsd-3-clause
193
0
5
44
57
35
22
-1
-1
-- {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {- Copyright 2017 The CodeWorld Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. -} module Main ( main ) where import GHCJS.DOM (currentDocument, ) import GHCJS.DOM.NonElementParentNode import GHCJS.DOM.GlobalEventHandlers import GHCJS.DOM.Document (getBody, Document(..)) import GHCJS.DOM.Element (setInnerHTML, Element) import GHCJS.DOM.HTMLButtonElement import GHCJS.DOM.EventM (on) import GHCJS.DOM.Types import GHCJS.Types import GHCJS.Foreign import GHCJS.Foreign.Callback import GHCJS.Marshal import Data.JSString.Text import qualified Data.JSString as JStr import qualified Data.Text as T import Control.Monad.Trans (liftIO, lift) import Blockly.Workspace hiding (workspaceToCode) import Blocks.Parser import Blocks.CodeGen import Blocks.Types import Blockly.Event import Blockly.General import Blockly.Block import Data.Monoid import Control.Monad pack = textToJSString unpack = textFromJSString setErrorMessage msg = do Just doc <- liftIO currentDocument -- Just msgEl <- getElementById doc "message" liftIO $ putStrLn msg liftIO $ js_stopErr (JStr.pack msg) -- setInnerHTML msgEl $ Just msg programBlocks :: [T.Text] programBlocks = map T.pack ["cwDrawingOf","cwAnimationOf", "cwSimulationOf", "cwInteractionOf"] btnStopClick = do liftIO js_stop runOrError :: Workspace -> IO () runOrError ws = do (code,errors) <- workspaceToCode ws case errors of ((Error msg block):es) -> do putStrLn $ T.unpack msg setWarningText block msg addErrorSelect block js_removeErrorsDelay setErrorMessage (T.unpack msg) [] -> do liftIO $ js_updateEditor (pack code) liftIO $ js_cwcompile (pack code) -- Update the hash on the workspace -- Mainly so that broken programs can be shared updateCode :: Workspace -> IO () updateCode ws = do (code,errors) <- workspaceToCode ws liftIO $ js_updateEditor (pack code) liftIO $ js_cwcompilesilent (pack code) btnRunClick ws = do Just doc <- liftIO currentDocument liftIO $ updateCode ws blocks <- liftIO $ getTopBlocks ws (block, w) <- liftIO $ isWarning ws if T.length w > 0 then do setErrorMessage (T.unpack w) liftIO $ addErrorSelect block liftIO $ js_removeErrorsDelay else do if not $ containsProgramBlock blocks then do setErrorMessage "No Program block on the workspace" else do liftIO $ runOrError ws return () where containsProgramBlock = any (\b -> getBlockType b `elem` programBlocks) hookEvent elementName evType func = do Just doc <- currentDocument Just btn <- getElementById doc elementName on (uncheckedCastTo HTMLButtonElement btn) evType func help = do js_injectReadOnly (JStr.pack "blocklyDiv") liftIO setBlockTypes funblocks = do Just doc <- currentDocument Just body <- getBody doc workspace <- liftIO $ setWorkspace "blocklyDiv" "toolbox" liftIO $ disableOrphans workspace -- Disable disconnected non-top level blocks liftIO $ warnOnInputs workspace -- Display warning if inputs are disconnected hookEvent "btnRun" click (btnRunClick workspace) hookEvent "btnStop" click btnStopClick liftIO setBlockTypes -- assign layout and types of Blockly blocks liftIO $ addChangeListener workspace (onChange workspace) liftIO js_showEast liftIO js_openEast -- Auto start liftIO $ setRunFunc workspace -- when (T.length hash > 0) $ liftIO $ runOrError workspace return () main = do Just doc <- currentDocument mayTool <- getElementById doc "toolbox" case mayTool of Just _ -> funblocks Nothing -> help -- Update code in real time onChange ws event = do (code, errs) <- workspaceToCode ws js_updateEditor (pack code) setRunFunc :: Workspace -> IO () setRunFunc ws = do cb <- syncCallback ContinueAsync (do runOrError ws) js_setRunFunc cb -- FFI -- call blockworld.js compile foreign import javascript unsafe "compile($1)" js_cwcompile :: JSString -> IO () foreign import javascript unsafe "compile($1,true)" js_cwcompilesilent :: JSString -> IO () -- call blockworld.js run -- run (xmlHash, codeHash, msg, error) foreign import javascript unsafe "run()" js_cwrun :: JSString -> JSString -> JSString -> Bool -> IO () -- call blockworld.js updateUI foreign import javascript unsafe "updateUI()" js_updateUI :: IO () -- funnily enough, If I'm calling run "" "" "" False I get errors foreign import javascript unsafe "run('','','',false)" js_stop :: IO () foreign import javascript unsafe "run('','',$1,true)" js_stopErr :: JSString -> IO () foreign import javascript unsafe "updateEditor($1)" js_updateEditor :: JSString -> IO () foreign import javascript unsafe "setTimeout(removeErrors,5000)" js_removeErrorsDelay :: IO () foreign import javascript unsafe "window.mainLayout.show('east')" js_showEast :: IO () foreign import javascript unsafe "window.mainLayout.open('east')" js_openEast :: IO () foreign import javascript unsafe "Blockly.inject($1, {});" js_injectReadOnly :: JSString -> IO Workspace foreign import javascript unsafe "runFunc = $1" js_setRunFunc :: Callback a -> IO ()
three/codeworld
funblocks-client/src/Main.hs
apache-2.0
6,083
24
16
1,415
1,362
679
683
133
3
module Tree where import Gofer -- Here are a collection of fairly standard functions for manipulating -- one form of binary trees data Tree a = Lf a | Tree a :^: Tree a reflect t@(Lf x) = t reflect (l:^:r) = r :^: l mapTree f (Lf x) = Lf (f x) mapTree f (l:^:r) = mapTree f l :^: mapTree f r -- Functions to calculate the list of leaves on a tree: leaves, leaves' :: Tree a -> [a] leaves (Lf l) = [l] -- direct version leaves (l:^:r) = leaves l ++ leaves r leaves' t = leavesAcc t [] -- using an accumulating parameter where leavesAcc (Lf l) = (l:) leavesAcc (l:^:r) = leavesAcc l . leavesAcc r -- Picturing a tree: drawTree :: Show a => Tree a -> IO () drawTree = putStr . unlines . thd3 . pic where pic (Lf a) = (1,1,["-- "++show a]) pic (l:^:r) = (hl+hr+1, hl+1, top pl ++ mid ++ bot pr) where (hl,bl,pl) = pic l (hr,br,pr) = pic r top = zipWith (++) (replicate (bl-1) " " ++ [" ,-"] ++ replicate (hl-bl) " | ") mid = ["-| "] bot = zipWith (++) (replicate (br-1) " | " ++ [" `-"] ++ replicate (hr-br) " ") -- Finally, here is an example due to Richard Bird, which uses lazy evaluation -- and recursion to create a `cyclic' program which avoids multiple traversals -- over a data structure: replaceAndMin m (Lf n) = (Lf m, n) replaceAndMin m (l:^:r) = (rl :^: rr, ml `min` mr) where (rl,ml) = replaceAndMin m l (rr,mr) = replaceAndMin m r replaceWithMin t = mt where (mt,m) = replaceAndMin m t sample, sample2, sample4 :: Num a => Tree a sample = (Lf 12 :^: (Lf 23 :^: Lf 13)) :^: Lf 10 sample2 = sample :^: sample sample4 = sample2 :^: sample2
FranklinChen/Hugs
demos/Tree.hs
bsd-3-clause
2,102
0
15
870
715
381
334
35
2
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE helpset PUBLIC "-//Sun Microsystems Inc.//DTD JavaHelp HelpSet Version 2.0//EN" "http://java.sun.com/products/javahelp/helpset_2_0.dtd"> <helpset version="2.0" xml:lang="ro-RO"> <title>Network Add-on</title> <maps> <homeID>addon.network</homeID> <mapref location="map.jhm"/> </maps> <view> <name>TOC</name> <label>Contents</label> <type>org.zaproxy.zap.extension.help.ZapTocView</type> <data>toc.xml</data> </view> <view> <name>Index</name> <label>Index</label> <type>javax.help.IndexView</type> <data>index.xml</data> </view> <view> <name>Search</name> <label>Search</label> <type>javax.help.SearchView</type> <data engine="com.sun.java.help.search.DefaultSearchEngine"> JavaHelpSearch </data> </view> <view> <name>Favorites</name> <label>Favorites</label> <type>javax.help.FavoritesView</type> </view> </helpset>
kingthorin/zap-extensions
addOns/network/src/main/javahelp/help_ro_RO/helpset_ro_RO.hs
apache-2.0
969
77
67
156
413
209
204
-1
-1
{-# LANGUAGE StandaloneKindSignatures #-} module T16727a where type T1 :: T2 data T1 type T2 :: T1 data T2
sdiehl/ghc
testsuite/tests/saks/should_fail/T16727a.hs
bsd-3-clause
110
0
4
22
23
16
7
-1
-1
module Test6 where f = (\ x y z -> x + y + z)
SAdams601/HaRe
old/testing/refacSlicing/Test6.hs
bsd-3-clause
47
0
8
16
29
17
12
2
1
module A3 where import C3 main xs = case xs of [] -> 0 [(x : xs)] -> (x ^ pow) + (case xs of ((x : xs)) -> (sq x) + (sumSquares1 xs) [] -> 0)
kmate/HaRe
old/testing/unfoldDef/A3_AstOut.hs
bsd-3-clause
181
4
15
76
105
57
48
10
3
----------------------------------------------------------------------------- -- | -- Module : Data.Traversable -- Copyright : Conor McBride and Ross Paterson 2005 -- License : BSD-style (see the LICENSE file in the distribution) -- -- Maintainer : ross@soi.city.ac.uk -- Stability : experimental -- Portability : portable -- -- Class of data structures that can be traversed from left to right, -- performing an action on each element. -- -- See also -- -- * /Applicative Programming with Effects/, -- by Conor McBride and Ross Paterson, online at -- <http://www.soi.city.ac.uk/~ross/papers/Applicative.html>. -- -- * /The Essence of the Iterator Pattern/, -- by Jeremy Gibbons and Bruno Oliveira, -- in /Mathematically-Structured Functional Programming/, 2006, and online at -- <http://web.comlab.ox.ac.uk/oucl/work/jeremy.gibbons/publications/#iterator>. -- -- Note that the functions 'mapM' and 'sequence' generalize "Prelude" -- functions of the same names from lists to any 'Traversable' functor. -- To avoid ambiguity, either import the "Prelude" hiding these names -- or qualify uses of these function names with an alias for this module. module Data.Traversable ( Traversable(..), for, forM, mapAccumL, mapAccumR, fmapDefault, foldMapDefault, ) where import Prelude hiding (mapM, sequence, foldr) import qualified Prelude (mapM, foldr) import Control.Applicative import Data.Foldable (Foldable()) import Data.Monoid (Monoid) -- | Functors representing data structures that can be traversed from -- left to right. -- -- Minimal complete definition: 'traverse' or 'sequenceA'. -- -- Instances are similar to 'Functor', e.g. given a data type -- -- > data Tree a = Empty | Leaf a | Node (Tree a) a (Tree a) -- -- a suitable instance would be -- -- > instance Traversable Tree -- > traverse f Empty = pure Empty -- > traverse f (Leaf x) = Leaf <$> f x -- > traverse f (Node l k r) = Node <$> traverse f l <*> f k <*> traverse f r -- -- This is suitable even for abstract types, as the laws for '<*>' -- imply a form of associativity. -- -- The superclass instances should satisfy the following: -- -- * In the 'Functor' instance, 'fmap' should be equivalent to traversal -- with the identity applicative functor ('fmapDefault'). -- -- * In the 'Foldable' instance, 'Data.Foldable.foldMap' should be -- equivalent to traversal with a constant applicative functor -- ('foldMapDefault'). -- class (Functor t, Foldable t) => Traversable t where -- | Map each element of a structure to an action, evaluate -- these actions from left to right, and collect the results. traverse :: Applicative f => (a -> f b) -> t a -> f (t b) traverse f = sequenceA . fmap f -- | Evaluate each action in the structure from left to right, -- and collect the results. sequenceA :: Applicative f => t (f a) -> f (t a) sequenceA = traverse id -- | Map each element of a structure to a monadic action, evaluate -- these actions from left to right, and collect the results. mapM :: Monad m => (a -> m b) -> t a -> m (t b) mapM f = unwrapMonad . traverse (WrapMonad . f) -- | Evaluate each monadic action in the structure from left to right, -- and collect the results. sequence :: Monad m => t (m a) -> m (t a) sequence = mapM id -- instances for Prelude types instance Traversable Maybe where traverse f Nothing = pure Nothing traverse f (Just x) = Just <$> f x instance Traversable [] where traverse f = Prelude.foldr cons_f (pure []) where cons_f x ys = (:) <$> f x <*> ys mapM = Prelude.mapM --instance Ix i => Traversable (Array i) where -- traverse f arr = listArray (bounds arr) `fmap` traverse f (elems arr) -- general functions -- | 'for' is 'traverse' with its arguments flipped. for :: (Traversable t, Applicative f) => t a -> (a -> f b) -> f (t b) {-# INLINE for #-} for = flip traverse -- | 'forM' is 'mapM' with its arguments flipped. forM :: (Traversable t, Monad m) => t a -> (a -> m b) -> m (t b) {-# INLINE forM #-} forM = flip mapM -- left-to-right state transformer newtype StateL s a = StateL { runStateL :: s -> (s, a) } instance Functor (StateL s) where fmap f (StateL k) = StateL $ \ s -> let (s', v) = k s in (s', f v) instance Applicative (StateL s) where pure x = StateL (\ s -> (s, x)) StateL kf <*> StateL kv = StateL $ \ s -> let (s', f) = kf s (s'', v) = kv s' in (s'', f v) -- |The 'mapAccumL' function behaves like a combination of 'fmap' -- and 'foldl'; it applies a function to each element of a structure, -- passing an accumulating parameter from left to right, and returning -- a final value of this accumulator together with the new structure. mapAccumL :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) mapAccumL f s t = runStateL (traverse (StateL . flip f) t) s -- right-to-left state transformer newtype StateR s a = StateR { runStateR :: s -> (s, a) } instance Functor (StateR s) where fmap f (StateR k) = StateR $ \ s -> let (s', v) = k s in (s', f v) instance Applicative (StateR s) where pure x = StateR (\ s -> (s, x)) StateR kf <*> StateR kv = StateR $ \ s -> let (s', v) = kv s (s'', f) = kf s' in (s'', f v) -- |The 'mapAccumR' function behaves like a combination of 'fmap' -- and 'foldr'; it applies a function to each element of a structure, -- passing an accumulating parameter from right to left, and returning -- a final value of this accumulator together with the new structure. mapAccumR :: Traversable t => (a -> b -> (a, c)) -> a -> t b -> (a, t c) mapAccumR f s t = runStateR (traverse (StateR . flip f) t) s -- | This function may be used as a value for `fmap` in a `Functor` instance. fmapDefault :: Traversable t => (a -> b) -> t a -> t b fmapDefault f = getId . traverse (Id . f) -- | This function may be used as a value for `Data.Foldable.foldMap` -- in a `Foldable` instance. foldMapDefault :: (Traversable t, Monoid m) => (a -> m) -> t a -> m foldMapDefault f = getConst . traverse (Const . f) -- local instances newtype Id a = Id { getId :: a } instance Functor Id where fmap f (Id x) = Id (f x) instance Applicative Id where pure = Id Id f <*> Id x = Id (f x)
m-alvarez/jhc
lib/applicative/Data/Traversable.hs
mit
6,555
0
12
1,659
1,414
774
640
69
1
{-# LANGUAGE GADTs #-} -- Trac #289 module ShouldCompile where class C a where f :: a -> Bool data T a where MkT :: (C a) => a -> T a tf1 :: T Int -> Bool tf1 (MkT aa) = f aa tf2 :: T a -> Bool tf2 (MkT aa) = f aa
urbanslug/ghc
testsuite/tests/gadt/data1.hs
bsd-3-clause
241
0
7
83
108
57
51
10
1
import Data.Char import Data.List --1 perimetro :: Float -> Float perimetro r = 2*3.14*r dist :: (Float, Float) -> (Float, Float) -> Float dist (x1, y1) (x2, y2) = sqrt ((x2 - x1)^2 + (y2 - y1)^2) primUlt :: [a] -> (a, a) primUlt [x] = (x, x) primUlt (x:xs) = (x, last xs) multiplo :: Int -> Int -> Bool multiplo x y = x `mod` y == 0 truncaImpar :: [a] -> [a] truncaImpar l = if multiplo (length l) 2 then (tail l) else l max2 :: Int -> Int -> Int max2 x y = if x > y then x else y max3 :: Int -> Int -> Int -> Int max3 x y z = max2 (max2 x y) y max3' :: Int -> Int -> Int -> Int max3' x y z = if x > y && x > z then x else if y > x && y > z then y else z --2 desigualdadeTriangular :: Int -> Int -> Int -> Bool desigualdadeTriangular x y z = (x + y) > z && (x + z) > y && (y + z) > x --3 type Ponto = (Float, Float) comprimentoVerticesTriangulo :: Ponto -> Ponto -> Ponto -> (Float, Float, Float) comprimentoVerticesTriangulo x y z = (dist x y, dist y z, dist z x) perimetroTriangulo :: Ponto -> Ponto -> Ponto -> Float perimetroTriangulo x y z = dist x y + dist y z + dist z x completaRectangulo :: Ponto -> Ponto -> [Ponto] completaRectangulo (x1, y1) (x2, y2) = [(x1, y1), (x2, y1), (x1, y2), (x2, y2)] --4 nRaizesReais :: Float -> Float -> Float -> Int nRaizesReais a b c | insideSqrt > 0 = 2 | insideSqrt == 0 = 1 | insideSqrt < 0 = 0 where insideSqrt = b^2 - 4*a*c --5 raizesReais :: Float -> Float -> Float -> [Float] raizesReais a b c | nRaizesReais a b c == 0 = [] | nRaizesReais a b c == 1 = [-b / 2*a] | nRaizesReais a b c == 2 = [(-b + sqrt(b^2 - 4*a*c)), (-b - sqrt(b^2 - 4*a*c))] --6 nRaizesReais' :: (Float, Float, Float) -> Int nRaizesReais' (a, b, c) | insideSqrt > 0 = 2 | insideSqrt == 0 = 1 | insideSqrt < 0 = 0 where insideSqrt = b^2 - 4*a*c raizesReais' :: (Float, Float, Float) -> [Float] raizesReais' (a, b, c) | nRaizesReais a b c == 0 = [] | nRaizesReais a b c == 1 = [-b / 2*a] | nRaizesReais a b c == 2 = [(-b + sqrt(b^2 - 4*a*c)), (-b - sqrt(b^2 - 4*a*c))] --7 isLower' :: Char -> Bool isLower' c = c >= 'a' && c <= 'z' isDigit' :: Char -> Bool isDigit' c = c >= '0' && c <= '9' isAlpha' :: Char -> Bool isAlpha' c = c >= 'A' && c <= 'Z' || isLower c toUpper' :: Char -> Char toUpper' c = if isLower c then chr (ord c - (ord 'a' - ord 'A')) else c intToDigit' :: Int -> Char intToDigit' n = chr (n + (ord '0')) digitToInt' :: Char -> Int digitToInt' c = (ord c) - (ord '0') --8 primMai :: String -> Bool primMai (x:xs) = isUpper x segMin :: String -> Bool segMin (x:y:xs) = isLower y --9 type Hora = (Int, Int) horaValida :: Hora -> Bool horaValida (h, m) = h > 0 && h < 24 && m > 0 && m < 60 depoisDe :: Hora -> Hora -> Bool depoisDe (h1, m1) (h2, m2) | h1 > h2 = True | h1 < h2 = False | otherwise = m1 > m2 horasParaMinutos :: Hora -> Int horasParaMinutos (h, m) = h*60 + m minutosParaHoras :: Int -> Hora minutosParaHoras m = (m `div` 60, m `mod` 60) deltaHoras :: Hora -> Hora -> Int deltaHoras h1 h2 = horasParaMinutos h1 - horasParaMinutos h2 addHoras :: Hora -> Int -> Hora addHoras h n = minutosParaHoras ((horasParaMinutos h) + n) --10 opp :: (Int, (Int, Int)) -> Int opp (1, (y, z)) = y + z opp (2, (y, z)) = y - z opp _ = 0 --11 funA :: [Float] -> [Float] funA [] = [] funA (h:t) = if h >= 0 then h : (funA t) else (funA t) -- [3, 0, 2] -- A função está a discartar os números negativos na condição. funB :: [Float] -> Float funB [] = 1 funB (x:xs) = x * (funB xs) -- 30 -- A função multiplica os números todos. funC :: [Float] -> Float funC [] = 0 funC (y:ys) = y^2 + (funC ys) -- 2^2 + 3^2 + 5^2 = 38 -- A função é a soma dos quadrados funD :: [Int] -> [Int] funD [] = [] funD (h:t) = if (mod h 2) == 0 then h : (funD t) else (funD t) -- [8, 12] -- Esta função discarda os números impares p :: Int -> Bool p 0 = True p 1 = False p x | x > 1 = p (x - 2) -- False -- Esta função verifica se x é par. f l = g [] l g l [] = l g l (h:t) = g (h:l) t -- "certo" -- A função reverte uma lista --12 dobros :: [Float] -> [Float] dobros [] = [] dobros (x:xs) = 2*x : dobros xs ocorre :: Char -> String -> Int ocorre c "" = 0 ocorre c (x:xs) = if c == x then 1 + ocorre c xs else ocorre c xs pmaior :: Int -> [Int] -> Int pmaior n [] = n pmaior n (x:xs) = if x > n then x else pmaior n xs repetidos :: (Eq a) => [a] -> Bool repetidos [] = False repetidos (x:xs) = x `elem` xs || repetidos xs nums :: String -> [Int] nums "" = [] nums (c:cs) = if isDigit c then digitToInt c : nums cs else nums cs tresUlt :: [a] -> [a] tresUlt [] = [] tresUlt [x] = [x] tresUlt [x, y] = [x, y] tresUlt [x, y, z] = [x, y, z] tresUlt (x:xs) = tresUlt xs posImpares :: [a] -> [a] posImpares [] = [] posImpares [x] = [] posImpares (x:y:xs) = y : posImpares xs somaNeg :: [Int] -> Int somaNeg [] = 0 somaNeg (x:xs) = if x < 0 then x + somaNeg xs else somaNeg xs soDigitos :: [Char] -> [Char] soDigitos [] = [] soDigitos (x:xs) = if isDigit x then x : soDigitos xs else soDigitos xs minusculas :: [Char] -> Int minusculas [] = 0 minusculas (x:xs) = if isLower x then 1 + minusculas xs else minusculas xs delete' :: (Eq a) => a -> [a] -> [a] delete' _ [] = [] delete' e (x:xs) = if e == x then xs else x : delete' e xs ordena :: (Ord a) => [a] -> [a] ordena [] = [] ordena xs = minVal : (ordena (delete' minVal xs)) where minVal = minimum xs --13 type Jogo = (String, Int, String, Int) golosEquipa :: Jogo -> String -> Int golosEquipa (s1, g1, s2, g2) equipa | s1 == equipa = g1 | s2 == equipa = g2 | otherwise = -1 resJogo :: Jogo -> Char resJogo (_, g1, _, g2) |g1 > g2 = '1' |g1 < g2 = '2' |otherwise = 'x' --caso seja empate. resJogo' :: Jogo -> String resJogo' (_, g1, _, g2) |g1 > g2 = "ganhou a equipa da casa" |g1 < g2 = "ganhou a equipa visitante" |otherwise = "empate" empates :: [Jogo] -> Int empates [] = 0 empates ((_, g1, _, g2):xs) = if g1 == g2 then 1 + empates xs else empates xs jogosComXGolos :: [Jogo] -> Int -> Int jogosComXGolos [] _ = 0 jogosComXGolos ((_, g1, _, g2):xs) golos = if g1 + g2 == golos then 1 + jogosComXGolos xs golos else jogosComXGolos xs golos jogosGanhosFora :: [Jogo] -> Int jogosGanhosFora [] = 0 jogosGanhosFora (x:xs) = if resJogo x == '2' then 1 + jogosGanhosFora xs else jogosGanhosFora xs type Circulo = (Ponto, Float) --(Centro, Raio) distP :: Ponto -> Ponto -> Float distP (a,b) (c,d) = sqrt ((a-c)^2 +(b-d)^2) fora :: Ponto -> Circulo -> Bool fora p (c, r) = distP p c > r filtraFora :: Circulo -> [Ponto] -> Int filtraFora c [] = 0 filtraFora c (p:ps) = if fora p c then 1 + filtraFora c ps else filtraFora c ps dentro :: Ponto -> Circulo -> Bool dentro p (c, r) = distP p c < r filtraDentro :: Ponto -> [Circulo] -> Int filtraDentro p [] = 0 filtraDentro p (c:cs) = if dentro p c then 1 + filtraDentro p cs else filtraDentro p cs type Rectangulo = (Ponto, Ponto) quadrado :: Rectangulo -> Bool quadrado ((x1, y1), (x2, y2)) = abs (x1 - x2) == abs (y1 - y2) contaQuadrados :: [Rectangulo] -> Int contaQuadrados [] = 0 contaQuadrados (x:xs) = if quadrado x then 1 + contaQuadrados xs else contaQuadrados xs roda :: Rectangulo -> Rectangulo roda (p1@(x1, y1), (x2, y2)) = (p1, (x1 + (y1 - y2), y1 + (x1 - x2))) rodaTudo :: [Rectangulo] -> [Rectangulo] rodaTudo [] = [] rodaTudo (x:xs) = roda x : rodaTudo xs area :: Rectangulo -> Float area ((x1, y1), (x2, y2)) = abs (x1 - x2) * abs (y1 - y2) areaTotal :: [Rectangulo] -> Float areaTotal [] = 0 areaTotal (x:xs) = area x + areaTotal xs escala :: Float -> Rectangulo -> Rectangulo escala s ((x1, y1), (x2, y2)) = ((x1, y1), ((s*(x2 - x1)) + x1, s*(y2 - y1) + y1)) escalaTudo :: Float -> [Rectangulo] -> [Rectangulo] escalaTudo _ [] = [] escalaTudo e (x:xs) = escala e x : escalaTudo e xs --16 (><) :: Int -> Int -> Int (><) 0 y = 0 (><) x 0 = 0 (><) x 1 = x (><) 1 y = y (><) x y = x + (x >< (y - 1)) div' :: Int -> Int -> Int div' n d | n < d = 0 | n >= d = 1 + div' (n - d) d mod' :: Int -> Int -> Int mod' n d = n - (d * (div' n d)) power :: Int -> Int -> Int power b 0 = 1 power b e = b * power b (e - 1) uns :: Int -> Int uns 1 = 1 uns n | even n = uns (div' n 2) | odd n = 1 + uns (div' n 2) primo :: Int -> Bool primo 1 = False primo n = testePrimo n (n - 1) where testePrimo :: Int -> Int -> Bool testePrimo n 1 = True testePrimo n t = mod' n t /= 0 && testePrimo n (t - 1) --17 primeiros :: [(a, b)] -> [a] primeiros [] = [] primeiros ((a, _):xs) = a : primeiros xs nosPrimeiros :: (Eq a) => a -> [(a, b)] -> Bool nosPrimeiros _ [] = False nosPrimeiros x ((a, _):xs) = x == a || nosPrimeiros x xs minFst :: (Ord a) => [(a, b)] -> a minFst [(a, b)] = a minFst ((a, b):xs) = min a (minFst xs) minimumFst :: (Ord a) => [(a, b)] -> (a, b) minimumFst [x] = x minimumFst (x:xs) = minFstTuple x (minimumFst xs) sndMinFst :: (Ord a) => [(a, b)] -> b sndMinFst xs = snd (minimumFst xs) minFstTuple :: (Ord a) => (a, b) -> (a, b) -> (a, b) minFstTuple t1@(a, b) t2@(c, d) = if min a c == a then t1 else t2 ordenaSnd :: (Ord b, Eq a) => [(a, b)] -> [(a, b)] ordenaSnd [] = [] ordenaSnd xs = minVal : (ordenaSnd (delete' minVal xs)) where minVal = minimumSnd xs minSndTuple :: (Ord b) => (a, b) -> (a, b) -> (a, b) minSndTuple t1@(a, b) t2@(c, d) = if min b d == b then t1 else t2 minimumSnd :: (Ord b) => [(a, b)] -> (a, b) minimumSnd [x] = x minimumSnd (x:xs) = minSndTuple x (minimumSnd xs) --18 type Aluno = (Numero, Nome, ParteI, ParteII) type Numero = Int type Nome = String type ParteI = Float type ParteII = Float type Turma = [Aluno] turmaValida :: Turma -> Bool turmaValida [] = True turmaValida ((n, _, p1, p2):xs) = p1 >= 0 && p1 <= 12 && p2 >= 0 && p2 <= 8 && notElem n (numerosAluno xs) && turmaValida xs where numerosAluno :: Turma -> [Int] numerosAluno [] = [] numerosAluno ((n, _, _, _):xs) = n : numerosAluno xs alunosTransitados :: Turma -> Turma alunosTransitados [] = [] alunosTransitados (aluno@(_, _, p1, p2):xs) = if p1 >= 8 && (p1 + p2) >= 9.5 then aluno : alunosTransitados xs else alunosTransitados xs notaFinal :: Turma -> [Float] notaFinal [] = [] notaFinal xs = (p1 + p2) : notaFinal as where ((_, _, p1, p2):as) = alunosTransitados xs mediaNotaFinal :: Turma -> Float mediaNotaFinal xs = realToFrac (sum notas) / genericLength notas where notas = notaFinal xs melhorNota :: Turma -> String melhorNota t = nome where (_, nome, _, _) = melhorAluno t maxNota :: Aluno -> Aluno -> Aluno maxNota a1@(_, _, p11, p21) a2@(_, _, p12, p22) = if (p11 + p21) >= (p12 + p22) then a1 else a2 melhorAluno :: Turma -> Aluno melhorAluno [x] = x melhorAluno (x:xs) = maxNota x (melhorAluno xs) --19 type Etapa = (Hora, Hora) type Viagem = [Etapa] etapaValida :: Etapa -> Bool etapaValida (h1, h2) = horaValida h1 && horaValida h2 && h2 `depoisDe` h1 viagemValida :: Viagem -> Bool viagemValida [] = True viagemValida [x] = True viagemValida (e1@(_, h1):e2@(h2, _):xs) = etapaValida e1 && etapaValida e2 && h2 `depoisDe` h1 && viagemValida (e2:xs) partidaChegada :: Viagem -> Etapa partidaChegada ((partida, _):xs) = (partida, snd (last xs)) tempoViagemEfectiva :: Viagem -> Int tempoViagemEfectiva [] = 0 tempoViagemEfectiva ((h1, h2):xs) = abs (deltaHoras h1 h2) + tempoViagemEfectiva xs tempoEspera :: Viagem -> Int tempoEspera [] = 0 tempoEspera [(h1, h2)] = 0 tempoEspera ((h1, h2), x@(h3, h4):xs) = abs (deltaHoras h3 h2) + tempoEspera (x:xs) tempoViagemTotal :: Viagem -> Int tempoViagemTotal viagem = tempoViagemEfectiva viagem + tempoEspera viagem --20 type Rectangulo2 = (Ponto, Float, Float) type Triangulo = (Ponto, Ponto, Ponto) type Poligonal = [Ponto] comprimentoLinhaPoligonal :: Poligonal -> Int comprimentoLinhaPoligonal [] = 0 comprimentoLinhaPoligonal [x] = 0 comprimentoLinhaPoligonal (x:y:xs) = dist x y + comprimentoLinhaPoligonal (y:xs) trianguloParaPoligonal :: Triangulo -> Poligonal trianguloParaPoligonal (x, y, z) = [x, y, z, x] rectanguloParaPoligonal :: Rectangulo2 -> Poligonal rectanguloParaPoligonal (p@(x, y), w, h) = [p, (x + w, y), (x + w, y - h), (x, y - h), p] fechada :: Poligonal -> Bool fechada [] = False fechada [x] = False fechada [x, y] = False fechada (x:xs) = x == last xs triangula :: Poligonal -> [Triangulo] triangula [] = [] triangula (x:y:z:xs) = (x, y, z) : triangula (x:z:xs) areaTriangulo :: Triangulo -> Float areaTriangulo (x, y, z) = let a = dist x y b = dist y z c = dist z y s = (a + b + c) / 2 --semi-perimetro in --formula de Heron sqrt (s * (s - a) * (s - b) * (s - c)) areaPoligono :: Poligonal -> Float areaPoligono xs = sum (map areaTriangulo (triangula xs)) mover :: Poligonal -> Poligonal
Qu4tro/PF
CadernoTP-1314.hs
mit
14,110
0
14
4,331
6,836
3,698
3,138
362
3
{-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE QuasiQuotes, TypeFamilies, TemplateHaskell, MultiParamTypeClasses #-} import Yesod.Core import Yesod.Form import Yesod.Form.MassInput import Control.Applicative import Data.Text (Text, pack) import Network.Wai.Handler.Warp (run) import Data.Time (utctDay, getCurrentTime) import qualified Data.Text as T import Control.Monad.IO.Class (liftIO) data Fruit = Apple | Banana | Pear deriving (Show, Enum, Bounded, Eq) fruits :: [(Text, Fruit)] fruits = map (\x -> (pack $ show x, x)) [minBound..maxBound] mkYesod "HelloForms" [parseRoutes| / RootR GET /mass MassR GET /valid ValidR GET /file FileR GET POST |] myForm = fixType $ runFormGet $ renderDivs $ pure (,,,,,,,,) <*> areq boolField "Bool field" Nothing <*> aopt boolField "Opt bool field" Nothing <*> areq textField "Text field" Nothing <*> areq (selectFieldList fruits) "Select field" Nothing <*> aopt (selectFieldList fruits) "Opt select field" Nothing <*> areq (multiSelectFieldList fruits) "Multi select field" Nothing <*> aopt (multiSelectFieldList fruits) "Opt multi select field" Nothing <*> aopt intField "Opt int field" Nothing <*> aopt (radioFieldList fruits) "Opt radio" Nothing data HelloForms = HelloForms instance RenderMessage HelloForms FormMessage where renderMessage _ _ = defaultFormMessage instance Yesod HelloForms fixType :: Handler a -> Handler a fixType = id getRootR = do ((res, form), enctype) <- myForm defaultLayout [whamlet| <p>Result: #{show res} <form enctype=#{enctype}> ^{form} <div> <input type=submit> <p> <a href=@{MassR}>See the mass form <p> <a href=@{ValidR}>Validation form <p> <a href=@{FileR}>File form |] myMassForm = fixType $ runFormGet $ renderTable $ inputList "People" massTable (\x -> (,) <$> areq textField "Name" (fmap fst x) <*> areq intField "Age" (fmap snd x)) (Just [("Michael", 26)]) getMassR = do ((res, form), enctype) <- myMassForm defaultLayout [whamlet| <p>Result: #{show res} <form enctype=#{enctype}> <table> ^{form} <div> <input type=submit> <p> <a href=@{RootR}>See the regular form |] myValidForm = fixType $ runFormGet $ renderTable $ pure (,,) <*> areq (check (\x -> if T.length x < 3 then Left ("Need at least 3 letters" :: Text) else Right x ) textField) "Name" Nothing <*> areq (checkBool (>= 18) ("Must be 18 or older" :: Text) intField) "Age" Nothing <*> areq (checkM inPast dayField) "Anniversary" Nothing where inPast x = do now <- liftIO $ getCurrentTime return $ if utctDay now < x then Left ("Need a date in the past" :: Text) else Right x getValidR = do ((res, form), enctype) <- myValidForm defaultLayout [whamlet| <p>Result: #{show res} <form enctype=#{enctype}> <table> ^{form} <div> <input type=submit> <p> <a href=@{RootR}>See the regular form |] main = toWaiApp HelloForms >>= run 3000 fileForm = renderTable $ pure (,) <*> fileAFormReq "Required file" <*> fileAFormOpt "Optional file" getFileR = do ((res, form), enctype) <- runFormPost fileForm defaultLayout [whamlet| <p>Result: #{show res} <form method=post enctype=#{enctype}> <table> ^{form} <tr> <td> <input type=submit> <p> <a href=@{RootR}>See the regular form |] postFileR = getFileR
piyush-kurur/yesod
yesod-form/hello-forms.hs
mit
3,531
0
16
847
852
460
392
68
3
module GHCJS.DOM.Rect ( ) where
manyoo/ghcjs-dom
ghcjs-dom-webkit/src/GHCJS/DOM/Rect.hs
mit
34
0
3
7
10
7
3
1
0
module D20.Internal.Utils.Transform where import qualified Data.Map as M import Data.List flipTuple :: (a,b) -> (b,a) flipTuple (a,b) = (b,a) flipMap :: (Ord b) => M.Map a b -> M.Map b a flipMap = M.fromList . map flipTuple . M.toList zipWithIndex :: [a] -> [(a,Int)] zipWithIndex = zipWith (\index el -> (el,index)) [0 ..]
elkorn/d20
src/D20/Internal/Utils/Transform.hs
mit
348
0
8
77
165
97
68
12
1
module SDL.Image.Raw.Loading ( -- * Automagic Loading imgLoad , imgLoadRW , imgLoadRWTyped -- * Specific Loaders , imgLoadRWJPG , imgLoadRWPNG , imgLoadRWBMP , imgLoadRWCUR , imgLoadRWGIF , imgLoadRWICO , imgLoadRWLBM , imgLoadRWPCX , imgLoadRWPNM , imgLoadRWTGA , imgLoadRWTIF , imgLoadRWXCF , imgLoadRWXPM , imgLoadRWXV )where -- import Foreign.Marshal.Utils (fromBool) import Foreign.Ptr import Foreign.C.Types import Foreign.C.String -- import Control.Monad.IO.Class -- import qualified SDL.Raw.Types as RowType -- foreign import ccall "SDL_image.h IMG_Load" imgLoad_FFI :: CString -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_Load_RW" imgLoadRW_FFI :: Ptr RowType.RWops -> CInt -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadTyped_RW" imgLoadRWTyped_FFI :: Ptr RowType.RWops -> CInt -> CString -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadJPG_RW" imgLoadRWJPG_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadPNG_RW" imgLoadRWPNG_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadBMP_RW" imgLoadRWBMP_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadCUR_RW" imgLoadRWCUR_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadGIF_RW" imgLoadRWGIF_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadICO_RW" imgLoadRWICO_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadLBM_RW" imgLoadRWLBM_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadPCX_RW" imgLoadRWPCX_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadPNM_RW" imgLoadRWPNM_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadTGA_RW" imgLoadRWTGA_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadTIF_RW" imgLoadRWTIF_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadXCF_RW" imgLoadRWXCF_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadXPM_RW" imgLoadRWXPM_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- foreign import ccall "SDL_image.h IMG_LoadXV_RW" imgLoadRWXV_FFI :: Ptr RowType.RWops -> IO (Ptr RowType.Surface) -- -- imgLoad :: MonadIO m => CString -> m (Ptr RowType.Surface) imgLoad path = liftIO $ imgLoad_FFI path {-# INLINE imgLoad #-} -- imgLoadRW :: MonadIO m => Ptr RowType.RWops -> Bool -> m (Ptr RowType.Surface) imgLoadRW p autoFree = liftIO $ imgLoadRW_FFI p (fromBool autoFree) {-# INLINE imgLoadRW #-} -- imgLoadRWTyped :: MonadIO m => Ptr RowType.RWops -> Bool -> CString -> m (Ptr RowType.Surface) imgLoadRWTyped p autoFree typeStr = liftIO $ imgLoadRWTyped_FFI p (fromBool autoFree) typeStr {-# INLINE imgLoadRWTyped #-} -- imgLoadRWJPG :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWJPG p = liftIO $ imgLoadRWJPG_FFI p {-# INLINE imgLoadRWJPG #-} -- imgLoadRWPNG :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWPNG p = liftIO $ imgLoadRWPNG_FFI p {-# INLINE imgLoadRWPNG #-} -- imgLoadRWBMP :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWBMP p = liftIO $ imgLoadRWBMP_FFI p {-# INLINE imgLoadRWBMP #-} -- imgLoadRWCUR :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWCUR p = liftIO $ imgLoadRWCUR_FFI p {-# INLINE imgLoadRWCUR #-} -- imgLoadRWGIF :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWGIF p = liftIO $ imgLoadRWGIF_FFI p {-# INLINE imgLoadRWGIF #-} -- imgLoadRWICO :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWICO p = liftIO $ imgLoadRWICO_FFI p {-# INLINE imgLoadRWICO #-} -- imgLoadRWLBM :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWLBM p = liftIO $ imgLoadRWLBM_FFI p {-# INLINE imgLoadRWLBM #-} -- imgLoadRWPCX :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWPCX p = liftIO $ imgLoadRWPCX_FFI p {-# INLINE imgLoadRWPCX #-} -- imgLoadRWPNM :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWPNM p = liftIO $ imgLoadRWPNM_FFI p {-# INLINE imgLoadRWPNM #-} -- imgLoadRWTGA :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWTGA p = liftIO $ imgLoadRWTGA_FFI p {-# INLINE imgLoadRWTGA #-} -- imgLoadRWTIF :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWTIF p = liftIO $ imgLoadRWTIF_FFI p {-# INLINE imgLoadRWTIF #-} -- imgLoadRWXCF :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWXCF p = liftIO $ imgLoadRWXCF_FFI p {-# INLINE imgLoadRWXCF #-} -- imgLoadRWXPM :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWXPM p = liftIO $ imgLoadRWXPM_FFI p {-# INLINE imgLoadRWXPM #-} -- imgLoadRWXV :: MonadIO m => Ptr RowType.RWops -> m (Ptr RowType.Surface) imgLoadRWXV p = liftIO $ imgLoadRWXV_FFI p {-# INLINE imgLoadRWXV #-} --
jaiyalas/sdl2-image
src/SDL/Image/Raw/Loading.hs
mit
5,880
0
12
1,427
1,544
795
749
148
1
module Main where import Control.Monad (forM_) import Data.Function import Network.Monitoring.Riemann.BatchClient import Network.Monitoring.Riemann.Client import qualified Network.Monitoring.Riemann.Event as Event main :: IO () main = do client <- batchClient "localhost" 5555 100 100 print putStrLn "doing some IO work" event <- pure $ Event.warn "my service" & Event.description "my description" & Event.metric (length ["some data"]) & Event.ttl 20 & Event.tags ["tag1", "tag2"] forM_ [1 .. 1000000] $ \i -> sendEvent client $ event & Event.metric (i :: Int) close client putStrLn "finished"
shmish111/hriemann
app/Main.hs
mit
632
0
14
118
204
106
98
20
1
-- Type annotation (optional) factorial :: Integer -> Integer -- Point-free style factorial = foldr (*) 1 . enumFromTo 1
butchhoward/xhaskell
factorial_point_free.hs
mit
124
0
6
22
31
17
14
2
1
f :: Num a => a -> a f x = (^2) x main1 = print (f 42) -- 1764 -- ------------------------------------------------------ data Maybe' a = Just' a | Nothing' deriving (Show) -- To achieve -- f (Just' 42) -- we could either write a new function fMaybe _ Nothing' = Nothing' fMaybe f (Just' x) = Just' (f x) main2 = print $ fMaybe f (Just' 42) -- Just' 1764 -- ------------------------------------------------------ -- or, preferably, make Maybe' an instance of Functor instance Functor Maybe' where fmap _ Nothing' = Nothing' fmap f (Just' x) = Just' (f x) {- class Functor f where fmap :: (a -> b) -> f a -> f b -} main3 = do print $ fmap f (Just' 42) -- Just' 1764 print $ fmap show (Just' 42) -- Just' "42" -- ------------------------------------------------------ -- Functor Laws {- -- law of composition fmap (f . g) == fmap f . fmap g -- e.g. fmap (f . read) getLine = ((fmap f) . (fmap read)) getLine -- identity law fmap id == id -- e.g. fmap id (Just 1) = id (Just 1) -} -- ------------------------------------------------------ main4 = do print $ fmap (^2) [1, 2, 3, 5, 7] -- same as List.map print $ map (^2) [1, 2, 3, 5, 7] -- [1,4,9,25,49]
uroboros/haskell_design_patterns
chapter3/1_functor.hs
mit
1,240
0
10
308
289
158
131
17
1
-- http://stackoverflow.com/questions/2349233/catching-control-c-exception-in-ghc-haskell import Control.Exception as E import Control.Concurrent import System.Posix.Signals import System.IO main :: IO () main = do tid <- myThreadId installHandler keyboardSignal (Catch (throwTo tid UserInterrupt)) Nothing --hSetBuffering stdout NoBuffering --hSetBuffering stdin NoBuffering repLoop repLoop :: IO () repLoop = do putStr "> " line <- interruptible "<interrupted>" getLine if line == "exit" then putStrLn "goodbye" else do putStrLn $ "input was: " ++ line repLoop interruptible :: a -> IO a -> IO a interruptible a m = E.handleJust f return m where f UserInterrupt = Just a f _ = Nothing
tychon/phrases
test_catch_ctrlc.hs
mit
781
0
11
188
200
99
101
24
2
----------------------------------------------------------------------------- -- | -- Module : Numeric.Transform.Fourier.R2DIF -- Copyright : (c) Matthew Donadio 2003 -- License : GPL -- -- Maintainer : m.p.donadio@ieee.org -- Stability : experimental -- Portability : portable -- -- Radix-2 Decimation in Frequency FFT -- ----------------------------------------------------------------------------- module Numeric.Transform.Fourier.R2DIF (fft_r2dif) where import DSP.Basic (interleave) import Data.Array import Data.Complex ------------------------------------------------------------------------------- -- | Radix-2 Decimation in Frequency FFT {-# specialize fft_r2dif :: Array Int (Complex Float) -> Int -> (Array Int (Complex Float) -> Array Int (Complex Float)) -> Array Int (Complex Float) #-} {-# specialize fft_r2dif :: Array Int (Complex Double) -> Int -> (Array Int (Complex Double) -> Array Int (Complex Double)) -> Array Int (Complex Double) #-} fft_r2dif :: (Ix a, Integral a, RealFloat b) => Array a (Complex b) -- ^ x[n] -> a -- ^ N -> (Array a (Complex b) -> Array a (Complex b)) -- ^ FFT function -> Array a (Complex b) -- ^ X[k] fft_r2dif a n fft = y where wn = cis (-2 * pi / fromIntegral n) w = listArray (0,n-1) $ iterate (* wn) 1 ae = listArray (0,n2-1) [ a!k + a!(k+n2) | k <- [0..(n2-1)] ] ao = listArray (0,n2-1) [ (a!k - a!(k+n2)) * w!k | k <- [0..(n2-1)] ] ye = fft ae yo = fft ao y = listArray (0,n-1) (interleave (elems ye) (elems yo)) n2 = n `div` 2
tolysz/dsp
Numeric/Transform/Fourier/R2DIF.hs
gpl-2.0
1,621
0
14
369
414
232
182
19
1
data PatriciaTrieR a = Tip a | Arm Bool (PatriciaTrieR a) | Branch (PatriciaTrieR a) (PatriciaTrieR a) data Maybe a = Just a | Nothing type PatriciaTrie a = Maybe (PatriciaTrieR a) type BVec = [Bool] singletonR :: {n : ℕ} -> BVec n -> A -> PatriciaTrieR n singletonR [] a = Tip a singletonR (x ∷ xs) a = Arm x (singletonR xs a) singleton :: BVec -> a -> PatriciaTrie a singleton xs a = just (singletonR xs a) getR :: BVec n -> PatriciaTrieR n -> Maybe A getR [] (Tip a) = just a getR (x ∷ xs) (Arm b t) with x ≟ b ... | yes p = getR xs t ... | no ¬p = nothing getR (true ∷ xs) (Branch l r) = getR xs r getR (false ∷ xs) (Branch l r) = getR xs l get : {n : ℕ} -> BVec n -> PatriciaTrie n -> Maybe A get xs nothing = nothing get xs (just t) = getR xs t setR : {n : ℕ} -> BVec n -> PatriciaTrieR n -> Maybe A -> PatriciaTrie n setR [] (Tip a) m = Tip <$> m setR (x ∷ xs) (Arm b t) m with cmp x b | m ... | tri< _ _ _ | nothing = just (Arm b t) ... | tri< _ _ _ | just a = just (Branch (singletonR xs a) t) ... | tri≈ _ _ _ | _ = Arm b <$> setR xs t m ... | tri> _ _ _ | nothing = just (Arm b t) ... | tri> _ _ _ | just a = just (Branch t (singletonR xs a)) setR (true ∷ xs) (Branch l r) m with setR xs r m ... | nothing = just (Arm false l) ... | just r′ = just (Branch l r′) setR (false ∷ xs) (Branch l r) m with setR xs l m ... | nothing = just (Arm true r) ... | just l′ = just (Branch l′ r) set : {n : ℕ} -> BVec n -> PatriciaTrie n -> Maybe A -> PatriciaTrie n set xs (just t) m = setR xs t m set xs nothing m = singletonR xs <$> m
danr/hipspec
examples/old-examples/quickspec/Patricia.hs
gpl-3.0
1,662
38
11
476
966
482
484
-1
-1
module FRP.Chimera.Environment.Discrete ( Discrete2dDimension , Discrete2dCoord , Discrete2dNeighbourhood , Discrete2dCell , Discrete2d (..) , SingleOccupantCell , SingleOccupantDiscrete2d , MultiOccupantCell , MultiOccupantDiscrete2d , createDiscrete2d , dimensionsDisc2d , dimensionsDisc2dM , allCellsWithCoords , updateCells , updateCellsM , updateCellsWithCoords , updateCellsWithCoordsM , updateCellAt , changeCellAt , changeCellAtM , cellsAroundRadius , cellsAroundRadiusM , cellsAroundRect , cellsAt , cellAt , cellAtM , randomCell , randomCellWithinRect --, environmentDisc2dRandom , neighbours , neighboursM , neighbourCells , neighbourCellsM , neighboursInNeumannDistance , neighboursInNeumannDistanceM , neighboursCellsInNeumannDistance , neighboursCellsInNeumannDistanceM , distanceManhattanDisc2d , distanceEuclideanDisc2d , neighbourhoodOf , neighbourhoodScale , wrapCells , neumann , moore , wrapNeighbourhood , wrapDisc2d , wrapDisc2dEnv , randomNeighbourCell , randomNeighbour , occupied , unoccupy , occupy , occupier , addOccupant , removeOccupant , hasOccupiers , occupiers ) where import Data.Array.IArray import Data.List import Data.Maybe import Control.Monad.Random import Control.Monad.Trans.State import FRP.Chimera.Environment.Spatial type Discrete2dDimension = (Int, Int) type Discrete2dCoord = Discrete2dDimension type Discrete2dNeighbourhood = [Discrete2dCoord] type Discrete2dCell c = (Discrete2dCoord, c) type SingleOccupantCell c = Maybe c type SingleOccupantDiscrete2d c = Discrete2d (SingleOccupantCell c) type MultiOccupantCell c = [c] type MultiOccupantDiscrete2d c = Discrete2d (MultiOccupantCell c) data Discrete2d c = Discrete2d { envDisc2dDims :: Discrete2dDimension , envDisc2dNeighbourhood :: Discrete2dNeighbourhood , envDisc2dWrapping :: EnvironmentWrapping , envDisc2dCells :: Array Discrete2dCoord c -- , envDisc2dRng :: StdGen } deriving (Show, Read) createDiscrete2d :: Discrete2dDimension -> Discrete2dNeighbourhood -> EnvironmentWrapping -> [Discrete2dCell c] -- -> StdGen -> Discrete2d c createDiscrete2d d@(xLimit, yLimit) n w cs = Discrete2d { envDisc2dDims = d , envDisc2dNeighbourhood = n , envDisc2dWrapping = w , envDisc2dCells = arr --, envDisc2dRng = rng } where arr = array ((0, 0), (xLimit - 1, yLimit - 1)) cs {- environmentDisc2dRandom :: Rand StdGen (Discrete2d c) -> Discrete2d c -> Discrete2d c environmentDisc2dRandom f e = e'' where g = envDisc2dRng e (e', g') = runRand f g e'' = e' { envDisc2dRng = g' } -} dimensionsDisc2d :: Discrete2d c -> Discrete2dDimension dimensionsDisc2d = envDisc2dDims dimensionsDisc2dM :: State (Discrete2d c) Discrete2dDimension dimensionsDisc2dM = state (\e -> (envDisc2dDims e, e)) allCellsWithCoords :: Discrete2d c -> [Discrete2dCell c] allCellsWithCoords e = assocs $ envDisc2dCells e updateCellsM :: (c -> c) -> State (Discrete2d c) () updateCellsM f = state (\e -> ((), updateCells f e)) updateCells :: (c -> c) -> Discrete2d c -> Discrete2d c updateCells f e = e { envDisc2dCells = ec' } where ec = envDisc2dCells e ec' = amap f ec updateCellsWithCoordsM :: (Discrete2dCell c -> c) -> State (Discrete2d c) () updateCellsWithCoordsM f = state (\e -> ((), updateCellsWithCoords f e)) updateCellsWithCoords :: (Discrete2dCell c -> c) -> Discrete2d c -> Discrete2d c updateCellsWithCoords f e = e' where ecs = allCellsWithCoords e cs = map f ecs ecCoords = map fst ecs e' = foldr (\(coord, c) accEnv -> changeCellAt coord c accEnv) e (zip ecCoords cs) updateCellAt :: Discrete2dCoord -> (c -> c) -> Discrete2d c -> Discrete2d c updateCellAt coord f e = e { envDisc2dCells = arr' } where arr = envDisc2dCells e c = arr ! coord c' = f c arr' = arr // [(coord, c')] changeCellAt :: Discrete2dCoord -> c -> Discrete2d c -> Discrete2d c changeCellAt coord c e = e { envDisc2dCells = arr' } where arr = envDisc2dCells e arr' = arr // [(coord, c)] changeCellAtM :: Discrete2dCoord -> c -> State (Discrete2d c) () changeCellAtM coord c = state (\e -> ((), changeCellAt coord c e)) cellsAroundRadius :: Discrete2dCoord -> Double -> Discrete2d c -> [Discrete2dCell c] cellsAroundRadius pos r e = filter (\(coord, _) -> r >= distanceEuclideanDisc2d pos coord) ecs where ecs = allCellsWithCoords e -- TODO: does not yet wrap around boundaries cellsAroundRadiusM :: Discrete2dCoord -> Double -> State (Discrete2d c) [Discrete2dCell c] cellsAroundRadiusM pos r = state (\e -> (cellsAroundRadius pos r e, e)) cellsAroundRect :: Discrete2dCoord -> Int -> Discrete2d c -> [Discrete2dCell c] cellsAroundRect (cx, cy) r e = zip wrappedCs cells where cs = [(x, y) | x <- [cx - r .. cx + r], y <- [cy - r .. cy + r]] l = envDisc2dDims e w = envDisc2dWrapping e wrappedCs = wrapCells l w cs cells = cellsAt wrappedCs e cellsAt :: [Discrete2dCoord] -> Discrete2d c -> [c] cellsAt cs e = map (arr !) cs where arr = envDisc2dCells e cellAt :: Discrete2dCoord -> Discrete2d c -> c cellAt coord e = arr ! coord where arr = envDisc2dCells e cellAtM :: Discrete2dCoord -> State (Discrete2d c) c cellAtM coord = state (\e -> (cellAt coord e, e)) randomCell :: RandomGen g => Discrete2d c -> Rand g (c, Discrete2dCoord) randomCell e = do let (maxX, maxY) = envDisc2dDims e randX <- getRandomR (0, maxX - 1) randY <- getRandomR (0, maxY - 1) let randCoord = (randX, randY) let randCell = cellAt randCoord e return (randCell, randCoord) randomCellWithinRect :: RandomGen g => Discrete2dCoord -> Int -> Discrete2d c -> Rand g (c, Discrete2dCoord) randomCellWithinRect (x, y) r e = do randX <- getRandomR (-r, r) randY <- getRandomR (-r, r) let randCoord = (x + randX, y + randY) let randCoordWrapped = wrapDisc2d (envDisc2dDims e) (envDisc2dWrapping e) randCoord let randCell = cellAt randCoordWrapped e return (randCell, randCoordWrapped) -- NOTE: this function does only work for neumann-neighbourhood, it ignores the environments neighbourhood. also it does not include the coord itself neighboursInNeumannDistance :: Discrete2dCoord -> Int -> Bool -> Discrete2d c -> [Discrete2dCell c] neighboursInNeumannDistance coord dist ic e = zip wrappedNs cells where n = neumann coordDeltas = foldr (\v acc -> acc ++ neighbourhoodScale n v) [] [1 .. dist] l = envDisc2dDims e w = envDisc2dWrapping e ns = neighbourhoodOf coord ic coordDeltas wrappedNs = wrapNeighbourhood l w ns cells = cellsAt wrappedNs e neighboursInNeumannDistanceM :: Discrete2dCoord -> Int -> Bool -> State (Discrete2d c) [Discrete2dCell c] neighboursInNeumannDistanceM coord dist ic = state (\e -> (neighboursInNeumannDistance coord dist ic e, e)) neighboursCellsInNeumannDistance :: Discrete2dCoord -> Int -> Bool -> Discrete2d c -> [c] neighboursCellsInNeumannDistance coord dist ic e = map snd (neighboursInNeumannDistance coord dist ic e) neighboursCellsInNeumannDistanceM :: Discrete2dCoord -> Int -> Bool -> State (Discrete2d c) [c] neighboursCellsInNeumannDistanceM coord dist ic = state (\e -> (neighboursCellsInNeumannDistance coord dist ic e, e)) neighbours :: Discrete2dCoord -> Bool -> Discrete2d c -> [Discrete2dCell c] neighbours coord ic e = zip wrappedNs cells where n = envDisc2dNeighbourhood e l = envDisc2dDims e w = envDisc2dWrapping e ns = neighbourhoodOf coord ic n wrappedNs = wrapNeighbourhood l w ns cells = cellsAt wrappedNs e neighboursM :: Discrete2dCoord -> Bool -> State (Discrete2d c) [Discrete2dCell c] neighboursM coord ic = state (\e -> (neighbours coord ic e, e)) neighbourCells :: Discrete2dCoord -> Bool -> Discrete2d c -> [c] neighbourCells coord ic e = map snd (neighbours coord ic e) neighbourCellsM :: Discrete2dCoord -> Bool -> State (Discrete2d c) [c] neighbourCellsM coord ic = state (\e -> (neighbourCells coord ic e, e)) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- distanceManhattanDisc2d :: Discrete2dCoord -> Discrete2dCoord -> Int distanceManhattanDisc2d (x1, y1) (x2, y2) = abs (x1 - x2) + abs (y1 - y2) distanceEuclideanDisc2d :: Discrete2dCoord -> Discrete2dCoord -> Double distanceEuclideanDisc2d (x1, y1) (x2, y2) = sqrt (xDelta*xDelta + yDelta*yDelta) where xDelta = fromRational $ toRational (x2 - x1) yDelta = fromRational $ toRational (y2 - y1) neighbourhoodOf :: Discrete2dCoord -> Bool -> Discrete2dNeighbourhood -> Discrete2dNeighbourhood neighbourhoodOf coord@(x,y) includeCoord ns | includeCoord = coord : ns' | otherwise = ns' where ns' = map (\(x', y') -> (x + x', y + y')) ns neighbourhoodScale :: Discrete2dNeighbourhood -> Int -> Discrete2dNeighbourhood neighbourhoodScale ns s = map (\(x,y) -> (x * s, y * s)) ns wrapCells :: Discrete2dDimension -> EnvironmentWrapping -> Discrete2dNeighbourhood -> Discrete2dNeighbourhood wrapCells = wrapNeighbourhood neumann :: Discrete2dNeighbourhood neumann = [topDelta, leftDelta, rightDelta, bottomDelta] moore :: Discrete2dNeighbourhood moore = [ topLeftDelta, topDelta, topRightDelta, leftDelta, rightDelta, bottomLeftDelta, bottomDelta, bottomRightDelta ] wrapNeighbourhood :: Discrete2dDimension -> EnvironmentWrapping -> Discrete2dNeighbourhood -> Discrete2dNeighbourhood wrapNeighbourhood l w ns = map (wrapDisc2d l w) ns wrapDisc2dEnv :: Discrete2d c -> Discrete2dCoord -> Discrete2dCoord wrapDisc2dEnv e c = wrapDisc2d d w c where d = envDisc2dDims e w = envDisc2dWrapping e wrapDisc2d :: Discrete2dDimension -> EnvironmentWrapping -> Discrete2dCoord -> Discrete2dCoord wrapDisc2d (maxX, maxY) ClipToMax (x, y) = (max 0 (min x (maxX - 1)), max 0 (min y (maxY - 1))) wrapDisc2d l@(maxX, _) WrapHorizontal (x, y) | x < 0 = wrapDisc2d l WrapHorizontal (x + maxX, y) | x >= maxX = wrapDisc2d l WrapHorizontal (x - maxX, y) | otherwise = (x, y) wrapDisc2d l@(_, maxY) WrapVertical (x, y) | y < 0 = wrapDisc2d l WrapVertical (x, y + maxY) | y >= maxY = wrapDisc2d l WrapVertical (x, y - maxY) | otherwise = (x, y) wrapDisc2d l WrapBoth c = wrapDisc2d l WrapHorizontal $ wrapDisc2d l WrapVertical c topLeftDelta :: Discrete2dCoord topLeftDelta = (-1, -1) topDelta :: Discrete2dCoord topDelta = ( 0, -1) topRightDelta :: Discrete2dCoord topRightDelta = ( 1, -1) leftDelta :: Discrete2dCoord leftDelta = (-1, 0) rightDelta :: Discrete2dCoord rightDelta = ( 1, 0) bottomLeftDelta :: Discrete2dCoord bottomLeftDelta = (-1, 1) bottomDelta :: Discrete2dCoord bottomDelta = ( 0, 1) bottomRightDelta :: Discrete2dCoord bottomRightDelta = ( 1, 1) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- UTILITIES ------------------------------------------------------------------------------- randomNeighbourCell :: RandomGen g => Discrete2dCoord -> Bool -> Discrete2d c -> Rand g c randomNeighbourCell pos ic e = randomNeighbour pos ic e >>= (\(_, c) -> return c) randomNeighbour :: RandomGen g => Discrete2dCoord -> Bool -> Discrete2d c -> Rand g (Discrete2dCell c) randomNeighbour pos ic e = do let ncc = neighbours pos ic e let l = length ncc randIdx <- getRandomR (0, l - 1) return (ncc !! randIdx) ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- OCCUPIERS ------------------------------------------------------------------------------- occupied :: Discrete2dCoord -> SingleOccupantDiscrete2d c -> Bool occupied coord e = isJust $ cellAt coord e unoccupy :: Discrete2dCoord -> SingleOccupantDiscrete2d c -> SingleOccupantDiscrete2d c unoccupy coord e = changeCellAt coord Nothing e occupy :: Discrete2dCoord -> c -> SingleOccupantDiscrete2d c -> SingleOccupantDiscrete2d c occupy coord c e = changeCellAt coord (Just c) e occupier :: Discrete2dCoord -> SingleOccupantDiscrete2d c -> c occupier coord e = fromJust $ cellAt coord e addOccupant :: Discrete2dCoord -> c -> MultiOccupantDiscrete2d c -> MultiOccupantDiscrete2d c addOccupant coord c e = updateCellAt coord (\cs -> c : cs) e removeOccupant :: (Eq c) => Discrete2dCoord -> c -> MultiOccupantDiscrete2d c -> MultiOccupantDiscrete2d c removeOccupant coord c e = updateCellAt coord (\cs -> delete c cs) e hasOccupiers :: Discrete2dCoord -> MultiOccupantDiscrete2d c -> Bool hasOccupiers coord e = not . null $ cellAt coord e occupiers :: Discrete2dCoord -> MultiOccupantDiscrete2d c -> [c] occupiers = cellAt -------------------------------------------------------------------------------
thalerjonathan/phd
coding/libraries/chimera/src/FRP/Chimera/Environment/Discrete.hs
gpl-3.0
13,227
0
12
2,642
3,919
2,096
1,823
269
1
-- | Monomorphises the Simple language, given some initial activated -- records. The idea is that these activation records come from -- a monomorphised conjecture. {-# LANGUAGE RecordWildCards, ScopedTypeVariables, PatternGuards #-} module HipSpec.Lang.Monomorphise (monoClauses, IdInst(..),Lemma(..),toList,Records) where import Prelude hiding (lookup) import HipSpec.Lang.PolyFOL import qualified Data.Set as S import Data.Set (Set) import qualified Data.Map as M import Data.Map (Map) import Data.Monoid import Data.Maybe import Data.List (partition) import Control.Arrow import Control.Monad type Records a b = Map (Trigger a) (Set [Type a b]) empty :: Records a b empty = M.empty member :: (Ord a,Ord b) => (Trigger a,[Type a b]) -> Records a b -> Bool (t,ts) `member` r = maybe False (ts `S.member`) (M.lookup t r) (\\) :: (Ord a,Ord b) => Records a b -> Records a b -> Records a b (\\) = M.differenceWith $ \ s1 s2 -> do let s' = s1 S.\\ s2 guard (not (S.null s')) return s' union :: (Ord a,Ord b) => Records a b -> Records a b -> Records a b union = M.unionWith S.union unions :: (Ord a,Ord b) => [Records a b] -> Records a b unions = M.unionsWith S.union fromList :: (Ord a,Ord b) => [(Trigger a,[Type a b])] -> Records a b fromList = M.fromListWith S.union . map (second S.singleton) toList :: (Ord a,Ord b) => Records a b -> [(Trigger a,[Type a b])] toList r = [ (t,ts) | (t,s) <- M.toList r, ts <- S.toList s ] minView :: (Ord a,Ord b) => Records a b -> Maybe ((Trigger a,[Type a b]),Records a b) minView m = case M.minViewWithKey m of Just ((t,s),m') -> case S.minView s of Just (ts,s') -> Just ((t,ts),M.insert t s' m') Nothing -> minView m' Nothing -> Nothing insert :: (Ord a,Ord b) => Trigger a -> [Type a b] -> Records a b -> Records a b insert i t = M.insertWith S.union i (S.singleton t) lookup :: (Ord a,Ord b) => Trigger a -> Records a b -> [[Type a b]] lookup t r = maybe [] S.toList (M.lookup t r) -- | Get the records from a clause clauseRecs :: (Ord a,Ord b) => Clause a b -> Records a b clauseRecs cl = fromList $ [ (TySymb tc,ts) | TyCon tc ts <- clTyUniv cl ] ++ [ (Symb f,ts) | Apply f ts _ <- clTmUniv cl ] instClauseWith :: forall a b . Eq b => Clause a b -> [(b,Type a b)] -> Clause a b instClauseWith cl su = case cl of Clause nm _trg ty _tvs fm -> Clause nm [] ty [] (fmInsts su fm) _ -> cl -- or error! instClause :: forall a b . Eq b => Clause a b -> [Type a b] -> Clause a b instClause cl ts = case cl of Clause{..} -> instClauseWith cl (zip ty_vars ts) _ -> cl type InstMap a b = Map b (Type a b) data Lemma a b = Lemma { lm_cl :: Clause a b -- ^ the clause , lm_act :: [(Trigger a,[Type a b])] -- Records a b -- ^ The instantiation records it requires , lm_eff :: Records a b -- ^ The effect of instantiating it , lm_inst :: [InstMap a b] -- ^ The types it has already been instantiated at } deriving Show -- | Stage one monomorphisation -- 1st component: monomorphically applied clauses -- 2nd component: type signatures to be monomorphised monoClauses1 :: forall a b . (Ord a,Ord b) => [Clause a b] -> (([Clause a b],[Clause a b]),([Lemma a b],Records a b)) monoClauses1 cls0 = ((source ++ defs ++ lemma_cls,sigs),fin) where trg_pred p Clause{..} = p cl_ty_triggers trg_pred _ _ = False (source,other) = partition (trg_pred (Source `elem`)) cls0 (defs_poly,rest) = partition (trg_pred (not . null)) other (lem_cls,sigs) = partition (trg_pred (const True)) rest mono = mkMono defs_poly (defs,def_irs) = mono empty (unions (map clauseRecs source)) lemmas :: [Lemma a b] lemmas = [ Lemma cl (toList recs) (snd (mono empty recs)) [] | cl <- lem_cls , let recs = clauseRecs cl ] go :: Int -> Bool -> [Lemma a b] -> [Lemma a b] -> Records a b -> ([Clause a b],([Lemma a b],Records a b)) go _rounds False [] acc irs = ([],(acc,irs)) go rounds True [] acc irs = go (rounds+1) False acc [] irs go rounds b (l:ls) acc irs = case new of [] -> go rounds b ls (l:acc) irs (l',cl):_ -> let (cls,irs') = mono irs (clauseRecs cl) in first (\ c -> cl:cls ++ c) (go rounds True ls (l':acc) irs') where new = catMaybes [ instLemma (rounds < 2) l im irs | im <- possibleInsts l irs ] (lemma_cls,fin) = go 0 False lemmas [] def_irs instLemma :: (Ord a,Ord b) => Bool {- ^ allow new type instantiations -} -> Lemma a b {- ^ lemma to maybe instantiate -} -> InstMap a b {- ^ type to instantiate it at -} -> Records a b {- ^ instantiated records so far -} -> Maybe (Lemma a b,Clause a b) {- Just (l,r,c) : l: Lemma with new info c: The clause that got instantiated -} instLemma allow_new l@Lemma{..} im rs -- Instantiate lemmas as long as they don't trigger new -- types to be instantiated | (allow_new || and [ (t,map (tySubsts (M.toList im)) ts) `member` rs | (t,ts) <- takeWhile (isTySymb . fst) (toList lm_eff) ]) -- and we haven't instantiated it before && im `notElem` lm_inst -- and all type variables are assigned && all (`M.member` im) (ty_vars lm_cl) = Just ( l { lm_inst = im : lm_inst } , instClauseWith lm_cl (M.toList im) ) | otherwise = Nothing -- | Possible instantiations of a lemma given some instantiation records possibleInsts :: (Ord a,Ord b) => Lemma a b -> Records a b -> [InstMap a b] possibleInsts Lemma{..} rs = go lm_act where go [] = [M.empty] go ((trg,ts):xs) = [ m1 `M.union` m2 | m1 <- M.empty : mapMaybe (tyInsts ts) (lookup trg rs) , m2 <- go xs , compatible m1 m2 ] tyInst :: (Ord a,Ord b) => Type a b {- ^ with type variables -} -> Type a b {- ^ without -} -> Maybe (InstMap a b) tyInst (TyVar x) t = Just (M.singleton x t) tyInst (TyCon u us) (TyCon v vs) | u == v = tyInsts us vs tyInst TType TType = Just M.empty tyInst Integer Integer = Just M.empty tyInst _ _ = Nothing tyInsts :: (Ord a,Ord b) => [Type a b] -> [Type a b] -> Maybe (InstMap a b) tyInsts (u:us) (v:vs) = do m1 <- tyInst u v m2 <- tyInsts us vs guard (compatible m1 m2) return (m1 `M.union` m2) tyInsts [] [] = Just M.empty tyInsts _ _ = Nothing compatible :: (Ord a,Ord b) => InstMap a b -> InstMap a b -> Bool compatible a b = oneway a b && oneway b a where oneway p q = and [ maybe True (== v) (M.lookup k q) | (k,v) <- M.toList p ] mkMono :: forall a b . (Ord a,Ord b) => [Clause a b] -> Records a b -- ^ Initial, already instantiated records -> Records a b -- ^ New record queue -> ([Clause a b],Records a b) -- ^ Instantiated clauses and final records mkMono cls0 irs0 q0 = go irs0 (q0 \\ irs0) where -- Since some clauses are activated by either of many triggers, -- we let one of them instantiate the clause, and the other ones just -- retrigger with the major pattern trg_targets :: Map (Trigger a) ([Clause a b],[Trigger a]) trg_targets = M.fromListWith mappend $ concat $ [ (trg,([cl],rtrs)) : [ (rtr,([],filter (rtr /=) trgs)) | rtr <- rtrs ] | cl <- cls0 , let trgs@(trg:rtrs) = cl_ty_triggers cl ] go :: Records a b -> Records a b -- ^ (invariant: no overlap) -> ([Clause a b],Records a b) go irs q = case minView q of Nothing -> ([],irs) Just ((trg,ts),q') -> case M.lookup trg trg_targets of Nothing -> go irs q' Just (cls,retrigs) -> let cls' = map (`instClause` ts) cls rtr = fromList (zip retrigs (repeat ts)) irs' = insert trg ts irs recs = (unions (map clauseRecs cls') `union` rtr) \\ irs' in first (cls' ++) (go irs' (q' `union` recs)) data IdInst a b = IdInst a [Type a b] deriving (Eq,Ord,Show) -- | Second pass monomorphisation: remove all type applications and change -- the identifier names instead monoClauses2 :: (Ord a,Ord b) => ([Clause a b],[Clause a b]) -> [Clause (IdInst a b) b] monoClauses2 (cls,sigs) = map (`SortSig` 0) (S.toList sorts) ++ ty_sigs ++ cls' where cls' = [ Clause { cl_name = cl_name cl , cl_ty_triggers = [] , cl_type = cl_type cl , ty_vars = [] , cl_formula = fmMod tyCon apply (cl_formula cl) } | cl <- cls ] tyCon f ts = IdInst f ts apply f ts = Apply (IdInst f ts) [] (sorts1,ty_apps) = clsDeps cls' sig_map = M.fromList [ (f,(tvs,args,res)) | TypeSig f tvs args res <- sigs ] ty_sigs = [ TypeSig f' [] args' res' | f'@(IdInst f ts) <- S.toList ty_apps , Just (tvs,args,res) <- [M.lookup f sig_map] , let su = tyMod tyCon . tySubsts (zip tvs ts) args' = map su args res' = su res ] (sorts2,_) = clsDeps ty_sigs sorts = sorts1 `S.union` sorts2 -- | Monomorphise clauses monoClauses :: (Ord a,Ord b) => [Clause a b] -> ([Clause (IdInst a b) b],([Lemma a b],Records a b)) monoClauses = first monoClauses2 . monoClauses1
danr/hipspec
src/HipSpec/Lang/Monomorphise.hs
gpl-3.0
9,634
0
22
2,943
3,991
2,100
1,891
183
5
{-# LANGUAGE ScopedTypeVariables, DeriveDataTypeable, MonadComprehensions #-} module Main where import Transient.Move import Transient.Logged import Transient.Base import Transient.Indeterminism import Network import Control.Applicative import Control.Monad.IO.Class import System.Environment import System.IO.Unsafe import Data.Monoid import System.IO import Control.Monad import Data.Maybe import Control.Exception import Control.Concurrent (threadDelay) import Data.Typeable import Control.Concurrent.STM import Data.IORef import Network import Network.Socket hiding (connect) -- .ByteString import Network.Simple.TCP (connectSock) import Control.Concurrent import Network.HTTP import Network.Stream -- some tests for distributed computing --main= do -- let port1 = PortNumber 2000 -- port2 = PortNumber 2001 -- -- -- keep $ do -- conn port1 port1 <|> conn port2 port1 -- -- examples' host port2 -- where -- host= "localhost" ---- delay = liftIO $ threadDelay 1000000 -- conn p p'= connect host p host p' -- -- -- -- -- test1= withSocketsDo $ do str <- simpleHTTP (getRequest $ "https://api.github.com/users/" ++ "PureScript" ++ "/repos") print str h <- connectTo "irc.freenode.net" (PortNumber 6667) keep $ (waitEvents (hGetLine h) >>= liftIO . putStrLn) <|> (waitEvents (getLine' $ const True) >>= liftIO . hPutStr h) test = do args <- getArgs let ports= [("localhost",PortNumber 2000), ("localhost",PortNumber 2001)] let [(_,port1), (_,port2)]= if null args then ports else reverse ports local= "localhost" print [port1, port2] let node = createNode local port2 addNodes [node] beamInit port1 $ do logged $ option "call" "call" r <- callTo node [(x,y)| x <- choose[1..4], y <- choose[1..(4 ::Int)] , x-y == 1] liftIO $ print r -- roundtrip 5 node <|> roundtrip 5 node -- where -- roundtrip 0 _ = return () -- roundtrip n (node@(Node _ port2 _))= do -- beamTo node -- step $ liftIO $ print "PING" -- -- beamTo node -- step $ liftIO $ print "PONG" -- roundtrip (n - 1) node -- to be executed with two or more nodes main = do args <- getArgs if length args < 2 then do putStrLn "The program need at least two parameters: localHost localPort remoteHost RemotePort" putStrLn "Start one node alone. The rest, connected to this node." return () else keep $ do let localHost= head args localPort= PortNumber . fromInteger . read $ args !! 1 (remoteHost,remotePort) = if length args >=4 then(args !! 2, PortNumber . fromInteger . read $ args !! 3) else (localHost,localPort) let localNode= createNode localHost localPort remoteNode= createNode remoteHost remotePort connect localNode remoteNode examples examples = do logged $ option "main" "to see the menu" <|> return "" r <- logged $ option "move" "move to another node" <|> option "call" "call a function in another node" <|> option "chat" "chat" <|> option "netev" "events propagating trough the network" case r of "call" -> callExample "move" -> moveExample "chat" -> chat "netev" -> networkEvents data Environ= Environ (IORef String) deriving Typeable callExample = do nodes <- logged getNodes let node= head $ tail nodes -- the first connected node logged $ putStrLnhp node "asking for the remote data" s <- callTo node $ do putStrLnhp node "remote callTo request" liftIO $ readIORef environ liftIO $ putStrLn $ "resp=" ++ show s {-# NOINLINE environ #-} environ= unsafePerformIO $ newIORef "Not Changed" moveExample = do nodes <- logged getNodes let node= head $ tail nodes putStrLnhp node "enter a string. It will be inserted in the other node by a migrating program" name <- logged $ input (const True) beamTo node putStrLnhp node "moved!" putStrLnhp node $ "inserting "++ name ++" as new data in this node" liftIO $ writeIORef environ name return() chat :: TransIO () chat = do name <- logged $ do liftIO $ putStrLn "Name?" ; input (const True) text <- logged $ waitEvents $ putStr ">" >> hFlush stdout >> getLine' (const True) let line= name ++": "++ text clustered $ liftIO $ putStrLn line networkEvents = do nodes <- logged getNodes let node= head $ tail nodes logged $ do putStrLnhp node "write \"fire\" in the other node" r <- callTo node $ do option "fire" "fire event" return "event fired" putStrLnhp node $ r ++ " in remote node" putStrLnhp p msg= liftIO $ putStr (show p) >> putStr " ->" >> putStrLn msg --call host port proc params= do -- port <- getPort -- listen port <|> return -- parms <- logged $ return params -- callTo host port proc parms -- close -- --distribute proc= do -- case dataFor proc -- Nothing -> proc -- Just dataproc -> do -- (h,p) <- bestNode dataproc -- callTo h p proc -- --bestNode dataproc= -- nodes <- getNodes -- (h,p) <- bestMatch dataproc nodes <- user defined -- --bestMatch (DataProc nodesAccesed cpuLoad resourcesNeeded) nodes= do -- nodesAccesed: node, response -- --bestMove= do -- thisproc <- gets myProc -- case dataFor thisproc -- Nothing -> return () -- Just dataproc -> do -- (h,p) <- bestNode dataproc -- moveTo h p -- -- --inNetwork= do -- p <- getPort -- listen p <|> return ()
haskellGardener/transient
move.hs
gpl-3.0
5,751
0
19
1,571
1,310
670
640
110
4
{-#LANGUAGE RankNTypes, ScopedTypeVariables, FlexibleContexts, FlexibleInstances, UndecidableInstances, MultiParamTypeClasses #-} module Carnap.Languages.PurePropositional.Logic.Gentzen ( parseGentzenPropLK, gentzenPropLKCalc, GentzenPropLK() , parseGentzenPropLJ, gentzenPropLJCalc, GentzenPropLJ() , parseGentzenPropNJ, gentzenPropNJCalc, GentzenPropNJ() , parseGentzenPropNK, gentzenPropNKCalc, GentzenPropNK() ) where import Text.Parsec import Data.List import Data.Tree import Carnap.Languages.ClassicalSequent.Syntax import Carnap.Core.Data.Classes import Carnap.Core.Data.Optics import Carnap.Core.Data.Types (Form, FirstOrderLex(..)) import Carnap.Core.Unification.Unification import Carnap.Languages.PurePropositional.Syntax import Carnap.Languages.PurePropositional.Parser import Carnap.Languages.PurePropositional.Logic.Rules import Carnap.Calculi.Tableau.Data import Carnap.Calculi.NaturalDeduction.Syntax import Carnap.Calculi.Util import Control.Lens import Carnap.Languages.Util.LanguageClasses data GentzenPropLK = Ax | Rep | Cut | AndL1 | AndL2 | AndR | OrR1 | OrR2 | OrL | CondR | CondL | NegR | NegL deriving Eq newtype GentzenPropLJ = LJ GentzenPropLK data GentzenPropNJ = AndI | AndEL | AndER | OrIL | OrIR | OrE Int Int | OrELVac (Maybe Int) Int | OrERVac Int (Maybe Int)| OrEVac (Maybe Int) (Maybe Int) | IfI Int | IfIVac (Maybe Int) | IfE | NegI Int | NegIVac (Maybe Int) | NegE | FalsumE | As Int | Pr deriving Eq data GentzenPropNK = NJ GentzenPropNJ | LEM deriving Eq instance Show GentzenPropLK where show Ax = "Ax" show Rep = "Rep" show Cut = "Cut" show AndL1 = "L&1" show AndL2 = "L&2" show AndR = "R&" show OrR1 = "R∨1" show OrR2 = "R∨2" show OrL = "L∨" show CondR = "R→" show CondL = "L→" show NegR = "R¬" show NegL = "L¬" instance Show GentzenPropLJ where show (LJ x) = show x instance Show GentzenPropNJ where show AndI = "&I" show AndEL = "&E" show AndER = "&E" show OrIL = "∨I" show OrIR = "∨I" show (OrE n m) = "∨E (" ++ show n ++ ") (" ++ show m ++ ")" show (OrELVac (Just n) m) = "∨E (" ++ show n ++ ") (" ++ show m ++ ")" show (OrELVac Nothing m) = "∨E (" ++ show m ++ ")" show (OrERVac n (Just m)) = "∨E (" ++ show n ++ ") (" ++ show m ++ ")" show (OrERVac n Nothing) = "∨E (" ++ show n ++ ")" show (OrEVac (Just n) (Just m)) = "∨E (" ++ show n ++ ") (" ++ show m ++ ")" show (OrEVac Nothing (Just m)) = "∨E (" ++ show m ++ ")" show (OrEVac (Just n) Nothing) = "∨E (" ++ show n ++ ")" show (OrEVac Nothing Nothing) = "∨E" show (IfI n) = "⊃I (" ++ show n ++ ")" show (IfIVac (Just n)) = "⊃I (" ++ show n ++ ")" show (IfIVac Nothing) = "⊃I" show IfE = "⊃E" show (NegI n) = "¬I (" ++ show n ++ ")" show (NegIVac (Just n)) = "¬I (" ++ show n ++ ")" show (NegIVac Nothing) = "¬I" show NegE = "¬E" show FalsumE = "¬E" show (As n) = "(" ++ show n ++ ")" show Pr = "Pr" instance Show GentzenPropNK where show (NJ x) = show x show LEM = "LEM" parseGentzenPropLK :: Parsec String u [GentzenPropLK] parseGentzenPropLK = do r <- choice (map (try . string) [ "Ax", "Rep", "Cut" , "R&","R∧","R/\\" ,"L&1","L∧1","L/\\1" ,"L&2","L∧2","L/\\2" , "L∨","Lv","L\\/" ,"R∨1","Rv1","R\\/1" ,"R∨2","Rv2","R\\/2" , "L→","L->" , "R→","R->" , "L¬","L~","L-" , "R¬","R~","R-" ]) return $ (\x -> [x]) $ case r of r | r == "Ax" -> Ax | r == "Rep" -> Rep | r == "Cut" -> Cut | r `elem` ["R&","R∧","R/\\"] -> AndR | r `elem` ["L&1","L∧1","L/\\1"] -> AndL1 | r `elem` ["L&2","L∧2","L/\\2"] -> AndL2 | r `elem` ["L∨","Lv","L\\/"] -> OrL | r `elem` ["R∨1","Rv1","R\\/1"] -> OrR1 | r `elem` ["R∨2","Rv2","R\\/2"] -> OrR2 | r `elem` ["L→","L->"] -> CondL | r `elem` ["R→","R->"] -> CondR | r `elem` ["L¬","L~","L-"] -> NegL | r `elem` ["R¬","R~","R-"] -> NegR parseGentzenPropLJ = map LJ <$> parseGentzenPropLK parseGentzenPropNJ :: Parsec String u [GentzenPropNJ] parseGentzenPropNJ = choice . map try $ [ stringOpts ["&I","/\\I"] >> return [AndI] , stringOpts ["&E","/\\E"] >> return [AndER, AndEL] , stringOpts ["∨I","\\/I"] >> return [OrIL, OrIR] , stringOpts ["⊃E",">E", "->E"] >> return [IfE] , stringOpts ["¬E","-E"] >> return [NegE, FalsumE] , char '(' *> many1 digit <* char ')' >>= \s -> return [As (read s :: Int)] , (stringOpts ["->I", ">I","⊃I"] *> spaces *> char '(' *> many1 digit <* char ')') >>= \s -> return (let val = read s :: Int in [IfI val, IfIVac (Just val)]) , stringOpts ["->I", ">I","⊃I"] >> return [IfIVac Nothing] , (stringOpts ["¬I", "-I"] *> spaces *> char '(' *> many1 digit <* char ')') >>= \s -> return (let val = read s :: Int in [NegI val, NegIVac (Just val)]) , stringOpts ["¬I", "-I"] >> return [NegIVac Nothing] , (,) <$> (stringOpts ["∨E","\\/E"] *> spaces *> char '(' *> many1 digit <* char ')') <*> (spaces *> char '(' *> many1 digit <* char ')') >>= \(s1,s2) -> return $ let val1 = read s1 :: Int val2 = read s2 :: Int in [OrE val1 val2, OrELVac (Just val1) val2, OrERVac val1 (Just val2), OrEVac (Just val1) (Just val2)] , (stringOpts ["∨E","\\/E"] *> spaces *> char '(' *> many1 digit <* char ')') >>= \s -> return (let val = read s :: Int in [OrELVac Nothing val, OrERVac val Nothing, OrEVac (Just val) Nothing]) , stringOpts ["∨E","\\/E"] >> return [OrEVac Nothing Nothing] , eof >> return [Pr] ] where stringOpts = choice . map (try . string) parseGentzenPropNK :: Parsec String u [GentzenPropNK] parseGentzenPropNK = (map NJ <$> parseGentzenPropNJ) <|> (string "LEM" >> return [LEM]) instance ( BooleanLanguage (ClassicalSequentOver lex (Form Bool)) , BooleanConstLanguage (ClassicalSequentOver lex (Form Bool)) , IndexedSchemePropLanguage (ClassicalSequentOver lex (Form Bool)) ) => CoreInference GentzenPropLK lex (Form Bool) where corePremisesOf AndL1 = [SA (phin 1) :+: GammaV 1 :|-: DeltaV 1] corePremisesOf AndL2 = [SA (phin 2) :+: GammaV 1 :|-: DeltaV 1] corePremisesOf AndR = [ GammaV 1 :|-: SS (phin 1) :-: DeltaV 1 , GammaV 2 :|-: SS (phin 2) :-: DeltaV 2 ] corePremisesOf OrR1 = [ GammaV 1 :|-: DeltaV 1 :-: SS(phin 1)] corePremisesOf OrR2 = [ GammaV 1 :|-: DeltaV 1 :-: SS(phin 2)] corePremisesOf OrL = [ GammaV 1 :+: SA (phin 1) :|-: DeltaV 1 , GammaV 2 :+: SA (phin 1) :|-: DeltaV 2 ] corePremisesOf CondL = [ GammaV 1 :|-: SS (phin 1) :-: DeltaV 1 , GammaV 2 :+: SA (phin 2) :|-: DeltaV 2 ] corePremisesOf CondR = [ GammaV 1 :+: SA (phin 1) :|-: SS (phin 2) :-: DeltaV 2 ] corePremisesOf NegL = [ GammaV 1 :|-: SS (phin 1) :-: DeltaV 1 ] corePremisesOf NegR = [ SA (phin 1) :+: GammaV 1 :|-: DeltaV 1 ] corePremisesOf Rep = [ GammaV 1 :|-: DeltaV 1 ] corePremisesOf Cut = [ SA (phin 1) :+: GammaV 1 :|-: DeltaV 1 , GammaV 2 :|-: DeltaV 2 :-: SS (phin 1) ] corePremisesOf Ax = [] coreConclusionOf AndL1 = SA (phin 1 ./\. phin 2) :+: GammaV 1 :|-: DeltaV 1 coreConclusionOf AndL2 = SA (phin 1 ./\. phin 2) :+: GammaV 1 :|-: DeltaV 1 coreConclusionOf AndR = GammaV 1 :+: GammaV 2 :|-: SS (phin 1 ./\. phin 2) :-: DeltaV 1 :-: DeltaV 2 coreConclusionOf OrR1 = GammaV 1 :|-: SS (phin 1 .\/. phin 2) :-: DeltaV 1 coreConclusionOf OrR2 = GammaV 1 :|-: SS (phin 1 .\/. phin 2) :-: DeltaV 1 coreConclusionOf OrL = SA (phin 1 .\/. phin 2) :+: GammaV 1 :+: GammaV 2 :|-: DeltaV 1 :-: DeltaV 2 coreConclusionOf CondL = SA (phin 1 .=>. phin 2) :+: GammaV 1 :+: GammaV 2 :|-: DeltaV 1 :-: DeltaV 2 coreConclusionOf CondR = GammaV 1 :+: GammaV 2 :|-: SS (phin 1 .=>. phin 2) :-: DeltaV 1 :-: DeltaV 2 coreConclusionOf NegL = SA (lneg $ phin 1) :+: GammaV 1 :|-: DeltaV 1 coreConclusionOf NegR = GammaV 1 :|-: SS (lneg $ phin 1) :-: DeltaV 1 coreConclusionOf Rep = GammaV 1 :|-: DeltaV 1 coreConclusionOf Cut = GammaV 1 :+: GammaV 2 :|-: DeltaV 1 :-: DeltaV 2 coreConclusionOf Ax = GammaV 1 :+: SA (phin 1) :|-: SS (phin 1) :-: DeltaV 1 instance ( BooleanLanguage (ClassicalSequentOver lex (Form Bool)) , BooleanConstLanguage (ClassicalSequentOver lex (Form Bool)) , IndexedSchemePropLanguage (ClassicalSequentOver lex (Form Bool)) , PrismSubstitutionalVariable lex , FirstOrderLex (lex (ClassicalSequentOver lex)) , Eq (ClassicalSequentOver lex (Form Bool)) , ReLex lex ) => CoreInference GentzenPropLJ lex (Form Bool) where corePremisesOf (LJ x) = corePremisesOf x coreConclusionOf (LJ x) = coreConclusionOf x coreRestriction x = Just $ \sub -> monoConsequent (applySub sub $ coreConclusionOf x) where monoConsequent :: forall lex . Eq (ClassicalSequentOver lex (Form Bool)) => ClassicalSequentOver lex (Sequent (Form Bool)) -> Maybe String monoConsequent (_:|-:x)= case nub (toListOf concretes x :: [ClassicalSequentOver lex (Form Bool)]) of _:_:xs -> Just "LJ requires that the right hand side of each sequent contain at most one formula" _ -> Nothing instance ( BooleanLanguage (ClassicalSequentOver lex (Form Bool)) , BooleanConstLanguage (ClassicalSequentOver lex (Form Bool)) , IndexedSchemePropLanguage (ClassicalSequentOver lex (Form Bool)) , PrismSubstitutionalVariable lex , FirstOrderLex (lex (ClassicalSequentOver lex)) , Eq (ClassicalSequentOver lex (Form Bool)) , ReLex lex ) => CoreInference GentzenPropNJ lex (Form Bool) where coreRuleOf AndI = adjunction coreRuleOf AndEL = simplificationVariations !! 0 coreRuleOf AndER = simplificationVariations !! 1 coreRuleOf OrIL = additionVariations !! 0 coreRuleOf OrIR = additionVariations !! 1 coreRuleOf (OrE n m) = proofByCasesVariations !! 0 coreRuleOf (OrELVac _ _) = proofByCasesVariations !! 1 coreRuleOf (OrERVac _ _) = proofByCasesVariations !! 2 coreRuleOf (OrEVac _ _) = proofByCasesVariations !! 3 coreRuleOf (IfI _) = conditionalProofVariations !! 0 coreRuleOf (IfIVac _) = conditionalProofVariations !! 1 coreRuleOf IfE = modusPonens coreRuleOf (NegI _) = constructiveFalsumReductioVariations !! 0 coreRuleOf (NegIVac _) = constructiveFalsumReductioVariations !! 1 coreRuleOf NegE = falsumIntroduction coreRuleOf FalsumE = falsumElimination coreRuleOf (As _) = axiom coreRuleOf Pr = axiom instance ( BooleanLanguage (ClassicalSequentOver lex (Form Bool)) , BooleanConstLanguage (ClassicalSequentOver lex (Form Bool)) , IndexedSchemePropLanguage (ClassicalSequentOver lex (Form Bool)) , PrismSubstitutionalVariable lex , FirstOrderLex (lex (ClassicalSequentOver lex)) , Eq (ClassicalSequentOver lex (Form Bool)) , ReLex lex ) => CoreInference GentzenPropNK lex (Form Bool) where coreRuleOf (NJ x) = coreRuleOf x coreRuleOf LEM = [] ∴ Top :|-: SS (phin 1 .\/. (lneg $ phin 1)) instance Inference GentzenPropNJ PurePropLexicon (Form Bool) where ruleOf x = coreRuleOf x instance Inference GentzenPropNK PurePropLexicon (Form Bool) where ruleOf x = coreRuleOf x instance (Eq r, AssumptionNumbers r) => StructuralInference GentzenPropNJ PurePropLexicon (ProofTree r PurePropLexicon (Form Bool)) where structuralRestriction pt _ (As n) = Just noReps where noReps _ | allEq (leavesLabeled n pt) = Nothing | otherwise = Just "Distinct assumptions are getting the same index" allEq ((Node x _):xs) = all (\(Node pl _) -> content pl == content x) xs structuralRestriction pt _ (IfI n) = Just (usesAssumption n pt assump `andFurtherRestriction` exhaustsAssumptions n pt assump) where assump = SS . liftToSequent $ phin 1 structuralRestriction pt _ (IfIVac (Just n)) = Just (usesAssumption n pt (SS . liftToSequent $ phin 1)) structuralRestriction pt _ (NegI n) = Just (usesAssumption n pt assump `andFurtherRestriction` exhaustsAssumptions n pt assump ) where assump = SS . liftToSequent $ phin 1 structuralRestriction pt _ (NegIVac (Just n)) = Just (usesAssumption n pt (SS . liftToSequent $ phin 1)) structuralRestriction pt _ (OrE n m) = Just $ \sub -> doubleAssumption 1 2 sub >> doubleAssumption 2 1 sub where doubleAssumption j k = usesAssumption n pt (assump j) `andFurtherRestriction` usesAssumption m pt (assump k) `andFurtherRestriction` exhaustsAssumptions n pt (assump j) `andFurtherRestriction` exhaustsAssumptions m pt (assump k) assump n = SS . liftToSequent $ phin n structuralRestriction pt _ (OrERVac n (Just m)) = Just (usesAssumption n pt (assump 1) `andFurtherRestriction` usesAssumption m pt (assump 2) `andFurtherRestriction` exhaustsAssumptions n pt (assump 1)) where assump n = SS . liftToSequent $ phin n structuralRestriction pt _ (OrERVac n Nothing) = Just (usesAssumption n pt (assump 1) `andFurtherRestriction` exhaustsAssumptions n pt (assump 1)) where assump n = SS . liftToSequent $ phin n structuralRestriction pt _ (OrELVac (Just n) m) = Just (usesAssumption n pt (assump 1) `andFurtherRestriction` usesAssumption m pt (assump 2) `andFurtherRestriction` exhaustsAssumptions m pt (assump 2)) where assump n = SS . liftToSequent $ phin n structuralRestriction pt _ (OrELVac Nothing m) = Just (usesAssumption m pt (assump 2) `andFurtherRestriction` exhaustsAssumptions m pt (assump 2)) where assump n = SS . liftToSequent $ phin n structuralRestriction pt _ (OrEVac (Just n) (Just m)) = Just (usesAssumption n pt (assump 1) `andFurtherRestriction` usesAssumption m pt (assump 2)) where assump n = SS . liftToSequent $ phin n structuralRestriction pt _ (OrEVac Nothing (Just m)) = Just (usesAssumption m pt (assump 2)) where assump n = SS . liftToSequent $ phin n structuralRestriction pt _ (OrEVac (Just n) Nothing) = Just (usesAssumption n pt (assump 1)) where assump n = SS . liftToSequent $ phin n structuralRestriction pt _ r = Nothing instance (Eq r, AssumptionNumbers r) => StructuralInference GentzenPropNK PurePropLexicon (ProofTree r PurePropLexicon (Form Bool)) where structuralRestriction pt y (NJ x) = structuralRestriction pt y x structuralRestriction pt _ r = Nothing instance StructuralOverride GentzenPropNJ (ProofTree r PurePropLexicon (Form Bool)) instance StructuralOverride GentzenPropNK (ProofTree r PurePropLexicon (Form Bool)) instance AssumptionNumbers GentzenPropNJ where introducesAssumptions (As n) = [n] introducesAssumptions Pr = [-1] --XXX: premises introduce assumptions that can't be discharged. introducesAssumptions _ = [] dischargesAssumptions (IfI n) = [n] dischargesAssumptions (IfIVac (Just n)) = [n] dischargesAssumptions (NegI n) = [n] dischargesAssumptions (NegIVac (Just n)) = [n] dischargesAssumptions (OrE n m) = [n,m] dischargesAssumptions (OrELVac (Just n) m) = [n,m] dischargesAssumptions (OrELVac Nothing m) = [m] dischargesAssumptions (OrERVac n (Just m)) = [n,m] dischargesAssumptions (OrERVac n Nothing) = [n] dischargesAssumptions (OrEVac (Just n) (Just m)) = [n,m] dischargesAssumptions (OrEVac (Just n) Nothing) = [n] dischargesAssumptions (OrEVac Nothing (Just m)) = [m] dischargesAssumptions _ = [] instance AssumptionNumbers GentzenPropNK where introducesAssumptions (NJ x) = introducesAssumptions x introducesAssumptions _ = [] dischargesAssumptions (NJ x) = dischargesAssumptions x dischargesAssumptions _ = [] gentzenPropNJCalc :: TableauCalc PurePropLexicon (Form Bool) GentzenPropNJ gentzenPropNJCalc = mkTBCalc { tbParseForm = purePropFormulaParser hardegreeOpts , tbParseRule = parseGentzenPropNJ } gentzenPropNKCalc :: TableauCalc PurePropLexicon (Form Bool) GentzenPropNK gentzenPropNKCalc = mkTBCalc { tbParseForm = purePropFormulaParser hardegreeOpts , tbParseRule = parseGentzenPropNK } gentzenPropLKCalc :: TableauCalc PurePropLexicon (Form Bool) GentzenPropLK gentzenPropLKCalc = mkTBCalc { tbParseForm = langParser , tbParseRule = parseGentzenPropLK } gentzenPropLJCalc :: TableauCalc PurePropLexicon (Form Bool) GentzenPropLJ gentzenPropLJCalc = mkTBCalc { tbParseForm = langParser , tbParseRule = parseGentzenPropLJ }
gleachkr/Carnap
Carnap/src/Carnap/Languages/PurePropositional/Logic/Gentzen.hs
gpl-3.0
19,486
0
16
6,520
6,275
3,190
3,085
319
1
import IniParserTest import LogFileTest main :: IO () main = do iniParserTest logParserTest
nirvinm/Solving-Exercises-in-Haskell-Programming-From-First-Principles
ParserCombinators/test/Spec.hs
gpl-3.0
101
0
6
22
28
14
14
6
1
{-| Module: Environment Description: Internal state and environment of the interpreter License: GPL-3 This module contains all the auxiliary logic necessary to represent the internal state of the interpreter. -} module Environment ( -- * Environment Environment , context , defaultEnv , emptyContext -- * Reading the environment , getVerbose , getColor , getSki , getTypes , getExpressionName , getStrategy , getTopo -- * Modifying the environment , addBind , changeColor , changeVerbose , changeSkioutput , changeTypes , changeStrategy , changeTopo -- * Filenames and Modulenames , Filename , Modulename ) where import Data.List import MultiBimap import Lambda -- | A filename is a string containing the directory path and -- the real name of the file. type Filename = String -- | A modulename is a string naming a module. type Modulename = String data Environment = Environment { context :: Context , loadedFiles :: [Filename] , verbose :: Bool , color :: Bool , skioutput :: Bool , types :: Bool , strategy :: String , topo :: Bool } -- | Default environment for the interpreter. defaultEnv :: Environment defaultEnv = Environment { context = emptyContext , loadedFiles = [] , verbose = False , color = True , skioutput = False , types = False , strategy = "full" , topo = False } -- | Get current settings getColor, getVerbose, getSki, getTypes, getTopo :: Environment -> Bool getColor = color getVerbose = verbose getSki = skioutput getTypes = types getTopo = topo getStrategy :: Environment -> String getStrategy = strategy -- | Adds a name binding to the environment addBind :: Environment -> String -> Exp -> Environment addBind env s e = -- If the binding already exists, it changes nothing if s `elem` MultiBimap.lookup e (context env) then env else env {context = MultiBimap.insert e s (context env)} -- | Sets the verbose configuration on/off. changeVerbose :: Environment -> Bool -> Environment changeVerbose options setting = options {verbose = setting} -- | Sets the color configuration on/off changeColor :: Environment -> Bool -> Environment changeColor options setting = options {color = setting} -- | Sets the ski output configuration on/off changeSkioutput :: Environment -> Bool -> Environment changeSkioutput options setting = options {skioutput = setting} -- | Sets the types output configuration on/off changeTypes :: Environment -> Bool -> Environment changeTypes options setting = options {types = setting} -- | Sets the reduction strategy changeStrategy :: Environment -> String -> Environment changeStrategy options setting = options {strategy = setting} changeTopo :: Environment -> Bool -> Environment changeTopo options setting = options {topo = setting} -- | Given an expression, returns its name if it is bounded to any. getExpressionName :: Environment -> Exp -> Maybe String getExpressionName environment expr = case MultiBimap.lookup expr (context environment) of [] -> Nothing xs -> Just $ intercalate ", " xs -- | A context is an application between expressions and the names -- they may have. type Context = MultiBimap Exp String -- | Empty context without any bindings emptyContext :: Context emptyContext = MultiBimap.empty
M42/mikrokosmos
source/Environment.hs
gpl-3.0
3,377
0
10
721
642
384
258
78
2
{-# LANGUAGE ConstraintKinds #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE KindSignatures #-} {-# LANGUAGE RecursiveDo #-} {-# LANGUAGE Rank2Types #-} {-# LANGUAGE PartialTypeSignatures #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeOperators #-} module Lib where import Data.Comp.Term import Data.Constraint import Reflex.Dom import Hie.Ui.Types import Data.Proxy import qualified Data.ByteString.Char8 as BS8 import qualified Data.Map as M hieJsMain :: forall uidomain caps. (UiDomain uidomain caps) => HieValue caps -> IO () hieJsMain val = mainWidgetWithCss (BS8.pack "") $ do _ <- runHieValueUi val return () runHieValueUi :: forall caps t m uidomain. (Reflex t, MonadWidget t m, UiDomain uidomain caps) => -- Proxy caps -> HieValue caps -> m (Maybe (ReactiveHieValue t caps uidomain)) runHieValueUi -- pcaps HieValue { hieVal = val :: a, hieUi = uiMaybe, hieCapabilites = caps } = case uiMaybe of Nothing -> text "No ui specified" >> return Nothing Just (Term uiTerm) -> case extractUiCap (Proxy :: Proxy caps) uiTerm caps of Nothing -> text "Specified ui not supported (impossible)" >> return Nothing Just WUI { wuiV = ui', wuiDict = (Dict :: Dict (ListMember ui uidomain, Ui ui a)) } -> Just <$> ui ui' val caps (unsafeDynamic (pure M.empty) never) extractUiCap :: forall subuidomain uidomain caps a. (AllUiInCaps uidomain uidomain caps, AllUiInCaps subuidomain uidomain caps) => Proxy caps -> (Sum subuidomain) (Term (Sum uidomain)) -> Capabilities caps a -> Maybe (WrappedUi uidomain a) extractUiCap pcaps (SumThere uiSum) cs = extractUiCap pcaps uiSum cs extractUiCap _ (SumHere (ui' :: ui (Term (Sum uidomain)))) cs = do Dict <- project' return $ WUI ui' Dict where -- We should use 'Projectable', but it needs a refactoring to be usable it -- seems. project' :: Maybe (Dict (Ui ui a)) project' = lookupCap cs (listIx :: ListIx caps (Ui ui)) lookupCap :: Capabilities cs a -> ListIx cs (Ui ui) -> Maybe (Dict (Ui ui a)) lookupCap (HCons d _) ListIxHead = d lookupCap (HCons _ xs) (ListIxTail t) = lookupCap xs t lookupCap HNil _ = error "Truly impossible" data WrappedUi uidomain a = forall (ui :: * -> *). WUI { wuiV :: ui (Term (Sum uidomain)), wuiDict :: Dict (ListMember ui uidomain, Ui ui a) } {- lookupCap :: forall (c :: * -> Constraint) caps a. ListIx caps c -> Capabilities caps a -> Maybe (Dict (c a)) lookupCap = undefined -} {- import Data.Comp import Data.Dynamic.PolyDyn import Data.Serialize import Hie.Session import Hie.Ui.DownloadLink import Hie.Ui.Func import Hie.Ui.List import Hie.Ui.NonShowable import Hie.Ui.TextLabel import Hie.Ui.Types import Reflex.Dom import qualified Data.ByteString as BS import qualified Data.ByteString.Char8 as BS8 import qualified Data.Map as M hieJsMain :: IO () hieJsMain = mainWidgetWithCss (BS8.pack "button {\ \ color: black;\ \ border: 1px solid black;\ \}\ \input {\ \ border: 1px solid black;\ \}\ \.bindingWidget {\ \ background: rgb(240, 240, 240);\ \}\ \.bindingWidget:hover .uiSelector {\ \ display: block;\ \}\ \.uiSelector {\ \ display: none;\ \ background-color: rgb(240, 240, 240);\ \ border: 1px solid rgb(100, 100, 150);\ \ padding: 10px;\ \ float: right;\ \}\ \.uiSelector ul {\ \ display: block;\ \ margin: 0px;\ \ padding: 0px;\ \}\ \.uiSelector ul li {\ \ display: inline;\ \ font-style: italic;\ \ font-size: small;\ \}\ \.uiSelector ul li:after {\ \ content: \", \";\ \}\ \.uiSelector ul li + li {\ \ margin-left: 5px;\ \}\ \.uiSelector ul li:last-child:after {\ \ content: \"\";\ \}\ \.uiSelector > .uiSelectorStep {\ \ display: none;\ \}\ \.uiSelector:hover > .uiSelectorStep {\ \ display: block;\ \}\ \.uiSelectorStep {\ \ background-color: rgb(240, 240, 240);\ \ mix-blend-mode: multiply;\ \}\ \.uiSelectorStep > .uiSelectorStep {\ \ margin-left: 20px;\ \}\ \") $ mdo el "h1" (text "HIE Document") -- Initial test bindings addBindingEvent <- (M.fromList [ ("Introduction", Just $ HieValue ( polyDyn "This is a document in an instance of the \"Haskell Interactive\ \Environment\". Like in a REPL-session, names are bound to \ \values of some type. New bindings can be added by applying \ \bound function values interactively, or by manipulating the map \ \of bindings through the API. Polymorphic types are supported \ \by of (unsafely but carefully) monomorphising them to \"FreeVar\". \ \The Ui of a binding can be changed dynamically.") uiTextLabel), ("foo", Just $ HieValue (polyDyn (42 :: Int)) uiTextLabel), ("bar", Just $ HieValue (polyDyn ([1,2,3,4,5] :: [Int])) (uiList uiTextLabel)), ("map", Just $ HieValue (polyDyn (map :: (FreeVar "a" -> FreeVar "b") -> [FreeVar "a"] -> [FreeVar "b"])) (uiFunc (uiFunc (uiList uiTextLabel)))), ("compose", Just $ HieValue (polyDyn ((.) :: (FreeVar "b" -> FreeVar "c") -> (FreeVar "a" -> FreeVar "b") -> FreeVar "a" -> FreeVar "c")) (uiFunc (uiFunc (uiFunc (uiTextLabel))))), ("id", Just $ HieValue (polyDyn (id :: FreeVar "a" -> FreeVar "a")) (uiFunc (uiTextLabel))), ("plus3", Just $ HieValue (polyDyn ( (+3) :: Int -> Int)) (uiFunc (uiTextLabel))), ("download", Just $ HieValue (polyDyn (encode :: Serialize (FreeVar "a") => FreeVar "a" -> BS.ByteString)) (uiFunc uiDownloadLink)) -- ("downloadDyn", Just $ HieValue (polyDynTC (encode :: Serialize a => a -> BS.ByteString)) (uiDynamic uiDownloadLink)) ] <$) <$> getPostBuild uiEnv' <- uiEnv wireSession uiEnv' addBindingEvent return () type UiDomain = UiDownloadLink :+: UiList :+: UiTextLabel :+: UiNonShowable :+: UiFunc uiEnv :: forall t m . (MonadWidget t m) => m (UiEnv UiDomain t m) uiEnv = return [ (uiTextLabelImpl (show :: Double -> String)), (uiTextLabelImpl (show :: Int -> String)), (uiTextLabelImpl (show :: Char -> String)), (uiTextLabelImpl (id :: String -> String)), uiListImpl, uiNonShowableImpl, uiFuncImpl ] -}
plcplc/hie
hie-js/src/Lib.hs
agpl-3.0
6,991
0
19
2,092
787
413
374
-1
-1
module CGTools.Validate.Test ( validateSuite ) where import Data.Char (isPrint,isSymbol) import Test.Tasty (testGroup, TestTree) import Test.Tasty.HUnit import Test.Tasty.SmallCheck (forAll) import qualified Test.Tasty.SmallCheck as SC import qualified Test.Tasty.QuickCheck as QC import Test.SmallCheck.Series (Serial) import CGTools.Validate as V -- | Test with QuickCheck and SmallCheck tp name prop = testGroup name [ QC.testProperty "QC" prop , SC.testProperty "SC" prop ] validateSuite :: TestTree validateSuite = testGroup "Validate" [ tp "pass" $ True , tp "fail" $ False , testCase "unit" $ V.dropFromEndWhile even [1,2,3,4,4,4,4,4] @?= [1,2,3]] -- import Data.List -- import Data.Ord -- -- validateSuite :: TestTree -- validateSuite = testGroup "Tests" [properties, unitTests] -- -- properties :: TestTree -- properties = testGroup "Properties" [scProps, qcProps] -- -- scProps = testGroup "(checked by SmallCheck)" -- [ SC.testProperty "sort == sort . reverse" $ -- \list -> sort (list :: [Int]) == sort (reverse list) -- , SC.testProperty "Fermat's little theorem" $ -- \x -> ((x :: Integer)^7 - x) `mod` 7 == 0 -- -- the following property does not hold -- , SC.testProperty "Fermat's last theorem" $ -- \x y z n -> -- (n :: Integer) >= 3 SC.==> x^n + y^n /= (z^n :: Integer) -- ] -- -- qcProps = testGroup "(checked by QuickCheck)" -- [ QC.testProperty "sort == sort . reverse" $ -- \list -> sort (list :: [Int]) == sort (reverse list) -- , QC.testProperty "Fermat's little theorem" $ -- \x -> ((x :: Integer)^7 - x) `mod` 7 == 0 -- -- the following property does not hold -- , QC.testProperty "Fermat's last theorem" $ -- \x y z n -> -- (n :: Integer) >= 3 QC.==> x^n + y^n /= (z^n :: Integer) -- ] -- -- unitTests = testGroup "Unit tests" -- [ testCase "List comparison (different length)" $ -- [1, 2, 3] `compare` [1,2] @?= GT -- -- -- the following test does not hold -- , testCase "List comparison (same length)" $ -- [1, 2, 3] `compare` [1,2,2] @?= LT -- ]
shanewilson/cgtools
test/CGTools/Validate/Test.hs
apache-2.0
2,269
0
10
623
255
168
87
17
1
-- http://book.realworldhaskell.org/read/using-parsec.html -- JSON parser import JSONClass import Numeric (readFloat, readHex, readSigned) import Control.Applicative (empty) import Text.ParserCombinators.Parsec p_text :: CharParser () JValue p_text = spaces *> text <?> "JSON text" where text = JObject <$> p_object <|> JArray <$> p_array p_value :: CharParser () JValue p_value = value <* spaces where value = JString <$> p_string <|> JNumber <$> p_number -- <|> JObject <$> p_object <|> JArray <$> p_array <|> JBool <$> p_bool <|> JNull <$ string "null" <?> "JSON value" p_bool :: CharParser () Bool p_bool = True <$ string "true" <|> False <$ string "false" p_value_choice = value <* spaces where value = choice [ JString <$> p_string , JNumber <$> p_number , JObject <$> p_object , JArray <$> p_array , JBool <$> p_bool , JNull <$ string "null" ] <?> "JSON value" p_string :: CharParser () String p_string = between (char '\"') (char '\"') (many jchar) where jchar = char '\\' *> (p_escape <|> p_unicode) <|> satisfy (`notElem` "\"\\") p_escape :: CharParser () Char p_escape = choice (zipWith decode "bnfrt\\\"/" "\b\n\f\r\t\\\"/") where decode :: Char -> Char -> CharParser () Char decode c r = r <$ char c p_unicode :: CharParser () Char p_unicode = char 'u' *> (decode <$> count 4 hexDigit) where decode x = toEnum code where ((code,_):_) = readHex x p_number :: CharParser () Double p_number = do s <- getInput case readSigned readFloat s of [(n, s')] -> n <$ setInput s' _ -> empty p_series :: Char -> CharParser () a -> Char -> CharParser () [a] p_series left parser right = between (char left <* spaces) (char right) $ (parser <* spaces) `sepBy` (char ',' <* spaces) p_object :: CharParser () (JObj JValue) p_object = JObj <$> p_series '{' p_field '}' where p_field = (,) <$> (p_string <* char ':' <* spaces) <*> p_value p_array :: CharParser () (JAry JValue) p_array = JAry <$> p_series '[' p_value ']' str = unlines ["{", "\"glossary\": \"example glossary\", ", "\"test\": 42", "}"] main = do print $ parse p_text "" str
egaburov/funstuff
Haskell/parsec/p05.hs
apache-2.0
2,455
0
16
759
770
400
370
60
2
import Data.List import Data.Char (ord) import Numeric import Data.List.Split (splitOn) import Math.NumberTheory.Primes.Testing (isPrime) -- Remove quotes at the beginning and the end of a string removeQuotes name = reverse $ drop 1 $ reverse $ drop 1 name triangleNumbers :: [Integer] triangleNumbers = triangleWorker (1::Integer) (0::Integer) triangleWorker :: Integer -> Integer -> [Integer] triangleWorker n lastval = let current = n + lastval in [current] ++ triangleWorker (n + 1) current wordToNum :: String -> Integer wordToNum word = sum $ map (\x -> toInteger((ord x) - (ord 'A' - 1))) word isTriangleNumber n = let filtered = head $ filter (\x -> x >= n) triangleNumbers in (filtered == n) main = do fileContent <- readFile "words.txt" let theWords = map removeQuotes $ splitOn "," fileContent print $ length $ filter (isTriangleNumber . wordToNum) theWords
ulikoehler/ProjectEuler
Euler42.hs
apache-2.0
938
0
14
205
327
171
156
19
1
-- Based on O.Kiselyov work -- Copyright (C) 2009 Kyra -- Copyright (C) 2016 Braam Research, LLC. {-# LANGUAGE GADTs #-} module Text.Scanf where import Data.List ( isPrefixOf, uncons ) import Data.Char ( isDigit, isSpace ) -- import Control.Parallel ( par, pseq ) t2j, t2n :: Bool -> a -> Maybe a t2j True v = Just v t2j False _ = Nothing t2n = t2j . not readInt :: Read a => String -> Maybe (a, String) readInt s = let (nums,rest) = span isDigit s in null nums `t2n` (read nums, rest) readIntR :: Read a => String -> Maybe (a, String) readIntR = readInt . reverse type Scan a = String -> Maybe (a, String) data Scanner a b where SLit :: String -> Scanner a a SDrop:: Int -> Scanner a a SSkip:: (Char -> Bool) -> Scanner a a SC :: Scan b -> Scanner a (b -> a) (:^) :: Scanner b c -> Scanner a b -> Scanner a c -- Basics lit :: String -> Scanner a a lit = SLit dr :: Int -> Scanner a a dr = SDrop skip :: (Char -> Bool) -> Scanner a a skip = SSkip gen :: b -> Scanner a (b -> a) gen v = SC (\bs -> Just (v, bs)) int :: Scanner a (Int -> a) int = SC readInt intR :: Scanner a (Int -> a) intR = SC readIntR bigint :: Scanner a (Integer -> a) bigint = SC readInt intwe :: Int -> Scanner a (Int -> a) intwe w = SC $ \bs -> let (pre, post) = splitAt w bs in readInt pre >>= (\(v, rest) -> null rest `t2j` (v, post)) char :: Scanner a (Char -> a) char = SC uncons -- Utils litc :: Char -> Scanner a a litc = SLit . (:[]) sk :: Char -> Scanner a a sk c = SSkip (== c) skws :: Scanner a a skws = SSkip isSpace -- Eats em all str :: Scanner a (String -> a) str = SC $ \bs -> Just (bs, []) strw :: Int -> Scanner a (String -> a) strw w = SC (Just . (splitAt w)) str_to :: Char -> Scanner a (String -> a) str_to stop = SC $ \input -> let (done, rest) = break (== stop) input in Just (done, rest) -- Default unoptimized deffmt :: Read b => Scanner a (b -> a) deffmt = SC parse where parse s = case reads s of [(v,s')] -> Just (v, s') _ -> Nothing sdouble :: Scanner a (Double -> a) sdouble = deffmt type ReadM a = String -> Maybe (a, String) ints :: Scanner a b -> b -> ReadM a ints (SLit s) x inp = t2j (isPrefixOf s inp) (x, drop (length s) inp) ints (SDrop n) x inp = t2j (length inp >= n) (x, drop n inp) ints (SSkip p) x inp = Just (x, dropWhile p inp) ints (SC sc) f inp = fmap (\(v, s) -> (f v, s)) (sc inp) ints (a :^ b) f inp = ints a f inp >>= (\(vb, inp') -> ints b vb inp') sscanf :: Scanner a b -> b -> String -> Maybe a sscanf fm f = fmap fst . ints fm f liftR :: (a -> b) -> ReadM a -> ReadM b liftR f rd = fmap (\(v,r) -> (f v, r)) . rd infixr 4 ^: (^:) :: ReadM a -> ReadM a -> ReadM a (^:) r1 r2 s = go (r1 s) (r2 s) where go v@(Just _) _ = v go _ c = c {- (^:) r1 r2 s = par r2r (pseq r1r (go r1r r2r)) where r2r = r2 s r1r = r1 s go v@(Just _) _ = v go _ c = c -} {- ts = sscanf sdouble id "543.98767" ts1 = sscanf (sdouble :^ str) (\s1 s2 -> (s1, s2)) "543.98767swean" ts2 = sscanf (str_to_and_eat ';' :^ str) (\s1 s2 -> (s1, s2)) "gago;swin" fmt30 = lit "abc" :^ int :^ lit "cde" fmt3 = fmt30 :^ sdouble :^ char ts3 = sscanf fmt3 (\i f c -> (i,f,c)) "abc5cde15.0c" -- Just (5,15.0,'c') fmt4 = skDigs :^ lit ":" :^ skDigs :^ str ts4 = sscanf fmt4 id "40000:0 dsoiewr" ts41 = sscanf fmt4 id "40000::0 dsoiewr" -}
SKA-ScienceDataProcessor/RC
MS6/LogAn/Text/Scanf.hs
apache-2.0
3,396
0
13
912
1,450
767
683
78
2
-- forever takes an I/O action and returns an I/O action that just repeats the -- I/O action it got forever. It's located in Control.Monad. This little program -- will indefinitely ask the user for some input and spit it back to him, -- CAPSLOCKED: import Control.Monad import Data.Char main = forever $ do putStr "Give me some input: " l <- getLine putStrLn $ map toUpper l
Oscarzhao/haskell
learnyouahaskell/forever.hs
apache-2.0
383
0
9
76
49
25
24
6
1
{-# OPTIONS -fglasgow-exts #-} ----------------------------------------------------------------------------- {-| Module : QDialogButtonBox_h.hs Copyright : (c) David Harley 2010 Project : qtHaskell Version : 1.1.4 Modified : 2010-09-02 17:02:14 Warning : this file is machine generated - do not modify. --} ----------------------------------------------------------------------------- module Qtc.Gui.QDialogButtonBox_h where import Foreign.C.Types import Qtc.Enums.Base import Qtc.Enums.Gui.QPaintDevice import Qtc.Enums.Core.Qt import Qtc.Classes.Base import Qtc.Classes.Qccs_h import Qtc.Classes.Core_h import Qtc.ClassTypes.Core import Qth.ClassTypes.Core import Qtc.Classes.Gui_h import Qtc.ClassTypes.Gui import Foreign.Marshal.Array instance QunSetUserMethod (QDialogButtonBox ()) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialogButtonBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) foreign import ccall "qtc_QDialogButtonBox_unSetUserMethod" qtc_QDialogButtonBox_unSetUserMethod :: Ptr (TQDialogButtonBox a) -> CInt -> CInt -> IO (CBool) instance QunSetUserMethod (QDialogButtonBoxSc a) where unSetUserMethod qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialogButtonBox_unSetUserMethod cobj_qobj (toCInt 0) (toCInt evid) instance QunSetUserMethodVariant (QDialogButtonBox ()) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialogButtonBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariant (QDialogButtonBoxSc a) where unSetUserMethodVariant qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialogButtonBox_unSetUserMethod cobj_qobj (toCInt 1) (toCInt evid) instance QunSetUserMethodVariantList (QDialogButtonBox ()) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialogButtonBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QunSetUserMethodVariantList (QDialogButtonBoxSc a) where unSetUserMethodVariantList qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> qtc_QDialogButtonBox_unSetUserMethod cobj_qobj (toCInt 2) (toCInt evid) instance QsetUserMethod (QDialogButtonBox ()) (QDialogButtonBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDialogButtonBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDialogButtonBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialogButtonBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setUserMethod" qtc_QDialogButtonBox_setUserMethod :: Ptr (TQDialogButtonBox a) -> CInt -> Ptr (Ptr (TQDialogButtonBox x0) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethod_QDialogButtonBox :: (Ptr (TQDialogButtonBox x0) -> IO ()) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> IO ())) foreign import ccall "wrapper" wrapSetUserMethod_QDialogButtonBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> IO ()) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethod_QDialogButtonBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethod_QDialogButtonBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialogButtonBox_setUserMethod cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO () setHandlerWrapper x0 = do x0obj <- objectFromPtr_nf x0 if (objectIsNull x0obj) then return () else _handler x0obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetUserMethod (QDialogButtonBox ()) (QDialogButtonBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDialogButtonBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDialogButtonBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialogButtonBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setUserMethodVariant" qtc_QDialogButtonBox_setUserMethodVariant :: Ptr (TQDialogButtonBox a) -> CInt -> Ptr (Ptr (TQDialogButtonBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetUserMethodVariant_QDialogButtonBox :: (Ptr (TQDialogButtonBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())))) foreign import ccall "wrapper" wrapSetUserMethodVariant_QDialogButtonBox_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetUserMethod (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> QVariant () -> IO (QVariant ())) where setUserMethod _eobj _eid _handler = do funptr <- wrapSetUserMethodVariant_QDialogButtonBox setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetUserMethodVariant_QDialogButtonBox_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> qtc_QDialogButtonBox_setUserMethodVariant cobj_eobj (toCInt _eid) (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return () where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ())) setHandlerWrapper x0 x1 = do x0obj <- objectFromPtr_nf x0 x1obj <- objectFromPtr_nf x1 rv <- if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1obj withObjectPtr rv $ \cobj_rv -> return cobj_rv setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QunSetHandler (QDialogButtonBox ()) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDialogButtonBox_unSetHandler cobj_qobj cstr_evid foreign import ccall "qtc_QDialogButtonBox_unSetHandler" qtc_QDialogButtonBox_unSetHandler :: Ptr (TQDialogButtonBox a) -> CWString -> IO (CBool) instance QunSetHandler (QDialogButtonBoxSc a) where unSetHandler qobj evid = withBoolResult $ withObjectPtr qobj $ \cobj_qobj -> withCWString evid $ \cstr_evid -> qtc_QDialogButtonBox_unSetHandler cobj_qobj cstr_evid instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler1" qtc_QDialogButtonBox_setHandler1 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox1 :: (Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO ()) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox1_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> QEvent t1 -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox1 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox1_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler1 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 if (objectIsNull x0obj) then return () else _handler x0obj x1obj setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QchangeEvent_h (QDialogButtonBox ()) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_changeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_changeEvent" qtc_QDialogButtonBox_changeEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQEvent t1) -> IO () instance QchangeEvent_h (QDialogButtonBoxSc a) ((QEvent t1)) where changeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_changeEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler2" qtc_QDialogButtonBox_setHandler2 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox2 :: (Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox2_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> QEvent t1 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox2 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox2_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler2 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQEvent t1) -> IO (CBool) setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 x1obj <- objectFromPtr_nf x1 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance Qevent_h (QDialogButtonBox ()) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_event cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_event" qtc_QDialogButtonBox_event :: Ptr (TQDialogButtonBox a) -> Ptr (TQEvent t1) -> IO CBool instance Qevent_h (QDialogButtonBoxSc a) ((QEvent t1)) where event_h x0 (x1) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_event cobj_x0 cobj_x1 instance QactionEvent_h (QDialogButtonBox ()) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_actionEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_actionEvent" qtc_QDialogButtonBox_actionEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQActionEvent t1) -> IO () instance QactionEvent_h (QDialogButtonBoxSc a) ((QActionEvent t1)) where actionEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_actionEvent cobj_x0 cobj_x1 instance QcloseEvent_h (QDialogButtonBox ()) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_closeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_closeEvent" qtc_QDialogButtonBox_closeEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQCloseEvent t1) -> IO () instance QcloseEvent_h (QDialogButtonBoxSc a) ((QCloseEvent t1)) where closeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_closeEvent cobj_x0 cobj_x1 instance QcontextMenuEvent_h (QDialogButtonBox ()) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_contextMenuEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_contextMenuEvent" qtc_QDialogButtonBox_contextMenuEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQContextMenuEvent t1) -> IO () instance QcontextMenuEvent_h (QDialogButtonBoxSc a) ((QContextMenuEvent t1)) where contextMenuEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_contextMenuEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDialogButtonBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler3" qtc_QDialogButtonBox_setHandler3 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox3 :: (Ptr (TQDialogButtonBox x0) -> IO (CInt)) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox3_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox3 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox3_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler3 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO (CInt) setHandlerWrapper x0 = do x0obj <- qDialogButtonBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QdevType_h (QDialogButtonBox ()) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_devType cobj_x0 foreign import ccall "qtc_QDialogButtonBox_devType" qtc_QDialogButtonBox_devType :: Ptr (TQDialogButtonBox a) -> IO CInt instance QdevType_h (QDialogButtonBoxSc a) (()) where devType_h x0 () = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_devType cobj_x0 instance QdragEnterEvent_h (QDialogButtonBox ()) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dragEnterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_dragEnterEvent" qtc_QDialogButtonBox_dragEnterEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQDragEnterEvent t1) -> IO () instance QdragEnterEvent_h (QDialogButtonBoxSc a) ((QDragEnterEvent t1)) where dragEnterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dragEnterEvent cobj_x0 cobj_x1 instance QdragLeaveEvent_h (QDialogButtonBox ()) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dragLeaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_dragLeaveEvent" qtc_QDialogButtonBox_dragLeaveEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQDragLeaveEvent t1) -> IO () instance QdragLeaveEvent_h (QDialogButtonBoxSc a) ((QDragLeaveEvent t1)) where dragLeaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dragLeaveEvent cobj_x0 cobj_x1 instance QdragMoveEvent_h (QDialogButtonBox ()) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dragMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_dragMoveEvent" qtc_QDialogButtonBox_dragMoveEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQDragMoveEvent t1) -> IO () instance QdragMoveEvent_h (QDialogButtonBoxSc a) ((QDragMoveEvent t1)) where dragMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dragMoveEvent cobj_x0 cobj_x1 instance QdropEvent_h (QDialogButtonBox ()) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dropEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_dropEvent" qtc_QDialogButtonBox_dropEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQDropEvent t1) -> IO () instance QdropEvent_h (QDialogButtonBoxSc a) ((QDropEvent t1)) where dropEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_dropEvent cobj_x0 cobj_x1 instance QenterEvent_h (QDialogButtonBox ()) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_enterEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_enterEvent" qtc_QDialogButtonBox_enterEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQEvent t1) -> IO () instance QenterEvent_h (QDialogButtonBoxSc a) ((QEvent t1)) where enterEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_enterEvent cobj_x0 cobj_x1 instance QfocusInEvent_h (QDialogButtonBox ()) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_focusInEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_focusInEvent" qtc_QDialogButtonBox_focusInEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusInEvent_h (QDialogButtonBoxSc a) ((QFocusEvent t1)) where focusInEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_focusInEvent cobj_x0 cobj_x1 instance QfocusOutEvent_h (QDialogButtonBox ()) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_focusOutEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_focusOutEvent" qtc_QDialogButtonBox_focusOutEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQFocusEvent t1) -> IO () instance QfocusOutEvent_h (QDialogButtonBoxSc a) ((QFocusEvent t1)) where focusOutEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_focusOutEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler4" qtc_QDialogButtonBox_setHandler4 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> CInt -> IO (CInt)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox4 :: (Ptr (TQDialogButtonBox x0) -> CInt -> IO (CInt)) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> CInt -> IO (CInt))) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox4_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> Int -> IO (Int)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox4 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox4_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler4 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> CInt -> IO (CInt) setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 let x1int = fromCInt x1 let rv = if (objectIsNull x0obj) then return 0 else _handler x0obj x1int rvf <- rv return (toCInt rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QheightForWidth_h (QDialogButtonBox ()) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_heightForWidth cobj_x0 (toCInt x1) foreign import ccall "qtc_QDialogButtonBox_heightForWidth" qtc_QDialogButtonBox_heightForWidth :: Ptr (TQDialogButtonBox a) -> CInt -> IO CInt instance QheightForWidth_h (QDialogButtonBoxSc a) ((Int)) where heightForWidth_h x0 (x1) = withIntResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_heightForWidth cobj_x0 (toCInt x1) instance QhideEvent_h (QDialogButtonBox ()) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_hideEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_hideEvent" qtc_QDialogButtonBox_hideEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQHideEvent t1) -> IO () instance QhideEvent_h (QDialogButtonBoxSc a) ((QHideEvent t1)) where hideEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_hideEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler5" qtc_QDialogButtonBox_setHandler5 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox5 :: (Ptr (TQDialogButtonBox x0) -> CLong -> IO (Ptr (TQVariant t0))) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> CLong -> IO (Ptr (TQVariant t0)))) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox5_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> InputMethodQuery -> IO (QVariant t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox5 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox5_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler5 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> CLong -> IO (Ptr (TQVariant t0)) setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 let x1enum = qEnum_fromInt $ fromCLong x1 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj x1enum rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QinputMethodQuery_h (QDialogButtonBox ()) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) foreign import ccall "qtc_QDialogButtonBox_inputMethodQuery" qtc_QDialogButtonBox_inputMethodQuery :: Ptr (TQDialogButtonBox a) -> CLong -> IO (Ptr (TQVariant ())) instance QinputMethodQuery_h (QDialogButtonBoxSc a) ((InputMethodQuery)) where inputMethodQuery_h x0 (x1) = withQVariantResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_inputMethodQuery cobj_x0 (toCLong $ qEnum_toInt x1) instance QkeyPressEvent_h (QDialogButtonBox ()) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_keyPressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_keyPressEvent" qtc_QDialogButtonBox_keyPressEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyPressEvent_h (QDialogButtonBoxSc a) ((QKeyEvent t1)) where keyPressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_keyPressEvent cobj_x0 cobj_x1 instance QkeyReleaseEvent_h (QDialogButtonBox ()) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_keyReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_keyReleaseEvent" qtc_QDialogButtonBox_keyReleaseEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQKeyEvent t1) -> IO () instance QkeyReleaseEvent_h (QDialogButtonBoxSc a) ((QKeyEvent t1)) where keyReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_keyReleaseEvent cobj_x0 cobj_x1 instance QleaveEvent_h (QDialogButtonBox ()) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_leaveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_leaveEvent" qtc_QDialogButtonBox_leaveEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQEvent t1) -> IO () instance QleaveEvent_h (QDialogButtonBoxSc a) ((QEvent t1)) where leaveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_leaveEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qDialogButtonBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler6" qtc_QDialogButtonBox_setHandler6 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQSize t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox6 :: (Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQSize t0))) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQSize t0)))) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox6_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> IO (QSize t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox6 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox6_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler6 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQSize t0)) setHandlerWrapper x0 = do x0obj <- qDialogButtonBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QqminimumSizeHint_h (QDialogButtonBox ()) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_minimumSizeHint cobj_x0 foreign import ccall "qtc_QDialogButtonBox_minimumSizeHint" qtc_QDialogButtonBox_minimumSizeHint :: Ptr (TQDialogButtonBox a) -> IO (Ptr (TQSize ())) instance QqminimumSizeHint_h (QDialogButtonBoxSc a) (()) where qminimumSizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_minimumSizeHint cobj_x0 instance QminimumSizeHint_h (QDialogButtonBox ()) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDialogButtonBox_minimumSizeHint_qth" qtc_QDialogButtonBox_minimumSizeHint_qth :: Ptr (TQDialogButtonBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QminimumSizeHint_h (QDialogButtonBoxSc a) (()) where minimumSizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_minimumSizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QmouseDoubleClickEvent_h (QDialogButtonBox ()) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mouseDoubleClickEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_mouseDoubleClickEvent" qtc_QDialogButtonBox_mouseDoubleClickEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseDoubleClickEvent_h (QDialogButtonBoxSc a) ((QMouseEvent t1)) where mouseDoubleClickEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mouseDoubleClickEvent cobj_x0 cobj_x1 instance QmouseMoveEvent_h (QDialogButtonBox ()) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mouseMoveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_mouseMoveEvent" qtc_QDialogButtonBox_mouseMoveEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseMoveEvent_h (QDialogButtonBoxSc a) ((QMouseEvent t1)) where mouseMoveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mouseMoveEvent cobj_x0 cobj_x1 instance QmousePressEvent_h (QDialogButtonBox ()) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mousePressEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_mousePressEvent" qtc_QDialogButtonBox_mousePressEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmousePressEvent_h (QDialogButtonBoxSc a) ((QMouseEvent t1)) where mousePressEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mousePressEvent cobj_x0 cobj_x1 instance QmouseReleaseEvent_h (QDialogButtonBox ()) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mouseReleaseEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_mouseReleaseEvent" qtc_QDialogButtonBox_mouseReleaseEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQMouseEvent t1) -> IO () instance QmouseReleaseEvent_h (QDialogButtonBoxSc a) ((QMouseEvent t1)) where mouseReleaseEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_mouseReleaseEvent cobj_x0 cobj_x1 instance QmoveEvent_h (QDialogButtonBox ()) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_moveEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_moveEvent" qtc_QDialogButtonBox_moveEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQMoveEvent t1) -> IO () instance QmoveEvent_h (QDialogButtonBoxSc a) ((QMoveEvent t1)) where moveEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_moveEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qDialogButtonBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler7" qtc_QDialogButtonBox_setHandler7 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQPaintEngine t0))) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox7 :: (Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQPaintEngine t0))) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQPaintEngine t0)))) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox7_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> IO (QPaintEngine t0)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox7 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox7_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler7 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> IO (Ptr (TQPaintEngine t0)) setHandlerWrapper x0 = do x0obj <- qDialogButtonBoxFromPtr x0 let rv = if (objectIsNull x0obj) then return $ objectCast x0obj else _handler x0obj rvf <- rv withObjectPtr rvf $ \cobj_rvf -> return (cobj_rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QpaintEngine_h (QDialogButtonBox ()) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_paintEngine cobj_x0 foreign import ccall "qtc_QDialogButtonBox_paintEngine" qtc_QDialogButtonBox_paintEngine :: Ptr (TQDialogButtonBox a) -> IO (Ptr (TQPaintEngine ())) instance QpaintEngine_h (QDialogButtonBoxSc a) (()) where paintEngine_h x0 () = withObjectRefResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_paintEngine cobj_x0 instance QpaintEvent_h (QDialogButtonBox ()) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_paintEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_paintEvent" qtc_QDialogButtonBox_paintEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQPaintEvent t1) -> IO () instance QpaintEvent_h (QDialogButtonBoxSc a) ((QPaintEvent t1)) where paintEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_paintEvent cobj_x0 cobj_x1 instance QresizeEvent_h (QDialogButtonBox ()) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_resizeEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_resizeEvent" qtc_QDialogButtonBox_resizeEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQResizeEvent t1) -> IO () instance QresizeEvent_h (QDialogButtonBoxSc a) ((QResizeEvent t1)) where resizeEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_resizeEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler8" qtc_QDialogButtonBox_setHandler8 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> CBool -> IO ()) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox8 :: (Ptr (TQDialogButtonBox x0) -> CBool -> IO ()) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> CBool -> IO ())) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox8_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> Bool -> IO ()) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox8 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox8_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler8 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> CBool -> IO () setHandlerWrapper x0 x1 = do x0obj <- qDialogButtonBoxFromPtr x0 let x1bool = fromCBool x1 if (objectIsNull x0obj) then return () else _handler x0obj x1bool setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QsetVisible_h (QDialogButtonBox ()) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_setVisible cobj_x0 (toCBool x1) foreign import ccall "qtc_QDialogButtonBox_setVisible" qtc_QDialogButtonBox_setVisible :: Ptr (TQDialogButtonBox a) -> CBool -> IO () instance QsetVisible_h (QDialogButtonBoxSc a) ((Bool)) where setVisible_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_setVisible cobj_x0 (toCBool x1) instance QshowEvent_h (QDialogButtonBox ()) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_showEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_showEvent" qtc_QDialogButtonBox_showEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQShowEvent t1) -> IO () instance QshowEvent_h (QDialogButtonBoxSc a) ((QShowEvent t1)) where showEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_showEvent cobj_x0 cobj_x1 instance QqsizeHint_h (QDialogButtonBox ()) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_sizeHint cobj_x0 foreign import ccall "qtc_QDialogButtonBox_sizeHint" qtc_QDialogButtonBox_sizeHint :: Ptr (TQDialogButtonBox a) -> IO (Ptr (TQSize ())) instance QqsizeHint_h (QDialogButtonBoxSc a) (()) where qsizeHint_h x0 () = withQSizeResult $ withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_sizeHint cobj_x0 instance QsizeHint_h (QDialogButtonBox ()) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h foreign import ccall "qtc_QDialogButtonBox_sizeHint_qth" qtc_QDialogButtonBox_sizeHint_qth :: Ptr (TQDialogButtonBox a) -> Ptr CInt -> Ptr CInt -> IO () instance QsizeHint_h (QDialogButtonBoxSc a) (()) where sizeHint_h x0 () = withSizeResult $ \csize_ret_w csize_ret_h -> withObjectPtr x0 $ \cobj_x0 -> qtc_QDialogButtonBox_sizeHint_qth cobj_x0 csize_ret_w csize_ret_h instance QtabletEvent_h (QDialogButtonBox ()) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_tabletEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_tabletEvent" qtc_QDialogButtonBox_tabletEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQTabletEvent t1) -> IO () instance QtabletEvent_h (QDialogButtonBoxSc a) ((QTabletEvent t1)) where tabletEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_tabletEvent cobj_x0 cobj_x1 instance QwheelEvent_h (QDialogButtonBox ()) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_wheelEvent cobj_x0 cobj_x1 foreign import ccall "qtc_QDialogButtonBox_wheelEvent" qtc_QDialogButtonBox_wheelEvent :: Ptr (TQDialogButtonBox a) -> Ptr (TQWheelEvent t1) -> IO () instance QwheelEvent_h (QDialogButtonBoxSc a) ((QWheelEvent t1)) where wheelEvent_h x0 (x1) = withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> qtc_QDialogButtonBox_wheelEvent cobj_x0 cobj_x1 instance QsetHandler (QDialogButtonBox ()) (QDialogButtonBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDialogButtonBoxFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () foreign import ccall "qtc_QDialogButtonBox_setHandler9" qtc_QDialogButtonBox_setHandler9 :: Ptr (TQDialogButtonBox a) -> CWString -> Ptr (Ptr (TQDialogButtonBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> Ptr () -> Ptr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO () foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox9 :: (Ptr (TQDialogButtonBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool)) -> IO (FunPtr (Ptr (TQDialogButtonBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool))) foreign import ccall "wrapper" wrapSetHandler_QDialogButtonBox9_d :: (Ptr fun -> Ptr state -> Ptr fun_d -> IO ()) -> IO (FunPtr (Ptr fun -> Ptr state -> Ptr fun_d -> IO ())) instance QsetHandler (QDialogButtonBoxSc a) (QDialogButtonBox x0 -> QObject t1 -> QEvent t2 -> IO (Bool)) where setHandler _eobj _eid _handler = do funptr <- wrapSetHandler_QDialogButtonBox9 setHandlerWrapper stptr <- newStablePtr (Wrap _handler) funptr_d <- wrapSetHandler_QDialogButtonBox9_d setHandlerWrapper_d withObjectPtr _eobj $ \cobj_eobj -> withCWString _eid $ \cstr_eid -> qtc_QDialogButtonBox_setHandler9 cobj_eobj cstr_eid (toCFunPtr funptr) (castStablePtrToPtr stptr) (toCFunPtr funptr_d) return() where setHandlerWrapper :: Ptr (TQDialogButtonBox x0) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO (CBool) setHandlerWrapper x0 x1 x2 = do x0obj <- qDialogButtonBoxFromPtr x0 x1obj <- qObjectFromPtr x1 x2obj <- objectFromPtr_nf x2 let rv = if (objectIsNull x0obj) then return False else _handler x0obj x1obj x2obj rvf <- rv return (toCBool rvf) setHandlerWrapper_d :: Ptr fun -> Ptr () -> Ptr fun_d -> IO () setHandlerWrapper_d funptr stptr funptr_d = do when (stptr/=ptrNull) (freeStablePtr (castPtrToStablePtr stptr)) when (funptr/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr)) when (funptr_d/=ptrNull) (freeHaskellFunPtr (castPtrToFunPtr funptr_d)) return () instance QeventFilter_h (QDialogButtonBox ()) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDialogButtonBox_eventFilter cobj_x0 cobj_x1 cobj_x2 foreign import ccall "qtc_QDialogButtonBox_eventFilter" qtc_QDialogButtonBox_eventFilter :: Ptr (TQDialogButtonBox a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool instance QeventFilter_h (QDialogButtonBoxSc a) ((QObject t1, QEvent t2)) where eventFilter_h x0 (x1, x2) = withBoolResult $ withObjectPtr x0 $ \cobj_x0 -> withObjectPtr x1 $ \cobj_x1 -> withObjectPtr x2 $ \cobj_x2 -> qtc_QDialogButtonBox_eventFilter cobj_x0 cobj_x1 cobj_x2
keera-studios/hsQt
Qtc/Gui/QDialogButtonBox_h.hs
bsd-2-clause
60,085
0
18
12,271
18,825
9,082
9,743
-1
-1
module Test.Kibr where import Preamble import Test.Framework (defaultMainWithArgs) import qualified Test.Kibr.Css as Css import qualified Test.Kibr.Http as Http import qualified Test.Kibr.Irc as Irc import qualified Test.Kibr.Xml as Xml run :: [String] -> IO () run = defaultMainWithArgs [Css.tests, Http.tests, Irc.tests, Xml.tests]
dag/kibr
src/Test/Kibr.hs
bsd-2-clause
341
0
7
48
100
65
35
9
1
{-# LANGUAGE UndecidableInstances, FlexibleContexts, FlexibleInstances, EmptyDataDecls, MultiParamTypeClasses, FunctionalDependencies #-} ----------------------------------------------------------------------------- -- | -- Module : Data.Type.Ord -- Copyright : (C) 2006-2007 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable (FD and MPTC, undecidable-instances) -- -- Simple equality and ordering for types. -- Extended to include common usage cases. -- -- Instances should all really be decidable. ---------------------------------------------------------------------------- module Data.Type.Ord ( TEq, tEq , TLt, tLt , TGe, tGe -- closed, extend via TEq/TLt , TLe, tLe -- closed, extend via TEq/TLt , TGt, tGt -- closed, extend via TEq/TLt ) where import Data.Type.Boolean data Closure class Closed a | -> a instance Closed Closure -- two open classes class TBool b => TEq x y b | x y -> b instance TEq T T T instance TEq T F F instance TEq F T F instance TEq F F T tEq :: TEq x y b => x -> y -> b; tEq = undefined class TBool b => TLt x y b | x y -> b tLt :: TLt x y b => x -> y -> b tLt = undefined class TBool b => TCGe c x y b | x y -> b, x y b -> c instance (TBool b', TLt x y b, TNot b b') => TCGe Closure x y b' class TCGe Closure x y b => TGe x y b | x y -> b instance (TBool b', TLt x y b, TNot b b') => TGe x y b' tGe :: TGe x y b => x -> y -> b tGe = undefined class TBool b => TCLe c x y b | x y -> b, x y b -> c instance (TBool b'', TEq x y b, TLt x y b', TOr b b' b'') => TCLe Closure x y b'' class TBool b => TLe x y b | x y -> b instance (TBool b'', TEq x y b, TLt x y b', TOr b b' b'') => TLe x y b'' tLe :: TGt x y b => x -> y -> b tLe = undefined class TBool b => TCGt c x y b | x y -> b, x y b -> c instance (TBool b', TLe x y b, TNot b b') => TCGt Closure x y b' class TBool b => TGt x y b | x y -> b instance (TBool b', TLe x y b, TNot b b') => TGt x y b' tGt :: TGt x y b => x -> y -> b tGt = undefined
ekmett/type-int
Data/Type/Ord.hs
bsd-2-clause
2,095
0
7
496
769
415
354
-1
-1
module FieldML.Utility01 ( -- Todo: rename and relocate this module. freeVariables, domain, codomain, expressionType, canonicalSuperset, simplifyFSet, validExpression, lambdaLike, cardinality ) where import FieldML.Core import Data.List ( delete, nub, (\\) ) import Data.Set (size, member) -- Focus here is on *processing* the FieldML data structures. -- | simplifyFSet m will attempt to produce a new FSet that is equivalent to m, but has a simpler definition. simplifyFSet :: FSet -> FSet simplifyFSet (Factor n (CartesianProduct ys)) = simplifyFSet (ys !! (n-1)) simplifyFSet (CartesianProduct []) = UnitSpace simplifyFSet (CartesianProduct (UnitSpace:ms)) = simplifyFSet (CartesianProduct ms) simplifyFSet (CartesianProduct [m]) = simplifyFSet m simplifyFSet (SignatureSpace UnitSpace m) = simplifyFSet m simplifyFSet (Domain (Lambda x _)) = simplifyFSet (codomain x) simplifyFSet m = m freeVariables :: Expression -> [Expression] freeVariables UnitElement = [] freeVariables (BooleanConstant _) = [] freeVariables (RealConstant _ ) = [] freeVariables (LabelValue _) = [] freeVariables f@(GeneralVariable _ _ ) = [f] freeVariables (Unspecified _) = [] freeVariables (Cast x _) = freeVariables x -- Todo: currently ignoring free variables in definition of FSet. freeVariables (Tuple xs) = nub (concatMap freeVariables xs) freeVariables (Project _ x) = freeVariables x -- Note, could have used more general pattern for Lambda, but the lack of exhaustive pattern matching is serving in the interim as poor man's validation. freeVariables (Lambda t@(Tuple _) expr1) = (freeVariables expr1) \\ (freeVariables t) freeVariables (Lambda x@(GeneralVariable _ _) expr1 ) = delete x (freeVariables expr1) freeVariables x@(Lambda _ _) = error ("freeVariables not implemented yet for Lambda for case where bound variable is anything other than variable Tuple. Args:" ++ show x) freeVariables (Inverse f) = freeVariables f freeVariables (Lambdify _) = [] freeVariables (Apply f x) = nub ((freeVariables f) ++ (freeVariables x) ) freeVariables (Compose f g) = freeVariables $ Tuple [ f, g ] freeVariables (PartialApplication f n x) = nub ( (freeVariables f) ++ (freeVariables x) ) freeVariables (Where expr xs) = (freeVariables expr) \\ (localVars xs) where localVars ((local `Equal` _):x1s) = (freeVariables local) ++ (localVars x1s) localVars [] = [] freeVariables (And a b) = freeVariables $ Tuple [ a, b ] freeVariables (Or a b) = freeVariables $ Tuple [ a, b ] freeVariables (Not a) = freeVariables a freeVariables (LessThan a b) = freeVariables $ Tuple [ a, b ] freeVariables (Equal a b) = freeVariables $ Tuple [ a, b ] freeVariables (Plus a b) = freeVariables $ Tuple [ a, b ] freeVariables (Minus a b) = freeVariables $ Tuple [ a, b ] freeVariables (Negate a) = freeVariables a freeVariables (Times a b) = freeVariables $ Tuple [ a, b ] freeVariables (Divide a b) = freeVariables $ Tuple [ a, b ] freeVariables (Modulus a b) = freeVariables $ Tuple [ a, b ] freeVariables (Sin x) = freeVariables x freeVariables (Cos x) = freeVariables x freeVariables (Exp x) = freeVariables x freeVariables (Power x y) = freeVariables $ Tuple [ x, y ] freeVariables Pi = [] freeVariables (If x a b ) = freeVariables $ Tuple [ x, a, b ] freeVariables (Max f) = freeVariables f freeVariables (Min f) = freeVariables f freeVariables (ElementOf x m) = freeVariables x -- Todo: What if there are free variables in the definition of m? Assuming here and elsewhere that there are not. Could merge FSet and Expression, so that an expression may represent an FSet? freeVariables (Exists x@(GeneralVariable _ _) f) = delete x (freeVariables f) freeVariables (Restriction _ f) = freeVariables f -- Todo: What if the restriction fixes one of the variables? Is it still free, but only valid if it has that value? freeVariables (Interior _) = [] -- Todo: definition of m in Interior m may have free variables, but we aren't yet processing defintions of FSet. freeVariables (MultiDimArray (AlgebraicVector x) _) = freeVariables x freeVariables (MultiDimArray _ _) = [] freeVariables (Contraction a1 _ a2 _) = (freeVariables a1) ++ (freeVariables a2) -- Todo: This assumes that the index selector is always "hard coded", we will possibly in future want to support using an integer expression for the index. freeVariables (KroneckerProduct xs) = freeVariables $ Tuple xs freeVariables (DistributedAccordingTo x f) = freeVariables $ Tuple [ x, f ] freeVariables (DistributionFromRealisations xs) = freeVariables $ Tuple xs freeVariables x = error ("freeVariables not implemented yet for this constructor. Args:" ++ show x) -- | Returns the FSet from which a function maps values. Unless it is actually a function, the expression is treated as a value, which is treated as a function from UnitSpace. -- Todo: make "return type" "Either FSet or InvalidExpression" so that validation can be built in. -- Todo: Explicit patterns all mentioned at this stage there is no 'catch-all', still using this to provide rudimentary debugging, but would look prettier with the UnitSpace case handled by a catch-all. domain :: Expression -> FSet domain UnitElement = UnitSpace domain (BooleanConstant _) = UnitSpace domain (RealConstant _ ) = UnitSpace domain (LabelValue _ ) = UnitSpace domain (GeneralVariable _ (SignatureSpace m _)) = simplifyFSet m domain (GeneralVariable _ _) = UnitSpace domain (Unspecified _) = UnitSpace domain (Cast _ (SignatureSpace m _)) = m domain (Cast _ _) = UnitSpace domain (Tuple _) = UnitSpace domain (Project n x) = simplifyFSet (domain x) domain (Lambda UnitElement _) = UnitSpace domain (Lambda x@(GeneralVariable _ _) _ ) = simplifyFSet $ codomain x domain (Lambda t@(Tuple _) _ ) = simplifyFSet $ codomain t domain x@(Lambda _ _ ) = error ("domain not implemented yet for Lambda for case where bound variable is anything other than variable Tuple. Args:" ++ show x) domain (Inverse f) = simplifyFSet (codomain f) domain (Lambdify expr) = simplifyFSet $ CartesianProduct $ map fSetOfVariable (freeVariables expr) domain (Apply f _) = effectiveResultingDomain $ (simplifyFSet (codomain f)) where effectiveResultingDomain (SignatureSpace m _) = m effectiveResultingDomain _ = UnitSpace domain (Compose _ g) = simplifyFSet $ domain g domain (PartialApplication f n _) = simplifyFSet $ CartesianProduct ((take (n-1) fFactors) ++ (drop n fFactors)) where fFactors = getFactors (domain f) getFactors (CartesianProduct ms) = ms getFactors m = [m] domain (Where expr _) = simplifyFSet $ domain expr domain (And _ _) = UnitSpace domain (Or _ _) = UnitSpace domain (Not _) = UnitSpace domain (LessThan _ _) = UnitSpace domain (Equal _ _) = UnitSpace domain (Plus _ _) = UnitSpace domain (Minus _ _) = UnitSpace domain (Negate _) = UnitSpace domain (Times _ _) = UnitSpace domain (Divide _ _) = UnitSpace domain (Modulus _ _) = UnitSpace domain (Sin _) = UnitSpace domain (Cos _) = UnitSpace domain (Exp _) = UnitSpace domain (Power _ _) = UnitSpace domain Pi = UnitSpace domain (If _ _ _ ) = UnitSpace domain (Max _) = UnitSpace domain (Min _) = UnitSpace domain (ElementOf _ _) = UnitSpace domain (Exists _ _) = UnitSpace domain (Restriction m _ ) = simplifyFSet m domain (Interior (SimpleSubset l@(Lambda _ _)) ) = simplifyFSet $ domain l domain x@(Interior _) = error ("domain not implemented yet for Interior for anything other than SimpleSubset of a Lambda. Args:" ++ show x) domain (MultiDimArray _ m) = simplifyFSet m domain (Contraction a1 n1 a2 n2) = simplifyFSet ( CartesianProduct [ domain (PartialApplication a1 n1 boundIndexVariable), domain (PartialApplication a2 n2 boundIndexVariable) ] ) where boundIndexVariable = GeneralVariable "boundIndexVariable" (getFactor n1 (domain a1)) --Todo: Assumes this is the same as (getFactor n2 (domain a2)). domain (KroneckerProduct _) = UnitSpace domain (DistributedAccordingTo _ _ ) = UnitSpace domain (DistributionFromRealisations xs ) = simplifyFSet $ codomain (head xs) -- Note: this Assumes all xs also have codomain same as head xs. This is checked by validExpression. -- Todo: breaks if xs is [] domain x = error ("domain not implemented yet for this constructor. Args:" ++ show x) -- | Returns the FSet to which a function maps values. Even if it is actually just a value expression, rather than a function, the expression is treated as a function from UnitSpace, and then the codomain is the 'type' of the value. -- Todo: make "return type" "Either FSet or InvalidExpression" so that validation can be built in. -- Todo: make it so that it can be assumed that codomain has simplified the FSet before returning it, same for domain codomain :: Expression -> FSet codomain UnitElement = UnitSpace codomain (BooleanConstant _) = Booleans codomain (RealConstant _ ) = Reals codomain (LabelValue (StringLabel _ m)) = Labels m codomain (LabelValue (IntegerLabel _ m)) = Labels m codomain (GeneralVariable _ (SignatureSpace _ m)) = simplifyFSet m codomain (GeneralVariable _ m) = m codomain (Unspecified m) = m codomain (Cast _ (SignatureSpace _ m)) = m codomain (Cast _ m) = m codomain (Tuple fs) = CartesianProduct (map codomain fs) codomain (Project n f) = getFactor n (codomain f) codomain (Lambda _ expr ) | lambdaLike expr = SignatureSpace (domain expr) (codomain expr) | otherwise = codomain expr codomain (Inverse f) = domain f codomain (Lambdify expr) = codomain expr codomain (Apply f _) = effectiveResultingCodomain $ (simplifyFSet (codomain f)) where effectiveResultingCodomain (SignatureSpace _ n) = n effectiveResultingCodomain _ = simplifyFSet $ codomain f codomain (Compose f _) = simplifyFSet $ codomain f codomain (PartialApplication f _ _) = simplifyFSet $ codomain f codomain (Where expr _) = simplifyFSet $ codomain expr codomain (And _ _) = Booleans codomain (Or _ _) = Booleans codomain (Not _) = Booleans codomain (LessThan _ _) = Booleans codomain (Equal _ _) = Booleans codomain (Plus _ _) = Reals codomain (Minus _ _) = Reals codomain (Negate _) = Reals codomain (Times _ _) = Reals codomain (Divide _ _) = Reals codomain (Modulus _ _) = Reals codomain (Sin _) = Reals codomain (Cos _) = Reals codomain (Exp _) = Reals codomain (Power _ _) = Reals codomain Pi = Reals codomain (If _ a _ ) = codomain a codomain (Max _) = Reals codomain (Min _) = Reals codomain (ElementOf _ _) = Booleans codomain (Exists _ _) = Booleans codomain (Restriction _ f ) = codomain f codomain (Interior _) = Booleans codomain (MultiDimArray (RealParameterVector _) _) = Reals codomain (MultiDimArray (IntegerParameterVector _ m) _) = m codomain (MultiDimArray (AlgebraicVector (Tuple (x:xs))) _) = expressionType x codomain (MultiDimArray (AlgebraicVector x) _) = expressionType x codomain (Contraction _ _ _ _) = Reals codomain (KroneckerProduct fs ) = SignatureSpace (Labels (IntegerRange 1 m)) Reals where m = product ( map tupleLength fs ) tupleLength (Tuple gs) = length gs tupleLength (Apply (Lambda _ (Tuple gs)) _ ) = length gs tupleLength x = error ("codomain.tupleLength not implemented yet for this constructor. Args:" ++ show x) -- Todo: Should consider perhaps having an expression simplifier that performs the substitution that an Apply represents. See also validTupleOfRealValues. codomain (DistributedAccordingTo _ _ ) = Booleans codomain (DistributionFromRealisations _) = Reals codomain x = error ("codomain not implemented yet for this constructor. Args:" ++ show x) -- | True if expression passes a limited set of tests. Note: this is under construction, so sometimes an expression is reported as valid, even if it is not valid. validExpression :: Expression -> Bool validExpression UnitElement = True validExpression (BooleanConstant _) = True validExpression (RealConstant _ ) = True validExpression x@(LabelValue _) = x `inLabelSet` m where m = case x of LabelValue (StringLabel _ m') -> m' LabelValue (IntegerLabel _ m') -> m' validExpression (GeneralVariable _ _) = True -- Todo: Could validate the name of the variable according to some rules for identifier names. validExpression (Unspecified _) = True -- validExpression (Cast x (SignatureSpace m n)) = validExpression x -- Todo: Major omission here: a lot of work is probably required to validate all possibilities. validExpression (Cast (Tuple (x:xs)) d@(DisjointUnion _ _)) = (simplifyFSet (codomain (Tuple xs))) == simplifyFSet (getPart d x) validExpression (Cast x (SimpleSubset f)) = domain f == codomain x && validExpression x && validExpression f -- Todo: Can't tell though whether f is true when evaluated at f validExpression x1@(Cast _ _) = error ("validExpression not implemented yet for Cast of this form. Args:" ++ show x1) validExpression (Tuple xs) = all validExpression xs validExpression (Project n x) = validExpression x && factorCount (codomain x) >= n validExpression (Lambda x expr ) = (isVariableTuple x) && (validExpression expr) where isVariableTuple (GeneralVariable _ _) = True isVariableTuple (Tuple xs) = all isVariableTuple xs isVariableTuple _ = False -- Todo: Other expressions are lambda like, and can be inverted, add their cases. Probably will treat inverse of values that are not lambda-like as invalid though. validExpression (Inverse f) = validExpression f && lambdaLike f validExpression (Lambdify expr) = validExpression expr && not (lambdaLike expr) -- Todo: Not sure if the restriction that expr is "not lambda-like" is necessary. validExpression (Apply f x) = lambdaLike f && codomain x == domain f && validExpression f && validExpression x validExpression (Compose f g) = lambdaLike f && lambdaLike g && validExpression f && validExpression g && codomain g == domain f validExpression (PartialApplication f n x) = lambdaLike f && factorCount (domain f) >= n && canonicalSuperset (codomain x) == getFactor n (domain f) && validExpression f && validExpression x validExpression (Where expr locals) = validExpression expr && all validExpression locals && all localVarAssignment locals where localVarAssignment (Equal (GeneralVariable _ _) _) = True localVarAssignment _ = False validExpression (And a b) = validBinaryOp Booleans a b validExpression (Or a b) = validBinaryOp Booleans a b validExpression (Not a) = validExpression a && codomain a == Booleans && not (lambdaLike a) validExpression (LessThan a b) = validBinaryOp Reals a b validExpression (Equal a b) = validExpression a && validExpression b && canonicalSuperset (codomain a) == canonicalSuperset (codomain b) && not (lambdaLike a) && not (lambdaLike b) validExpression (Plus a b) = validBinaryOp Reals a b validExpression (Minus a b) = validBinaryOp Reals a b validExpression (Negate a) = validUnaryOp Reals a validExpression (Times a b) = validBinaryOp Reals a b validExpression (Divide a b) = validBinaryOp Reals a b validExpression (Modulus a b) = validBinaryOp Reals a b validExpression (Sin x) = validUnaryOp Reals x validExpression (Cos x) = validUnaryOp Reals x validExpression (Exp x) = validUnaryOp Reals x validExpression (Power x y) = validBinaryOp Reals x y validExpression Pi = True validExpression (If x a b ) = validExpression a && validExpression b && validExpression x && codomain a == codomain b && codomain x == Booleans && not (lambdaLike x) validExpression (Max f) = realCodomain f validExpression (Min f) = realCodomain f validExpression (ElementOf _ _) = True validExpression (Exists (GeneralVariable _ _) f) = codomain f == Booleans && validExpression f validExpression (Restriction (SimpleSubset p) f ) = lambdaLike f && validExpression f && validExpression p && domain p == domain f validExpression (Interior _) = True -- Todo: validate the FSet operand. validExpression (MultiDimArray v m) = ((isDiscreteFSet m) || (isProductOfDFSs m)) && validateCardinality && validVector v where validateCardinality = (cardinality m == vectorLength v) isDiscreteFSet (Labels _) = True isDiscreteFSet _ = False isProductOfDFSs (CartesianProduct ms) = all isDiscreteFSet ms isProductOfDFSs _ = False validExpression (Contraction a1 n1 a2 n2) = lambdaLike a1 && lambdaLike a2 && validExpression a1 && validExpression a2 && codomain a1 == Reals && codomain a2 == Reals && n1 <= factorCount m1 && n2 <= factorCount m2 && getFactor n1 m1 == getFactor n2 m2 where m1 = domain a1 m2 = domain a2 validExpression ( KroneckerProduct xs ) = all validTupleOfRealValues xs where validTupleOfRealValues (Tuple ys) = all validRealValue ys validTupleOfRealValues (Apply (Lambda _ expr) _) = validTupleOfRealValues expr -- Todo: see comment made at codomain for KroneckerProduct validExpression (DistributedAccordingTo expr f) = realCodomain f && domain f == codomain expr validExpression (DistributionFromRealisations xs) = all validExpression xs && length (nub (map (simplifyFSet . codomain) xs)) == 1 -- Secondary utility methods follow -- | Returns True if vector is valid. --Todo: Vector construction is just a kind of expression, this really hints at using typeclasses, and having a "isValid" function for Vectors, Expressions and FSets. validVector :: SimpleVector -> Bool validVector (IntegerParameterVector xs (Labels intLabels)) = all (inLabels intLabels) xs where inLabels (IntegerRange x1 x2) x = x >= x1 && x <= x2 inLabels Integers x = True inLabels (DiscreteSetUnion n1 n2) x = inLabels n1 x || inLabels n2 x inLabels (Intersection n1 n2) x = inLabels n1 x && inLabels n2 x inLabels _ _ = False validVector _ = True -- | Returns the length of the various types of vectors. vectorLength :: SimpleVector -> Int vectorLength (AlgebraicVector (Tuple xs)) = length xs vectorLength (AlgebraicVector (Apply (Lambda _ x1) _) ) = vectorLength (AlgebraicVector x1) -- Todo: This is along the lines of algebraic manipulation of the expression, and should probably be extracted. vectorLength (AlgebraicVector _) = 1 vectorLength (RealParameterVector xs) = length xs vectorLength (IntegerParameterVector xs _) = length xs fSetOfVariable :: Expression -> FSet fSetOfVariable (GeneralVariable _ a) = a -- | Simply wraps a lambda like expression's domain and codomain in SignatureSpace, and for all others, the codomain FSet is returned directly. expressionType :: Expression -> FSet expressionType x | lambdaLike x = SignatureSpace (domain x) (codomain x) | otherwise = simplifyFSet (codomain x) -- Todo: more comprehensive handling of FSet types, e.g. subset of Cartesian product. getFactor :: Int -> FSet -> FSet getFactor n (CartesianProduct xs) = xs !! (n-1) getFactor 1 m = m -- Todo: more comprehensive handling of other FSet types, e.g. subset of cartesian power, currently this would come out as 1. factorCount :: FSet -> Int factorCount (CartesianProduct ms) = length ms factorCount _ = 1 -- | Given the index of an DisjointUnion, returns the part of the disjoint union at that index, without the index as a factor. getPart :: FSet -> Expression -> FSet getPart (DisjointUnion m1 dm) x = getPart' dm where getPart' (DomainMapConstant m) = m getPart' (DomainMapIf mtest dmt dmf) = if (x `inLabelSet` mtest) then (getPart' dmt) else (getPart' dmf) -- | inLabelSet m x is true if x is in m, otherwise false. inLabelSet :: Expression -> SetOfLabels -> Bool inLabelSet (LabelValue (StringLabel x _)) (StringLabels sset) = x `member` sset inLabelSet (LabelValue (IntegerLabel x _)) (IntegerRange min max) = x >= min && x <= max inLabelSet (LabelValue (IntegerLabel x _)) Integers = True inLabelSet x (DiscreteSetUnion m1 m2) = (x `inLabelSet` m1) || (x `inLabelSet` m2) inLabelSet x (Intersection m1 m2) = (x `inLabelSet` m1) && (x `inLabelSet` m2) inLabelSet x y = error ("inLabelSet not implemented for this expression form. Args: " ++ show x ++ ", " ++ show y) -- | Cardinality of discrete space. Zero if can't be easily determined, or has continuous components. -- Todo: only some cases have been covered, i.e. only the bare minimum as required by existing unit tests. cardinality :: FSet -> Int cardinality UnitSpace = 1 cardinality (Labels (IntegerRange a b) ) = b - a + 1 cardinality (Labels (StringLabels a)) = size a cardinality (CartesianProduct fs) = product (map cardinality fs) cardinality x = error ("cardinality not implemented this constructor. Args: " ++ show x) lambdaLike :: Expression -> Bool lambdaLike x = not (domain x == UnitSpace) -- | canonicalSuperset m returns n where m is a simple subset of n, or factors of m are subsets of factors of n. canonicalSuperset :: FSet -> FSet canonicalSuperset (CartesianProduct ms) = CartesianProduct (map canonicalSuperset ms) canonicalSuperset (SimpleSubset f) = canonicalSuperset (domain f) canonicalSuperset (Image f) = canonicalSuperset (codomain f) canonicalSuperset (Factor n (CartesianProduct ms)) = canonicalSuperset (ms!!(n-1)) canonicalSuperset m = m -- | Checks that both expressions are of the same codomain, and are each valid, and are each value-like, not lambda-like. -- Todo: add a flag to indicate whether lambda's are considered valid or not. validBinaryOp :: FSet -> Expression -> Expression -> Bool validBinaryOp m a b = validUnaryOp m a && validUnaryOp m b validUnaryOp :: FSet -> Expression -> Bool validUnaryOp m x = validExpression x && (canonicalSuperset . simplifyFSet . codomain) x == m && not (lambdaLike x) realCodomain :: Expression -> Bool realCodomain x = (canonicalSuperset . simplifyFSet . codomain) x == Reals validRealValue :: Expression -> Bool validRealValue x = validUnaryOp Reals x
codecurve/FieldML-Haskell-01
src/FieldML/Utility01.hs
bsd-2-clause
21,775
0
18
3,941
6,762
3,360
3,402
381
8
{-# LANGUAGE ViewPatterns #-} module Typecheck where import Control.Monad.Except import Control.Monad.Trans import Debug.Trace import Term import qualified Data.Map as Map import qualified Data.Set as Set import Unbound.Generics.LocallyNameless import Control.Applicative import Control.Monad.Reader type Env = Map.Map (Name Term) Type type Constraint = (Type, Type) data TypeError = BadApp { expected :: Type, received :: Type } | NotAFn { got :: Type } | UnboundVariable (Name Term) deriving (Show) empty :: Env empty = Map.empty freshtv :: InferM Type freshtv = do x <- fresh (string2Name "T") return $ TVar x type InferM = ExceptT TypeError FreshM type TypeM = ExceptT TypeError LFreshM infer' :: Env -> Term -> InferM (Type, [Constraint]) infer' env term | trace ("infer was called: "++show term) False = undefined infer' env term = case term of Lambda b -> do (n, e) <- unbind b tv <- freshtv let env' = Map.insert n tv env traceM (show env') (t, cs) <- infer' env' e return (TArr tv t, cs) App e1 t1 e2 -> do (t1, cs1) <- infer' env e1 (t2, cs2) <- infer' env e2 tv <- freshtv return (tv, (t1, TArr t2 tv) : cs1 ++ cs2) Var n -> case Map.lookup n env of Nothing -> throwError $ UnboundVariable n Just t -> return (t, []) Data -> return (TData,[]) typeof' :: Env -> Term -> Type -> TypeM Bool typeof' env (Var n) ty= case Map.lookup n env of Nothing -> throwError $ UnboundVariable n Just ty' -> return (ty `aeq` ty') typeof' env (Lambda bnd) (TArr t1 t2) = lunbind bnd (\(x , e) -> typeof' (Map.insert x t1 env) e t2) typeof' env (App e1 t1 e2) t2 = do b1 <- typeof' env e1 (TArr t1 t2) b2 <- typeof' env e2 t1 return $ b1 && b2 typeof' _ _ _ = return False typeof :: Env -> Term -> Type -> Either TypeError Bool typeof env term ty = runLFreshM (runExceptT (typeof' env term ty)) infer :: Env -> Term -> Either TypeError (Type, [Constraint]) infer env term = runFreshM (runExceptT (infer' env term))
faineance/totes
src/Typecheck.hs
bsd-3-clause
2,226
0
15
668
874
449
425
61
5
{-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE FlexibleInstances #-} module EFA.Data.Type where --import EFA.Data.Type.Physical --import EFA.Data.Type.Efa newtype TC p f e a = TC a instance Functor (TC p f e) where fmap f (TC x) = TC $ f x {- data Wrap a = WrapPower (TC Power Time Edge a) | WrapFlow (TC Energy Flow Edge a) | WrapStoEnergy (TC Energy Cum Sto a) class WrapIt p f e where wrap :: TC p f e a -> Wrap a instance WrapIt Power Time Edge where wrap x = WrapPower x instance WrapIt Energy Flow Edge where wrap x = WrapFlow x class UnWrap p f e where unwrap :: Wrap a -> TC p f e a instance UnWrap Power Time Edge where unwrap (WrapPower x) = x instance UnWrap Energy Flow Edge where unwrap (WrapFlow x) = x -}
energyflowanalysis/efa-2.1
src/EFA/Data/Type.hs
bsd-3-clause
764
0
8
181
65
39
26
6
0
{-# LANGUAGE EmptyDataDecls, FlexibleInstances, TypeFamilies #-} -- | Type functions: interpretations of the type constants -- -- <http://okmij.org/ftp/gengo/NASSLLI10/> -- module Lambda.CFG3Sem where data S -- clause data NP -- noun phrase data VP -- verb phrase data TV -- transitive verb type family Tr (a :: *) :: * type instance Tr S = Bool type instance Tr NP = Entity type instance Tr VP = Entity -> Bool type instance Tr TV = Entity -> Entity -> Bool data Sem a = Sem { unSem :: Tr a } data Entity = John | Mary deriving (Eq, Show) john, mary :: Sem NP like :: Sem TV r2 :: Sem TV -> Sem NP -> Sem VP r1 :: Sem NP -> Sem VP -> Sem S john = Sem John mary = Sem Mary like = Sem (\o s -> elem (s,o) [(John,Mary), (Mary,John)]) r2 (Sem f) (Sem x) = Sem (f x) r1 (Sem x) (Sem f) = Sem (f x) instance Show (Sem S) where show (Sem x) = show x sentence :: Sem S sentence = r1 john (r2 like mary) -- How to tell if the result of evaluating the sentence -- shows that John likes Mary or that Mary likes John? -- We could trace the evaluation. -- A better idea is to display the denotation as a formula -- rather than as its value in one particular world.
suhailshergill/liboleg
Lambda/CFG3Sem.hs
bsd-3-clause
1,363
0
10
446
383
213
170
-1
-1
module Main where import Test.Tasty (defaultMain,testGroup) import qualified Data.RDF.Graph.TriplesList_Test as TriplesList import qualified Data.RDF.Graph.HashMapS_Test as HashMapS import qualified Data.RDF.Graph.HashMapSP_Test as HashMapSP import qualified Data.RDF.Graph.MapSP_Test as MapSP import qualified Data.RDF.Graph.TriplesPatriciaTree_Test as TriplesPatriciaTree import Data.RDF.Types import qualified Text.RDF.RDF4H.XmlParser_Test as XmlParser import qualified Text.RDF.RDF4H.TurtleParser_ConformanceTest as TurtleParser import qualified W3C.TurtleTest as W3CTurtleTest import qualified W3C.RdfXmlTest as W3CRdfXmlTest import qualified W3C.NTripleTest as W3CNTripleTest import Data.RDF.GraphTestUtils import qualified Data.Text as T import System.Directory (getCurrentDirectory) import W3C.Manifest suiteFilesDirTurtle,suiteFilesDirXml,suiteFilesDirNTriples :: T.Text suiteFilesDirTurtle = "rdf-tests/turtle/" suiteFilesDirXml = "rdf-tests/rdf-xml/" suiteFilesDirNTriples = "rdf-tests/ntriples/" mfPathTurtle,mfPathXml,mfPathNTriples :: T.Text mfPathTurtle = T.concat [suiteFilesDirTurtle, "manifest.ttl"] mfPathXml = T.concat [suiteFilesDirXml, "manifest.ttl"] mfPathNTriples = T.concat [suiteFilesDirNTriples, "manifest.ttl"] mfBaseURITurtle,mfBaseURIXml,mfBaseURINTriples :: BaseUrl mfBaseURITurtle = BaseUrl "http://www.w3.org/2013/TurtleTests/" mfBaseURIXml = BaseUrl "http://www.w3.org/2013/RDFXMLTests/" mfBaseURINTriples = BaseUrl "http://www.w3.org/2013/N-TriplesTests/" main :: IO () main = do -- obtain manifest files for W3C tests before running tests -- justification for separation: http://stackoverflow.com/a/33046723 dir <- getCurrentDirectory let fileSchemeUri suitesDir = T.pack ("file://" ++ dir ++ "/" ++ T.unpack suitesDir) turtleManifest <- loadManifest mfPathTurtle (fileSchemeUri suiteFilesDirTurtle) xmlManifest <- loadManifest mfPathXml (fileSchemeUri suiteFilesDirXml) nTriplesManifest <- loadManifest mfPathNTriples (fileSchemeUri suiteFilesDirNTriples) -- run tests defaultMain (testGroup "rdf4h tests" [ -- RDF graph API tests graphTests "TriplesList" TriplesList.triplesOf' TriplesList.uniqTriplesOf' TriplesList.empty' TriplesList.mkRdf' , graphTests "HashMapS" HashMapS.triplesOf' HashMapS.uniqTriplesOf' HashMapS.empty' HashMapS.mkRdf' , graphTests "HashMapSP" HashMapSP.triplesOf' HashMapSP.uniqTriplesOf' HashMapSP.empty' HashMapSP.mkRdf' , graphTests "MapSP" MapSP.triplesOf' MapSP.uniqTriplesOf' MapSP.empty' MapSP.mkRdf' , graphTests "TriplesPatriciaTree" TriplesPatriciaTree.triplesOf' TriplesPatriciaTree.uniqTriplesOf' TriplesPatriciaTree.empty' TriplesPatriciaTree.mkRdf' -- rdf4h unit tests , TurtleParser.tests , XmlParser.tests -- W3C tests , W3CTurtleTest.tests turtleManifest , W3CRdfXmlTest.tests xmlManifest , W3CNTripleTest.tests nTriplesManifest ])
jutaro/rdf4h
testsuite/tests/Test.hs
bsd-3-clause
3,239
0
14
665
541
316
225
72
1
{-# LANGUAGE CPP #-} {-# LANGUAGE DeriveGeneric #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.PackageIndex -- Copyright : (c) David Himmelstrup 2005, -- Bjorn Bringert 2007, -- Duncan Coutts 2008-2009 -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- An index of packages. -- module Distribution.Simple.PackageIndex ( -- * Package index data type InstalledPackageIndex, PackageIndex, FakeMap, -- * Creating an index fromList, -- * Updates merge, insert, deleteInstalledPackageId, deleteSourcePackageId, deletePackageName, -- deleteDependency, -- * Queries -- ** Precise lookups lookupInstalledPackageId, lookupSourcePackageId, lookupPackageId, lookupPackageName, lookupDependency, -- ** Case-insensitive searches searchByName, SearchResult(..), searchByNameSubstring, -- ** Bulk queries allPackages, allPackagesByName, allPackagesBySourcePackageId, -- ** Special queries brokenPackages, dependencyClosure, reverseDependencyClosure, topologicalOrder, reverseTopologicalOrder, dependencyInconsistencies, dependencyCycles, dependencyGraph, moduleNameIndex, -- ** Variants of special queries supporting fake map fakeLookupInstalledPackageId, brokenPackages', dependencyClosure', reverseDependencyClosure', dependencyInconsistencies', dependencyCycles', dependencyGraph', ) where import Control.Exception (assert) import Data.Array ((!)) import qualified Data.Array as Array import Distribution.Compat.Binary (Binary) import qualified Data.Graph as Graph import Data.List as List ( null, foldl', sort , groupBy, sortBy, find, isInfixOf, nubBy, deleteBy, deleteFirstsBy ) #if __GLASGOW_HASKELL__ < 710 import Data.Monoid (Monoid(..)) #endif import Data.Map (Map) import qualified Data.Map as Map import Data.Maybe (isNothing, fromMaybe) import qualified Data.Tree as Tree import GHC.Generics (Generic) import Prelude hiding (lookup) import Distribution.Package ( PackageName(..), PackageId , Package(..), packageName, packageVersion , Dependency(Dependency)--, --PackageFixedDeps(..) , InstalledPackageId(..), PackageInstalled(..) ) import Distribution.ModuleName ( ModuleName ) import Distribution.InstalledPackageInfo ( InstalledPackageInfo ) import qualified Distribution.InstalledPackageInfo as IPI import Distribution.Version ( Version, withinRange ) import Distribution.Simple.Utils (lowercase, comparing, equating) -- Note [FakeMap] ----------------- -- We'd like to use the PackageIndex defined in this module for -- cabal-install's InstallPlan. However, at the moment, this -- data structure is indexed by InstalledPackageId, which we don't -- know until after we've compiled a package (whereas InstallPlan -- needs to store not-compiled packages in the index.) Eventually, -- an InstalledPackageId will be calculatable prior to actually -- building the package (making it something of a misnomer), but -- at the moment, the "fake installed package ID map" is a workaround -- to solve this problem while reusing PackageIndex. The basic idea -- is that, since we don't know what an InstalledPackageId is -- beforehand, we just fake up one based on the package ID (it only -- needs to be unique for the particular install plan), and fill -- it out with the actual generated InstalledPackageId after the -- package is successfully compiled. -- -- However, there is a problem: in the index there may be -- references using the old package ID, which are now dangling if -- we update the InstalledPackageId. We could map over the entire -- index to update these pointers as well (a costly operation), but -- instead, we've chosen to parametrize a variety of important functions -- by a FakeMap, which records what a fake installed package ID was -- actually resolved to post-compilation. If we do a lookup, we first -- check and see if it's a fake ID in the FakeMap. -- -- It's a bit grungy, but we expect this to only be temporary anyway. -- (Another possible workaround would have been to *not* update -- the installed package ID, but I decided this would be hard to -- understand.) -- | Map from fake installed package IDs to real ones. See Note [FakeMap] type FakeMap = Map InstalledPackageId InstalledPackageId -- | The collection of information about packages from one or more 'PackageDB's. -- These packages generally should have an instance of 'PackageInstalled' -- -- Packages are uniquely identified in by their 'InstalledPackageId', they can -- also be efficiently looked up by package name or by name and version. -- data PackageIndex a = PackageIndex -- The primary index. Each InstalledPackageInfo record is uniquely identified -- by its InstalledPackageId. -- !(Map InstalledPackageId a) -- This auxiliary index maps package names (case-sensitively) to all the -- versions and instances of that package. This allows us to find all -- versions satisfying a dependency. -- -- It is a three-level index. The first level is the package name, -- the second is the package version and the final level is instances -- of the same package version. These are unique by InstalledPackageId -- and are kept in preference order. -- -- FIXME: Clarify what "preference order" means. Check that this invariant is -- preserved. See #1463 for discussion. !(Map PackageName (Map Version [a])) deriving (Generic, Show, Read) instance Binary a => Binary (PackageIndex a) -- | The default package index which contains 'InstalledPackageInfo'. Normally -- use this. type InstalledPackageIndex = PackageIndex InstalledPackageInfo instance PackageInstalled a => Monoid (PackageIndex a) where mempty = PackageIndex Map.empty Map.empty mappend = merge --save one mappend with empty in the common case: mconcat [] = mempty mconcat xs = foldr1 mappend xs invariant :: PackageInstalled a => PackageIndex a -> Bool invariant (PackageIndex pids pnames) = map installedPackageId (Map.elems pids) == sort [ assert pinstOk (installedPackageId pinst) | (pname, pvers) <- Map.toList pnames , let pversOk = not (Map.null pvers) , (pver, pinsts) <- assert pversOk $ Map.toList pvers , let pinsts' = sortBy (comparing installedPackageId) pinsts pinstsOk = all (\g -> length g == 1) (groupBy (equating installedPackageId) pinsts') , pinst <- assert pinstsOk $ pinsts' , let pinstOk = packageName pinst == pname && packageVersion pinst == pver ] -- -- * Internal helpers -- mkPackageIndex :: PackageInstalled a => Map InstalledPackageId a -> Map PackageName (Map Version [a]) -> PackageIndex a mkPackageIndex pids pnames = assert (invariant index) index where index = PackageIndex pids pnames -- -- * Construction -- -- | Build an index out of a bunch of packages. -- -- If there are duplicates by 'InstalledPackageId' then later ones mask earlier -- ones. -- fromList :: PackageInstalled a => [a] -> PackageIndex a fromList pkgs = mkPackageIndex pids pnames where pids = Map.fromList [ (installedPackageId pkg, pkg) | pkg <- pkgs ] pnames = Map.fromList [ (packageName (head pkgsN), pvers) | pkgsN <- groupBy (equating packageName) . sortBy (comparing packageId) $ pkgs , let pvers = Map.fromList [ (packageVersion (head pkgsNV), nubBy (equating installedPackageId) (reverse pkgsNV)) | pkgsNV <- groupBy (equating packageVersion) pkgsN ] ] -- -- * Updates -- -- | Merge two indexes. -- -- Packages from the second mask packages from the first if they have the exact -- same 'InstalledPackageId'. -- -- For packages with the same source 'PackageId', packages from the second are -- \"preferred\" over those from the first. Being preferred means they are top -- result when we do a lookup by source 'PackageId'. This is the mechanism we -- use to prefer user packages over global packages. -- merge :: PackageInstalled a => PackageIndex a -> PackageIndex a -> PackageIndex a merge (PackageIndex pids1 pnames1) (PackageIndex pids2 pnames2) = mkPackageIndex (Map.unionWith (\_ y -> y) pids1 pids2) (Map.unionWith (Map.unionWith mergeBuckets) pnames1 pnames2) where -- Packages in the second list mask those in the first, however preferred -- packages go first in the list. mergeBuckets xs ys = ys ++ (xs \\ ys) (\\) = deleteFirstsBy (equating installedPackageId) -- | Inserts a single package into the index. -- -- This is equivalent to (but slightly quicker than) using 'mappend' or -- 'merge' with a singleton index. -- insert :: PackageInstalled a => a -> PackageIndex a -> PackageIndex a insert pkg (PackageIndex pids pnames) = mkPackageIndex pids' pnames' where pids' = Map.insert (installedPackageId pkg) pkg pids pnames' = insertPackageName pnames insertPackageName = Map.insertWith' (\_ -> insertPackageVersion) (packageName pkg) (Map.singleton (packageVersion pkg) [pkg]) insertPackageVersion = Map.insertWith' (\_ -> insertPackageInstance) (packageVersion pkg) [pkg] insertPackageInstance pkgs = pkg : deleteBy (equating installedPackageId) pkg pkgs -- | Removes a single installed package from the index. -- deleteInstalledPackageId :: PackageInstalled a => InstalledPackageId -> PackageIndex a -> PackageIndex a deleteInstalledPackageId ipkgid original@(PackageIndex pids pnames) = case Map.updateLookupWithKey (\_ _ -> Nothing) ipkgid pids of (Nothing, _) -> original (Just spkgid, pids') -> mkPackageIndex pids' (deletePkgName spkgid pnames) where deletePkgName spkgid = Map.update (deletePkgVersion spkgid) (packageName spkgid) deletePkgVersion spkgid = (\m -> if Map.null m then Nothing else Just m) . Map.update deletePkgInstance (packageVersion spkgid) deletePkgInstance = (\xs -> if List.null xs then Nothing else Just xs) . List.deleteBy (\_ pkg -> installedPackageId pkg == ipkgid) undefined -- | Removes all packages with this source 'PackageId' from the index. -- deleteSourcePackageId :: PackageInstalled a => PackageId -> PackageIndex a -> PackageIndex a deleteSourcePackageId pkgid original@(PackageIndex pids pnames) = case Map.lookup (packageName pkgid) pnames of Nothing -> original Just pvers -> case Map.lookup (packageVersion pkgid) pvers of Nothing -> original Just pkgs -> mkPackageIndex (foldl' (flip (Map.delete . installedPackageId)) pids pkgs) (deletePkgName pnames) where deletePkgName = Map.update deletePkgVersion (packageName pkgid) deletePkgVersion = (\m -> if Map.null m then Nothing else Just m) . Map.delete (packageVersion pkgid) -- | Removes all packages with this (case-sensitive) name from the index. -- deletePackageName :: PackageInstalled a => PackageName -> PackageIndex a -> PackageIndex a deletePackageName name original@(PackageIndex pids pnames) = case Map.lookup name pnames of Nothing -> original Just pvers -> mkPackageIndex (foldl' (flip (Map.delete . installedPackageId)) pids (concat (Map.elems pvers))) (Map.delete name pnames) {- -- | Removes all packages satisfying this dependency from the index. -- deleteDependency :: Dependency -> PackageIndex -> PackageIndex deleteDependency (Dependency name verstionRange) = delete' name (\pkg -> packageVersion pkg `withinRange` verstionRange) -} -- -- * Bulk queries -- -- | Get all the packages from the index. -- allPackages :: PackageIndex a -> [a] allPackages (PackageIndex pids _) = Map.elems pids -- | Get all the packages from the index. -- -- They are grouped by package name (case-sensitively). -- allPackagesByName :: PackageIndex a -> [(PackageName, [a])] allPackagesByName (PackageIndex _ pnames) = [ (pkgname, concat (Map.elems pvers)) | (pkgname, pvers) <- Map.toList pnames ] -- | Get all the packages from the index. -- -- They are grouped by source package id (package name and version). -- allPackagesBySourcePackageId :: PackageInstalled a => PackageIndex a -> [(PackageId, [a])] allPackagesBySourcePackageId (PackageIndex _ pnames) = [ (packageId ipkg, ipkgs) | pvers <- Map.elems pnames , ipkgs@(ipkg:_) <- Map.elems pvers ] -- -- * Lookups -- -- | Does a lookup by source package id (name & version). -- -- Since multiple package DBs mask each other by 'InstalledPackageId', -- then we get back at most one package. -- lookupInstalledPackageId :: PackageIndex a -> InstalledPackageId -> Maybe a lookupInstalledPackageId (PackageIndex pids _) pid = Map.lookup pid pids -- | Does a lookup by source package id (name & version). -- -- There can be multiple installed packages with the same source 'PackageId' -- but different 'InstalledPackageId'. They are returned in order of -- preference, with the most preferred first. -- lookupSourcePackageId :: PackageIndex a -> PackageId -> [a] lookupSourcePackageId (PackageIndex _ pnames) pkgid = case Map.lookup (packageName pkgid) pnames of Nothing -> [] Just pvers -> case Map.lookup (packageVersion pkgid) pvers of Nothing -> [] Just pkgs -> pkgs -- in preference order -- | Convenient alias of 'lookupSourcePackageId', but assuming only -- one package per package ID. lookupPackageId :: PackageIndex a -> PackageId -> Maybe a lookupPackageId index pkgid = case lookupSourcePackageId index pkgid of [] -> Nothing [pkg] -> Just pkg _ -> error "Distribution.Simple.PackageIndex: multiple matches found" -- | Does a lookup by source package name. -- lookupPackageName :: PackageIndex a -> PackageName -> [(Version, [a])] lookupPackageName (PackageIndex _ pnames) name = case Map.lookup name pnames of Nothing -> [] Just pvers -> Map.toList pvers -- | Does a lookup by source package name and a range of versions. -- -- We get back any number of versions of the specified package name, all -- satisfying the version range constraint. -- lookupDependency :: PackageIndex a -> Dependency -> [(Version, [a])] lookupDependency (PackageIndex _ pnames) (Dependency name versionRange) = case Map.lookup name pnames of Nothing -> [] Just pvers -> [ entry | entry@(ver, _) <- Map.toList pvers , ver `withinRange` versionRange ] -- -- * Case insensitive name lookups -- -- | Does a case-insensitive search by package name. -- -- If there is only one package that compares case-insensitively to this name -- then the search is unambiguous and we get back all versions of that package. -- If several match case-insensitively but one matches exactly then it is also -- unambiguous. -- -- If however several match case-insensitively and none match exactly then we -- have an ambiguous result, and we get back all the versions of all the -- packages. The list of ambiguous results is split by exact package name. So -- it is a non-empty list of non-empty lists. -- searchByName :: PackageIndex a -> String -> SearchResult [a] searchByName (PackageIndex _ pnames) name = case [ pkgs | pkgs@(PackageName name',_) <- Map.toList pnames , lowercase name' == lname ] of [] -> None [(_,pvers)] -> Unambiguous (concat (Map.elems pvers)) pkgss -> case find ((PackageName name==) . fst) pkgss of Just (_,pvers) -> Unambiguous (concat (Map.elems pvers)) Nothing -> Ambiguous (map (concat . Map.elems . snd) pkgss) where lname = lowercase name data SearchResult a = None | Unambiguous a | Ambiguous [a] -- | Does a case-insensitive substring search by package name. -- -- That is, all packages that contain the given string in their name. -- searchByNameSubstring :: PackageIndex a -> String -> [a] searchByNameSubstring (PackageIndex _ pnames) searchterm = [ pkg | (PackageName name, pvers) <- Map.toList pnames , lsearchterm `isInfixOf` lowercase name , pkgs <- Map.elems pvers , pkg <- pkgs ] where lsearchterm = lowercase searchterm -- -- * Special queries -- -- None of the stuff below depends on the internal representation of the index. -- -- | Find if there are any cycles in the dependency graph. If there are no -- cycles the result is @[]@. -- -- This actually computes the strongly connected components. So it gives us a -- list of groups of packages where within each group they all depend on each -- other, directly or indirectly. -- dependencyCycles :: PackageInstalled a => PackageIndex a -> [[a]] dependencyCycles = dependencyCycles' Map.empty -- | Variant of 'dependencyCycles' which accepts a 'FakeMap'. See Note [FakeMap]. dependencyCycles' :: PackageInstalled a => FakeMap -> PackageIndex a -> [[a]] dependencyCycles' fakeMap index = [ vs | Graph.CyclicSCC vs <- Graph.stronglyConnComp adjacencyList ] where adjacencyList = [ (pkg, installedPackageId pkg, fakeInstalledDepends fakeMap pkg) | pkg <- allPackages index ] -- | All packages that have immediate dependencies that are not in the index. -- -- Returns such packages along with the dependencies that they're missing. -- brokenPackages :: PackageInstalled a => PackageIndex a -> [(a, [InstalledPackageId])] brokenPackages = brokenPackages' Map.empty -- | Variant of 'brokenPackages' which accepts a 'FakeMap'. See Note [FakeMap]. brokenPackages' :: PackageInstalled a => FakeMap -> PackageIndex a -> [(a, [InstalledPackageId])] brokenPackages' fakeMap index = [ (pkg, missing) | pkg <- allPackages index , let missing = [ pkg' | pkg' <- installedDepends pkg , isNothing (fakeLookupInstalledPackageId fakeMap index pkg') ] , not (null missing) ] -- | Variant of 'lookupInstalledPackageId' which accepts a 'FakeMap'. See Note [FakeMap]. fakeLookupInstalledPackageId :: FakeMap -> PackageIndex a -> InstalledPackageId -> Maybe a fakeLookupInstalledPackageId fakeMap index pkg = lookupInstalledPackageId index (Map.findWithDefault pkg pkg fakeMap) -- | Tries to take the transitive closure of the package dependencies. -- -- If the transitive closure is complete then it returns that subset of the -- index. Otherwise it returns the broken packages as in 'brokenPackages'. -- -- * Note that if the result is @Right []@ it is because at least one of -- the original given 'PackageId's do not occur in the index. -- dependencyClosure :: PackageInstalled a => PackageIndex a -> [InstalledPackageId] -> Either (PackageIndex a) [(a, [InstalledPackageId])] dependencyClosure = dependencyClosure' Map.empty -- | Variant of 'dependencyClosure' which accepts a 'FakeMap'. See Note [FakeMap]. dependencyClosure' :: PackageInstalled a => FakeMap -> PackageIndex a -> [InstalledPackageId] -> Either (PackageIndex a) [(a, [InstalledPackageId])] dependencyClosure' fakeMap index pkgids0 = case closure mempty [] pkgids0 of (completed, []) -> Left completed (completed, _) -> Right (brokenPackages completed) where closure completed failed [] = (completed, failed) closure completed failed (pkgid:pkgids) = case fakeLookupInstalledPackageId fakeMap index pkgid of Nothing -> closure completed (pkgid:failed) pkgids Just pkg -> case fakeLookupInstalledPackageId fakeMap completed (installedPackageId pkg) of Just _ -> closure completed failed pkgids Nothing -> closure completed' failed pkgids' where completed' = insert pkg completed pkgids' = installedDepends pkg ++ pkgids -- | Takes the transitive closure of the packages reverse dependencies. -- -- * The given 'PackageId's must be in the index. -- reverseDependencyClosure :: PackageInstalled a => PackageIndex a -> [InstalledPackageId] -> [a] reverseDependencyClosure = reverseDependencyClosure' Map.empty -- | Variant of 'reverseDependencyClosure' which accepts a 'FakeMap'. See Note [FakeMap]. reverseDependencyClosure' :: PackageInstalled a => FakeMap -> PackageIndex a -> [InstalledPackageId] -> [a] reverseDependencyClosure' fakeMap index = map vertexToPkg . concatMap Tree.flatten . Graph.dfs reverseDepGraph . map (fromMaybe noSuchPkgId . pkgIdToVertex) where (depGraph, vertexToPkg, pkgIdToVertex) = dependencyGraph' fakeMap index reverseDepGraph = Graph.transposeG depGraph noSuchPkgId = error "reverseDependencyClosure: package is not in the graph" topologicalOrder :: PackageInstalled a => PackageIndex a -> [a] topologicalOrder index = map toPkgId . Graph.topSort $ graph where (graph, toPkgId, _) = dependencyGraph index reverseTopologicalOrder :: PackageInstalled a => PackageIndex a -> [a] reverseTopologicalOrder index = map toPkgId . Graph.topSort . Graph.transposeG $ graph where (graph, toPkgId, _) = dependencyGraph index -- | Builds a graph of the package dependencies. -- -- Dependencies on other packages that are not in the index are discarded. -- You can check if there are any such dependencies with 'brokenPackages'. -- dependencyGraph :: PackageInstalled a => PackageIndex a -> (Graph.Graph, Graph.Vertex -> a, InstalledPackageId -> Maybe Graph.Vertex) dependencyGraph = dependencyGraph' Map.empty -- | Variant of 'dependencyGraph' which accepts a 'FakeMap'. See Note [FakeMap]. dependencyGraph' :: PackageInstalled a => FakeMap -> PackageIndex a -> (Graph.Graph, Graph.Vertex -> a, InstalledPackageId -> Maybe Graph.Vertex) dependencyGraph' fakeMap index = (graph, vertex_to_pkg, id_to_vertex) where graph = Array.listArray bounds [ [ v | Just v <- map id_to_vertex (installedDepends pkg) ] | pkg <- pkgs ] pkgs = sortBy (comparing packageId) (allPackages index) vertices = zip (map installedPackageId pkgs) [0..] vertex_map = Map.fromList vertices id_to_vertex pid = Map.lookup (Map.findWithDefault pid pid fakeMap) vertex_map vertex_to_pkg vertex = pkgTable ! vertex pkgTable = Array.listArray bounds pkgs topBound = length pkgs - 1 bounds = (0, topBound) -- | Given a package index where we assume we want to use all the packages -- (use 'dependencyClosure' if you need to get such a index subset) find out -- if the dependencies within it use consistent versions of each package. -- Return all cases where multiple packages depend on different versions of -- some other package. -- -- Each element in the result is a package name along with the packages that -- depend on it and the versions they require. These are guaranteed to be -- distinct. -- dependencyInconsistencies :: PackageInstalled a => PackageIndex a -> [(PackageName, [(PackageId, Version)])] dependencyInconsistencies = dependencyInconsistencies' Map.empty -- | Variant of 'dependencyInconsistencies' which accepts a 'FakeMap'. See Note [FakeMap]. dependencyInconsistencies' :: PackageInstalled a => FakeMap -> PackageIndex a -> [(PackageName, [(PackageId, Version)])] dependencyInconsistencies' fakeMap index = [ (name, [ (pid,packageVersion dep) | (dep,pids) <- uses, pid <- pids]) | (name, ipid_map) <- Map.toList inverseIndex , let uses = Map.elems ipid_map , reallyIsInconsistent (map fst uses) ] where -- for each PackageName, -- for each package with that name, -- the InstalledPackageInfo and the package Ids of packages -- that depend on it. inverseIndex = Map.fromListWith (Map.unionWith (\(a,b) (_,b') -> (a,b++b'))) [ (packageName dep, Map.fromList [(ipid,(dep,[packageId pkg]))]) | pkg <- allPackages index , ipid <- fakeInstalledDepends fakeMap pkg , Just dep <- [fakeLookupInstalledPackageId fakeMap index ipid] ] reallyIsInconsistent :: PackageInstalled a => [a] -> Bool reallyIsInconsistent [] = False reallyIsInconsistent [_p] = False reallyIsInconsistent [p1, p2] = let pid1 = installedPackageId p1 pid2 = installedPackageId p2 in Map.findWithDefault pid1 pid1 fakeMap `notElem` fakeInstalledDepends fakeMap p2 && Map.findWithDefault pid2 pid2 fakeMap `notElem` fakeInstalledDepends fakeMap p1 reallyIsInconsistent _ = True -- | Variant of 'installedDepends' which accepts a 'FakeMap'. See Note [FakeMap]. fakeInstalledDepends :: PackageInstalled a => FakeMap -> a -> [InstalledPackageId] fakeInstalledDepends fakeMap = map (\pid -> Map.findWithDefault pid pid fakeMap) . installedDepends -- | A rough approximation of GHC's module finder, takes a 'InstalledPackageIndex' and -- turns it into a map from module names to their source packages. It's used to -- initialize the @build-deps@ field in @cabal init@. moduleNameIndex :: InstalledPackageIndex -> Map ModuleName [InstalledPackageInfo] moduleNameIndex index = Map.fromListWith (++) $ do pkg <- allPackages index IPI.ExposedModule m reexport _ <- IPI.exposedModules pkg case reexport of Nothing -> return (m, [pkg]) Just (IPI.OriginalModule _ m') | m == m' -> [] | otherwise -> return (m', [pkg]) -- The heuristic is this: we want to prefer the original package -- which originally exported a module. However, if a reexport -- also *renamed* the module (m /= m'), then we have to use the -- downstream package, since the upstream package has the wrong -- module name!
christiaanb/cabal
Cabal/Distribution/Simple/PackageIndex.hs
bsd-3-clause
26,576
0
19
6,073
5,097
2,764
2,333
356
5
import Logic.BasicGate main :: IO () main = do putStrLn ("[L,L]->" ++ (show $ lc_and [sLO,sLO])) putStrLn ("[L,H]->" ++ (show $ lc_and [sLO,sHI])) putStrLn ("[H,L]->" ++ (show $ lc_and [sHI,sLO])) putStrLn ("[H,H]->" ++ (show $ lc_and [sHI,sHI]))
eijian/mkcpu
test/TestGate.hs
bsd-3-clause
258
0
13
48
137
71
66
7
1
{-# LANGUAGE Rank2Types, TemplateHaskell #-} module Data.Foldable1 where import Control.Arrow import Data.Functor1 import Language.Haskell.TH import Language.Haskell.TH.Util class Functor1 f => Foldable1 f where foldrf :: (forall a. g a -> r -> r) -> r -> f g -> r collect :: Foldable1 f => (forall a. g a -> v) -> f g -> [v] collect f = foldrf (\v ac -> f v : ac) [] mkFoldable1 :: Name -> Q [Dec] mkFoldable1 = withTyConReify mkFoldable1' mkFoldable1' :: Dec -> Q [Dec] mkFoldable1' (DataD _ tnm pars cons _) = do names <- mapM newName $ map (('v':) . show) [1..(30 :: Int)] let (ps, f) = (\(x: xs) -> (reverse xs, x)) $ reverse $ map getTV pars funcName = mkName "f" baseName = mkName "b" mkCons c = let (cnm, tps) = getCons c (insts, exps) = unzip $ zipWith mkType names tps in ( concat insts , Clause [VarP funcName, VarP baseName, ConP cnm $ map VarP $ take (length exps) names] (NormalB $ foldr AppE (VarE baseName) exps) [] ) mkType vnm (AppT tf a) | tf == VarT f = ([], VarE funcName `AppE` VarE vnm) | a == VarT f = ([tf], VarE (mkName "foldrf") `AppE` VarE funcName `AppE` VarE vnm) mkType vnm _ = ([], VarE vnm) (preds, clauses) = first concat $ unzip $ map mkCons cons return [InstanceD (map (ClassP (mkName "Foldable1") . (:[])) preds) (ConT (mkName "Foldable1") `AppT` (foldl AppT (ConT tnm) $ map VarT ps)) [FunD (mkName "foldrf") clauses] ] mkFoldable1' _ = error "Can only derive Foldable1 for data type"
craffit/flexdb
src/Data/Foldable1.hs
bsd-3-clause
1,711
0
18
552
722
370
352
35
2
module Test3 where import qualified Data.HashMap.Strict as H import qualified Data.ByteString.Char8 as BS import Data.List isAlpha ch = 'a' <= ch && ch <= 'z' wrds :: BS.ByteString -> [ BS.ByteString ] wrds bs = let (_, r1) = BS.span (not . isAlpha) bs (w, r2) = BS.span isAlpha r1 in if BS.null w then [] else w : wrds r2 readDict = do allwords <- fmap wrds $ BS.readFile "big.lower" let h = foldl' add H.empty allwords add h w = let c = H.lookupDefault (0 :: Int) w h in H.insert w (c+1) h member = \k -> H.member k h frequency = \k -> H.lookupDefault 0 k h return (member, frequency, BS.pack)
erantapaa/test-spelling
src/Test3.hs
bsd-3-clause
659
0
15
178
291
153
138
19
2
{-# LANGUAGE CPP, ForeignFunctionInterface #-} {-# OPTIONS_NHC98 -cpp #-} {-# OPTIONS_JHC -fcpp -fffi #-} ----------------------------------------------------------------------------- -- | -- Module : Distribution.Simple.Utils -- Copyright : Isaac Jones, Simon Marlow 2003-2004 -- portions Copyright (c) 2007, Galois Inc. -- -- Maintainer : cabal-devel@haskell.org -- Portability : portable -- -- A large and somewhat miscellaneous collection of utility functions used -- throughout the rest of the Cabal lib and in other tools that use the Cabal -- lib like @cabal-install@. It has a very simple set of logging actions. It -- has low level functions for running programs, a bunch of wrappers for -- various directory and file functions that do extra logging. {- 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 Isaac Jones nor the names of other 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 OWNER 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 Distribution.Simple.Utils ( cabalVersion, cabalBootstrapping, -- * logging and errors die, dieWithLocation, warn, notice, setupMessage, info, debug, chattyTry, -- * running programs rawSystemExit, rawSystemStdout, rawSystemStdout', maybeExit, xargs, -- * copying files smartCopySources, createDirectoryIfMissingVerbose, copyFileVerbose, copyDirectoryRecursiveVerbose, copyFiles, -- * installing files installOrdinaryFile, installExecutableFile, installOrdinaryFiles, installDirectoryContents, -- * file names currentDir, -- * finding files findFile, findFileWithExtension, findFileWithExtension', findModuleFile, findModuleFiles, getDirectoryContentsRecursive, -- * simple file globbing matchFileGlob, matchDirFileGlob, parseFileGlob, FileGlob(..), -- * temp files and dirs withTempFile, withTempDirectory, -- * .cabal and .buildinfo files defaultPackageDesc, findPackageDesc, defaultHookedPackageDesc, findHookedPackageDesc, -- * reading and writing files safely withFileContents, writeFileAtomic, rewriteFile, -- * Unicode fromUTF8, toUTF8, readUTF8File, withUTF8FileContents, writeUTF8File, -- * generic utils equating, comparing, isInfixOf, intercalate, lowercase, wrapText, wrapLine, ) where import Control.Monad ( when, unless, filterM ) import Data.List ( nub, unfoldr, isPrefixOf, tails, intersperse ) import Data.Char as Char ( toLower, chr, ord ) import Data.Bits ( Bits((.|.), (.&.), shiftL, shiftR) ) import System.Directory ( getDirectoryContents, doesDirectoryExist, doesFileExist, removeFile ) import System.Environment ( getProgName ) import System.Cmd ( rawSystem ) import System.Exit ( exitWith, ExitCode(..) ) import System.FilePath ( normalise, (</>), (<.>), takeDirectory, splitFileName , splitExtension, splitExtensions ) import System.Directory ( createDirectoryIfMissing, renameFile, removeDirectoryRecursive ) import System.IO ( Handle, openFile, openBinaryFile, IOMode(ReadMode), hSetBinaryMode , hGetContents, stderr, stdout, hPutStr, hFlush, hClose ) import System.IO.Error as IO.Error ( isDoesNotExistError ) import System.IO.Unsafe ( unsafeInterleaveIO ) import qualified Control.Exception as Exception import Distribution.Text ( display ) import Distribution.Package ( PackageIdentifier ) import Distribution.ModuleName (ModuleName) import qualified Distribution.ModuleName as ModuleName import Distribution.Version (Version(..)) import Control.Exception (evaluate) #ifdef __GLASGOW_HASKELL__ import Control.Concurrent (forkIO) import System.Process (runInteractiveProcess, waitForProcess) #else import System.Cmd (system) import System.Directory (getTemporaryDirectory) #endif import Distribution.Compat.CopyFile ( copyFile, copyOrdinaryFile, copyExecutableFile ) import Distribution.Compat.TempFile ( openTempFile, openNewBinaryFile, createTempDirectory ) import Distribution.Compat.Exception (catchIO, onException) import Distribution.Verbosity -- We only get our own version number when we're building with ourselves cabalVersion :: Version #ifdef CABAL_VERSION cabalVersion = Version [CABAL_VERSION] [] #else cabalVersion = error "Cabal was not bootstrapped correctly" #endif cabalBootstrapping :: Bool #ifdef CABAL_VERSION cabalBootstrapping = False #else cabalBootstrapping = True #endif -- ------------------------------------------------------------------------------- Utils for setup dieWithLocation :: FilePath -> Maybe Int -> String -> IO a dieWithLocation filename lineno msg = die $ normalise filename ++ maybe "" (\n -> ":" ++ show n) lineno ++ ": " ++ msg die :: String -> IO a die msg = do hFlush stdout pname <- getProgName hPutStr stderr (wrapText (pname ++ ": " ++ msg)) exitWith (ExitFailure 1) -- | Non fatal conditions that may be indicative of an error or problem. -- -- We display these at the 'normal' verbosity level. -- warn :: Verbosity -> String -> IO () warn verbosity msg = when (verbosity >= normal) $ do hFlush stdout hPutStr stderr (wrapText ("Warning: " ++ msg)) -- | Useful status messages. -- -- We display these at the 'normal' verbosity level. -- -- This is for the ordinary helpful status messages that users see. Just -- enough information to know that things are working but not floods of detail. -- notice :: Verbosity -> String -> IO () notice verbosity msg = when (verbosity >= normal) $ putStr (wrapText msg) setupMessage :: Verbosity -> String -> PackageIdentifier -> IO () setupMessage verbosity msg pkgid = notice verbosity (msg ++ ' ': display pkgid ++ "...") -- | More detail on the operation of some action. -- -- We display these messages when the verbosity level is 'verbose' -- info :: Verbosity -> String -> IO () info verbosity msg = when (verbosity >= verbose) $ putStr (wrapText msg) -- | Detailed internal debugging information -- -- We display these messages when the verbosity level is 'deafening' -- debug :: Verbosity -> String -> IO () debug verbosity msg = when (verbosity >= deafening) $ do putStr (wrapText msg) hFlush stdout -- | Perform an IO action, catching any IO exceptions and printing an error -- if one occurs. chattyTry :: String -- ^ a description of the action we were attempting -> IO () -- ^ the action itself -> IO () chattyTry desc action = catchIO action $ \exception -> putStrLn $ "Error while " ++ desc ++ ": " ++ show exception -- ----------------------------------------------------------------------------- -- Helper functions -- | Wraps text to the default line width. Existing newlines are preserved. wrapText :: String -> String wrapText = unlines . concatMap (map unwords . wrapLine 79 . words) . lines -- | Wraps a list of words to a list of lines of words of a particular width. wrapLine :: Int -> [String] -> [[String]] wrapLine width = wrap 0 [] where wrap :: Int -> [String] -> [String] -> [[String]] wrap 0 [] (w:ws) | length w + 1 > width = wrap (length w) [w] ws wrap col line (w:ws) | col + length w + 1 > width = reverse line : wrap 0 [] (w:ws) wrap col line (w:ws) = let col' = col + length w + 1 in wrap col' (w:line) ws wrap _ [] [] = [] wrap _ line [] = [reverse line] -- ----------------------------------------------------------------------------- -- rawSystem variants maybeExit :: IO ExitCode -> IO () maybeExit cmd = do res <- cmd unless (res == ExitSuccess) $ exitWith res printRawCommandAndArgs :: Verbosity -> FilePath -> [String] -> IO () printRawCommandAndArgs verbosity path args | verbosity >= deafening = print (path, args) | verbosity >= verbose = putStrLn $ unwords (path : args) | otherwise = return () -- Exit with the same exitcode if the subcommand fails rawSystemExit :: Verbosity -> FilePath -> [String] -> IO () rawSystemExit verbosity path args = do printRawCommandAndArgs verbosity path args hFlush stdout exitcode <- rawSystem path args unless (exitcode == ExitSuccess) $ do debug verbosity $ path ++ " returned " ++ show exitcode exitWith exitcode -- | Run a command and return its output. -- -- The output is assumed to be encoded as UTF8. -- rawSystemStdout :: Verbosity -> FilePath -> [String] -> IO String rawSystemStdout verbosity path args = do (output, exitCode) <- rawSystemStdout' verbosity path args unless (exitCode == ExitSuccess) $ exitWith exitCode return output rawSystemStdout' :: Verbosity -> FilePath -> [String] -> IO (String, ExitCode) rawSystemStdout' verbosity path args = do printRawCommandAndArgs verbosity path args #ifdef __GLASGOW_HASKELL__ Exception.bracket (runInteractiveProcess path args Nothing Nothing) (\(inh,outh,errh,_) -> hClose inh >> hClose outh >> hClose errh) $ \(_,outh,errh,pid) -> do -- We want to process the output as text. hSetBinaryMode outh False -- fork off a thread to pull on (and discard) the stderr -- so if the process writes to stderr we do not block. -- NB. do the hGetContents synchronously, otherwise the outer -- bracket can exit before this thread has run, and hGetContents -- will fail. err <- hGetContents errh forkIO $ do evaluate (length err); return () -- wait for all the output output <- hGetContents outh evaluate (length output) -- wait for the program to terminate exitcode <- waitForProcess pid unless (exitcode == ExitSuccess) $ debug verbosity $ path ++ " returned " ++ show exitcode ++ if null err then "" else " with error message:\n" ++ err return (output, exitcode) #else tmpDir <- getTemporaryDirectory withTempFile tmpDir ".cmd.stdout" $ \tmpName tmpHandle -> do hClose tmpHandle let quote name = "'" ++ name ++ "'" exitcode <- system $ unwords (map quote (path:args)) ++ " >" ++ quote tmpName unless (exitcode == ExitSuccess) $ debug verbosity $ path ++ " returned " ++ show exitcode withFileContents tmpName $ \output -> length output `seq` return (output, exitcode) #endif -- | Like the unix xargs program. Useful for when we've got very long command -- lines that might overflow an OS limit on command line length and so you -- need to invoke a command multiple times to get all the args in. -- -- Use it with either of the rawSystem variants above. For example: -- -- > xargs (32*1024) (rawSystemExit verbosity) prog fixedArgs bigArgs -- xargs :: Int -> ([String] -> IO ()) -> [String] -> [String] -> IO () xargs maxSize rawSystemFun fixedArgs bigArgs = let fixedArgSize = sum (map length fixedArgs) + length fixedArgs chunkSize = maxSize - fixedArgSize in mapM_ (rawSystemFun . (fixedArgs ++)) (chunks chunkSize bigArgs) where chunks len = unfoldr $ \s -> if null s then Nothing else Just (chunk [] len s) chunk acc _ [] = (reverse acc,[]) chunk acc len (s:ss) | len' < len = chunk (s:acc) (len-len'-1) ss | otherwise = (reverse acc, s:ss) where len' = length s -- ------------------------------------------------------------ -- * File Utilities -- ------------------------------------------------------------ ---------------- -- Finding files -- | Find a file by looking in a search path. The file path must match exactly. -- findFile :: [FilePath] -- ^search locations -> FilePath -- ^File Name -> IO FilePath findFile searchPath fileName = findFirstFile id [ path </> fileName | path <- nub searchPath] >>= maybe (die $ fileName ++ " doesn't exist") return -- | Find a file by looking in a search path with one of a list of possible -- file extensions. The file base name should be given and it will be tried -- with each of the extensions in each element of the search path. -- findFileWithExtension :: [String] -> [FilePath] -> FilePath -> IO (Maybe FilePath) findFileWithExtension extensions searchPath baseName = findFirstFile id [ path </> baseName <.> ext | path <- nub searchPath , ext <- nub extensions ] -- | Like 'findFileWithExtension' but returns which element of the search path -- the file was found in, and the file path relative to that base directory. -- findFileWithExtension' :: [String] -> [FilePath] -> FilePath -> IO (Maybe (FilePath, FilePath)) findFileWithExtension' extensions searchPath baseName = findFirstFile (uncurry (</>)) [ (path, baseName <.> ext) | path <- nub searchPath , ext <- nub extensions ] findFirstFile :: (a -> FilePath) -> [a] -> IO (Maybe a) findFirstFile file = findFirst where findFirst [] = return Nothing findFirst (x:xs) = do exists <- doesFileExist (file x) if exists then return (Just x) else findFirst xs -- | Finds the files corresponding to a list of Haskell module names. -- -- As 'findModuleFile' but for a list of module names. -- findModuleFiles :: [FilePath] -- ^ build prefix (location of objects) -> [String] -- ^ search suffixes -> [ModuleName] -- ^ modules -> IO [(FilePath, FilePath)] findModuleFiles searchPath extensions moduleNames = mapM (findModuleFile searchPath extensions) moduleNames -- | Find the file corresponding to a Haskell module name. -- -- This is similar to 'findFileWithExtension'' but specialised to a module -- name. The function fails if the file corresponding to the module is missing. -- findModuleFile :: [FilePath] -- ^ build prefix (location of objects) -> [String] -- ^ search suffixes -> ModuleName -- ^ module -> IO (FilePath, FilePath) findModuleFile searchPath extensions moduleName = maybe notFound return =<< findFileWithExtension' extensions searchPath (ModuleName.toFilePath moduleName) where notFound = die $ "Error: Could not find module: " ++ display moduleName ++ " with any suffix: " ++ show extensions ++ " in the search path: " ++ show searchPath -- | List all the files in a directory and all subdirectories. -- -- The order places files in sub-directories after all the files in their -- parent directories. The list is generated lazily so is not well defined if -- the source directory structure changes before the list is used. -- getDirectoryContentsRecursive :: FilePath -> IO [FilePath] getDirectoryContentsRecursive topdir = recurseDirectories [""] where recurseDirectories :: [FilePath] -> IO [FilePath] recurseDirectories [] = return [] recurseDirectories (dir:dirs) = unsafeInterleaveIO $ do (files, dirs') <- collect [] [] =<< getDirectoryContents (topdir </> dir) files' <- recurseDirectories (dirs' ++ dirs) return (files ++ files') where collect files dirs' [] = return (reverse files, reverse dirs') collect files dirs' (entry:entries) | ignore entry = collect files dirs' entries collect files dirs' (entry:entries) = do let dirEntry = dir </> entry isDirectory <- doesDirectoryExist (topdir </> dirEntry) if isDirectory then collect files (dirEntry:dirs') entries else collect (dirEntry:files) dirs' entries ignore ['.'] = True ignore ['.', '.'] = True ignore _ = False ---------------- -- File globbing data FileGlob -- | No glob at all, just an ordinary file = NoGlob FilePath -- | dir prefix and extension, like @\"foo\/bar\/\*.baz\"@ corresponds to -- @FileGlob \"foo\/bar\" \".baz\"@ | FileGlob FilePath String parseFileGlob :: FilePath -> Maybe FileGlob parseFileGlob filepath = case splitExtensions filepath of (filepath', ext) -> case splitFileName filepath' of (dir, "*") | '*' `elem` dir || '*' `elem` ext || null ext -> Nothing | null dir -> Just (FileGlob "." ext) | otherwise -> Just (FileGlob dir ext) _ | '*' `elem` filepath -> Nothing | otherwise -> Just (NoGlob filepath) matchFileGlob :: FilePath -> IO [FilePath] matchFileGlob = matchDirFileGlob "." matchDirFileGlob :: FilePath -> FilePath -> IO [FilePath] matchDirFileGlob dir filepath = case parseFileGlob filepath of Nothing -> die $ "invalid file glob '" ++ filepath ++ "'. Wildcards '*' are only allowed in place of the file" ++ " name, not in the directory name or file extension." ++ " If a wildcard is used it must be with an file extension." Just (NoGlob filepath') -> return [filepath'] Just (FileGlob dir' ext) -> do files <- getDirectoryContents (dir </> dir') case [ dir' </> file | file <- files , let (name, ext') = splitExtensions file , not (null name) && ext' == ext ] of [] -> die $ "filepath wildcard '" ++ filepath ++ "' does not match any files." matches -> return matches ---------------------------------------- -- Copying and installing files and dirs -- | Same as 'createDirectoryIfMissing' but logs at higher verbosity levels. -- createDirectoryIfMissingVerbose :: Verbosity -> Bool -> FilePath -> IO () createDirectoryIfMissingVerbose verbosity parentsToo dir = do let msgParents = if parentsToo then " (and its parents)" else "" info verbosity ("Creating " ++ dir ++ msgParents) createDirectoryIfMissing parentsToo dir -- | Copies a file without copying file permissions. The target file is created -- with default permissions. Any existing target file is replaced. -- -- At higher verbosity levels it logs an info message. -- copyFileVerbose :: Verbosity -> FilePath -> FilePath -> IO () copyFileVerbose verbosity src dest = do info verbosity ("copy " ++ src ++ " to " ++ dest) copyFile src dest -- | Install an ordinary file. This is like a file copy but the permissions -- are set appropriately for an installed file. On Unix it is \"-rw-r--r--\" -- while on Windows it uses the default permissions for the target directory. -- installOrdinaryFile :: Verbosity -> FilePath -> FilePath -> IO () installOrdinaryFile verbosity src dest = do info verbosity ("Installing " ++ src ++ " to " ++ dest) copyOrdinaryFile src dest -- | Install an executable file. This is like a file copy but the permissions -- are set appropriately for an installed file. On Unix it is \"-rwxr-xr-x\" -- while on Windows it uses the default permissions for the target directory. -- installExecutableFile :: Verbosity -> FilePath -> FilePath -> IO () installExecutableFile verbosity src dest = do info verbosity ("Installing executable " ++ src ++ " to " ++ dest) copyExecutableFile src dest -- | Copies a bunch of files to a target directory, preserving the directory -- structure in the target location. The target directories are created if they -- do not exist. -- -- The files are identified by a pair of base directory and a path relative to -- that base. It is only the relative part that is preserved in the -- destination. -- -- For example: -- -- > copyFiles normal "dist/src" -- > [("", "src/Foo.hs"), ("dist/build/", "src/Bar.hs")] -- -- This would copy \"src\/Foo.hs\" to \"dist\/src\/src\/Foo.hs\" and -- copy \"dist\/build\/src\/Bar.hs\" to \"dist\/src\/src\/Bar.hs\". -- -- This operation is not atomic. Any IO failure during the copy (including any -- missing source files) leaves the target in an unknown state so it is best to -- use it with a freshly created directory so that it can be simply deleted if -- anything goes wrong. -- copyFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO () copyFiles verbosity targetDir srcFiles = do -- Create parent directories for everything let dirs = map (targetDir </>) . nub . map (takeDirectory . snd) $ srcFiles mapM_ (createDirectoryIfMissingVerbose verbosity True) dirs -- Copy all the files sequence_ [ let src = srcBase </> srcFile dest = targetDir </> srcFile in copyFileVerbose verbosity src dest | (srcBase, srcFile) <- srcFiles ] -- | This is like 'copyFiles' but uses 'installOrdinaryFile'. -- installOrdinaryFiles :: Verbosity -> FilePath -> [(FilePath, FilePath)] -> IO () installOrdinaryFiles verbosity targetDir srcFiles = do -- Create parent directories for everything let dirs = map (targetDir </>) . nub . map (takeDirectory . snd) $ srcFiles mapM_ (createDirectoryIfMissingVerbose verbosity True) dirs -- Copy all the files sequence_ [ let src = srcBase </> srcFile dest = targetDir </> srcFile in installOrdinaryFile verbosity src dest | (srcBase, srcFile) <- srcFiles ] -- | This installs all the files in a directory to a target location, -- preserving the directory layout. All the files are assumed to be ordinary -- rather than executable files. -- installDirectoryContents :: Verbosity -> FilePath -> FilePath -> IO () installDirectoryContents verbosity srcDir destDir = do info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.") srcFiles <- getDirectoryContentsRecursive srcDir installOrdinaryFiles verbosity destDir [ (srcDir, f) | f <- srcFiles ] --------------------------------- -- Deprecated file copy functions {-# DEPRECATED smartCopySources "Use findModuleFiles and copyFiles or installOrdinaryFiles" #-} smartCopySources :: Verbosity -> [FilePath] -> FilePath -> [ModuleName] -> [String] -> IO () smartCopySources verbosity searchPath targetDir moduleNames extensions = findModuleFiles searchPath extensions moduleNames >>= copyFiles verbosity targetDir {-# DEPRECATED copyDirectoryRecursiveVerbose "You probably want installDirectoryContents instead" #-} copyDirectoryRecursiveVerbose :: Verbosity -> FilePath -> FilePath -> IO () copyDirectoryRecursiveVerbose verbosity srcDir destDir = do info verbosity ("copy directory '" ++ srcDir ++ "' to '" ++ destDir ++ "'.") srcFiles <- getDirectoryContentsRecursive srcDir copyFiles verbosity destDir [ (srcDir, f) | f <- srcFiles ] --------------------------- -- Temporary files and dirs -- | Use a temporary filename that doesn't already exist. -- withTempFile :: FilePath -- ^ Temp dir to create the file in -> String -- ^ File name template. See 'openTempFile'. -> (FilePath -> Handle -> IO a) -> IO a withTempFile tmpDir template action = Exception.bracket (openTempFile tmpDir template) (\(name, handle) -> hClose handle >> removeFile name) (uncurry action) -- | Use a temporary directory. -- -- Use this exact given dir which must not already exist. -- withTempDirectory :: Verbosity -> FilePath -> String -> (FilePath -> IO a) -> IO a withTempDirectory _verbosity targetDir template = Exception.bracket (createTempDirectory targetDir template) (removeDirectoryRecursive) ----------------------------------- -- Safely reading and writing files -- | Gets the contents of a file, but guarantee that it gets closed. -- -- The file is read lazily but if it is not fully consumed by the action then -- the remaining input is truncated and the file is closed. -- withFileContents :: FilePath -> (String -> IO a) -> IO a withFileContents name action = Exception.bracket (openFile name ReadMode) hClose (\hnd -> hGetContents hnd >>= action) -- | Writes a file atomically. -- -- The file is either written sucessfully or an IO exception is raised and -- the original file is left unchanged. -- -- * Warning: On Windows this operation is very nearly but not quite atomic. -- See below. -- -- On Posix it works by writing a temporary file and atomically renaming over -- the top any pre-existing target file with the temporary one. -- -- On Windows it is not possible to rename over an existing file so the target -- file has to be deleted before the temporary file is renamed to the target. -- Therefore there is a race condition between the existing file being removed -- and the temporary file being renamed. Another thread could write to the -- target or change the permission on the target directory between the deleting -- and renaming steps. An exception would be raised but the target file would -- either no longer exist or have the content as written by the other thread. -- -- On windows it is not possible to delete a file that is open by a process. -- This case will give an IO exception but the atomic property is not affected. -- writeFileAtomic :: FilePath -> String -> IO () writeFileAtomic targetFile content = do (tmpFile, tmpHandle) <- openNewBinaryFile targetDir template do hPutStr tmpHandle content hClose tmpHandle renameFile tmpFile targetFile `onException` do hClose tmpHandle removeFile tmpFile where template = targetName <.> "tmp" targetDir | null targetDir_ = currentDir | otherwise = targetDir_ --TODO: remove this when takeDirectory/splitFileName is fixed -- to always return a valid dir (targetDir_,targetName) = splitFileName targetFile -- | Write a file but only if it would have new content. If we would be writing -- the same as the existing content then leave the file as is so that we do not -- update the file's modification time. -- rewriteFile :: FilePath -> String -> IO () rewriteFile path newContent = flip catch mightNotExist $ do existingContent <- readFile path evaluate (length existingContent) unless (existingContent == newContent) $ writeFileAtomic path newContent where mightNotExist e | isDoesNotExistError e = writeFileAtomic path newContent | otherwise = ioError e -- | The path name that represents the current directory. -- In Unix, it's @\".\"@, but this is system-specific. -- (E.g. AmigaOS uses the empty string @\"\"@ for the current directory.) currentDir :: FilePath currentDir = "." -- ------------------------------------------------------------ -- * Finding the description file -- ------------------------------------------------------------ -- |Package description file (/pkgname/@.cabal@) defaultPackageDesc :: Verbosity -> IO FilePath defaultPackageDesc _verbosity = findPackageDesc currentDir -- |Find a package description file in the given directory. Looks for -- @.cabal@ files. findPackageDesc :: FilePath -- ^Where to look -> IO FilePath -- ^<pkgname>.cabal findPackageDesc dir = do files <- getDirectoryContents dir -- to make sure we do not mistake a ~/.cabal/ dir for a <pkgname>.cabal -- file we filter to exclude dirs and null base file names: cabalFiles <- filterM doesFileExist [ dir </> file | file <- files , let (name, ext) = splitExtension file , not (null name) && ext == ".cabal" ] case cabalFiles of [] -> noDesc [cabalFile] -> return cabalFile multiple -> multiDesc multiple where noDesc :: IO a noDesc = die $ "No cabal file found.\n" ++ "Please create a package description file <pkgname>.cabal" multiDesc :: [String] -> IO a multiDesc l = die $ "Multiple cabal files found.\n" ++ "Please use only one of: " ++ show l -- |Optional auxiliary package information file (/pkgname/@.buildinfo@) defaultHookedPackageDesc :: IO (Maybe FilePath) defaultHookedPackageDesc = findHookedPackageDesc currentDir -- |Find auxiliary package information in the given directory. -- Looks for @.buildinfo@ files. findHookedPackageDesc :: FilePath -- ^Directory to search -> IO (Maybe FilePath) -- ^/dir/@\/@/pkgname/@.buildinfo@, if present findHookedPackageDesc dir = do files <- getDirectoryContents dir buildInfoFiles <- filterM doesFileExist [ dir </> file | file <- files , let (name, ext) = splitExtension file , not (null name) && ext == buildInfoExt ] case buildInfoFiles of [] -> return Nothing [f] -> return (Just f) _ -> die ("Multiple files with extension " ++ buildInfoExt) buildInfoExt :: String buildInfoExt = ".buildinfo" -- ------------------------------------------------------------ -- * Unicode stuff -- ------------------------------------------------------------ -- This is a modification of the UTF8 code from gtk2hs and the -- utf8-string package. fromUTF8 :: String -> String fromUTF8 [] = [] fromUTF8 (c:cs) | c <= '\x7F' = c : fromUTF8 cs | c <= '\xBF' = replacementChar : fromUTF8 cs | c <= '\xDF' = twoBytes c cs | c <= '\xEF' = moreBytes 3 0x800 cs (ord c .&. 0xF) | c <= '\xF7' = moreBytes 4 0x10000 cs (ord c .&. 0x7) | c <= '\xFB' = moreBytes 5 0x200000 cs (ord c .&. 0x3) | c <= '\xFD' = moreBytes 6 0x4000000 cs (ord c .&. 0x1) | otherwise = replacementChar : fromUTF8 cs where twoBytes c0 (c1:cs') | ord c1 .&. 0xC0 == 0x80 = let d = ((ord c0 .&. 0x1F) `shiftL` 6) .|. (ord c1 .&. 0x3F) in if d >= 0x80 then chr d : fromUTF8 cs' else replacementChar : fromUTF8 cs' twoBytes _ cs' = replacementChar : fromUTF8 cs' moreBytes :: Int -> Int -> [Char] -> Int -> [Char] moreBytes 1 overlong cs' acc | overlong <= acc && acc <= 0x10FFFF && (acc < 0xD800 || 0xDFFF < acc) && (acc < 0xFFFE || 0xFFFF < acc) = chr acc : fromUTF8 cs' | otherwise = replacementChar : fromUTF8 cs' moreBytes byteCount overlong (cn:cs') acc | ord cn .&. 0xC0 == 0x80 = moreBytes (byteCount-1) overlong cs' ((acc `shiftL` 6) .|. ord cn .&. 0x3F) moreBytes _ _ cs' _ = replacementChar : fromUTF8 cs' replacementChar = '\xfffd' toUTF8 :: String -> String toUTF8 [] = [] toUTF8 (c:cs) | c <= '\x07F' = c : toUTF8 cs | c <= '\x7FF' = chr (0xC0 .|. (w `shiftR` 6)) : chr (0x80 .|. (w .&. 0x3F)) : toUTF8 cs | c <= '\xFFFF'= chr (0xE0 .|. (w `shiftR` 12)) : chr (0x80 .|. ((w `shiftR` 6) .&. 0x3F)) : chr (0x80 .|. (w .&. 0x3F)) : toUTF8 cs | otherwise = chr (0xf0 .|. (w `shiftR` 18)) : chr (0x80 .|. ((w `shiftR` 12) .&. 0x3F)) : chr (0x80 .|. ((w `shiftR` 6) .&. 0x3F)) : chr (0x80 .|. (w .&. 0x3F)) : toUTF8 cs where w = ord c -- | Reads a UTF8 encoded text file as a Unicode String -- -- Reads lazily using ordinary 'readFile'. -- readUTF8File :: FilePath -> IO String readUTF8File f = fmap fromUTF8 . hGetContents =<< openBinaryFile f ReadMode -- | Reads a UTF8 encoded text file as a Unicode String -- -- Same behaviour as 'withFileContents'. -- withUTF8FileContents :: FilePath -> (String -> IO a) -> IO a withUTF8FileContents name action = Exception.bracket (openBinaryFile name ReadMode) hClose (\hnd -> hGetContents hnd >>= action . fromUTF8) -- | Writes a Unicode String as a UTF8 encoded text file. -- -- Uses 'writeFileAtomic', so provides the same guarantees. -- writeUTF8File :: FilePath -> String -> IO () writeUTF8File path = writeFileAtomic path . toUTF8 -- ------------------------------------------------------------ -- * Common utils -- ------------------------------------------------------------ equating :: Eq a => (b -> a) -> b -> b -> Bool equating p x y = p x == p y comparing :: Ord a => (b -> a) -> b -> b -> Ordering comparing p x y = p x `compare` p y isInfixOf :: String -> String -> Bool isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack) intercalate :: [a] -> [[a]] -> [a] intercalate sep = concat . intersperse sep lowercase :: String -> String lowercase = map Char.toLower
dcreager/cabal
Distribution/Simple/Utils.hs
bsd-3-clause
34,274
0
18
8,420
6,878
3,629
3,249
513
7
type Cartesian = (Double, Double) mulC :: Cartesian -> Double -> Cartesian mulC (x, y) n = (x * n, y * n) point1 :: Cartesian point1 = (8, 5) type Polar = (Double, Double) mulP :: Polar -> Double -> Polar mulP (d, r) n = (d * n, r) point2 :: Polar point2 = (10, pi / 6)
YoshikuniJujo/funpaala
samples/21_adt/cpt.hs
bsd-3-clause
275
0
6
65
143
84
59
10
1
module Appoint.Import (IssueStatus(..)) where import Appoint.IssueStatus(IssueStatus(..))
rob-b/appoint
src/Appoint/Import.hs
bsd-3-clause
91
0
6
7
29
19
10
2
0
{-# LANGUAGE AllowAmbiguousTypes #-} module Patches.Diff3 where import Language.Clojure.AST import Language.Clojure.Lang import Language.Common import VCS.Multirec change a b = As (Contract (a, b)) keep a = change a a recurse a = Ai (AlmuH a) variable a = (Term (TaggedString "Var" a emptyRange) emptyRange) nil = (Nil emptyRange) cons a b c = Cons a b c emptyRange trash1Line = UExpr (Collection "Parens" (cons (variable "trash1") "Space" (cons (variable "trash") "Space" (cons (variable "trash") "Space" nil ))) emptyRange) trash2Line = UExpr (Collection "Parens" (cons (variable "trash3") "Space" (cons (variable "trash") "Space" nil)) emptyRange) lvl1 :: (Almu (ToSing Expr) (ToSing Expr)) lvl1 = Alspn (Scns C3CollectionProof (keep (UString "Parens") .@. recurse lvl2 .@. An)) lvl2 = Alspn (Scns C1ConsProof (recurse (Alspn Scp) .@. keep (UString "Space") .@. recurse lvl3 .@. An)) lvl3 = Alspn (Scns C1ConsProof (recurse (Alspn Scp) .@. keep (UString "NewLine") .@. recurse lvl4 .@. An)) lvl4 = Alspn (Scns C1ConsProof (recurse (Alspn Scp) .@. keep (UString "Space") .@. recurse lvl5 .@. An)) lvl5 = Aldel C1ConsProof (There trash1Line (There (UString "NewLine") (Here (FixNeg (lvl6)) An))) lvl6 = Alspn (Scns C1ConsProof (recurse lvl7 .@. keep (UString "NewLine") .@. recurse lvl8_Del .@. An)) lvl7 = Alspn (Scns C3CollectionProof (keep (UString "Parens") .@. recurse lvl9 .@. An) ) ----------- lvl9 = Alspn (Scns C1ConsProof (recurse (Alspn Scp) .@. keep (UString "Space") .@. recurse lvl10 .@. An)) lvl10 = Alspn (Scns C1ConsProof (recurse (Alspn Scp) .@. keep (UString "Space") .@. recurse tmp .@. An)) tmp = Alspn (Scns C1ConsProof (recurse (Alspn Scp) .@. keep (UString "Space") .@. recurse lvl11 .@. An)) lvl11 = Alspn (Schg C1NilProof C1ConsProof (Ains (UExpr (Term (TaggedString "Var" "new" emptyRange) emptyRange)) ( Ains (UString "Space") ( Ains (USepExprList (Nil emptyRange)) ( A0))))) ------------ lvl8 = Alspn (Scns C1ConsProof (recurse lvl12 .@. keep (UString "NewLine") .@. recurse lvl17 .@. An)) lvl8_Del = Aldel C1ConsProof (There trash2Line (There (UString "NewLine") (Here (FixNeg (Alspn (Scp))) An))) lvl12 = Alspn (Scns C3CollectionProof (keep (UString "Parens") .@. recurse lvl13 .@. An)) lvl13 = Alspn (Scns C1ConsProof (recurse lvl14 .@. keep (UString "Space") .@. recurse lvl15 .@. An)) lvl14 = Alspn (Scns C3TermProof (recurse (Alspn (Scns C6TaggedStringProof (keep (UString "Var") .@. change (UString "trash3") (UString "keep4") .@. An)) ) .@. An)) lvl15 = Alspn (Scns C1ConsProof (recurse lvl16 .@. keep (UString "Space") .@. recurse (Alspn Scp) .@. An)) lvl16 = Alspn (Scns C3TermProof (recurse (Alspn (Scns C6TaggedStringProof (keep (UString "Var") .@. change (UString "trash") (UString "keep") .@. An)) ) .@. An)) lvl17 = Alspn (Schg C1ConsProof C1NilProof (Adel keep4 ( Adel (UString "NewLine") ( Adel (USepExprList (Nil emptyRange)) A0 )))) keep4 = UExpr (Collection "Parens" (Cons (Term (TaggedString "Var" "keep4" emptyRange) emptyRange) "Space" (Cons (Term (TaggedString "Var" "keep" emptyRange) emptyRange) "Space" (Nil emptyRange) emptyRange) emptyRange) emptyRange)
nazrhom/vcs-clojure
src/Patches/Diff3.hs
bsd-3-clause
4,245
0
20
1,584
1,393
691
702
145
1
{-# LANGUAGE InstanceSigs #-} -- c の取り扱いが sml と異なっている(データ構造に c を含めている)点に注意 module PFDS.Commons.BankersDeque where import PFDS.Commons.Deque data BankersDeque a = Q Int Int [a] Int [a] deriving (Show) instance Deque BankersDeque where empty :: BankersDeque a empty = Q 4 0 [] 0 [] isEmpty :: BankersDeque a -> Bool isEmpty (Q _ _ [] _ []) = True isEmpty _ = False cons :: a -> BankersDeque a -> BankersDeque a cons x (Q c lenf f lenr r) = check (Q c (lenf + 1) (x : f) lenr r) head :: BankersDeque a -> a head (Q _ _ [] _ []) = error "empty" head (Q _ _ [] _ (x:_)) = x head (Q _ _ (x:_) _ _) = x tail :: BankersDeque a -> BankersDeque a tail (Q _ _ [] _ []) = error "empty" tail (Q c _ [] _ (_:_)) = emptyc c tail (Q c lenf (_:f') lenr r) = check (Q c (lenf - 1) f' lenr r) snoc :: BankersDeque a -> a -> BankersDeque a snoc (Q c lenf f lenr r) x = check (Q c lenf f (lenr + 1) (x : r)) last :: BankersDeque a -> a last (Q _ _ [] _ []) = error "empty" last (Q _ _ (x:_) _ []) = x last (Q _ _ _ _ (x:_)) = x init :: BankersDeque a -> BankersDeque a init (Q _ _ [] _ []) = error "empty" init (Q c _ (_:_) _ []) = emptyc c init (Q c lenf f lenr (_:r')) = check (Q c lenf f (lenr - 1) r') check :: BankersDeque a -> BankersDeque a check q@(Q c lenf f lenr r) | lenf > c * lenr + 1 = let i = (lenf + lenr) `div` 2 j = lenf + lenr - i f' = take i f r' = r ++ reverse (drop i f) in Q c i f' j r' | lenr > c * lenf + 1 = let j = (lenf + lenr) `div` 2 i = lenf + lenr - j r' = take j r f' = f ++ reverse (drop j r) in Q c i f' j r' | otherwise = q emptyc :: Int -> BankersDeque a emptyc c = Q c 0 [] 0 []
matonix/pfds
src/PFDS/Commons/BankersDeque.hs
bsd-3-clause
1,830
0
13
570
1,019
515
504
47
1
module Pos.Chain.Lrc.Error ( LrcError (..) ) where import Universum import Formatting (bprint, build, int, stext, (%)) import qualified Formatting.Buildable import Pos.Core.Slotting (EpochIndex) data LrcError = LrcDataUnknown !EpochIndex !Text | UnknownBlocksForLrc | CanNotReuseSeedForLrc !EpochIndex | LrcAfterGenesis deriving (Show) instance Exception LrcError instance Buildable LrcError where build (LrcDataUnknown epoch reason) = bprint ("LRC data isn't presented for epoch #"%int% " so raise the exception with reason: "%stext) epoch reason build UnknownBlocksForLrc = bprint "there are no blocks for LRC computation" build (CanNotReuseSeedForLrc epoch) = bprint ("LRC attempted to reuse seed from previous epoch "% "(i.e. epoch "%build%"), but the seed wasn't in the db") epoch build LrcAfterGenesis = bprint "LRC was attempted after adoption of genesis block"
input-output-hk/pos-haskell-prototype
chain/src/Pos/Chain/Lrc/Error.hs
mit
1,049
0
10
295
200
110
90
33
0
{-# OPTIONS_GHC -fglasgow-exts #-} ----------------------------------------------------------------------------- -- | -- Module : Control.Morphism.Cata -- Copyright : (C) 2008 Edward Kmett -- License : BSD-style (see the file LICENSE) -- -- Maintainer : Edward Kmett <ekmett@gmail.com> -- Stability : experimental -- Portability : non-portable (rank-2 polymorphism) -- ---------------------------------------------------------------------------- module Control.Morphism.Cata ( cata, g_cata, distCata , bicata, g_bicata , hcata , kcata, runkcata ) where import Control.Comonad import Control.Category.Hask import Control.Functor import Control.Functor.Pointed import Control.Functor.Algebra import Control.Functor.Extras import Control.Functor.Fix import Control.Functor.HigherOrder import Control.Functor.KanExtension import Control.Functor.KanExtension.Interpreter import Control.Monad.Identity cata :: Functor f => Algebra f a -> FixF f -> a cata f = f . fmap (cata f) . outF -- cata f = g_cata distCata (liftAlgebra f) g_cata :: (Functor f, Comonad w) => Dist f w -> GAlgebra f w a -> FixF f -> a g_cata k g = extract . c where c = liftW g . k . fmap (duplicate . c) . outF -- g_cata k f = g_hylo k distAna f id outM distCata :: Functor f => Dist f Identity distCata = Identity . fmap runIdentity bicata :: QFunctor f Hask Hask => Algebra (f b) a -> Fix f b -> a bicata f = f . second (bicata f) . outB g_bicata :: (QFunctor f Hask Hask, Comonad w) => Dist (f b) w -> GAlgebra (f b) w a -> Fix f b -> a g_bicata k g = extract . c where c = liftW g . k . second (duplicate . c) . outB hcata :: HFunctor f => HAlgebra f a -> FixH f :~> a hcata f = f . hfmap (hcata f) . outH kcata :: HFunctor f => InterpreterT f g h -> FixH f :~> Ran g h kcata i = hcata (interpreterAlgebra i) runkcata :: HFunctor f => InterpreterT f g h -> FixH f a -> (a -> g b) -> h b runkcata i = runRan . kcata i
urska19/MFP---Samodejno-racunanje-dvosmernih-preslikav
Control/Morphism/Cata.hs
apache-2.0
1,924
4
11
363
636
331
305
-1
-1
{- POSIX files (and compatablity wrappers). - - This is like System.PosixCompat.Files, but with a few fixes. - - Copyright 2014 Joey Hess <id@joeyh.name> - - License: BSD-2-clause -} {-# LANGUAGE CPP #-} {-# OPTIONS_GHC -fno-warn-tabs #-} module Utility.PosixFiles ( module X, rename ) where import System.PosixCompat.Files as X hiding (rename) #ifndef mingw32_HOST_OS import System.Posix.Files (rename) #else import qualified System.Win32.File as Win32 import qualified System.Win32.HardLink as Win32 #endif {- System.PosixCompat.Files.rename on Windows calls renameFile, - so cannot rename directories. - - Instead, use Win32 moveFile, which can. It needs to be told to overwrite - any existing file. -} #ifdef mingw32_HOST_OS rename :: FilePath -> FilePath -> IO () rename src dest = Win32.moveFileEx src dest Win32.mOVEFILE_REPLACE_EXISTING #endif {- System.PosixCompat.Files.createLink throws an error, but windows - does support hard links. -} #ifdef mingw32_HOST_OS createLink :: FilePath -> FilePath -> IO () createLink = Win32.createHardLink #endif
ArchiveTeam/glowing-computing-machine
src/Utility/PosixFiles.hs
bsd-2-clause
1,079
4
8
166
120
73
47
7
0
{- (c) The University of Glasgow 2006 (c) The AQUA Project, Glasgow University, 1998 Desugaring foreign declarations (see also DsCCall). -} {-# LANGUAGE CPP #-} module DsForeign ( dsForeigns , dsForeigns' , dsFImport, dsCImport, dsFCall, dsPrimCall , dsFExport, dsFExportDynamic, mkFExportCBits , toCType , foreignExportInitialiser ) where #include "HsVersions.h" import TcRnMonad -- temp import TypeRep import CoreSyn import DsCCall import DsMonad import HsSyn import DataCon import CoreUnfold import Id import Literal import Module import Name import Type import TyCon import Coercion import TcEnv import TcType import CmmExpr import CmmUtils import HscTypes import ForeignCall import TysWiredIn import TysPrim import PrelNames import BasicTypes import SrcLoc import Outputable import FastString import DynFlags import Platform import Config import OrdList import Pair import Util import Hooks import Data.Maybe import Data.List {- Desugaring of @foreign@ declarations is naturally split up into parts, an @import@ and an @export@ part. A @foreign import@ declaration \begin{verbatim} foreign import cc nm f :: prim_args -> IO prim_res \end{verbatim} is the same as \begin{verbatim} f :: prim_args -> IO prim_res f a1 ... an = _ccall_ nm cc a1 ... an \end{verbatim} so we reuse the desugaring code in @DsCCall@ to deal with these. -} type Binding = (Id, CoreExpr) -- No rec/nonrec structure; -- the occurrence analyser will sort it all out dsForeigns :: [LForeignDecl Id] -> DsM (ForeignStubs, OrdList Binding) dsForeigns fos = getHooked dsForeignsHook dsForeigns' >>= ($ fos) dsForeigns' :: [LForeignDecl Id] -> DsM (ForeignStubs, OrdList Binding) dsForeigns' [] = return (NoStubs, nilOL) dsForeigns' fos = do fives <- mapM do_ldecl fos let (hs, cs, idss, bindss) = unzip4 fives fe_ids = concat idss fe_init_code = map foreignExportInitialiser fe_ids -- return (ForeignStubs (vcat hs) (vcat cs $$ vcat fe_init_code), foldr (appOL . toOL) nilOL bindss) where do_ldecl (L loc decl) = putSrcSpanDs loc (do_decl decl) do_decl (ForeignImport id _ co spec) = do traceIf (text "fi start" <+> ppr id) (bs, h, c) <- dsFImport (unLoc id) co spec traceIf (text "fi end" <+> ppr id) return (h, c, [], bs) do_decl (ForeignExport (L _ id) _ co (CExport (L _ (CExportStatic ext_nm cconv)) _)) = do (h, c, _, _) <- dsFExport id co ext_nm cconv False return (h, c, [id], []) {- ************************************************************************ * * \subsection{Foreign import} * * ************************************************************************ Desugaring foreign imports is just the matter of creating a binding that on its RHS unboxes its arguments, performs the external call (using the @CCallOp@ primop), before boxing the result up and returning it. However, we create a worker/wrapper pair, thus: foreign import f :: Int -> IO Int ==> f x = IO ( \s -> case x of { I# x# -> case fw s x# of { (# s1, y# #) -> (# s1, I# y# #)}}) fw s x# = ccall f s x# The strictness/CPR analyser won't do this automatically because it doesn't look inside returned tuples; but inlining this wrapper is a Really Good Idea because it exposes the boxing to the call site. -} dsFImport :: Id -> Coercion -> ForeignImport -> DsM ([Binding], SDoc, SDoc) dsFImport id co (CImport cconv safety mHeader spec _) = do (ids, h, c) <- dsCImport id co spec (unLoc cconv) (unLoc safety) mHeader return (ids, h, c) dsCImport :: Id -> Coercion -> CImportSpec -> CCallConv -> Safety -> Maybe Header -> DsM ([Binding], SDoc, SDoc) dsCImport id co (CLabel cid) cconv _ _ = do dflags <- getDynFlags let ty = pFst $ coercionKind co fod = case tyConAppTyCon_maybe (dropForAlls ty) of Just tycon | tyConUnique tycon == funPtrTyConKey -> IsFunction _ -> IsData (resTy, foRhs) <- resultWrapper ty ASSERT(fromJust resTy `eqType` addrPrimTy) -- typechecker ensures this let rhs = foRhs (Lit (MachLabel cid stdcall_info fod)) rhs' = Cast rhs co stdcall_info = fun_type_arg_stdcall_info dflags cconv ty in return ([(id, rhs')], empty, empty) dsCImport id co (CFunction target) cconv@PrimCallConv safety _ = dsPrimCall id co (CCall (CCallSpec target cconv safety)) dsCImport id co (CFunction target) cconv safety mHeader = dsFCall id co (CCall (CCallSpec target cconv safety)) mHeader dsCImport id co CWrapper cconv _ _ = dsFExportDynamic id co cconv -- For stdcall labels, if the type was a FunPtr or newtype thereof, -- then we need to calculate the size of the arguments in order to add -- the @n suffix to the label. fun_type_arg_stdcall_info :: DynFlags -> CCallConv -> Type -> Maybe Int fun_type_arg_stdcall_info dflags StdCallConv ty | Just (tc,[arg_ty]) <- splitTyConApp_maybe ty, tyConUnique tc == funPtrTyConKey = let (_tvs,sans_foralls) = tcSplitForAllTys arg_ty (fe_arg_tys, _orig_res_ty) = tcSplitFunTys sans_foralls in Just $ sum (map (widthInBytes . typeWidth . typeCmmType dflags . getPrimTyOf) fe_arg_tys) fun_type_arg_stdcall_info _ _other_conv _ = Nothing {- ************************************************************************ * * \subsection{Foreign calls} * * ************************************************************************ -} dsFCall :: Id -> Coercion -> ForeignCall -> Maybe Header -> DsM ([(Id, Expr TyVar)], SDoc, SDoc) dsFCall fn_id co fcall mDeclHeader = do let ty = pFst $ coercionKind co (tvs, fun_ty) = tcSplitForAllTys ty (arg_tys, io_res_ty) = tcSplitFunTys fun_ty -- Must use tcSplit* functions because we want to -- see that (IO t) in the corner args <- newSysLocalsDs arg_tys (val_args, arg_wrappers) <- mapAndUnzipM unboxArg (map Var args) let work_arg_ids = [v | Var v <- val_args] -- All guaranteed to be vars (ccall_result_ty, res_wrapper) <- boxResult io_res_ty ccall_uniq <- newUnique work_uniq <- newUnique dflags <- getDynFlags (fcall', cDoc) <- case fcall of CCall (CCallSpec (StaticTarget cName mPackageKey isFun) CApiConv safety) -> do wrapperName <- mkWrapperName "ghc_wrapper" (unpackFS cName) let fcall' = CCall (CCallSpec (StaticTarget wrapperName mPackageKey True) CApiConv safety) c = includes $$ fun_proto <+> braces (cRet <> semi) includes = vcat [ text "#include <" <> ftext h <> text ">" | Header h <- nub headers ] fun_proto = cResType <+> pprCconv <+> ppr wrapperName <> parens argTypes cRet | isVoidRes = cCall | otherwise = text "return" <+> cCall cCall = if isFun then ppr cName <> parens argVals else if null arg_tys then ppr cName else panic "dsFCall: Unexpected arguments to FFI value import" raw_res_ty = case tcSplitIOType_maybe io_res_ty of Just (_ioTyCon, res_ty) -> res_ty Nothing -> io_res_ty isVoidRes = raw_res_ty `eqType` unitTy (mHeader, cResType) | isVoidRes = (Nothing, text "void") | otherwise = toCType raw_res_ty pprCconv = ccallConvAttribute CApiConv mHeadersArgTypeList = [ (header, cType <+> char 'a' <> int n) | (t, n) <- zip arg_tys [1..] , let (header, cType) = toCType t ] (mHeaders, argTypeList) = unzip mHeadersArgTypeList argTypes = if null argTypeList then text "void" else hsep $ punctuate comma argTypeList mHeaders' = mDeclHeader : mHeader : mHeaders headers = catMaybes mHeaders' argVals = hsep $ punctuate comma [ char 'a' <> int n | (_, n) <- zip arg_tys [1..] ] return (fcall', c) _ -> return (fcall, empty) let -- Build the worker worker_ty = mkForAllTys tvs (mkFunTys (map idType work_arg_ids) ccall_result_ty) the_ccall_app = mkFCall dflags ccall_uniq fcall' val_args ccall_result_ty work_rhs = mkLams tvs (mkLams work_arg_ids the_ccall_app) work_id = mkSysLocal (fsLit "$wccall") work_uniq worker_ty -- Build the wrapper work_app = mkApps (mkVarApps (Var work_id) tvs) val_args wrapper_body = foldr ($) (res_wrapper work_app) arg_wrappers wrap_rhs = mkLams (tvs ++ args) wrapper_body wrap_rhs' = Cast wrap_rhs co fn_id_w_inl = fn_id `setIdUnfolding` mkInlineUnfolding (Just (length args)) wrap_rhs' return ([(work_id, work_rhs), (fn_id_w_inl, wrap_rhs')], empty, cDoc) {- ************************************************************************ * * \subsection{Primitive calls} * * ************************************************************************ This is for `@foreign import prim@' declarations. Currently, at the core level we pretend that these primitive calls are foreign calls. It may make more sense in future to have them as a distinct kind of Id, or perhaps to bundle them with PrimOps since semantically and for calling convention they are really prim ops. -} dsPrimCall :: Id -> Coercion -> ForeignCall -> DsM ([(Id, Expr TyVar)], SDoc, SDoc) dsPrimCall fn_id co fcall = do let ty = pFst $ coercionKind co (tvs, fun_ty) = tcSplitForAllTys ty (arg_tys, io_res_ty) = tcSplitFunTys fun_ty -- Must use tcSplit* functions because we want to -- see that (IO t) in the corner args <- newSysLocalsDs arg_tys ccall_uniq <- newUnique dflags <- getDynFlags let call_app = mkFCall dflags ccall_uniq fcall (map Var args) io_res_ty rhs = mkLams tvs (mkLams args call_app) rhs' = Cast rhs co return ([(fn_id, rhs')], empty, empty) {- ************************************************************************ * * \subsection{Foreign export} * * ************************************************************************ The function that does most of the work for `@foreign export@' declarations. (see below for the boilerplate code a `@foreign export@' declaration expands into.) For each `@foreign export foo@' in a module M we generate: \begin{itemize} \item a C function `@foo@', which calls \item a Haskell stub `@M.\$ffoo@', which calls \end{itemize} the user-written Haskell function `@M.foo@'. -} dsFExport :: Id -- Either the exported Id, -- or the foreign-export-dynamic constructor -> Coercion -- Coercion between the Haskell type callable -- from C, and its representation type -> CLabelString -- The name to export to C land -> CCallConv -> Bool -- True => foreign export dynamic -- so invoke IO action that's hanging off -- the first argument's stable pointer -> DsM ( SDoc -- contents of Module_stub.h , SDoc -- contents of Module_stub.c , String -- string describing type to pass to createAdj. , Int -- size of args to stub function ) dsFExport fn_id co ext_name cconv isDyn = do let ty = pSnd $ coercionKind co (_tvs,sans_foralls) = tcSplitForAllTys ty (fe_arg_tys', orig_res_ty) = tcSplitFunTys sans_foralls -- We must use tcSplits here, because we want to see -- the (IO t) in the corner of the type! fe_arg_tys | isDyn = tail fe_arg_tys' | otherwise = fe_arg_tys' -- Look at the result type of the exported function, orig_res_ty -- If it's IO t, return (t, True) -- If it's plain t, return (t, False) (res_ty, is_IO_res_ty) = case tcSplitIOType_maybe orig_res_ty of -- The function already returns IO t Just (_ioTyCon, res_ty) -> (res_ty, True) -- The function returns t Nothing -> (orig_res_ty, False) dflags <- getDynFlags return $ mkFExportCBits dflags ext_name (if isDyn then Nothing else Just fn_id) fe_arg_tys res_ty is_IO_res_ty cconv {- @foreign import "wrapper"@ (previously "foreign export dynamic") lets you dress up Haskell IO actions of some fixed type behind an externally callable interface (i.e., as a C function pointer). Useful for callbacks and stuff. \begin{verbatim} type Fun = Bool -> Int -> IO Int foreign import "wrapper" f :: Fun -> IO (FunPtr Fun) -- Haskell-visible constructor, which is generated from the above: -- SUP: No check for NULL from createAdjustor anymore??? f :: Fun -> IO (FunPtr Fun) f cback = bindIO (newStablePtr cback) (\StablePtr sp# -> IO (\s1# -> case _ccall_ createAdjustor cconv sp# ``f_helper'' <arg info> s1# of (# s2#, a# #) -> (# s2#, A# a# #))) foreign import "&f_helper" f_helper :: FunPtr (StablePtr Fun -> Fun) -- and the helper in C: (approximately; see `mkFExportCBits` below) f_helper(StablePtr s, HsBool b, HsInt i) { Capability *cap; cap = rts_lock(); rts_evalIO(&cap, rts_apply(rts_apply(deRefStablePtr(s), rts_mkBool(b)), rts_mkInt(i))); rts_unlock(cap); } \end{verbatim} -} dsFExportDynamic :: Id -> Coercion -> CCallConv -> DsM ([Binding], SDoc, SDoc) dsFExportDynamic id co0 cconv = do fe_id <- newSysLocalDs ty mod <- getModule dflags <- getDynFlags let -- hack: need to get at the name of the C stub we're about to generate. -- TODO: There's no real need to go via String with -- (mkFastString . zString). In fact, is there a reason to convert -- to FastString at all now, rather than sticking with FastZString? fe_nm = mkFastString (zString (zEncodeFS (moduleNameFS (moduleName mod))) ++ "_" ++ toCName dflags fe_id) cback <- newSysLocalDs arg_ty newStablePtrId <- dsLookupGlobalId newStablePtrName stable_ptr_tycon <- dsLookupTyCon stablePtrTyConName let stable_ptr_ty = mkTyConApp stable_ptr_tycon [arg_ty] export_ty = mkFunTy stable_ptr_ty arg_ty bindIOId <- dsLookupGlobalId bindIOName stbl_value <- newSysLocalDs stable_ptr_ty (h_code, c_code, typestring, args_size) <- dsFExport id (mkReflCo Representational export_ty) fe_nm cconv True let {- The arguments to the external function which will create a little bit of (template) code on the fly for allowing the (stable pointed) Haskell closure to be entered using an external calling convention (stdcall, ccall). -} adj_args = [ mkIntLitInt dflags (ccallConvToInt cconv) , Var stbl_value , Lit (MachLabel fe_nm mb_sz_args IsFunction) , Lit (mkMachString typestring) ] -- name of external entry point providing these services. -- (probably in the RTS.) adjustor = fsLit "createAdjustor" -- Determine the number of bytes of arguments to the stub function, -- so that we can attach the '@N' suffix to its label if it is a -- stdcall on Windows. mb_sz_args = case cconv of StdCallConv -> Just args_size _ -> Nothing ccall_adj <- dsCCall adjustor adj_args PlayRisky (mkTyConApp io_tc [res_ty]) -- PlayRisky: the adjustor doesn't allocate in the Haskell heap or do a callback let io_app = mkLams tvs $ Lam cback $ mkApps (Var bindIOId) [ Type stable_ptr_ty , Type res_ty , mkApps (Var newStablePtrId) [ Type arg_ty, Var cback ] , Lam stbl_value ccall_adj ] fed = (id `setInlineActivation` NeverActive, Cast io_app co0) -- Never inline the f.e.d. function, because the litlit -- might not be in scope in other modules. return ([fed], h_code, c_code) where ty = pFst (coercionKind co0) (tvs,sans_foralls) = tcSplitForAllTys ty ([arg_ty], fn_res_ty) = tcSplitFunTys sans_foralls Just (io_tc, res_ty) = tcSplitIOType_maybe fn_res_ty -- Must have an IO type; hence Just toCName :: DynFlags -> Id -> String toCName dflags i = showSDoc dflags (pprCode CStyle (ppr (idName i))) {- * \subsection{Generating @foreign export@ stubs} * For each @foreign export@ function, a C stub function is generated. The C stub constructs the application of the exported Haskell function using the hugs/ghc rts invocation API. -} mkFExportCBits :: DynFlags -> FastString -> Maybe Id -- Just==static, Nothing==dynamic -> [Type] -> Type -> Bool -- True <=> returns an IO type -> CCallConv -> (SDoc, SDoc, String, -- the argument reps Int -- total size of arguments ) mkFExportCBits dflags c_nm maybe_target arg_htys res_hty is_IO_res_ty cc = (header_bits, c_bits, type_string, sum [ widthInBytes (typeWidth rep) | (_,_,_,rep) <- aug_arg_info] -- all the args -- NB. the calculation here isn't strictly speaking correct. -- We have a primitive Haskell type (eg. Int#, Double#), and -- we want to know the size, when passed on the C stack, of -- the associated C type (eg. HsInt, HsDouble). We don't have -- this information to hand, but we know what GHC's conventions -- are for passing around the primitive Haskell types, so we -- use that instead. I hope the two coincide --SDM ) where -- list the arguments to the C function arg_info :: [(SDoc, -- arg name SDoc, -- C type Type, -- Haskell type CmmType)] -- the CmmType arg_info = [ let stg_type = showStgType ty in (arg_cname n stg_type, stg_type, ty, typeCmmType dflags (getPrimTyOf ty)) | (ty,n) <- zip arg_htys [1::Int ..] ] arg_cname n stg_ty | libffi = char '*' <> parens (stg_ty <> char '*') <> ptext (sLit "args") <> brackets (int (n-1)) | otherwise = text ('a':show n) -- generate a libffi-style stub if this is a "wrapper" and libffi is enabled libffi = cLibFFI && isNothing maybe_target type_string -- libffi needs to know the result type too: | libffi = primTyDescChar dflags res_hty : arg_type_string | otherwise = arg_type_string arg_type_string = [primTyDescChar dflags ty | (_,_,ty,_) <- arg_info] -- just the real args -- add some auxiliary args; the stable ptr in the wrapper case, and -- a slot for the dummy return address in the wrapper + ccall case aug_arg_info | isNothing maybe_target = stable_ptr_arg : insertRetAddr dflags cc arg_info | otherwise = arg_info stable_ptr_arg = (text "the_stableptr", text "StgStablePtr", undefined, typeCmmType dflags (mkStablePtrPrimTy alphaTy)) -- stuff to do with the return type of the C function res_hty_is_unit = res_hty `eqType` unitTy -- Look through any newtypes cResType | res_hty_is_unit = text "void" | otherwise = showStgType res_hty -- when the return type is integral and word-sized or smaller, it -- must be assigned as type ffi_arg (#3516). To see what type -- libffi is expecting here, take a look in its own testsuite, e.g. -- libffi/testsuite/libffi.call/cls_align_ulonglong.c ffi_cResType | is_ffi_arg_type = text "ffi_arg" | otherwise = cResType where res_ty_key = getUnique (getName (typeTyCon res_hty)) is_ffi_arg_type = res_ty_key `notElem` [floatTyConKey, doubleTyConKey, int64TyConKey, word64TyConKey] -- Now we can cook up the prototype for the exported function. pprCconv = ccallConvAttribute cc header_bits = ptext (sLit "extern") <+> fun_proto <> semi fun_args | null aug_arg_info = text "void" | otherwise = hsep $ punctuate comma $ map (\(nm,ty,_,_) -> ty <+> nm) aug_arg_info fun_proto | libffi = ptext (sLit "void") <+> ftext c_nm <> parens (ptext (sLit "void *cif STG_UNUSED, void* resp, void** args, void* the_stableptr")) | otherwise = cResType <+> pprCconv <+> ftext c_nm <> parens fun_args -- the target which will form the root of what we ask rts_evalIO to run the_cfun = case maybe_target of Nothing -> text "(StgClosure*)deRefStablePtr(the_stableptr)" Just hs_fn -> char '&' <> ppr hs_fn <> text "_closure" cap = text "cap" <> comma -- the expression we give to rts_evalIO expr_to_run = foldl appArg the_cfun arg_info -- NOT aug_arg_info where appArg acc (arg_cname, _, arg_hty, _) = text "rts_apply" <> parens (cap <> acc <> comma <> mkHObj arg_hty <> parens (cap <> arg_cname)) -- various other bits for inside the fn declareResult = text "HaskellObj ret;" declareCResult | res_hty_is_unit = empty | otherwise = cResType <+> text "cret;" assignCResult | res_hty_is_unit = empty | otherwise = text "cret=" <> unpackHObj res_hty <> parens (text "ret") <> semi -- an extern decl for the fn being called extern_decl = case maybe_target of Nothing -> empty Just hs_fn -> text "extern StgClosure " <> ppr hs_fn <> text "_closure" <> semi -- finally, the whole darn thing c_bits = space $$ extern_decl $$ fun_proto $$ vcat [ lbrace , ptext (sLit "Capability *cap;") , declareResult , declareCResult , text "cap = rts_lock();" -- create the application + perform it. , ptext (sLit "rts_evalIO") <> parens ( char '&' <> cap <> ptext (sLit "rts_apply") <> parens ( cap <> text "(HaskellObj)" <> ptext (if is_IO_res_ty then (sLit "runIO_closure") else (sLit "runNonIO_closure")) <> comma <> expr_to_run ) <+> comma <> text "&ret" ) <> semi , ptext (sLit "rts_checkSchedStatus") <> parens (doubleQuotes (ftext c_nm) <> comma <> text "cap") <> semi , assignCResult , ptext (sLit "rts_unlock(cap);") , ppUnless res_hty_is_unit $ if libffi then char '*' <> parens (ffi_cResType <> char '*') <> ptext (sLit "resp = cret;") else ptext (sLit "return cret;") , rbrace ] foreignExportInitialiser :: Id -> SDoc foreignExportInitialiser hs_fn = -- Initialise foreign exports by registering a stable pointer from an -- __attribute__((constructor)) function. -- The alternative is to do this from stginit functions generated in -- codeGen/CodeGen.lhs; however, stginit functions have a negative impact -- on binary sizes and link times because the static linker will think that -- all modules that are imported directly or indirectly are actually used by -- the program. -- (this is bad for big umbrella modules like Graphics.Rendering.OpenGL) vcat [ text "static void stginit_export_" <> ppr hs_fn <> text "() __attribute__((constructor));" , text "static void stginit_export_" <> ppr hs_fn <> text "()" , braces (text "foreignExportStablePtr" <> parens (text "(StgPtr) &" <> ppr hs_fn <> text "_closure") <> semi) ] mkHObj :: Type -> SDoc mkHObj t = text "rts_mk" <> text (showFFIType t) unpackHObj :: Type -> SDoc unpackHObj t = text "rts_get" <> text (showFFIType t) showStgType :: Type -> SDoc showStgType t = text "Hs" <> text (showFFIType t) showFFIType :: Type -> String showFFIType t = getOccString (getName (typeTyCon t)) toCType :: Type -> (Maybe Header, SDoc) toCType = f False where f voidOK t -- First, if we have (Ptr t) of (FunPtr t), then we need to -- convert t to a C type and put a * after it. If we don't -- know a type for t, then "void" is fine, though. | Just (ptr, [t']) <- splitTyConApp_maybe t , tyConName ptr `elem` [ptrTyConName, funPtrTyConName] = case f True t' of (mh, cType') -> (mh, cType' <> char '*') -- Otherwise, if we have a type constructor application, then -- see if there is a C type associated with that constructor. -- Note that we aren't looking through type synonyms or -- anything, as it may be the synonym that is annotated. | TyConApp tycon _ <- t , Just (CType mHeader cType) <- tyConCType_maybe tycon = (mHeader, ftext cType) -- If we don't know a C type for this type, then try looking -- through one layer of type synonym etc. | Just t' <- coreView t = f voidOK t' -- Otherwise we don't know the C type. If we are allowing -- void then return that; otherwise something has gone wrong. | voidOK = (Nothing, ptext (sLit "void")) | otherwise = pprPanic "toCType" (ppr t) typeTyCon :: Type -> TyCon typeTyCon ty | UnaryRep rep_ty <- repType ty , Just (tc, _) <- tcSplitTyConApp_maybe rep_ty = tc | otherwise = pprPanic "DsForeign.typeTyCon" (ppr ty) insertRetAddr :: DynFlags -> CCallConv -> [(SDoc, SDoc, Type, CmmType)] -> [(SDoc, SDoc, Type, CmmType)] insertRetAddr dflags CCallConv args = case platformArch platform of ArchX86_64 | platformOS platform == OSMinGW32 -> -- On other Windows x86_64 we insert the return address -- after the 4th argument, because this is the point -- at which we need to flush a register argument to the stack -- (See rts/Adjustor.c for details). let go :: Int -> [(SDoc, SDoc, Type, CmmType)] -> [(SDoc, SDoc, Type, CmmType)] go 4 args = ret_addr_arg dflags : args go n (arg:args) = arg : go (n+1) args go _ [] = [] in go 0 args | otherwise -> -- On other x86_64 platforms we insert the return address -- after the 6th integer argument, because this is the point -- at which we need to flush a register argument to the stack -- (See rts/Adjustor.c for details). let go :: Int -> [(SDoc, SDoc, Type, CmmType)] -> [(SDoc, SDoc, Type, CmmType)] go 6 args = ret_addr_arg dflags : args go n (arg@(_,_,_,rep):args) | cmmEqType_ignoring_ptrhood rep b64 = arg : go (n+1) args | otherwise = arg : go n args go _ [] = [] in go 0 args _ -> ret_addr_arg dflags : args where platform = targetPlatform dflags insertRetAddr _ _ args = args ret_addr_arg :: DynFlags -> (SDoc, SDoc, Type, CmmType) ret_addr_arg dflags = (text "original_return_addr", text "void*", undefined, typeCmmType dflags addrPrimTy) -- This function returns the primitive type associated with the boxed -- type argument to a foreign export (eg. Int ==> Int#). getPrimTyOf :: Type -> UnaryType getPrimTyOf ty | isBoolTy rep_ty = intPrimTy -- Except for Bool, the types we are interested in have a single constructor -- with a single primitive-typed argument (see TcType.legalFEArgTyCon). | otherwise = case splitDataProductType_maybe rep_ty of Just (_, _, data_con, [prim_ty]) -> ASSERT(dataConSourceArity data_con == 1) ASSERT2(isUnLiftedType prim_ty, ppr prim_ty) prim_ty _other -> pprPanic "DsForeign.getPrimTyOf" (ppr ty) where UnaryRep rep_ty = repType ty -- represent a primitive type as a Char, for building a string that -- described the foreign function type. The types are size-dependent, -- e.g. 'W' is a signed 32-bit integer. primTyDescChar :: DynFlags -> Type -> Char primTyDescChar dflags ty | ty `eqType` unitTy = 'v' | otherwise = case typePrimRep (getPrimTyOf ty) of IntRep -> signed_word WordRep -> unsigned_word Int64Rep -> 'L' Word64Rep -> 'l' AddrRep -> 'p' FloatRep -> 'f' DoubleRep -> 'd' _ -> pprPanic "primTyDescChar" (ppr ty) where (signed_word, unsigned_word) | wORD_SIZE dflags == 4 = ('W','w') | wORD_SIZE dflags == 8 = ('L','l') | otherwise = panic "primTyDescChar"
bitemyapp/ghc
compiler/deSugar/DsForeign.hs
bsd-3-clause
31,364
0
26
10,593
5,933
3,063
2,870
-1
-1
{-# LANGUAGE RecursiveDo, TypeFamilies, LambdaCase #-} module Control.Monad.Ref where import Control.Monad import Control.Monad.Trans import Control.Monad.Reader import Control.Monad.Writer import Data.IORef class Monad m => MonadRef m where type Ref m :: * -> * newRef :: a -> m (Ref m a) readRef :: Ref m a -> m a writeRef :: Ref m a -> a -> m () atomicModifyRef :: Ref m a -> (a -> (a, b)) -> m b instance MonadRef IO where type Ref IO = IORef {-# INLINE newRef #-} newRef = newIORef {-# INLINE readRef #-} readRef = readIORef {-# INLINE writeRef #-} writeRef = writeIORef {-# INLINE atomicModifyRef #-} atomicModifyRef r f = do result <- atomicModifyIORef' r f -- evaluate =<< readIORef r --TODO: Verify that ghcjs now strictly evaluates the values in atomicModifyIORef', then remove this line return result {-# INLINE cacheM #-} cacheM :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a, m ()) cacheM a = do r <- newRef undefined let invalidate = writeRef r $ do result <- a writeRef r $ return result return result invalidate return (join $ readRef r, invalidate) {-# INLINE cacheMWithTry #-} cacheMWithTry :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a, m (Maybe a), m ()) cacheMWithTry a = do r <- newRef $ Left a let invalidate = writeRef r $ Left a get = readRef r >>= \case Left a' -> do result <- a' writeRef r $ Right result return result Right result -> return result tryGet = readRef r >>= \case Left _ -> return Nothing Right result -> return $ Just result return (get, tryGet, invalidate) -- | Not thread-safe or reentrant {-# INLINE memoM #-} memoM :: (MonadRef m, MonadRef m', Ref m ~ Ref m') => m' a -> m (m' a) memoM = liftM fst . cacheM {-# INLINE replaceRef #-} replaceRef :: MonadRef m => Ref m a -> a -> m a replaceRef r new = atomicModifyRef r $ \old -> (new, old) {-# INLINE modifyRef #-} modifyRef :: MonadRef m => Ref m a -> (a -> a) -> m () modifyRef r f = atomicModifyRef r $ \a -> (f a, ()) instance (Monoid w, MonadRef m) => MonadRef (WriterT w m) where {-# SPECIALIZE instance Monoid w => MonadRef (WriterT w IO) #-} type Ref (WriterT w m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r atomicModifyRef r f = lift $ atomicModifyRef r f instance MonadRef m => MonadRef (ReaderT r m) where {-# SPECIALIZE instance MonadRef (ReaderT r IO) #-} type Ref (ReaderT r m) = Ref m newRef = lift . newRef readRef = lift . readRef writeRef r = lift . writeRef r atomicModifyRef r f = lift $ atomicModifyRef r f
mightybyte/reflex
src/Control/Monad/Ref.hs
bsd-3-clause
2,688
0
17
671
985
488
497
73
3
{-# LANGUAGE CPP, GeneralizedNewtypeDeriving, OverloadedStrings #-} -- | Core types and operations for DOM manipulation. module Haste.DOM.Core ( Elem (..), IsElem (..), Attribute, AttrName (..), set, with, attribute, children, click, focus, blur, document, documentBody, deleteChild, clearChildren, setChildren, getChildren, getLastChild, getFirstChild, getChildBefore, insertChildBefore, appendChild, -- Low level stuff jsSet, jsSetAttr, jsSetStyle, -- Deprecated removeChild, addChild, addChildBefore ) where import Haste.Prim import Control.Monad.IO.Class import Haste.Foreign import Data.String jsSet :: Elem -> JSString -> JSString -> IO () jsSet = ffi "(function(e,p,v){e[p] = v;})" jsSetAttr :: Elem -> JSString -> JSString -> IO () jsSetAttr = ffi "(function(e,p,v){e.setAttribute(p, v);})" jsSetStyle :: Elem -> JSString -> JSString -> IO () jsSetStyle = ffi "(function(e,p,v){e.style[p] = v;})" jsAppendChild :: Elem -> Elem -> IO () jsAppendChild = ffi "(function(c,p){p.appendChild(c);})" jsGetFirstChild :: Elem -> IO (Maybe Elem) jsGetFirstChild = ffi "(function(e){\ for(e = e.firstChild; e != null; e = e.nextSibling)\ {if(e instanceof HTMLElement) {return e;}}\ return null;})" jsGetLastChild :: Elem -> IO (Maybe Elem) jsGetLastChild = ffi "(function(e){\ for(e = e.lastChild; e != null; e = e.previousSibling)\ {if(e instanceof HTMLElement) {return e;}}\ return null;})" jsGetChildren :: Elem -> IO [Elem] jsGetChildren = ffi "(function(e){\ var ch = [];\ for(e = e.firstChild; e != null; e = e.nextSibling)\ {if(e instanceof HTMLElement) {ch.push(e);}}\ return ch;})" jsSetChildren :: Elem -> [Elem] -> IO () jsSetChildren = ffi "(function(e,ch){\ while(e.firstChild) {e.removeChild(e.firstChild);}\ for(var i in ch) {e.appendChild(ch[i]);}})" jsAddChildBefore :: Elem -> Elem -> Elem -> IO () jsAddChildBefore = ffi "(function(c,p,a){p.insertBefore(c,a);})" jsGetChildBefore :: Elem -> IO (Maybe Elem) jsGetChildBefore = ffi "(function(e){\ for(; e != null; e = e.previousSibling)\ {if(e instanceof HTMLElement) {return e;}\ return null;})" jsKillChild :: Elem -> Elem -> IO () jsKillChild = ffi "(function(c,p){p.removeChild(c);})" jsClearChildren :: Elem -> IO () jsClearChildren = ffi "(function(e){\ while(e.firstChild){e.removeChild(e.firstChild);}})" -- | A DOM node. newtype Elem = Elem JSAny deriving (ToAny, FromAny) -- | The class of types backed by DOM elements. class IsElem a where -- | Get the element representing the object. elemOf :: a -> Elem -- | Attempt to create a DOM element backed object from an 'Elem'. -- The default instance always returns @Nothing@. fromElem :: Elem -> IO (Maybe a) fromElem = const $ return Nothing instance IsElem Elem where elemOf = id fromElem = return . Just -- | The name of an attribute. May be either a common property, an HTML -- attribute or a style attribute. data AttrName = PropName !JSString | StyleName !JSString | AttrName !JSString deriving (Eq, Ord) instance IsString AttrName where fromString = PropName . fromString -- | A key/value pair representing the value of an attribute. -- May represent a property, an HTML attribute, a style attribute or a list -- of child elements. data Attribute = Attribute !AttrName !JSString | Children ![Elem] -- | Construct an 'Attribute'. attribute :: AttrName -> JSString -> Attribute attribute = Attribute -- | Set a number of 'Attribute's on an element. set :: (IsElem e, MonadIO m) => e -> [Attribute] -> m () set e as = liftIO $ mapM_ set' as where e' = elemOf e set' (Attribute (PropName k) v) = jsSet e' k v set' (Attribute (StyleName k) v) = jsSetStyle e' k v set' (Attribute (AttrName k) v) = jsSetAttr e' k v set' (Children cs) = mapM_ (flip jsAppendChild e') cs -- | Attribute adding a list of child nodes to an element. children :: [Elem] -> Attribute children = Children -- | Set a number of 'Attribute's on the element produced by an IO action. -- Gives more convenient syntax when creating elements: -- -- > newElem "div" `with` [ -- > style "border" =: "1px solid black", -- > ... -- > ] -- with :: (IsElem e, MonadIO m) => m e -> [Attribute] -> m e with m attrs = do x <- m set x attrs return x -- | Generate a click event on an element. click :: (IsElem e, MonadIO m) => e -> m () click = liftIO . click' . elemOf click' :: Elem -> IO () click' = ffi "(function(e) {e.click();})" -- | Generate a focus event on an element. focus :: (IsElem e, MonadIO m) => e -> m () focus = liftIO . focus' . elemOf focus' :: Elem -> IO () focus' = ffi "(function(e) {e.focus();})" -- | Generate a blur event on an element. blur :: (IsElem e, MonadIO m) => e -> m () blur = liftIO . blur' . elemOf blur' :: Elem -> IO () blur' = ffi "(function(e) {e.blur();})" -- | The DOM node corresponding to document. document :: Elem document = constant "document" -- | The DOM node corresponding to document.body. documentBody :: Elem documentBody = constant "document.body" -- | Append the second element as a child of the first. appendChild :: (IsElem parent, IsElem child, MonadIO m) => parent -> child -> m () appendChild parent child = liftIO $ jsAppendChild (elemOf child) (elemOf parent) {-# DEPRECATED addChild "Use appendChild instead. Note that appendChild == flip addChild." #-} -- | Append the first element as a child of the second element. addChild :: (IsElem parent, IsElem child, MonadIO m) => child -> parent -> m () addChild = flip appendChild -- | Insert an element into a container, before another element. -- For instance: -- @ -- insertChildBefore theContainer olderChild childToAdd -- @ insertChildBefore :: (IsElem parent, IsElem before, IsElem child, MonadIO m) => parent -> before -> child -> m () insertChildBefore parent oldChild child = liftIO $ jsAddChildBefore (elemOf child) (elemOf parent) (elemOf oldChild) {-# DEPRECATED addChildBefore "Use insertChildBefore instead. Note insertChildBefore == \\parent new old -> addChildBefore new parent old." #-} -- | Insert an element into a container, before another element. -- For instance: -- @ -- addChildBefore childToAdd theContainer olderChild -- @ addChildBefore :: (IsElem parent, IsElem child, MonadIO m) => child -> parent -> child -> m () addChildBefore child parent oldChild = insertChildBefore parent oldChild child -- | Get the sibling before the given one, if any. getChildBefore :: (IsElem e, MonadIO m) => e -> m (Maybe Elem) getChildBefore e = liftIO $ jsGetChildBefore (elemOf e) -- | Get the first of an element's children. getFirstChild :: (IsElem e, MonadIO m) => e -> m (Maybe Elem) getFirstChild e = liftIO $ jsGetFirstChild (elemOf e) -- | Get the last of an element's children. getLastChild :: (IsElem e, MonadIO m) => e -> m (Maybe Elem) getLastChild e = liftIO $ jsGetLastChild (elemOf e) -- | Get a list of all children belonging to a certain element. getChildren :: (IsElem e, MonadIO m) => e -> m [Elem] getChildren e = liftIO $ jsGetChildren (elemOf e) -- | Clear the given element's list of children, and append all given children -- to it. setChildren :: (IsElem parent, IsElem child, MonadIO m) => parent -> [child] -> m () setChildren e ch = liftIO $ jsSetChildren (elemOf e) (map elemOf ch) -- | Remove all children from the given element. clearChildren :: (IsElem e, MonadIO m) => e -> m () clearChildren = liftIO . jsClearChildren . elemOf -- | Remove the second element from the first's children. deleteChild :: (IsElem parent, IsElem child, MonadIO m) => parent -> child -> m () deleteChild parent child = liftIO $ jsKillChild (elemOf child) (elemOf parent) {-# DEPRECATED removeChild "Use deleteChild instead. Note that deleteChild = flip removeChild." #-} -- | DEPRECATED: use 'deleteChild' instead! -- Note that @deleteChild = flip removeChild@. removeChild :: (IsElem parent, IsElem child, MonadIO m) => child -> parent -> m () removeChild = flip deleteChild
kranich/haste-compiler
libraries/haste-lib/src/Haste/DOM/Core.hs
bsd-3-clause
8,154
46
12
1,624
2,176
1,184
992
-1
-1
{-# LANGUAGE FlexibleContexts #-} module Kalium.Util where import Kalium.Prelude import qualified Data.Map as M import Control.Monad.Rename import Control.Monad.Except type Pairs a b = [(a, b)] type Endo' a = a -> a type Kleisli' m a b = a -> m b type EndoKleisli' m a = Kleisli' m a a mAsList :: Ord k => Iso' (Map k a) (Pairs k a) mAsList = iso M.toList M.fromList tryApply :: (a -> Maybe a) -> (a -> a) tryApply f a = maybe a id (f a) closureM :: (Eq a, Monad m) => LensLike' m a a closureM f = go where go x = f x >>= \y -> bool (go y) (return x) (x == y) amaybe :: Alternative f => Maybe a -> f a amaybe = maybe empty pure throwEither :: MonadError e m => Either e a -> m a throwEither = either throwError return throwMaybe :: MonadError e m => e -> Maybe a -> m a throwMaybe e = throwEither . maybe (Left e) Right uniform :: Eq a => [a] -> Maybe a uniform (x:xs) | all (==x) xs = Just x uniform _ = Nothing inContext :: Monad m => (m a -> a -> m b) -> m a -> m b inContext f ma = ma >>= f ma zipFilter :: [Bool] -> [a] -> Maybe [a] zipFilter (keep:keeps) (a:as) | keep = (a:) `fmap` zipFilter keeps as | otherwise = zipFilter keeps as zipFilter [] [] = Just [] zipFilter _ _ = Nothing keepByFst :: (b -> Bool) -> Pairs b a -> [a] keepByFst p = map snd . filter (p . fst) far :: EndoCon a -> (h -> a -> Maybe a) -> [h] -> Endo' a far k f = foldl (toEndoWith . k) id . fmap f -- Elements are traversed right-to-left asfar, nofar, sofar :: (h -> a -> Maybe a) -> [h] -> Endo' a -- Sequentially fuse elements until one fails asfar = far endoSuccess -- Fuse with the first successful element nofar = far endoFailure -- Sequentially fuse all successful elements sofar = far endoBoth data EndoConfig a = EndoConfig (Endo' a) (Endo' a) (Endo' a) type EndoCon a = Endo' a -> EndoConfig a endoSuccess, endoFailure, endoBoth :: EndoCon a endoSuccess fn = EndoConfig id fn id endoFailure fn = EndoConfig fn id id endoBoth fn = EndoConfig id id fn toEndoWith :: EndoConfig a -> EndoKleisli' Maybe a -> Endo' a toEndoWith (EndoConfig failure success both) f a = both (maybe (failure a) success (f a)) unionWithSame :: (Ord k, Eq v) => Map k v -> Map k v -> Maybe (Map k v) unionWithSame m1 m2 = sequenceA $ M.unionWith same (pure <$> m1) (pure <$> m2) where same (Just x) (Just y) | x == y = Just x same _ _ = Nothing type MonadNameGen m = MonadRename Integer String m
rscprof/kalium
src/Kalium/Util.hs
bsd-3-clause
2,415
0
11
544
1,136
583
553
56
2
-- | -- Module : Crypto.Cipher.RC4 -- License : BSD-style -- Maintainer : Vincent Hanquez <vincent@snarc.org> -- Stability : stable -- Portability : Good -- -- Simple implementation of the RC4 stream cipher. -- http://en.wikipedia.org/wiki/RC4 -- -- Initial FFI implementation by Peter White <peter@janrain.com> -- -- Reorganized and simplified to have an opaque context. -- {-# LANGUAGE ForeignFunctionInterface #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-} module Crypto.Cipher.RC4 ( initialize , combine , generate , State ) where import Data.Word import Foreign.Ptr import Crypto.Internal.ByteArray (ScrubbedBytes, ByteArray, ByteArrayAccess) import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Compat import Crypto.Internal.Imports -- | The encryption state for RC4 newtype State = State ScrubbedBytes deriving (ByteArrayAccess,NFData) -- | C Call for initializing the encryptor foreign import ccall unsafe "cryptonite_rc4.h cryptonite_rc4_init" c_rc4_init :: Ptr Word8 -- ^ The rc4 key -> Word32 -- ^ The key length -> Ptr State -- ^ The context -> IO () foreign import ccall unsafe "cryptonite_rc4.h cryptonite_rc4_combine" c_rc4_combine :: Ptr State -- ^ Pointer to the permutation -> Ptr Word8 -- ^ Pointer to the clear text -> Word32 -- ^ Length of the clear text -> Ptr Word8 -- ^ Output buffer -> IO () -- | RC4 context initialization. -- -- seed the context with an initial key. the key size need to be -- adequate otherwise security takes a hit. initialize :: ByteArrayAccess key => key -- ^ The key -> State -- ^ The RC4 context with the key mixed in initialize key = unsafeDoIO $ do st <- B.alloc 264 $ \stPtr -> B.withByteArray key $ \keyPtr -> c_rc4_init keyPtr (fromIntegral $ B.length key) (castPtr stPtr) return $ State st -- | generate the next len bytes of the rc4 stream without combining -- it to anything. generate :: ByteArray ba => State -> Int -> (State, ba) generate ctx len = combine ctx (B.zero len) -- | RC4 xor combination of the rc4 stream with an input combine :: ByteArray ba => State -- ^ rc4 context -> ba -- ^ input -> (State, ba) -- ^ new rc4 context, and the output combine (State prevSt) clearText = unsafeDoIO $ B.allocRet len $ \outptr -> B.withByteArray clearText $ \clearPtr -> do st <- B.copy prevSt $ \stPtr -> c_rc4_combine (castPtr stPtr) clearPtr (fromIntegral len) outptr return $! State st --return $! (State st, B.PS outfptr 0 len) where len = B.length clearText
nomeata/cryptonite
Crypto/Cipher/RC4.hs
bsd-3-clause
2,846
0
17
801
492
274
218
46
1
module Array ( module Ix, -- export all of Ix for convenience Array, array, listArray, (!), bounds, indices, elems, assocs, accumArray, (//), accum, ixmap ) where import Ix import Data.Array
FranklinChen/hugs98-plus-Sep2006
packages/haskell98/Array.hs
bsd-3-clause
208
0
4
47
59
41
18
-1
-1
foo = case v of v -> x
bitemyapp/apply-refact
tests/examples/Structure14.hs
bsd-3-clause
22
0
7
7
16
8
8
1
1
{-# OPTIONS_GHC -Wall -fwarn-tabs #-} {-# LANGUAGE ForeignFunctionInterface #-} ---------------------------------------------------------------- -- 2010.10.09 -- | -- Module : IsSpace -- Copyright : Copyright (c) 2010 wren ng thornton -- License : BSD -- Maintainer : wren@community.haskell.org -- Stability : experimental -- Portability : portable (FFI) -- -- A benchmark for comparing different definitions of predicates -- for detecting whitespace. As of the last run the results are: -- -- * Data.Char.isSpace : 14.44786 us +/- 258.0377 ns -- * isSpace_DataChar : 43.25154 us +/- 655.7037 ns -- * isSpace_Char : 29.26598 us +/- 454.1445 ns -- * isPerlSpace : -- * Data.Attoparsec.Char8.isSpace : 81.87335 us +/- 1.195903 us -- * isSpace_Char8 : 11.84677 us +/- 178.9795 ns -- * isSpace_w8 : 11.55470 us +/- 133.7644 ns ---------------------------------------------------------------- module IsSpace (main) where import qualified Data.Char as C import Data.Word (Word8) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as B8 import Foreign.C.Types (CInt) import Criterion (bench, nf) import Criterion.Main (defaultMain) ---------------------------------------------------------------- ----- Character predicates -- N.B. \x9..\xD == "\t\n\v\f\r" -- | Recognize the same characters as Perl's @/\s/@ in Unicode mode. -- In particular, we recognize POSIX 1003.2 @[[:space:]]@ except -- @\'\v\'@, and recognize the Unicode @\'\x85\'@, @\'\x2028\'@, -- @\'\x2029\'@. Notably, @\'\x85\'@ belongs to Latin-1 (but not -- ASCII) and therefore does not belong to POSIX 1003.2 @[[:space:]]@ -- (nor non-Unicode @/\s/@). isPerlSpace :: Char -> Bool isPerlSpace c = (' ' == c) || ('\t' <= c && c <= '\r' && c /= '\v') || ('\x85' == c) || ('\x2028' == c) || ('\x2029' == c) {-# INLINE isPerlSpace #-} -- | 'Data.Attoparsec.Char8.isSpace', duplicated here because it's -- not exported. This is the definition as of attoparsec-0.8.1.0. isSpace :: Char -> Bool isSpace c = c `B8.elem` spaces where spaces = B8.pack " \n\r\t\v\f" {-# NOINLINE spaces #-} {-# INLINE isSpace #-} -- | An alternate version of 'Data.Attoparsec.Char8.isSpace'. isSpace_Char8 :: Char -> Bool isSpace_Char8 c = (' ' == c) || ('\t' <= c && c <= '\r') {-# INLINE isSpace_Char8 #-} -- | An alternate version of 'Data.Char.isSpace'. This uses the -- same trick as 'isSpace_Char8' but we include Unicode whitespaces -- too, in order to have the same results as 'Data.Char.isSpace' -- (whereas 'isSpace_Char8' doesn't recognize Unicode whitespace). isSpace_Char :: Char -> Bool isSpace_Char c = (' ' == c) || ('\t' <= c && c <= '\r') || ('\xA0' == c) || (iswspace (fromIntegral (C.ord c)) /= 0) {-# INLINE isSpace_Char #-} foreign import ccall unsafe "u_iswspace" iswspace :: CInt -> CInt -- | Verbatim version of 'Data.Char.isSpace' (i.e., 'GHC.Unicode.isSpace' -- as of base-4.2.0.2) in order to try to figure out why 'isSpace_Char' -- is slower than 'Data.Char.isSpace'. It appears to be something -- special in how the base library was compiled. isSpace_DataChar :: Char -> Bool isSpace_DataChar c = c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v' || c == '\xa0' || iswspace (fromIntegral (C.ord c)) /= 0 {-# INLINE isSpace_DataChar #-} -- | A 'Word8' version of 'Data.Attoparsec.Char8.isSpace'. isSpace_w8 :: Word8 -> Bool isSpace_w8 w = (w == 32) || (9 <= w && w <= 13) {-# INLINE isSpace_w8 #-} ---------------------------------------------------------------- main :: IO () main = defaultMain [ bench "Data.Char.isSpace" $ nf (map C.isSpace) ['\x0'..'\255'] , bench "isSpace_DataChar" $ nf (map isSpace_DataChar) ['\x0'..'\255'] , bench "isSpace_Char" $ nf (map isSpace_Char) ['\x0'..'\255'] , bench "isPerlSpace" $ nf (map isPerlSpace) ['\x0'..'\255'] , bench "Data.Attoparsec.Char8.isSpace" $ nf (map isSpace) ['\x0'..'\255'] , bench "isSpace_Char8" $ nf (map isSpace_Char8) ['\x0'..'\255'] , bench "isSpace_w8" $ nf (map isSpace_w8) [0..255] ] ---------------------------------------------------------------- ----------------------------------------------------------- fin.
beni55/attoparsec
benchmarks/IsSpace.hs
bsd-3-clause
4,609
0
19
1,118
721
411
310
59
1
infixr 6 :< infixl 5 ++ infixl 9 ** data Int = Z | S Int data MyList a = Nil | a :< (MyList a) Nil ++ x = x (a :< as) ++ x = a :< (as ++ x) Nil ** x = Nil (a :< as) ** x = a :< (x ** as) class VC a where rpl :: a -> (MyList a) instance VC a => VC (MyList a) where rpl x = (rpl x) :< rpl x instance VC Int where rpl x = x :< (rpl x) p12 = S (S Z) q12 = rpl p12
forste/haReFork
tools/base/tests/test1.hs
bsd-3-clause
393
0
9
137
242
124
118
18
1