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
|
---|---|---|---|---|---|---|---|---|---|---|---|---|
module Lev1 where
import Data.Array
mft :: String -> String -> Array (Int, Int) Int
mft f t = m where
m = array bounds [ ((i, j), lev i j) | (i,j) <- range bounds ]
bounds = ((0, 0), (length t, length f))
lev 0 0 = 0
lev 0 j = succ $ m ! (0 , pred j)
lev i 0 = succ $ m ! (pred i, 0 )
lev i j | (f!! p j) == (t !! p i) = m!(p i,p j)
| otherwise = 1 + minimum [ m!(p i,j), m!(i,p j), m!(p i,p j) ]
score :: String -> String -> Int
score f t = let m = mft f t in m ! snd (bounds m)
p = pred
| sordina/mfug_levenshtein_difference_2016_07_07- | src/Lev1.hs | bsd-3-clause | 532 | 0 | 13 | 174 | 365 | 191 | 174 | 14 | 4 |
import Data.List (permutations)
main = do
let result = filter f $ permutations "0123456789"
print $ sum $ map read result
where
f x = f1 x && f2 x && f3 x && f4 x && f5 x && f6 x && f7 x
f1 x = read (x!!1 : x!!2 : [x!!3]) `mod` 2 == 0
f2 x = read (x!!2 : x!!3 : [x!!4]) `mod` 3 == 0
f3 x = read (x!!3 : x!!4 : [x!!5]) `mod` 5 == 0
f4 x = read (x!!4 : x!!5 : [x!!6]) `mod` 7 == 0
f5 x = read (x!!5 : x!!6 : [x!!7]) `mod` 11 == 0
f6 x = read (x!!6 : x!!7 : [x!!8]) `mod` 13 == 0
f7 x = read (x!!7 : x!!8 : [x!!9]) `mod` 17 == 0
| stulli/projectEuler | eu43.hs | bsd-3-clause | 587 | 0 | 14 | 197 | 435 | 223 | 212 | 12 | 1 |
{-
(c) The University of Glasgow 2006
-}
{-# LANGUAGE RankNTypes, CPP, MultiWayIf #-}
-- | Module for (a) type kinds and (b) type coercions,
-- as used in System FC. See 'CoreSyn.Expr' for
-- more on System FC and how coercions fit into it.
--
module Coercion (
-- * Main data type
Coercion, CoercionN, CoercionR, CoercionP,
UnivCoProvenance, CoercionHole, LeftOrRight(..),
Var, CoVar, TyCoVar,
Role(..), ltRole,
-- ** Functions over coercions
coVarTypes, coVarKind, coVarKindsTypesRole, coVarRole,
coercionType, coercionKind, coercionKinds,
mkCoercionType,
coercionRole, coercionKindRole,
-- ** Constructing coercions
mkReflCo, mkRepReflCo, mkNomReflCo,
mkCoVarCo, mkCoVarCos,
mkAxInstCo, mkUnbranchedAxInstCo,
mkAxInstRHS, mkUnbranchedAxInstRHS,
mkAxInstLHS, mkUnbranchedAxInstLHS,
mkPiCo, mkPiCos, mkCoCast,
mkSymCo, mkTransCo, mkTransAppCo,
mkNthCo, mkNthCoRole, mkLRCo,
mkInstCo, mkAppCo, mkAppCos, mkTyConAppCo, mkFunCo, mkFunCos,
mkForAllCo, mkForAllCos, mkHomoForAllCos, mkHomoForAllCos_NoRefl,
mkPhantomCo, mkHomoPhantomCo, toPhantomCo,
mkUnsafeCo, mkHoleCo, mkUnivCo, mkSubCo,
mkAxiomInstCo, mkProofIrrelCo,
downgradeRole, maybeSubCo, mkAxiomRuleCo,
mkCoherenceCo, mkCoherenceRightCo, mkCoherenceLeftCo,
mkKindCo, castCoercionKind,
mkHeteroCoercionType,
-- ** Decomposition
instNewTyCon_maybe,
NormaliseStepper, NormaliseStepResult(..), composeSteppers,
mapStepResult, unwrapNewTypeStepper,
topNormaliseNewType_maybe, topNormaliseTypeX,
decomposeCo, getCoVar_maybe,
splitTyConAppCo_maybe,
splitAppCo_maybe,
splitForAllCo_maybe,
nthRole, tyConRolesX, tyConRolesRepresentational, setNominalRole_maybe,
pickLR,
isReflCo, isReflCo_maybe, isReflexiveCo, isReflexiveCo_maybe,
-- ** Coercion variables
mkCoVar, isCoVar, coVarName, setCoVarName, setCoVarUnique,
isCoVar_maybe,
-- ** Free variables
tyCoVarsOfCo, tyCoVarsOfCos, coVarsOfCo,
tyCoFVsOfCo, tyCoFVsOfCos, tyCoVarsOfCoDSet,
coercionSize,
-- ** Substitution
CvSubstEnv, emptyCvSubstEnv,
lookupCoVar,
substCo, substCos, substCoVar, substCoVars, substCoWith,
substCoVarBndr,
extendTvSubstAndInScope, getCvSubstEnv,
-- ** Lifting
liftCoSubst, liftCoSubstTyVar, liftCoSubstWith, liftCoSubstWithEx,
emptyLiftingContext, extendLiftingContext,
liftCoSubstVarBndrCallback, isMappedByLC,
mkSubstLiftingContext, zapLiftingContext,
substForAllCoBndrCallbackLC, lcTCvSubst, lcInScopeSet,
LiftCoEnv, LiftingContext(..), liftEnvSubstLeft, liftEnvSubstRight,
substRightCo, substLeftCo, swapLiftCoEnv, lcSubstLeft, lcSubstRight,
-- ** Comparison
eqCoercion, eqCoercionX,
-- ** Forcing evaluation of coercions
seqCo,
-- * Pretty-printing
pprCo, pprParendCo, pprCoBndr,
pprCoAxiom, pprCoAxBranch, pprCoAxBranchHdr,
-- * Tidying
tidyCo, tidyCos,
-- * Other
promoteCoercion
) where
#include "HsVersions.h"
import TyCoRep
import Type
import TyCon
import CoAxiom
import Var
import VarEnv
import Name hiding ( varName )
import Util
import BasicTypes
import Outputable
import Unique
import Pair
import SrcLoc
import PrelNames
import TysPrim ( eqPhantPrimTyCon )
import ListSetOps
import Maybes
import UniqFM
import Control.Monad (foldM)
import Control.Arrow ( first )
import Data.Function ( on )
{-
%************************************************************************
%* *
-- The coercion arguments always *precisely* saturate
-- arity of (that branch of) the CoAxiom. If there are
-- any left over, we use AppCo. See
-- See [Coercion axioms applied to coercions] in TyCoRep
\subsection{Coercion variables}
%* *
%************************************************************************
-}
coVarName :: CoVar -> Name
coVarName = varName
setCoVarUnique :: CoVar -> Unique -> CoVar
setCoVarUnique = setVarUnique
setCoVarName :: CoVar -> Name -> CoVar
setCoVarName = setVarName
{-
%************************************************************************
%* *
Pretty-printing coercions
%* *
%************************************************************************
@pprCo@ is the standard @Coercion@ printer; the overloaded @ppr@
function is defined to use this. @pprParendCo@ is the same, except it
puts parens around the type, except for the atomic cases.
@pprParendCo@ works just by setting the initial context precedence
very high.
-}
-- Outputable instances are in TyCoRep, to avoid orphans
pprCo, pprParendCo :: Coercion -> SDoc
pprCo co = ppr_co TopPrec co
pprParendCo co = ppr_co TyConPrec co
ppr_co :: TyPrec -> Coercion -> SDoc
ppr_co _ (Refl r ty) = angleBrackets (ppr ty) <> ppr_role r
ppr_co p co@(TyConAppCo _ tc [_,_])
| tc `hasKey` funTyConKey = ppr_fun_co p co
ppr_co _ (TyConAppCo r tc cos) = pprTcAppCo TyConPrec ppr_co tc cos <> ppr_role r
ppr_co p (AppCo co arg) = maybeParen p TyConPrec $
pprCo co <+> ppr_co TyConPrec arg
ppr_co p co@(ForAllCo {}) = ppr_forall_co p co
ppr_co _ (CoVarCo cv) = parenSymOcc (getOccName cv) (ppr cv)
ppr_co p (AxiomInstCo con index args)
= pprPrefixApp p (ppr (getName con) <> brackets (ppr index))
(map (ppr_co TyConPrec) args)
ppr_co p co@(TransCo {}) = maybeParen p FunPrec $
case trans_co_list co [] of
[] -> panic "ppr_co"
(co:cos) -> sep ( ppr_co FunPrec co
: [ char ';' <+> ppr_co FunPrec co | co <- cos])
ppr_co p (InstCo co arg) = maybeParen p TyConPrec $
pprParendCo co <> text "@" <> ppr_co TopPrec arg
ppr_co p (UnivCo UnsafeCoerceProv r ty1 ty2)
= pprPrefixApp p (text "UnsafeCo" <+> ppr r)
[pprParendType ty1, pprParendType ty2]
ppr_co _ (UnivCo p r t1 t2)
= char 'U'
<> parens (ppr_prov <> comma <+> ppr t1 <> comma <+> ppr t2)
<> ppr_role r
where
ppr_prov = case p of
HoleProv h -> text "hole:" <> ppr h
PhantomProv kind_co -> text "phant:" <> ppr kind_co
ProofIrrelProv co -> text "irrel:" <> ppr co
PluginProv s -> text "plugin:" <> text s
UnsafeCoerceProv -> text "unsafe"
ppr_co p (SymCo co) = pprPrefixApp p (text "Sym") [pprParendCo co]
ppr_co p (NthCo n co) = pprPrefixApp p (text "Nth:" <> int n) [pprParendCo co]
ppr_co p (LRCo sel co) = pprPrefixApp p (ppr sel) [pprParendCo co]
ppr_co p (CoherenceCo c1 c2) = maybeParen p TyConPrec $
(ppr_co FunPrec c1) <+> (text "|>") <+>
(ppr_co FunPrec c2)
ppr_co p (KindCo co) = pprPrefixApp p (text "kind") [pprParendCo co]
ppr_co p (SubCo co) = pprPrefixApp p (text "Sub") [pprParendCo co]
ppr_co p (AxiomRuleCo co cs) = maybeParen p TopPrec $ ppr_axiom_rule_co co cs
ppr_axiom_rule_co :: CoAxiomRule -> [Coercion] -> SDoc
ppr_axiom_rule_co co ps = ppr (coaxrName co) <+> parens (interpp'SP ps)
ppr_role :: Role -> SDoc
ppr_role r = underscore <> pp_role
where pp_role = case r of
Nominal -> char 'N'
Representational -> char 'R'
Phantom -> char 'P'
trans_co_list :: Coercion -> [Coercion] -> [Coercion]
trans_co_list (TransCo co1 co2) cos = trans_co_list co1 (trans_co_list co2 cos)
trans_co_list co cos = co : cos
ppr_fun_co :: TyPrec -> Coercion -> SDoc
ppr_fun_co p co = pprArrowChain p (split co)
where
split :: Coercion -> [SDoc]
split (TyConAppCo _ f [arg, res])
| f `hasKey` funTyConKey
= ppr_co FunPrec arg : split res
split co = [ppr_co TopPrec co]
ppr_forall_co :: TyPrec -> Coercion -> SDoc
ppr_forall_co p (ForAllCo tv h co)
= maybeParen p FunPrec $
sep [pprCoBndr (tyVarName tv) h, ppr_co TopPrec co]
ppr_forall_co _ _ = panic "ppr_forall_co"
pprCoBndr :: Name -> Coercion -> SDoc
pprCoBndr name eta =
forAllLit <+> parens (ppr name <+> dcolon <+> ppr eta) <> dot
pprCoAxiom :: CoAxiom br -> SDoc
pprCoAxiom ax@(CoAxiom { co_ax_branches = branches })
= hang (text "axiom" <+> ppr ax <+> dcolon)
2 (vcat (map (ppr_co_ax_branch (const ppr) ax) $ fromBranches branches))
pprCoAxBranch :: CoAxiom br -> CoAxBranch -> SDoc
pprCoAxBranch = ppr_co_ax_branch pprRhs
where
pprRhs fam_tc (TyConApp tycon _)
| isDataFamilyTyCon fam_tc
= pprDataCons tycon
pprRhs _ rhs = ppr rhs
pprCoAxBranchHdr :: CoAxiom br -> BranchIndex -> SDoc
pprCoAxBranchHdr ax index = pprCoAxBranch ax (coAxiomNthBranch ax index)
ppr_co_ax_branch :: (TyCon -> Type -> SDoc) -> CoAxiom br -> CoAxBranch -> SDoc
ppr_co_ax_branch ppr_rhs
(CoAxiom { co_ax_tc = fam_tc, co_ax_name = name })
(CoAxBranch { cab_tvs = tvs
, cab_cvs = cvs
, cab_lhs = lhs
, cab_rhs = rhs
, cab_loc = loc })
= foldr1 (flip hangNotEmpty 2)
[ pprUserForAll (mkTyVarBinders Inferred (tvs ++ cvs))
, pprTypeApp fam_tc lhs <+> equals <+> ppr_rhs fam_tc rhs
, text "-- Defined" <+> pprLoc loc ]
where
pprLoc loc
| isGoodSrcSpan loc
= text "at" <+> ppr (srcSpanStart loc)
| otherwise
= text "in" <+>
quotes (ppr (nameModule name))
{-
%************************************************************************
%* *
Destructing coercions
%* *
%************************************************************************
-}
-- | This breaks a 'Coercion' with type @T A B C ~ T D E F@ into
-- a list of 'Coercion's of kinds @A ~ D@, @B ~ E@ and @E ~ F@. Hence:
--
-- > decomposeCo 3 c = [nth 0 c, nth 1 c, nth 2 c]
decomposeCo :: Arity -> Coercion -> [Coercion]
decomposeCo arity co
= [mkNthCo n co | n <- [0..(arity-1)] ]
-- Remember, Nth is zero-indexed
-- | Attempts to obtain the type variable underlying a 'Coercion'
getCoVar_maybe :: Coercion -> Maybe CoVar
getCoVar_maybe (CoVarCo cv) = Just cv
getCoVar_maybe _ = Nothing
-- | Attempts to tease a coercion apart into a type constructor and the application
-- of a number of coercion arguments to that constructor
splitTyConAppCo_maybe :: Coercion -> Maybe (TyCon, [Coercion])
splitTyConAppCo_maybe (Refl r ty)
= do { (tc, tys) <- splitTyConApp_maybe ty
; let args = zipWith mkReflCo (tyConRolesX r tc) tys
; return (tc, args) }
splitTyConAppCo_maybe (TyConAppCo _ tc cos) = Just (tc, cos)
splitTyConAppCo_maybe _ = Nothing
-- first result has role equal to input; third result is Nominal
splitAppCo_maybe :: Coercion -> Maybe (Coercion, Coercion)
-- ^ Attempt to take a coercion application apart.
splitAppCo_maybe (AppCo co arg) = Just (co, arg)
splitAppCo_maybe (TyConAppCo r tc args)
| mightBeUnsaturatedTyCon tc || args `lengthExceeds` tyConArity tc
-- Never create unsaturated type family apps!
, Just (args', arg') <- snocView args
, Just arg'' <- setNominalRole_maybe arg'
= Just ( mkTyConAppCo r tc args', arg'' )
-- Use mkTyConAppCo to preserve the invariant
-- that identity coercions are always represented by Refl
splitAppCo_maybe (Refl r ty)
| Just (ty1, ty2) <- splitAppTy_maybe ty
= Just (mkReflCo r ty1, mkNomReflCo ty2)
splitAppCo_maybe _ = Nothing
splitForAllCo_maybe :: Coercion -> Maybe (TyVar, Coercion, Coercion)
splitForAllCo_maybe (ForAllCo tv k_co co) = Just (tv, k_co, co)
splitForAllCo_maybe _ = Nothing
-------------------------------------------------------
-- and some coercion kind stuff
coVarTypes :: CoVar -> (Type,Type)
coVarTypes cv
| (_, _, ty1, ty2, _) <- coVarKindsTypesRole cv
= (ty1, ty2)
coVarKindsTypesRole :: CoVar -> (Kind,Kind,Type,Type,Role)
coVarKindsTypesRole cv
| Just (tc, [k1,k2,ty1,ty2]) <- splitTyConApp_maybe (varType cv)
= let role
| tc `hasKey` eqPrimTyConKey = Nominal
| tc `hasKey` eqReprPrimTyConKey = Representational
| otherwise = panic "coVarKindsTypesRole"
in (k1,k2,ty1,ty2,role)
| otherwise = pprPanic "coVarKindsTypesRole, non coercion variable"
(ppr cv $$ ppr (varType cv))
coVarKind :: CoVar -> Type
coVarKind cv
= ASSERT( isCoVar cv )
varType cv
coVarRole :: CoVar -> Role
coVarRole cv
| tc `hasKey` eqPrimTyConKey
= Nominal
| tc `hasKey` eqReprPrimTyConKey
= Representational
| otherwise
= pprPanic "coVarRole: unknown tycon" (ppr cv <+> dcolon <+> ppr (varType cv))
where
tc = case tyConAppTyCon_maybe (varType cv) of
Just tc0 -> tc0
Nothing -> pprPanic "coVarRole: not tyconapp" (ppr cv)
-- | Makes a coercion type from two types: the types whose equality
-- is proven by the relevant 'Coercion'
mkCoercionType :: Role -> Type -> Type -> Type
mkCoercionType Nominal = mkPrimEqPred
mkCoercionType Representational = mkReprPrimEqPred
mkCoercionType Phantom = \ty1 ty2 ->
let ki1 = typeKind ty1
ki2 = typeKind ty2
in
TyConApp eqPhantPrimTyCon [ki1, ki2, ty1, ty2]
mkHeteroCoercionType :: Role -> Kind -> Kind -> Type -> Type -> Type
mkHeteroCoercionType Nominal = mkHeteroPrimEqPred
mkHeteroCoercionType Representational = mkHeteroReprPrimEqPred
mkHeteroCoercionType Phantom = panic "mkHeteroCoercionType"
-- | Tests if this coercion is obviously reflexive. Guaranteed to work
-- very quickly. Sometimes a coercion can be reflexive, but not obviously
-- so. c.f. 'isReflexiveCo'
isReflCo :: Coercion -> Bool
isReflCo (Refl {}) = True
isReflCo _ = False
-- | Returns the type coerced if this coercion is reflexive. Guaranteed
-- to work very quickly. Sometimes a coercion can be reflexive, but not
-- obviously so. c.f. 'isReflexiveCo_maybe'
isReflCo_maybe :: Coercion -> Maybe (Type, Role)
isReflCo_maybe (Refl r ty) = Just (ty, r)
isReflCo_maybe _ = Nothing
-- | Slowly checks if the coercion is reflexive. Don't call this in a loop,
-- as it walks over the entire coercion.
isReflexiveCo :: Coercion -> Bool
isReflexiveCo = isJust . isReflexiveCo_maybe
-- | Extracts the coerced type from a reflexive coercion. This potentially
-- walks over the entire coercion, so avoid doing this in a loop.
isReflexiveCo_maybe :: Coercion -> Maybe (Type, Role)
isReflexiveCo_maybe (Refl r ty) = Just (ty, r)
isReflexiveCo_maybe co
| ty1 `eqType` ty2
= Just (ty1, r)
| otherwise
= Nothing
where (Pair ty1 ty2, r) = coercionKindRole co
{-
%************************************************************************
%* *
Building coercions
%* *
%************************************************************************
These "smart constructors" maintain the invariants listed in the definition
of Coercion, and they perform very basic optimizations.
Note [Role twiddling functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
There are a plethora of functions for twiddling roles:
mkSubCo: Requires a nominal input coercion and always produces a
representational output. This is used when you (the programmer) are sure you
know exactly that role you have and what you want.
downgradeRole_maybe: This function takes both the input role and the output role
as parameters. (The *output* role comes first!) It can only *downgrade* a
role -- that is, change it from N to R or P, or from R to P. This one-way
behavior is why there is the "_maybe". If an upgrade is requested, this
function produces Nothing. This is used when you need to change the role of a
coercion, but you're not sure (as you're writing the code) of which roles are
involved.
This function could have been written using coercionRole to ascertain the role
of the input. But, that function is recursive, and the caller of downgradeRole_maybe
often knows the input role. So, this is more efficient.
downgradeRole: This is just like downgradeRole_maybe, but it panics if the
conversion isn't a downgrade.
setNominalRole_maybe: This is the only function that can *upgrade* a coercion.
The result (if it exists) is always Nominal. The input can be at any role. It
works on a "best effort" basis, as it should never be strictly necessary to
upgrade a coercion during compilation. It is currently only used within GHC in
splitAppCo_maybe. In order to be a proper inverse of mkAppCo, the second
coercion that splitAppCo_maybe returns must be nominal. But, it's conceivable
that splitAppCo_maybe is operating over a TyConAppCo that uses a
representational coercion. Hence the need for setNominalRole_maybe.
splitAppCo_maybe, in turn, is used only within coercion optimization -- thus,
it is not absolutely critical that setNominalRole_maybe be complete.
Note that setNominalRole_maybe will never upgrade a phantom UnivCo. Phantom
UnivCos are perfectly type-safe, whereas representational and nominal ones are
not. Indeed, `unsafeCoerce` is implemented via a representational UnivCo.
(Nominal ones are no worse than representational ones, so this function *will*
change a UnivCo Representational to a UnivCo Nominal.)
Conal Elliott also came across a need for this function while working with the
GHC API, as he was decomposing Core casts. The Core casts use representational
coercions, as they must, but his use case required nominal coercions (he was
building a GADT). So, that's why this function is exported from this module.
One might ask: shouldn't downgradeRole_maybe just use setNominalRole_maybe as
appropriate? I (Richard E.) have decided not to do this, because upgrading a
role is bizarre and a caller should have to ask for this behavior explicitly.
Note [mkTransAppCo]
~~~~~~~~~~~~~~~~~~~
Suppose we have
co1 :: a ~R Maybe
co2 :: b ~R Int
and we want
co3 :: a b ~R Maybe Int
This seems sensible enough. But, we can't let (co3 = co1 co2), because
that's ill-roled! Note that mkAppCo requires a *nominal* second coercion.
The way around this is to use transitivity:
co3 = (co1 <b>_N) ; (Maybe co2) :: a b ~R Maybe Int
Or, it's possible everything is the other way around:
co1' :: Maybe ~R a
co2' :: Int ~R b
and we want
co3' :: Maybe Int ~R a b
then
co3' = (Maybe co2') ; (co1' <b>_N)
This is exactly what `mkTransAppCo` builds for us. Information for all
the arguments tends to be to hand at call sites, so it's quicker than
using, say, coercionKind.
-}
mkReflCo :: Role -> Type -> Coercion
mkReflCo r ty
= Refl r ty
-- | Make a representational reflexive coercion
mkRepReflCo :: Type -> Coercion
mkRepReflCo = mkReflCo Representational
-- | Make a nominal reflexive coercion
mkNomReflCo :: Type -> Coercion
mkNomReflCo = mkReflCo Nominal
-- | Apply a type constructor to a list of coercions. It is the
-- caller's responsibility to get the roles correct on argument coercions.
mkTyConAppCo :: Role -> TyCon -> [Coercion] -> Coercion
mkTyConAppCo r tc cos
-- Expand type synonyms
| Just (tv_co_prs, rhs_ty, leftover_cos) <- expandSynTyCon_maybe tc cos
= mkAppCos (liftCoSubst r (mkLiftingContext tv_co_prs) rhs_ty) leftover_cos
| Just tys_roles <- traverse isReflCo_maybe cos
= Refl r (mkTyConApp tc (map fst tys_roles)) -- See Note [Refl invariant]
| otherwise = TyConAppCo r tc cos
-- | Make a function 'Coercion' between two other 'Coercion's
mkFunCo :: Role -> Coercion -> Coercion -> Coercion
mkFunCo r co1 co2 = mkTyConAppCo r funTyCon [co1, co2]
-- | Make nested function 'Coercion's
mkFunCos :: Role -> [Coercion] -> Coercion -> Coercion
mkFunCos r cos res_co = foldr (mkFunCo r) res_co cos
-- | Apply a 'Coercion' to another 'Coercion'.
-- The second coercion must be Nominal, unless the first is Phantom.
-- If the first is Phantom, then the second can be either Phantom or Nominal.
mkAppCo :: Coercion -- ^ :: t1 ~r t2
-> Coercion -- ^ :: s1 ~N s2, where s1 :: k1, s2 :: k2
-> Coercion -- ^ :: t1 s1 ~r t2 s2
mkAppCo (Refl r ty1) arg
| Just (ty2, _) <- isReflCo_maybe arg
= Refl r (mkAppTy ty1 ty2)
| Just (tc, tys) <- splitTyConApp_maybe ty1
-- Expand type synonyms; a TyConAppCo can't have a type synonym (Trac #9102)
= TyConAppCo r tc (zip_roles (tyConRolesX r tc) tys)
where
zip_roles (r1:_) [] = [downgradeRole r1 Nominal arg]
zip_roles (r1:rs) (ty1:tys) = mkReflCo r1 ty1 : zip_roles rs tys
zip_roles _ _ = panic "zip_roles" -- but the roles are infinite...
mkAppCo (TyConAppCo r tc args) arg
= case r of
Nominal -> TyConAppCo Nominal tc (args ++ [arg])
Representational -> TyConAppCo Representational tc (args ++ [arg'])
where new_role = (tyConRolesRepresentational tc) !! (length args)
arg' = downgradeRole new_role Nominal arg
Phantom -> TyConAppCo Phantom tc (args ++ [toPhantomCo arg])
mkAppCo co arg = AppCo co arg
-- Note, mkAppCo is careful to maintain invariants regarding
-- where Refl constructors appear; see the comments in the definition
-- of Coercion and the Note [Refl invariant] in TyCoRep.
-- | Applies multiple 'Coercion's to another 'Coercion', from left to right.
-- See also 'mkAppCo'.
mkAppCos :: Coercion
-> [Coercion]
-> Coercion
mkAppCos co1 cos = foldl mkAppCo co1 cos
-- | Like `mkAppCo`, but allows the second coercion to be other than
-- nominal. See Note [mkTransAppCo]. Role r3 cannot be more stringent
-- than either r1 or r2.
mkTransAppCo :: Role -- ^ r1
-> Coercion -- ^ co1 :: ty1a ~r1 ty1b
-> Type -- ^ ty1a
-> Type -- ^ ty1b
-> Role -- ^ r2
-> Coercion -- ^ co2 :: ty2a ~r2 ty2b
-> Type -- ^ ty2a
-> Type -- ^ ty2b
-> Role -- ^ r3
-> Coercion -- ^ :: ty1a ty2a ~r3 ty1b ty2b
mkTransAppCo r1 co1 ty1a ty1b r2 co2 ty2a ty2b r3
-- How incredibly fiddly! Is there a better way??
= case (r1, r2, r3) of
(_, _, Phantom)
-> mkPhantomCo kind_co (mkAppTy ty1a ty2a) (mkAppTy ty1b ty2b)
where -- ty1a :: k1a -> k2a
-- ty1b :: k1b -> k2b
-- ty2a :: k1a
-- ty2b :: k1b
-- ty1a ty2a :: k2a
-- ty1b ty2b :: k2b
kind_co1 = mkKindCo co1 -- :: k1a -> k2a ~N k1b -> k2b
kind_co = mkNthCo 1 kind_co1 -- :: k2a ~N k2b
(_, _, Nominal)
-> ASSERT( r1 == Nominal && r2 == Nominal )
mkAppCo co1 co2
(Nominal, Nominal, Representational)
-> mkSubCo (mkAppCo co1 co2)
(_, Nominal, Representational)
-> ASSERT( r1 == Representational )
mkAppCo co1 co2
(Nominal, Representational, Representational)
-> go (mkSubCo co1)
(_ , _, Representational)
-> ASSERT( r1 == Representational && r2 == Representational )
go co1
where
go co1_repr
| Just (tc1b, tys1b) <- splitTyConApp_maybe ty1b
, nextRole ty1b == r2
= (mkAppCo co1_repr (mkNomReflCo ty2a)) `mkTransCo`
(mkTyConAppCo Representational tc1b
(zipWith mkReflCo (tyConRolesRepresentational tc1b) tys1b
++ [co2]))
| Just (tc1a, tys1a) <- splitTyConApp_maybe ty1a
, nextRole ty1a == r2
= (mkTyConAppCo Representational tc1a
(zipWith mkReflCo (tyConRolesRepresentational tc1a) tys1a
++ [co2]))
`mkTransCo`
(mkAppCo co1_repr (mkNomReflCo ty2b))
| otherwise
= pprPanic "mkTransAppCo" (vcat [ ppr r1, ppr co1, ppr ty1a, ppr ty1b
, ppr r2, ppr co2, ppr ty2a, ppr ty2b
, ppr r3 ])
-- | Make a Coercion from a tyvar, a kind coercion, and a body coercion.
-- The kind of the tyvar should be the left-hand kind of the kind coercion.
mkForAllCo :: TyVar -> Coercion -> Coercion -> Coercion
mkForAllCo tv kind_co co
| Refl r ty <- co
, Refl {} <- kind_co
= Refl r (mkInvForAllTy tv ty)
| otherwise
= ForAllCo tv kind_co co
-- | Make nested ForAllCos
mkForAllCos :: [(TyVar, Coercion)] -> Coercion -> Coercion
mkForAllCos bndrs (Refl r ty)
= let (refls_rev'd, non_refls_rev'd) = span (isReflCo . snd) (reverse bndrs) in
foldl (flip $ uncurry ForAllCo)
(Refl r $ mkInvForAllTys (reverse (map fst refls_rev'd)) ty)
non_refls_rev'd
mkForAllCos bndrs co = foldr (uncurry ForAllCo) co bndrs
-- | Make a Coercion quantified over a type variable;
-- the variable has the same type in both sides of the coercion
mkHomoForAllCos :: [TyVar] -> Coercion -> Coercion
mkHomoForAllCos tvs (Refl r ty)
= Refl r (mkInvForAllTys tvs ty)
mkHomoForAllCos tvs ty = mkHomoForAllCos_NoRefl tvs ty
-- | Like 'mkHomoForAllCos', but doesn't check if the inner coercion
-- is reflexive.
mkHomoForAllCos_NoRefl :: [TyVar] -> Coercion -> Coercion
mkHomoForAllCos_NoRefl tvs orig_co = foldr go orig_co tvs
where
go tv co = ForAllCo tv (mkNomReflCo (tyVarKind tv)) co
mkCoVarCo :: CoVar -> Coercion
-- cv :: s ~# t
mkCoVarCo cv
| ty1 `eqType` ty2 = Refl (coVarRole cv) ty1
| otherwise = CoVarCo cv
where
(ty1, ty2) = coVarTypes cv
mkCoVarCos :: [CoVar] -> [Coercion]
mkCoVarCos = map mkCoVarCo
-- | Extract a covar, if possible. This check is dirty. Be ashamed
-- of yourself. (It's dirty because it cares about the structure of
-- a coercion, which is morally reprehensible.)
isCoVar_maybe :: Coercion -> Maybe CoVar
isCoVar_maybe (CoVarCo cv) = Just cv
isCoVar_maybe _ = Nothing
mkAxInstCo :: Role -> CoAxiom br -> BranchIndex -> [Type] -> [Coercion]
-> Coercion
-- mkAxInstCo can legitimately be called over-staturated;
-- i.e. with more type arguments than the coercion requires
mkAxInstCo role ax index tys cos
| arity == n_tys = downgradeRole role ax_role $
mkAxiomInstCo ax_br index (rtys `chkAppend` cos)
| otherwise = ASSERT( arity < n_tys )
downgradeRole role ax_role $
mkAppCos (mkAxiomInstCo ax_br index
(ax_args `chkAppend` cos))
leftover_args
where
n_tys = length tys
ax_br = toBranchedAxiom ax
branch = coAxiomNthBranch ax_br index
tvs = coAxBranchTyVars branch
arity = length tvs
arg_roles = coAxBranchRoles branch
rtys = zipWith mkReflCo (arg_roles ++ repeat Nominal) tys
(ax_args, leftover_args)
= splitAt arity rtys
ax_role = coAxiomRole ax
-- worker function; just checks to see if it should produce Refl
mkAxiomInstCo :: CoAxiom Branched -> BranchIndex -> [Coercion] -> Coercion
mkAxiomInstCo ax index args
= ASSERT( coAxiomArity ax index == length args )
AxiomInstCo ax index args
-- to be used only with unbranched axioms
mkUnbranchedAxInstCo :: Role -> CoAxiom Unbranched
-> [Type] -> [Coercion] -> Coercion
mkUnbranchedAxInstCo role ax tys cos
= mkAxInstCo role ax 0 tys cos
mkAxInstRHS :: CoAxiom br -> BranchIndex -> [Type] -> [Coercion] -> Type
-- Instantiate the axiom with specified types,
-- returning the instantiated RHS
-- A companion to mkAxInstCo:
-- mkAxInstRhs ax index tys = snd (coercionKind (mkAxInstCo ax index tys))
mkAxInstRHS ax index tys cos
= ASSERT( tvs `equalLength` tys1 )
mkAppTys rhs' tys2
where
branch = coAxiomNthBranch ax index
tvs = coAxBranchTyVars branch
cvs = coAxBranchCoVars branch
(tys1, tys2) = splitAtList tvs tys
rhs' = substTyWith tvs tys1 $
substTyWithCoVars cvs cos $
coAxBranchRHS branch
mkUnbranchedAxInstRHS :: CoAxiom Unbranched -> [Type] -> [Coercion] -> Type
mkUnbranchedAxInstRHS ax = mkAxInstRHS ax 0
-- | Return the left-hand type of the axiom, when the axiom is instantiated
-- at the types given.
mkAxInstLHS :: CoAxiom br -> BranchIndex -> [Type] -> [Coercion] -> Type
mkAxInstLHS ax index tys cos
= ASSERT( tvs `equalLength` tys1 )
mkTyConApp fam_tc (lhs_tys `chkAppend` tys2)
where
branch = coAxiomNthBranch ax index
tvs = coAxBranchTyVars branch
cvs = coAxBranchCoVars branch
(tys1, tys2) = splitAtList tvs tys
lhs_tys = substTysWith tvs tys1 $
substTysWithCoVars cvs cos $
coAxBranchLHS branch
fam_tc = coAxiomTyCon ax
-- | Instantiate the left-hand side of an unbranched axiom
mkUnbranchedAxInstLHS :: CoAxiom Unbranched -> [Type] -> [Coercion] -> Type
mkUnbranchedAxInstLHS ax = mkAxInstLHS ax 0
-- | Manufacture an unsafe coercion from thin air.
-- Currently (May 14) this is used only to implement the
-- @unsafeCoerce#@ primitive. Optimise by pushing
-- down through type constructors.
mkUnsafeCo :: Role -> Type -> Type -> Coercion
mkUnsafeCo role ty1 ty2
= mkUnivCo UnsafeCoerceProv role ty1 ty2
-- | Make a coercion from a coercion hole
mkHoleCo :: CoercionHole -> Role
-> Type -> Type -> Coercion
mkHoleCo h r t1 t2 = mkUnivCo (HoleProv h) r t1 t2
-- | Make a universal coercion between two arbitrary types.
mkUnivCo :: UnivCoProvenance
-> Role -- ^ role of the built coercion, "r"
-> Type -- ^ t1 :: k1
-> Type -- ^ t2 :: k2
-> Coercion -- ^ :: t1 ~r t2
mkUnivCo prov role ty1 ty2
| ty1 `eqType` ty2 = Refl role ty1
| otherwise = UnivCo prov role ty1 ty2
-- | Create a symmetric version of the given 'Coercion' that asserts
-- equality between the same types but in the other "direction", so
-- a kind of @t1 ~ t2@ becomes the kind @t2 ~ t1@.
mkSymCo :: Coercion -> Coercion
-- Do a few simple optimizations, but don't bother pushing occurrences
-- of symmetry to the leaves; the optimizer will take care of that.
mkSymCo co@(Refl {}) = co
mkSymCo (SymCo co) = co
mkSymCo (SubCo (SymCo co)) = SubCo co
mkSymCo co = SymCo co
-- | Create a new 'Coercion' by composing the two given 'Coercion's transitively.
-- (co1 ; co2)
mkTransCo :: Coercion -> Coercion -> Coercion
mkTransCo co1 (Refl {}) = co1
mkTransCo (Refl {}) co2 = co2
mkTransCo co1 co2 = TransCo co1 co2
-- the Role is the desired one. It is the caller's responsibility to make
-- sure this request is reasonable
mkNthCoRole :: Role -> Int -> Coercion -> Coercion
mkNthCoRole role n co
= downgradeRole role nth_role $ nth_co
where
nth_co = mkNthCo n co
nth_role = coercionRole nth_co
mkNthCo :: Int -> Coercion -> Coercion
mkNthCo 0 (Refl _ ty)
| Just (tv, _) <- splitForAllTy_maybe ty
= Refl Nominal (tyVarKind tv)
mkNthCo n (Refl r ty)
= ASSERT( ok_tc_app ty n )
mkReflCo r' (tyConAppArgN n ty)
where tc = tyConAppTyCon ty
r' = nthRole r tc n
ok_tc_app :: Type -> Int -> Bool
ok_tc_app ty n
| Just (_, tys) <- splitTyConApp_maybe ty
= tys `lengthExceeds` n
| isForAllTy ty -- nth:0 pulls out a kind coercion from a hetero forall
= n == 0
| otherwise
= False
mkNthCo n (TyConAppCo _ _ cos) = cos `getNth` n
mkNthCo n co = NthCo n co
mkLRCo :: LeftOrRight -> Coercion -> Coercion
mkLRCo lr (Refl eq ty) = Refl eq (pickLR lr (splitAppTy ty))
mkLRCo lr co = LRCo lr co
-- | Instantiates a 'Coercion'.
mkInstCo :: Coercion -> Coercion -> Coercion
mkInstCo (ForAllCo tv _kind_co body_co) (Refl _ arg)
= substCoWithUnchecked [tv] [arg] body_co
mkInstCo co arg = InstCo co arg
-- This could work harder to produce Refl coercions, but that would be
-- quite inefficient. Seems better not to try.
mkCoherenceCo :: Coercion -> Coercion -> Coercion
mkCoherenceCo co1 (Refl {}) = co1
mkCoherenceCo (CoherenceCo co1 co2) co3
= CoherenceCo co1 (co2 `mkTransCo` co3)
mkCoherenceCo co1 co2 = CoherenceCo co1 co2
-- | A CoherenceCo c1 c2 applies the coercion c2 to the left-hand type
-- in the kind of c1. This function uses sym to get the coercion on the
-- right-hand type of c1. Thus, if c1 :: s ~ t, then mkCoherenceRightCo c1 c2
-- has the kind (s ~ (t |> c2)) down through type constructors.
-- The second coercion must be representational.
mkCoherenceRightCo :: Coercion -> Coercion -> Coercion
mkCoherenceRightCo c1 c2 = mkSymCo (mkCoherenceCo (mkSymCo c1) c2)
-- | An explictly directed synonym of mkCoherenceCo. The second
-- coercion must be representational.
mkCoherenceLeftCo :: Coercion -> Coercion -> Coercion
mkCoherenceLeftCo = mkCoherenceCo
infixl 5 `mkCoherenceCo`
infixl 5 `mkCoherenceRightCo`
infixl 5 `mkCoherenceLeftCo`
mkKindCo :: Coercion -> Coercion
mkKindCo (Refl _ ty) = Refl Nominal (typeKind ty)
mkKindCo (UnivCo (PhantomProv h) _ _ _) = h
mkKindCo (UnivCo (ProofIrrelProv h) _ _ _) = h
mkKindCo co
| Pair ty1 ty2 <- coercionKind co
-- generally, calling coercionKind during coercion creation is a bad idea,
-- as it can lead to exponential behavior. But, we don't have nested mkKindCos,
-- so it's OK here.
, typeKind ty1 `eqType` typeKind ty2
= Refl Nominal (typeKind ty1)
| otherwise
= KindCo co
-- input coercion is Nominal; see also Note [Role twiddling functions]
mkSubCo :: Coercion -> Coercion
mkSubCo (Refl Nominal ty) = Refl Representational ty
mkSubCo (TyConAppCo Nominal tc cos)
= TyConAppCo Representational tc (applyRoles tc cos)
mkSubCo co = ASSERT2( coercionRole co == Nominal, ppr co <+> ppr (coercionRole co) )
SubCo co
-- | Changes a role, but only a downgrade. See Note [Role twiddling functions]
downgradeRole_maybe :: Role -- ^ desired role
-> Role -- ^ current role
-> Coercion -> Maybe Coercion
-- In (downgradeRole_maybe dr cr co) it's a precondition that
-- cr = coercionRole co
downgradeRole_maybe Representational Nominal co = Just (mkSubCo co)
downgradeRole_maybe Nominal Representational _ = Nothing
downgradeRole_maybe Phantom Phantom co = Just co
downgradeRole_maybe Phantom _ co = Just (toPhantomCo co)
downgradeRole_maybe _ Phantom _ = Nothing
downgradeRole_maybe _ _ co = Just co
-- | Like 'downgradeRole_maybe', but panics if the change isn't a downgrade.
-- See Note [Role twiddling functions]
downgradeRole :: Role -- desired role
-> Role -- current role
-> Coercion -> Coercion
downgradeRole r1 r2 co
= case downgradeRole_maybe r1 r2 co of
Just co' -> co'
Nothing -> pprPanic "downgradeRole" (ppr co)
-- | If the EqRel is ReprEq, makes a SubCo; otherwise, does nothing.
-- Note that the input coercion should always be nominal.
maybeSubCo :: EqRel -> Coercion -> Coercion
maybeSubCo NomEq = id
maybeSubCo ReprEq = mkSubCo
mkAxiomRuleCo :: CoAxiomRule -> [Coercion] -> Coercion
mkAxiomRuleCo = AxiomRuleCo
-- | Make a "coercion between coercions".
mkProofIrrelCo :: Role -- ^ role of the created coercion, "r"
-> Coercion -- ^ :: phi1 ~N phi2
-> Coercion -- ^ g1 :: phi1
-> Coercion -- ^ g2 :: phi2
-> Coercion -- ^ :: g1 ~r g2
-- if the two coercion prove the same fact, I just don't care what
-- the individual coercions are.
mkProofIrrelCo r (Refl {}) g _ = Refl r (CoercionTy g)
mkProofIrrelCo r kco g1 g2 = mkUnivCo (ProofIrrelProv kco) r
(mkCoercionTy g1) (mkCoercionTy g2)
{-
%************************************************************************
%* *
Roles
%* *
%************************************************************************
-}
-- | Converts a coercion to be nominal, if possible.
-- See Note [Role twiddling functions]
setNominalRole_maybe :: Coercion -> Maybe Coercion
setNominalRole_maybe co
| Nominal <- coercionRole co = Just co
setNominalRole_maybe (SubCo co) = Just co
setNominalRole_maybe (Refl _ ty) = Just $ Refl Nominal ty
setNominalRole_maybe (TyConAppCo Representational tc cos)
= do { cos' <- mapM setNominalRole_maybe cos
; return $ TyConAppCo Nominal tc cos' }
setNominalRole_maybe (SymCo co)
= SymCo <$> setNominalRole_maybe co
setNominalRole_maybe (TransCo co1 co2)
= TransCo <$> setNominalRole_maybe co1 <*> setNominalRole_maybe co2
setNominalRole_maybe (AppCo co1 co2)
= AppCo <$> setNominalRole_maybe co1 <*> pure co2
setNominalRole_maybe (ForAllCo tv kind_co co)
= ForAllCo tv kind_co <$> setNominalRole_maybe co
setNominalRole_maybe (NthCo n co)
= NthCo n <$> setNominalRole_maybe co
setNominalRole_maybe (InstCo co arg)
= InstCo <$> setNominalRole_maybe co <*> pure arg
setNominalRole_maybe (CoherenceCo co1 co2)
= CoherenceCo <$> setNominalRole_maybe co1 <*> pure co2
setNominalRole_maybe (UnivCo prov _ co1 co2)
| case prov of UnsafeCoerceProv -> True -- it's always unsafe
PhantomProv _ -> False -- should always be phantom
ProofIrrelProv _ -> True -- it's always safe
PluginProv _ -> False -- who knows? This choice is conservative.
HoleProv _ -> False -- no no no.
= Just $ UnivCo prov Nominal co1 co2
setNominalRole_maybe _ = Nothing
-- | Make a phantom coercion between two types. The coercion passed
-- in must be a nominal coercion between the kinds of the
-- types.
mkPhantomCo :: Coercion -> Type -> Type -> Coercion
mkPhantomCo h t1 t2
= mkUnivCo (PhantomProv h) Phantom t1 t2
-- | Make a phantom coercion between two types of the same kind.
mkHomoPhantomCo :: Type -> Type -> Coercion
mkHomoPhantomCo t1 t2
= ASSERT( k1 `eqType` typeKind t2 )
mkPhantomCo (mkNomReflCo k1) t1 t2
where
k1 = typeKind t1
-- takes any coercion and turns it into a Phantom coercion
toPhantomCo :: Coercion -> Coercion
toPhantomCo co
= mkPhantomCo (mkKindCo co) ty1 ty2
where Pair ty1 ty2 = coercionKind co
-- Convert args to a TyConAppCo Nominal to the same TyConAppCo Representational
applyRoles :: TyCon -> [Coercion] -> [Coercion]
applyRoles tc cos
= zipWith (\r -> downgradeRole r Nominal) (tyConRolesRepresentational tc) cos
-- the Role parameter is the Role of the TyConAppCo
-- defined here because this is intimiately concerned with the implementation
-- of TyConAppCo
tyConRolesX :: Role -> TyCon -> [Role]
tyConRolesX Representational tc = tyConRolesRepresentational tc
tyConRolesX role _ = repeat role
tyConRolesRepresentational :: TyCon -> [Role]
tyConRolesRepresentational tc = tyConRoles tc ++ repeat Nominal
nthRole :: Role -> TyCon -> Int -> Role
nthRole Nominal _ _ = Nominal
nthRole Phantom _ _ = Phantom
nthRole Representational tc n
= (tyConRolesRepresentational tc) `getNth` n
ltRole :: Role -> Role -> Bool
-- Is one role "less" than another?
-- Nominal < Representational < Phantom
ltRole Phantom _ = False
ltRole Representational Phantom = True
ltRole Representational _ = False
ltRole Nominal Nominal = False
ltRole Nominal _ = True
-------------------------------
-- | like mkKindCo, but aggressively & recursively optimizes to avoid using
-- a KindCo constructor. The output role is nominal.
promoteCoercion :: Coercion -> Coercion
-- First cases handles anything that should yield refl.
promoteCoercion co = case co of
_ | ki1 `eqType` ki2
-> mkNomReflCo (typeKind ty1)
-- no later branch should return refl
-- The ASSERT( False )s throughout
-- are these cases explicitly, but they should never fire.
Refl _ ty -> ASSERT( False )
mkNomReflCo (typeKind ty)
TyConAppCo _ tc args
| Just co' <- instCoercions (mkNomReflCo (tyConKind tc)) args
-> co'
| otherwise
-> mkKindCo co
AppCo co1 arg
| Just co' <- instCoercion (coercionKind (mkKindCo co1))
(promoteCoercion co1) arg
-> co'
| otherwise
-> mkKindCo co
ForAllCo _ _ g
-> promoteCoercion g
CoVarCo {}
-> mkKindCo co
AxiomInstCo {}
-> mkKindCo co
UnivCo UnsafeCoerceProv _ t1 t2
-> mkUnsafeCo Nominal (typeKind t1) (typeKind t2)
UnivCo (PhantomProv kco) _ _ _
-> kco
UnivCo (ProofIrrelProv kco) _ _ _
-> kco
UnivCo (PluginProv _) _ _ _
-> mkKindCo co
UnivCo (HoleProv _) _ _ _
-> mkKindCo co
SymCo g
-> mkSymCo (promoteCoercion g)
TransCo co1 co2
-> mkTransCo (promoteCoercion co1) (promoteCoercion co2)
NthCo n co1
| Just (_, args) <- splitTyConAppCo_maybe co1
, n < length args
-> promoteCoercion (args !! n)
| Just _ <- splitForAllCo_maybe co
, n == 0
-> ASSERT( False ) mkNomReflCo liftedTypeKind
| otherwise
-> mkKindCo co
LRCo lr co1
| Just (lco, rco) <- splitAppCo_maybe co1
-> case lr of
CLeft -> promoteCoercion lco
CRight -> promoteCoercion rco
| otherwise
-> mkKindCo co
InstCo g _
-> promoteCoercion g
CoherenceCo g h
-> mkSymCo h `mkTransCo` promoteCoercion g
KindCo _
-> ASSERT( False )
mkNomReflCo liftedTypeKind
SubCo g
-> promoteCoercion g
AxiomRuleCo {}
-> mkKindCo co
where
Pair ty1 ty2 = coercionKind co
ki1 = typeKind ty1
ki2 = typeKind ty2
-- | say @g = promoteCoercion h@. Then, @instCoercion g w@ yields @Just g'@,
-- where @g' = promoteCoercion (h w)@.
-- fails if this is not possible, if @g@ coerces between a forall and an ->
-- or if second parameter has a representational role and can't be used
-- with an InstCo. The result role matches is representational.
instCoercion :: Pair Type -- type of the first coercion
-> Coercion -- ^ must be nominal
-> Coercion
-> Maybe Coercion
instCoercion (Pair lty rty) g w
| isForAllTy lty && isForAllTy rty
, Just w' <- setNominalRole_maybe w
= Just $ mkInstCo g w'
| isFunTy lty && isFunTy rty
= Just $ mkNthCo 1 g -- extract result type, which is the 2nd argument to (->)
| otherwise -- one forall, one funty...
= Nothing
where
instCoercions :: Coercion -> [Coercion] -> Maybe Coercion
instCoercions g ws
= let arg_ty_pairs = map coercionKind ws in
snd <$> foldM go (coercionKind g, g) (zip arg_ty_pairs ws)
where
go :: (Pair Type, Coercion) -> (Pair Type, Coercion)
-> Maybe (Pair Type, Coercion)
go (g_tys, g) (w_tys, w)
= do { g' <- instCoercion g_tys g w
; return (piResultTy <$> g_tys <*> w_tys, g') }
-- | Creates a new coercion with both of its types casted by different casts
-- castCoercionKind g h1 h2, where g :: t1 ~ t2, has type (t1 |> h1) ~ (t2 |> h2)
-- The second and third coercions must be nominal.
castCoercionKind :: Coercion -> Coercion -> Coercion -> Coercion
castCoercionKind g h1 h2
= g `mkCoherenceLeftCo` h1 `mkCoherenceRightCo` h2
-- See note [Newtype coercions] in TyCon
mkPiCos :: Role -> [Var] -> Coercion -> Coercion
mkPiCos r vs co = foldr (mkPiCo r) co vs
mkPiCo :: Role -> Var -> Coercion -> Coercion
mkPiCo r v co | isTyVar v = mkHomoForAllCos [v] co
| otherwise = mkFunCo r (mkReflCo r (varType v)) co
-- The second coercion is sometimes lifted (~) and sometimes unlifted (~#).
-- So, we have to make sure to supply the right parameter to decomposeCo.
-- mkCoCast (c :: s1 ~# t1) (g :: (s1 ~# s2) ~# (t1 ~# t2)) :: s2 ~# t2
-- Both coercions *must* have the same role.
mkCoCast :: Coercion -> Coercion -> Coercion
mkCoCast c g
= mkSymCo g1 `mkTransCo` c `mkTransCo` g2
where
-- g :: (s1 ~# s2) ~# (t1 ~# t2)
-- g1 :: s1 ~# t1
-- g2 :: s2 ~# t2
(_, args) = splitTyConApp (pFst $ coercionKind g)
n_args = length args
co_list = decomposeCo n_args g
g1 = co_list `getNth` (n_args - 2)
g2 = co_list `getNth` (n_args - 1)
{-
%************************************************************************
%* *
Newtypes
%* *
%************************************************************************
-}
-- | If @co :: T ts ~ rep_ty@ then:
--
-- > instNewTyCon_maybe T ts = Just (rep_ty, co)
--
-- Checks for a newtype, and for being saturated
instNewTyCon_maybe :: TyCon -> [Type] -> Maybe (Type, Coercion)
instNewTyCon_maybe tc tys
| Just (tvs, ty, co_tc) <- unwrapNewTyConEtad_maybe tc -- Check for newtype
, tvs `leLength` tys -- Check saturated enough
= Just (applyTysX tvs ty tys, mkUnbranchedAxInstCo Representational co_tc tys [])
| otherwise
= Nothing
{-
************************************************************************
* *
Type normalisation
* *
************************************************************************
-}
-- | A function to check if we can reduce a type by one step. Used
-- with 'topNormaliseTypeX'.
type NormaliseStepper ev = RecTcChecker
-> TyCon -- tc
-> [Type] -- tys
-> NormaliseStepResult ev
-- | The result of stepping in a normalisation function.
-- See 'topNormaliseTypeX'.
data NormaliseStepResult ev
= NS_Done -- ^ Nothing more to do
| NS_Abort -- ^ Utter failure. The outer function should fail too.
| NS_Step RecTcChecker Type ev -- ^ We stepped, yielding new bits;
-- ^ ev is evidence;
-- Usually a co :: old type ~ new type
mapStepResult :: (ev1 -> ev2)
-> NormaliseStepResult ev1 -> NormaliseStepResult ev2
mapStepResult f (NS_Step rec_nts ty ev) = NS_Step rec_nts ty (f ev)
mapStepResult _ NS_Done = NS_Done
mapStepResult _ NS_Abort = NS_Abort
-- | Try one stepper and then try the next, if the first doesn't make
-- progress.
-- So if it returns NS_Done, it means that both steppers are satisfied
composeSteppers :: NormaliseStepper ev -> NormaliseStepper ev
-> NormaliseStepper ev
composeSteppers step1 step2 rec_nts tc tys
= case step1 rec_nts tc tys of
success@(NS_Step {}) -> success
NS_Done -> step2 rec_nts tc tys
NS_Abort -> NS_Abort
-- | A 'NormaliseStepper' that unwraps newtypes, careful not to fall into
-- a loop. If it would fall into a loop, it produces 'NS_Abort'.
unwrapNewTypeStepper :: NormaliseStepper Coercion
unwrapNewTypeStepper rec_nts tc tys
| Just (ty', co) <- instNewTyCon_maybe tc tys
= case checkRecTc rec_nts tc of
Just rec_nts' -> NS_Step rec_nts' ty' co
Nothing -> NS_Abort
| otherwise
= NS_Done
-- | A general function for normalising the top-level of a type. It continues
-- to use the provided 'NormaliseStepper' until that function fails, and then
-- this function returns. The roles of the coercions produced by the
-- 'NormaliseStepper' must all be the same, which is the role returned from
-- the call to 'topNormaliseTypeX'.
--
-- Typically ev is Coercion.
--
-- If topNormaliseTypeX step plus ty = Just (ev, ty')
-- then ty ~ev1~ t1 ~ev2~ t2 ... ~evn~ ty'
-- and ev = ev1 `plus` ev2 `plus` ... `plus` evn
-- If it returns Nothing then no newtype unwrapping could happen
topNormaliseTypeX :: NormaliseStepper ev -> (ev -> ev -> ev)
-> Type -> Maybe (ev, Type)
topNormaliseTypeX stepper plus ty
| Just (tc, tys) <- splitTyConApp_maybe ty
, NS_Step rec_nts ty' ev <- stepper initRecTc tc tys
= go rec_nts ev ty'
| otherwise
= Nothing
where
go rec_nts ev ty
| Just (tc, tys) <- splitTyConApp_maybe ty
= case stepper rec_nts tc tys of
NS_Step rec_nts' ty' ev' -> go rec_nts' (ev `plus` ev') ty'
NS_Done -> Just (ev, ty)
NS_Abort -> Nothing
| otherwise
= Just (ev, ty)
topNormaliseNewType_maybe :: Type -> Maybe (Coercion, Type)
-- ^ Sometimes we want to look through a @newtype@ and get its associated coercion.
-- This function strips off @newtype@ layers enough to reveal something that isn't
-- a @newtype@. Specifically, here's the invariant:
--
-- > topNormaliseNewType_maybe rec_nts ty = Just (co, ty')
--
-- then (a) @co : ty0 ~ ty'@.
-- (b) ty' is not a newtype.
--
-- The function returns @Nothing@ for non-@newtypes@,
-- or unsaturated applications
--
-- This function does *not* look through type families, because it has no access to
-- the type family environment. If you do have that at hand, consider to use
-- topNormaliseType_maybe, which should be a drop-in replacement for
-- topNormaliseNewType_maybe
-- If topNormliseNewType_maybe ty = Just (co, ty'), then co : ty ~R ty'
topNormaliseNewType_maybe ty
= topNormaliseTypeX unwrapNewTypeStepper mkTransCo ty
{-
%************************************************************************
%* *
Comparison of coercions
%* *
%************************************************************************
-}
-- | Syntactic equality of coercions
eqCoercion :: Coercion -> Coercion -> Bool
eqCoercion = eqType `on` coercionType
-- | Compare two 'Coercion's, with respect to an RnEnv2
eqCoercionX :: RnEnv2 -> Coercion -> Coercion -> Bool
eqCoercionX env = eqTypeX env `on` coercionType
{-
%************************************************************************
%* *
"Lifting" substitution
[(TyCoVar,Coercion)] -> Type -> Coercion
%* *
%************************************************************************
Note [Lifting coercions over types: liftCoSubst]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The KPUSH rule deals with this situation
data T a = MkK (a -> Maybe a)
g :: T t1 ~ K t2
x :: t1 -> Maybe t1
case (K @t1 x) |> g of
K (y:t2 -> Maybe t2) -> rhs
We want to push the coercion inside the constructor application.
So we do this
g' :: t1~t2 = Nth 0 g
case K @t2 (x |> g' -> Maybe g') of
K (y:t2 -> Maybe t2) -> rhs
The crucial operation is that we
* take the type of K's argument: a -> Maybe a
* and substitute g' for a
thus giving *coercion*. This is what liftCoSubst does.
In the presence of kind coercions, this is a bit
of a hairy operation. So, we refer you to the paper introducing kind coercions,
available at www.cis.upenn.edu/~sweirich/papers/fckinds-extended.pdf
-}
-- ----------------------------------------------------
-- See Note [Lifting coercions over types: liftCoSubst]
-- ----------------------------------------------------
data LiftingContext = LC TCvSubst LiftCoEnv
-- in optCoercion, we need to lift when optimizing InstCo.
-- See Note [Optimising InstCo] in OptCoercion
-- We thus propagate the substitution from OptCoercion here.
instance Outputable LiftingContext where
ppr (LC _ env) = hang (text "LiftingContext:") 2 (ppr env)
type LiftCoEnv = VarEnv Coercion
-- Maps *type variables* to *coercions*.
-- That's the whole point of this function!
-- like liftCoSubstWith, but allows for existentially-bound types as well
liftCoSubstWithEx :: Role -- desired role for output coercion
-> [TyVar] -- universally quantified tyvars
-> [Coercion] -- coercions to substitute for those
-> [TyVar] -- existentially quantified tyvars
-> [Type] -- types to be bound to ex vars
-> (Type -> Coercion, [Type]) -- (lifting function, converted ex args)
liftCoSubstWithEx role univs omegas exs rhos
= let theta = mkLiftingContext (zipEqual "liftCoSubstWithExU" univs omegas)
psi = extendLiftingContextEx theta (zipEqual "liftCoSubstWithExX" exs rhos)
in (ty_co_subst psi role, substTyVars (lcSubstRight psi) exs)
liftCoSubstWith :: Role -> [TyCoVar] -> [Coercion] -> Type -> Coercion
-- NB: This really can be called with CoVars, when optimising axioms.
liftCoSubstWith r tvs cos ty
= liftCoSubst r (mkLiftingContext $ zipEqual "liftCoSubstWith" tvs cos) ty
-- | @liftCoSubst role lc ty@ produces a coercion (at role @role@)
-- that coerces between @lc_left(ty)@ and @lc_right(ty)@, where
-- @lc_left@ is a substitution mapping type variables to the left-hand
-- types of the mapped coercions in @lc@, and similar for @lc_right@.
liftCoSubst :: Role -> LiftingContext -> Type -> Coercion
liftCoSubst r lc@(LC subst env) ty
| isEmptyVarEnv env = Refl r (substTy subst ty)
| otherwise = ty_co_subst lc r ty
emptyLiftingContext :: InScopeSet -> LiftingContext
emptyLiftingContext in_scope = LC (mkEmptyTCvSubst in_scope) emptyVarEnv
mkLiftingContext :: [(TyCoVar,Coercion)] -> LiftingContext
mkLiftingContext pairs
= LC (mkEmptyTCvSubst $ mkInScopeSet $ tyCoVarsOfCos (map snd pairs))
(mkVarEnv pairs)
mkSubstLiftingContext :: TCvSubst -> LiftingContext
mkSubstLiftingContext subst = LC subst emptyVarEnv
-- | Extend a lifting context with a new /type/ mapping.
extendLiftingContext :: LiftingContext -- ^ original LC
-> TyVar -- ^ new variable to map...
-> Coercion -- ^ ...to this lifted version
-> LiftingContext
extendLiftingContext (LC subst env) tv arg
= ASSERT( isTyVar tv )
LC subst (extendVarEnv env tv arg)
-- | Extend a lifting context with existential-variable bindings.
-- This follows the lifting context extension definition in the
-- "FC with Explicit Kind Equality" paper.
extendLiftingContextEx :: LiftingContext -- ^ original lifting context
-> [(TyVar,Type)] -- ^ ex. var / value pairs
-> LiftingContext
-- Note that this is more involved than extendLiftingContext. That function
-- takes a coercion to extend with, so it's assumed that the caller has taken
-- into account any of the kind-changing stuff worried about here.
extendLiftingContextEx lc [] = lc
extendLiftingContextEx lc@(LC subst env) ((v,ty):rest)
-- This function adds bindings for *Nominal* coercions. Why? Because it
-- works with existentially bound variables, which are considered to have
-- nominal roles.
= let lc' = LC (subst `extendTCvInScopeSet` tyCoVarsOfType ty)
(extendVarEnv env v (mkSymCo $ mkCoherenceCo
(mkNomReflCo ty)
(ty_co_subst lc Nominal (tyVarKind v))))
in extendLiftingContextEx lc' rest
-- | Erase the environments in a lifting context
zapLiftingContext :: LiftingContext -> LiftingContext
zapLiftingContext (LC subst _) = LC (zapTCvSubst subst) emptyVarEnv
-- | Like 'substForAllCoBndr', but works on a lifting context
substForAllCoBndrCallbackLC :: Bool
-> (Coercion -> Coercion)
-> LiftingContext -> TyVar -> Coercion
-> (LiftingContext, TyVar, Coercion)
substForAllCoBndrCallbackLC sym sco (LC subst lc_env) tv co
= (LC subst' lc_env, tv', co')
where
(subst', tv', co') = substForAllCoBndrCallback sym sco subst tv co
-- | The \"lifting\" operation which substitutes coercions for type
-- variables in a type to produce a coercion.
--
-- For the inverse operation, see 'liftCoMatch'
ty_co_subst :: LiftingContext -> Role -> Type -> Coercion
ty_co_subst lc role ty
= go role ty
where
go :: Role -> Type -> Coercion
go Phantom ty = lift_phantom ty
go r (TyVarTy tv) = expectJust "ty_co_subst bad roles" $
liftCoSubstTyVar lc r tv
go r (AppTy ty1 ty2) = mkAppCo (go r ty1) (go Nominal ty2)
go r (TyConApp tc tys) = mkTyConAppCo r tc (zipWith go (tyConRolesX r tc) tys)
go r (FunTy ty1 ty2) = mkFunCo r (go r ty1) (go r ty2)
go r (ForAllTy (TvBndr v _) ty)
= let (lc', v', h) = liftCoSubstVarBndr lc v in
mkForAllCo v' h $! ty_co_subst lc' r ty
go r ty@(LitTy {}) = ASSERT( r == Nominal )
mkReflCo r ty
go r (CastTy ty co) = castCoercionKind (go r ty) (substLeftCo lc co)
(substRightCo lc co)
go r (CoercionTy co) = mkProofIrrelCo r kco (substLeftCo lc co)
(substRightCo lc co)
where kco = go Nominal (coercionType co)
lift_phantom ty = mkPhantomCo (go Nominal (typeKind ty))
(substTy (lcSubstLeft lc) ty)
(substTy (lcSubstRight lc) ty)
{-
Note [liftCoSubstTyVar]
~~~~~~~~~~~~~~~~~~~~~~~~~
This function can fail if a coercion in the environment is of too low a role.
liftCoSubstTyVar is called from two places: in liftCoSubst (naturally), and
also in matchAxiom in OptCoercion. From liftCoSubst, the so-called lifting
lemma guarantees that the roles work out. If we fail in this
case, we really should panic -- something is deeply wrong. But, in matchAxiom,
failing is fine. matchAxiom is trying to find a set of coercions
that match, but it may fail, and this is healthy behavior.
-}
-- See Note [liftCoSubstTyVar]
liftCoSubstTyVar :: LiftingContext -> Role -> TyVar -> Maybe Coercion
liftCoSubstTyVar (LC subst env) r v
| Just co_arg <- lookupVarEnv env v
= downgradeRole_maybe r (coercionRole co_arg) co_arg
| otherwise
= Just $ Refl r (substTyVar subst v)
liftCoSubstVarBndr :: LiftingContext -> TyVar
-> (LiftingContext, TyVar, Coercion)
liftCoSubstVarBndr lc tv
= let (lc', tv', h, _) = liftCoSubstVarBndrCallback callback lc tv in
(lc', tv', h)
where
callback lc' ty' = (ty_co_subst lc' Nominal ty', ())
-- the callback must produce a nominal coercion
liftCoSubstVarBndrCallback :: (LiftingContext -> Type -> (Coercion, a))
-> LiftingContext -> TyVar
-> (LiftingContext, TyVar, Coercion, a)
liftCoSubstVarBndrCallback fun lc@(LC subst cenv) old_var
= ( LC (subst `extendTCvInScope` new_var) new_cenv
, new_var, eta, stuff )
where
old_kind = tyVarKind old_var
(eta, stuff) = fun lc old_kind
Pair k1 _ = coercionKind eta
new_var = uniqAway (getTCvInScope subst) (setVarType old_var k1)
lifted = Refl Nominal (TyVarTy new_var)
new_cenv = extendVarEnv cenv old_var lifted
-- | Is a var in the domain of a lifting context?
isMappedByLC :: TyCoVar -> LiftingContext -> Bool
isMappedByLC tv (LC _ env) = tv `elemVarEnv` env
-- If [a |-> g] is in the substitution and g :: t1 ~ t2, substitute a for t1
-- If [a |-> (g1, g2)] is in the substitution, substitute a for g1
substLeftCo :: LiftingContext -> Coercion -> Coercion
substLeftCo lc co
= substCo (lcSubstLeft lc) co
-- Ditto, but for t2 and g2
substRightCo :: LiftingContext -> Coercion -> Coercion
substRightCo lc co
= substCo (lcSubstRight lc) co
-- | Apply "sym" to all coercions in a 'LiftCoEnv'
swapLiftCoEnv :: LiftCoEnv -> LiftCoEnv
swapLiftCoEnv = mapVarEnv mkSymCo
lcSubstLeft :: LiftingContext -> TCvSubst
lcSubstLeft (LC subst lc_env) = liftEnvSubstLeft subst lc_env
lcSubstRight :: LiftingContext -> TCvSubst
lcSubstRight (LC subst lc_env) = liftEnvSubstRight subst lc_env
liftEnvSubstLeft :: TCvSubst -> LiftCoEnv -> TCvSubst
liftEnvSubstLeft = liftEnvSubst pFst
liftEnvSubstRight :: TCvSubst -> LiftCoEnv -> TCvSubst
liftEnvSubstRight = liftEnvSubst pSnd
liftEnvSubst :: (forall a. Pair a -> a) -> TCvSubst -> LiftCoEnv -> TCvSubst
liftEnvSubst selector subst lc_env
= composeTCvSubst (TCvSubst emptyInScopeSet tenv cenv) subst
where
pairs = nonDetUFMToList lc_env
-- It's OK to use nonDetUFMToList here because we
-- immediately forget the ordering by creating
-- a VarEnv
(tpairs, cpairs) = partitionWith ty_or_co pairs
tenv = mkVarEnv_Directly tpairs
cenv = mkVarEnv_Directly cpairs
ty_or_co :: (Unique, Coercion) -> Either (Unique, Type) (Unique, Coercion)
ty_or_co (u, co)
| Just equality_co <- isCoercionTy_maybe equality_ty
= Right (u, equality_co)
| otherwise
= Left (u, equality_ty)
where
equality_ty = selector (coercionKind co)
-- | Extract the underlying substitution from the LiftingContext
lcTCvSubst :: LiftingContext -> TCvSubst
lcTCvSubst (LC subst _) = subst
-- | Get the 'InScopeSet' from a 'LiftingContext'
lcInScopeSet :: LiftingContext -> InScopeSet
lcInScopeSet (LC subst _) = getTCvInScope subst
{-
%************************************************************************
%* *
Sequencing on coercions
%* *
%************************************************************************
-}
seqCo :: Coercion -> ()
seqCo (Refl r ty) = r `seq` seqType ty
seqCo (TyConAppCo r tc cos) = r `seq` tc `seq` seqCos cos
seqCo (AppCo co1 co2) = seqCo co1 `seq` seqCo co2
seqCo (ForAllCo tv k co) = seqType (tyVarKind tv) `seq` seqCo k
`seq` seqCo co
seqCo (CoVarCo cv) = cv `seq` ()
seqCo (AxiomInstCo con ind cos) = con `seq` ind `seq` seqCos cos
seqCo (UnivCo p r t1 t2)
= seqProv p `seq` r `seq` seqType t1 `seq` seqType t2
seqCo (SymCo co) = seqCo co
seqCo (TransCo co1 co2) = seqCo co1 `seq` seqCo co2
seqCo (NthCo n co) = n `seq` seqCo co
seqCo (LRCo lr co) = lr `seq` seqCo co
seqCo (InstCo co arg) = seqCo co `seq` seqCo arg
seqCo (CoherenceCo co1 co2) = seqCo co1 `seq` seqCo co2
seqCo (KindCo co) = seqCo co
seqCo (SubCo co) = seqCo co
seqCo (AxiomRuleCo _ cs) = seqCos cs
seqProv :: UnivCoProvenance -> ()
seqProv UnsafeCoerceProv = ()
seqProv (PhantomProv co) = seqCo co
seqProv (ProofIrrelProv co) = seqCo co
seqProv (PluginProv _) = ()
seqProv (HoleProv _) = ()
seqCos :: [Coercion] -> ()
seqCos [] = ()
seqCos (co:cos) = seqCo co `seq` seqCos cos
{-
%************************************************************************
%* *
The kind of a type, and of a coercion
%* *
%************************************************************************
Note [Computing a coercion kind and role]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To compute a coercion's kind is straightforward: see coercionKind.
But to compute a coercion's role, in the case for NthCo we need
its kind as well. So if we have two separate functions (one for kinds
and one for roles) we can get exponentially bad behaviour, since each
NthCo node makes a separate call to coercionKind, which traverses the
sub-tree again. This was part of the problem in Trac #9233.
Solution: compute both together; hence coercionKindRole. We keep a
separate coercionKind function because it's a bit more efficient if
the kind is all you want.
-}
coercionType :: Coercion -> Type
coercionType co = case coercionKindRole co of
(Pair ty1 ty2, r) -> mkCoercionType r ty1 ty2
------------------
-- | If it is the case that
--
-- > c :: (t1 ~ t2)
--
-- i.e. the kind of @c@ relates @t1@ and @t2@, then @coercionKind c = Pair t1 t2@.
coercionKind :: Coercion -> Pair Type
coercionKind co = go co
where
go (Refl _ ty) = Pair ty ty
go (TyConAppCo _ tc cos)= mkTyConApp tc <$> (sequenceA $ map go cos)
go (AppCo co1 co2) = mkAppTy <$> go co1 <*> go co2
go (ForAllCo tv1 k_co co)
= let Pair _ k2 = go k_co
tv2 = setTyVarKind tv1 k2
Pair ty1 ty2 = go co
subst = zipTvSubst [tv1] [TyVarTy tv2 `mk_cast_ty` mkSymCo k_co]
ty2' = substTyAddInScope subst ty2 in
-- We need free vars of ty2 in scope to satisfy the invariant
-- from Note [The substitution invariant]
-- This is doing repeated substitutions and probably doesn't
-- need to, see #11735
mkInvForAllTy <$> Pair tv1 tv2 <*> Pair ty1 ty2'
go (CoVarCo cv) = toPair $ coVarTypes cv
go (AxiomInstCo ax ind cos)
| CoAxBranch { cab_tvs = tvs, cab_cvs = cvs
, cab_lhs = lhs, cab_rhs = rhs } <- coAxiomNthBranch ax ind
, let Pair tycos1 tycos2 = sequenceA (map go cos)
(tys1, cotys1) = splitAtList tvs tycos1
(tys2, cotys2) = splitAtList tvs tycos2
cos1 = map stripCoercionTy cotys1
cos2 = map stripCoercionTy cotys2
= ASSERT( cos `equalLength` (tvs ++ cvs) )
-- Invariant of AxiomInstCo: cos should
-- exactly saturate the axiom branch
Pair (substTyWith tvs tys1 $
substTyWithCoVars cvs cos1 $
mkTyConApp (coAxiomTyCon ax) lhs)
(substTyWith tvs tys2 $
substTyWithCoVars cvs cos2 rhs)
go (UnivCo _ _ ty1 ty2) = Pair ty1 ty2
go (SymCo co) = swap $ go co
go (TransCo co1 co2) = Pair (pFst $ go co1) (pSnd $ go co2)
go g@(NthCo d co)
| Just argss <- traverse tyConAppArgs_maybe tys
= ASSERT( and $ ((d <) . length) <$> argss )
(`getNth` d) <$> argss
| d == 0
, Just splits <- traverse splitForAllTy_maybe tys
= (tyVarKind . fst) <$> splits
| otherwise
= pprPanic "coercionKind" (ppr g)
where
tys = go co
go (LRCo lr co) = (pickLR lr . splitAppTy) <$> go co
go (InstCo aco arg) = go_app aco [arg]
go (CoherenceCo g h)
= let Pair ty1 ty2 = go g in
Pair (mkCastTy ty1 h) ty2
go (KindCo co) = typeKind <$> go co
go (SubCo co) = go co
go (AxiomRuleCo ax cos) = expectJust "coercionKind" $
coaxrProves ax (map go cos)
go_app :: Coercion -> [Coercion] -> Pair Type
-- Collect up all the arguments and apply all at once
-- See Note [Nested InstCos]
go_app (InstCo co arg) args = go_app co (arg:args)
go_app co args = piResultTys <$> go co <*> (sequenceA $ map go args)
-- The real mkCastTy is too slow, and we can easily have nested ForAllCos.
mk_cast_ty :: Type -> Coercion -> Type
mk_cast_ty ty (Refl {}) = ty
mk_cast_ty ty co = CastTy ty co
-- | Apply 'coercionKind' to multiple 'Coercion's
coercionKinds :: [Coercion] -> Pair [Type]
coercionKinds tys = sequenceA $ map coercionKind tys
-- | Get a coercion's kind and role.
-- Why both at once? See Note [Computing a coercion kind and role]
coercionKindRole :: Coercion -> (Pair Type, Role)
coercionKindRole = go
where
go (Refl r ty) = (Pair ty ty, r)
go (TyConAppCo r tc cos)
= (mkTyConApp tc <$> (sequenceA $ map coercionKind cos), r)
go (AppCo co1 co2)
= let (tys1, r1) = go co1 in
(mkAppTy <$> tys1 <*> coercionKind co2, r1)
go (ForAllCo tv1 k_co co)
= let Pair _ k2 = coercionKind k_co
tv2 = setTyVarKind tv1 k2
(Pair ty1 ty2, r) = go co
subst = zipTvSubst [tv1] [TyVarTy tv2 `mkCastTy` mkSymCo k_co]
ty2' = substTyAddInScope subst ty2 in
-- We need free vars of ty2 in scope to satisfy the invariant
-- from Note [The substitution invariant]
-- This is doing repeated substitutions and probably doesn't
-- need to, see #11735
(mkInvForAllTy <$> Pair tv1 tv2 <*> Pair ty1 ty2', r)
go (CoVarCo cv) = (toPair $ coVarTypes cv, coVarRole cv)
go co@(AxiomInstCo ax _ _) = (coercionKind co, coAxiomRole ax)
go (UnivCo _ r ty1 ty2) = (Pair ty1 ty2, r)
go (SymCo co) = first swap $ go co
go (TransCo co1 co2)
= let (tys1, r) = go co1 in
(Pair (pFst tys1) (pSnd $ coercionKind co2), r)
go (NthCo d co)
| Just (tv1, _) <- splitForAllTy_maybe ty1
= ASSERT( d == 0 )
let (tv2, _) = splitForAllTy ty2 in
(tyVarKind <$> Pair tv1 tv2, Nominal)
| otherwise
= let (tc1, args1) = splitTyConApp ty1
(_tc2, args2) = splitTyConApp ty2
in
ASSERT( tc1 == _tc2 )
((`getNth` d) <$> Pair args1 args2, nthRole r tc1 d)
where
(Pair ty1 ty2, r) = go co
go co@(LRCo {}) = (coercionKind co, Nominal)
go (InstCo co arg) = go_app co [arg]
go (CoherenceCo co1 co2)
= let (Pair t1 t2, r) = go co1 in
(Pair (t1 `mkCastTy` co2) t2, r)
go co@(KindCo {}) = (coercionKind co, Nominal)
go (SubCo co) = (coercionKind co, Representational)
go co@(AxiomRuleCo ax _) = (coercionKind co, coaxrRole ax)
go_app :: Coercion -> [Coercion] -> (Pair Type, Role)
-- Collect up all the arguments and apply all at once
-- See Note [Nested InstCos]
go_app (InstCo co arg) args = go_app co (arg:args)
go_app co args
= let (pair, r) = go co in
(piResultTys <$> pair <*> (sequenceA $ map coercionKind args), r)
-- | Retrieve the role from a coercion.
coercionRole :: Coercion -> Role
coercionRole = snd . coercionKindRole
-- There's not a better way to do this, because NthCo needs the *kind*
-- and role of its argument. Luckily, laziness should generally avoid
-- the need for computing kinds in other cases.
{-
Note [Nested InstCos]
~~~~~~~~~~~~~~~~~~~~~
In Trac #5631 we found that 70% of the entire compilation time was
being spent in coercionKind! The reason was that we had
(g @ ty1 @ ty2 .. @ ty100) -- The "@s" are InstCos
where
g :: forall a1 a2 .. a100. phi
If we deal with the InstCos one at a time, we'll do this:
1. Find the kind of (g @ ty1 .. @ ty99) : forall a100. phi'
2. Substitute phi'[ ty100/a100 ], a single tyvar->type subst
But this is a *quadratic* algorithm, and the blew up Trac #5631.
So it's very important to do the substitution simultaneously;
cf Type.piResultTys (which in fact we call here).
-}
| olsner/ghc | compiler/types/Coercion.hs | bsd-3-clause | 71,893 | 0 | 18 | 19,651 | 15,480 | 8,025 | 7,455 | -1 | -1 |
module Type where
import Control.Applicative
import Data.Int
import qualified Data.List as List
data Type = ObjectType ObjectType | PrimaryType PrimaryType | NullType
deriving Eq
instance Show Type where
show (ObjectType ot) = ot
show (PrimaryType pt) = show pt
show NullType = "null"
type ObjectType = String
data PrimaryType
= TBoolean
| TByte
| TShort
| TInt
| TLong
| TFloat
| TDouble
deriving (Eq, Ord)
instance Show PrimaryType where
show TBoolean = "boolean"
show TByte = "byte"
show TShort = "short"
show TInt = "int"
show TLong = "long"
show TFloat = "float"
show TDouble = "double"
data Literal
= LBoolean Bool
| LByte Int8
| LShort Int16
| LInt Int32
| LLong Int64
| LFloat Float
| LDouble Double
deriving Eq
instance Show Literal where
show (LBoolean b) = show b
show (LByte b) = show b
show (LShort s) = show s
show (LInt i) = show i
show (LLong l) = show l
show (LFloat f) = show f
show (LDouble d) = show d
data Ternary = Zero | Half | One
deriving (Show, Eq, Ord)
literalType :: Literal -> PrimaryType
literalType (LBoolean _) = TBoolean
literalType (LByte _) = TByte
literalType (LShort _) = TShort
literalType (LInt _) = TInt
literalType (LLong _) = TLong
literalType (LFloat _) = TFloat
literalType (LDouble _) = TDouble
inferPrimary :: PrimaryType -> PrimaryType -> Maybe PrimaryType
inferPrimary TBoolean TBoolean = Just TBoolean
inferPrimary TBoolean _ = Nothing
inferPrimary _ TBoolean = Nothing
inferPrimary t1 t2 = case compare t1 t2 of
GT -> Just t1
EQ -> Just t1
LT -> Just t2
infer :: Type -> Type -> Maybe Type
infer (PrimaryType t1) (PrimaryType t2) = PrimaryType <$> inferPrimary t1 t2
infer o@(ObjectType _) NullType = Just o
infer NullType o@(ObjectType _) = Just o
infer t1 t2 = if t1 == t2 then Just t1 else Nothing
castPrimary :: PrimaryType -> PrimaryType -> Bool
castPrimary TBoolean TBoolean = True
castPrimary TBoolean _ = False
castPrimary _ TBoolean = False
castPrimary t1 t2 = t1 <= t2
cast :: Type -> Type -> Bool
cast (PrimaryType t1) (PrimaryType t2) = castPrimary t1 t2
cast (PrimaryType _) _ = False
cast _ (PrimaryType _) = False
cast _ NullType = error "error in compiler"
cast NullType _ = True
cast t1 t2 = t1 == t2
canCast :: Type -> Type -> Ternary
canCast from to
| from == to = One
| cast from to = Half
| otherwise = Zero
castTypeLists :: [Type] -> [Type] -> Ternary
castTypeLists from to
| length from /= length to = Zero
| null from = One
| otherwise = List.minimum $ List.zipWith canCast from to
| ademinn/JavaWithClasses | src/Type.hs | bsd-3-clause | 2,653 | 0 | 9 | 644 | 1,013 | 513 | 500 | 90 | 3 |
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module AuthReqBodyCheck where
import Data.Text (Text)
import Models
import GHC.Generics
import Data.Typeable
import Config
import qualified Data.List as L
import qualified Web.Cookie as C
import Api.Session (sessionCookieName)
import Database.Persist.Sql
import Data.Time (getCurrentTime)
import Servant
import Data.Text.Encoding (encodeUtf8, decodeUtf8)
import Session (userId, expires, decodeSession)
import qualified HmacAuth as H
import Data.ByteString (ByteString)
import AuthReqBody
authReqBodyCheck :: Config -> AuthReqBodyCheck UserId
authReqBodyCheck cfg = AuthReqBodyCheck $ \t m ->
case H.parse (decodeUtf8 t) of
Just (a,d) -> do
mat <- runSqlPool (getBy $ UniqueApiKey a) (getPool cfg)
case mat of
Just (Entity _ at) ->
return $ if H.verify (apiKeySecretKey at) d m
then Just $ apiKeyUserId at
else Nothing
Nothing -> return Nothing
Nothing -> return Nothing
| tlaitinen/servant-cookie-hmac-auth-example | src/AuthReqBodyCheck.hs | bsd-3-clause | 1,217 | 0 | 19 | 286 | 293 | 166 | 127 | 35 | 4 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE ExistentialQuantification #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE OverloadedStrings #-}
module Base.Exception where
import Base.Import
import Control.Exception
import Control.Monad.Catch (throwM)
import Data.Text (Text)
import GHC.Stack
import Network.Wai (ResponseReceived)
import Servant.Server
import Servant.Server.Internal (responseServantErr)
class (Exception e) => CornException e where
convert :: e -> ServantErr
convert _ = err400
instance CornException SomeException
data BaseCornException = forall e . CornException e => BaseCornException String e deriving Exception
instance Show BaseCornException where
show (BaseCornException callstacks e) = show e <> ":\n" <> callstacks
instance CornException BaseCornException where
convert (BaseCornException _ e) = convert e
withAction :: (MonadIO m, MonadCatch m) => m a -> m b -> m c -> m c
withAction lock release action = do
lock
c <- action `catchAll` \e -> release >> Base.Exception.throwM e
release
return c
throwM :: (MonadThrow m, CornException e, ?loc :: CallStack) => e -> m a
throwM e = Control.Monad.Catch.throwM (BaseCornException (prettyCallStack ?loc) e)
maybeToMonad :: (MonadThrow m, CornException e) => e -> Maybe a -> m a
maybeToMonad e = maybe (Base.Exception.throwM e) return
exceptionHandler ::(MonadIO m) => (Text -> m ())
-> (m ResponseReceived -> IO ResponseReceived)
-> SomeException
-> Application
exceptionHandler log run e _ resH = run $ do
log $ showText e
liftIO $ resH $ responseServantErr $ maybe err400 convert (fromException e :: Maybe BaseCornException)
httpStatus code name = ServantErr code name "" []
http201 = httpStatus 201 "Created"
http202 = httpStatus 202 "Accepted"
http204 = httpStatus 204 "No Content"
data ServerException = DataSourceNotFound
| DataSource_NotSupported Text
| ServiceException_ Text
| ExtensionModificationRejectedException
| File_NotFound Text
| File_LoadException Text
| Property_NotFound Text
| Property_ParseException Text
deriving (Show, Exception, CornException)
data BaseException = User_NotFound ID
| Field_Invalid_ Text Text
| UserName_NotValid Text
| Password_NotValid Text
| TicketTypeNotGiven
| TokenType_CanNotSignAsTicket Text
deriving (Show, Exception)
instance CornException BaseException where
convert (User_NotFound _) = http204
convert _ = err400
data AuthException = UnauthorizationException Text
| AuthenticationException
| InsufficientPermissions
deriving (Show, Exception)
instance CornException AuthException where
convert _ = err401
| leptonyu/mint | corn/src/Base/Exception.hs | bsd-3-clause | 3,150 | 0 | 12 | 955 | 754 | 395 | 359 | 68 | 1 |
-- Simple data type to keep track of character positions
-- within a text file or other text stream.
module Text.Packrat.Pos where
data Pos = Pos { posFile :: !String
, posLine :: !Int
, posCol :: !Int
}
nextPos (Pos file line col) c
| c == '\n' = Pos file (line + 1) 1
| c == '\t' = Pos file line ((div (col + 8 - 1) 8) * 8 + 1)
| otherwise = Pos file line (col + 1)
instance Eq Pos where
Pos f1 l1 c1 == Pos f2 l2 c2 =
f1 == f2 && l1 == l2 && c1 == c2
instance Ord Pos where
Pos f1 l1 c1 <= Pos f2 l2 c2 =
(l1 < l2) || (l1 == l2 && c1 <= c2)
instance Show Pos where
show (Pos file line col) = file ++ ":" ++ show line ++ ":" ++ show col
showPosRel (Pos file line col) (Pos file' line' col')
| file == file' =
if (line == line')
then "column " ++ show col'
else "line " ++ show line' ++ ", column " ++ show col'
| otherwise = show (Pos file' line' col')
| d3zd3z/HaskellNet-old | Text/Packrat/Pos.hs | bsd-3-clause | 986 | 0 | 14 | 331 | 418 | 207 | 211 | 28 | 2 |
module Paths_simple (
version,
getBinDir, getLibDir, getDataDir, getLibexecDir,
getDataFileName, getSysconfDir
) where
import qualified Control.Exception as Exception
import Data.Version (Version(..))
import System.Environment (getEnv)
import Prelude
catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
catchIO = Exception.catch
version :: Version
version = Version [0,1,0,0] []
bindir, libdir, datadir, libexecdir, sysconfdir :: FilePath
bindir = "/home/chuck/.cabal/bin"
libdir = "/home/chuck/.cabal/lib/x86_64-linux-ghc-7.10.3/simple-0.1.0.0-KGxVTV6Obxb9vekqkAzy3h"
datadir = "/home/chuck/.cabal/share/x86_64-linux-ghc-7.10.3/simple-0.1.0.0"
libexecdir = "/home/chuck/.cabal/libexec"
sysconfdir = "/home/chuck/.cabal/etc"
getBinDir, getLibDir, getDataDir, getLibexecDir, getSysconfDir :: IO FilePath
getBinDir = catchIO (getEnv "simple_bindir") (\_ -> return bindir)
getLibDir = catchIO (getEnv "simple_libdir") (\_ -> return libdir)
getDataDir = catchIO (getEnv "simple_datadir") (\_ -> return datadir)
getLibexecDir = catchIO (getEnv "simple_libexecdir") (\_ -> return libexecdir)
getSysconfDir = catchIO (getEnv "simple_sysconfdir") (\_ -> return sysconfdir)
getDataFileName :: FilePath -> IO FilePath
getDataFileName name = do
dir <- getDataDir
return (dir ++ "/" ++ name)
| Chuck-Aguilar/haskell-opencv-work | dist/build/autogen/Paths_simple.hs | bsd-3-clause | 1,322 | 0 | 10 | 177 | 362 | 206 | 156 | 28 | 1 |
module Main where
import Prelude ()
import Air.Env
import Air.Extra
import System.Nemesis.Jinjing.Angel
import Test.Hspec
spec :: IO ()
spec = hspec - do
describe "main" - do
it "should run spec" True
main = do
with_spec spec halt | nfjinjing/nemesis-jinjing | src/SpecTemplate.hs | bsd-3-clause | 242 | 0 | 11 | 49 | 82 | 44 | 38 | 12 | 1 |
module Geordi.Request where
import qualified Data.Text.Lazy as T
import qualified Data.Map as M
import qualified Network.HTTP.Types.Method as H
import Geordi.FileInfo
data Request f = Request { queries :: M.Map T.Text [T.Text]
, cookies :: M.Map T.Text [T.Text]
, posts :: M.Map T.Text [T.Text]
, files :: M.Map T.Text [FileInfo f]
, urlpieces :: [T.Text]
, methodStr :: H.Method
}
| liamoc/geordi | Geordi/Request.hs | bsd-3-clause | 580 | 0 | 11 | 257 | 148 | 90 | 58 | 11 | 0 |
{-# LANGUAGE OverloadedStrings, LambdaCase, TemplateHaskell, QuasiQuotes, TypeFamilies, MultiParamTypeClasses, GADTs, EmptyDataDecls, GeneralizedNewtypeDeriving #-}
module Main where
import Control.Monad.IO.Class
import Control.Monad.Logger
import Control.Monad.Trans.Maybe
import Data.ByteString (ByteString)
import Data.Text (Text)
import Database.Persist
import Database.Persist.Sqlite
import Database.Persist.TH
import Network.HTTP.Types
import Network.Wai
import Network.Wai.Application.Static
import qualified Data.Aeson as JSON
import qualified Data.ByteString.Lazy as BL
import qualified Network.Wai.Handler.Warp as Warp
import Control.Monad.Trans.Class
share [mkPersist sqlSettings, mkMigrate "migrateAll"] [persistLowerCase|
Entry
tagId TagId
classId ClassId
payload ByteString
UniqueEntry tagId classId
Tag
name Text
UniqueTag name
Class
name Text
payload ByteString
UniqueClass name
|]
fromMaybeT :: Functor f => a -> MaybeT f a -> f a
fromMaybeT x m = fmap (maybe x id) $ runMaybeT m
main :: IO ()
main = do
pool <- runStderrLoggingT $ createSqlitePool "dev.sqlite3" 10
let runDb :: SqlPersistT (LoggingT IO) a -> IO a
runDb q = runStderrLoggingT $ runSqlPool q pool
runDb $ runMigration migrateAll
liftIO $ Warp.run 3000 $ \req sendResp -> case pathInfo req of
["tags"] -> do
xs <- runDb $ selectList [] []
sendResp $ responseLBS status200 [(hContentType, "application/json")]
$ JSON.encode $ map (tagName . entityVal) xs
["classes"] -> do
xs <- runDb $ selectList [] []
sendResp $ responseLBS status200 [(hContentType, "application/json")]
$ JSON.encode $ map (className . entityVal) xs
["tag", tag] -> case requestMethod req of
"GET" -> runDb (getBy (UniqueTag tag)) >>= \case
Just _ -> sendResp $ responseLBS status200 [] ""
Nothing -> sendResp $ responseLBS status404 [] "Not found"
"POST" -> do
_ <- runDb $ upsert (Tag tag) []
sendResp $ responseLBS status200 [] "Done"
"DELETE" -> do
runDb $ deleteBy (UniqueTag tag)
sendResp $ responseLBS status200 [] "Done"
_ -> sendResp $ responseLBS status400 [] "Bad Request"
["class", cls] -> case requestMethod req of
"GET" -> runDb (getBy (UniqueClass cls)) >>= \case
Just c -> sendResp $ responseLBS status200 [] $ BL.fromStrict $ classPayload $ entityVal c
Nothing -> sendResp $ responseLBS status404 [] "Not found"
"POST" -> do
body <- strictRequestBody req
_ <- runDb $ upsert (Class cls (BL.toStrict body)) []
sendResp $ responseLBS status200 [] "Done"
"DELETE" -> do
runDb $ deleteBy (UniqueClass cls)
sendResp $ responseLBS status200 [] "Done"
_ -> sendResp $ responseLBS status400 [] "Bad Request"
["payload", tag, cls] -> case requestMethod req of
"GET" -> (sendResp=<<) $ fromMaybeT (responseLBS status404 [] "Entry doesn't exist") $ do
t <- MaybeT $ runDb $ getBy (UniqueTag tag)
c <- MaybeT $ runDb $ getBy (UniqueClass cls)
x <- MaybeT $ runDb $ getBy $ UniqueEntry (entityKey t) (entityKey c)
return $ responseLBS status200 [] $ BL.fromStrict $ entryPayload $ entityVal x
"POST" -> (sendResp=<<) $ fromMaybeT (responseLBS status404 [] "Entry doesn't exist") $ do
t <- MaybeT $ runDb $ getBy (UniqueTag tag)
c <- MaybeT $ runDb $ getBy (UniqueClass cls)
body <- lift $ strictRequestBody req
_ <- lift $ runDb $ upsert (Entry (entityKey t) (entityKey c) (BL.toStrict body)) []
return $ responseLBS status200 [] "Done"
_ -> sendResp $ responseLBS status400 [] "Bad Request"
[] -> staticApp (defaultWebAppSettings "web") req { pathInfo = ["cardboard.html"]} sendResp
_ -> staticApp (defaultWebAppSettings "web") req sendResp
| fumieval/cardboard | app/Main.hs | bsd-3-clause | 3,867 | 0 | 25 | 881 | 1,271 | 631 | 640 | 73 | 17 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Safe #-}
#if __GLASGOW_HASKELL__ >= 706
{-# LANGUAGE PolyKinds #-}
#endif
{-| A monad morphism is a natural transformation:
> morph :: forall a . m a -> n a
... that obeys the following two laws:
> morph $ do x <- m = do x <- morph m
> f x morph (f x)
>
> morph (return x) = return x
... which are equivalent to the following two functor laws:
> morph . (f >=> g) = morph . f >=> morph . g
>
> morph . return = return
Examples of monad morphisms include:
* 'lift' (from 'MonadTrans')
* 'squash' (See below)
* @'hoist' f@ (See below), if @f@ is a monad morphism
* @(f . g)@, if @f@ and @g@ are both monad morphisms
* 'id'
Monad morphisms commonly arise when manipulating existing monad transformer
code for compatibility purposes. The 'MFunctor', 'MonadTrans', and
'MMonad' classes define standard ways to change monad transformer stacks:
* 'lift' introduces a new monad transformer layer of any type.
* 'squash' flattens two identical monad transformer layers into a single
layer of the same type.
* 'hoist' maps monad morphisms to modify deeper layers of the monad
transformer stack.
-}
module Control.Monad.Morph (
-- * Functors over Monads
MFunctor(..),
generalize,
-- * Monads over Monads
MMonad(..),
MonadTrans(lift),
squash,
(>|>),
(<|<),
(=<|),
(|>=)
-- * Tutorial
-- $tutorial
-- ** Generalizing base monads
-- $generalize
-- ** Monad morphisms
-- $mmorph
-- ** Mixing diverse transformers
-- $interleave
-- ** Embedding transformers
-- $embed
) where
import Control.Monad.Trans.Class (MonadTrans(lift))
import qualified Control.Monad.Trans.Accum as A
import qualified Control.Monad.Trans.Except as Ex
import qualified Control.Monad.Trans.Identity as I
import qualified Control.Monad.Trans.Maybe as M
import qualified Control.Monad.Trans.Reader as R
import qualified Control.Monad.Trans.RWS.Lazy as RWS
import qualified Control.Monad.Trans.RWS.Strict as RWS'
import qualified Control.Monad.Trans.State.Lazy as S
import qualified Control.Monad.Trans.State.Strict as S'
import qualified Control.Monad.Trans.Writer.Lazy as W'
import qualified Control.Monad.Trans.Writer.Strict as W
import Data.Monoid (Monoid, mappend)
import Data.Functor.Compose (Compose (Compose))
import Data.Functor.Identity (runIdentity)
import Data.Functor.Product (Product (Pair))
import Control.Applicative.Backwards (Backwards (Backwards))
import Control.Applicative.Lift (Lift (Pure, Other))
-- For documentation
import Control.Exception (try, IOException)
import Control.Monad ((=<<), (>=>), (<=<), join)
import Data.Functor.Identity (Identity)
{-| A functor in the category of monads, using 'hoist' as the analog of 'fmap':
> hoist (f . g) = hoist f . hoist g
>
> hoist id = id
-}
class MFunctor t where
{-| Lift a monad morphism from @m@ to @n@ into a monad morphism from
@(t m)@ to @(t n)@
The first argument to `hoist` must be a monad morphism, even though the
type system does not enforce this
-}
hoist :: (Monad m) => (forall a . m a -> n a) -> t m b -> t n b
instance MFunctor (A.AccumT w) where
hoist nat m = A.AccumT (nat . A.runAccumT m)
instance MFunctor (Ex.ExceptT e) where
hoist nat m = Ex.ExceptT (nat (Ex.runExceptT m))
instance MFunctor I.IdentityT where
hoist nat m = I.IdentityT (nat (I.runIdentityT m))
instance MFunctor M.MaybeT where
hoist nat m = M.MaybeT (nat (M.runMaybeT m))
instance MFunctor (R.ReaderT r) where
hoist nat m = R.ReaderT (\i -> nat (R.runReaderT m i))
instance MFunctor (RWS.RWST r w s) where
hoist nat m = RWS.RWST (\r s -> nat (RWS.runRWST m r s))
instance MFunctor (RWS'.RWST r w s) where
hoist nat m = RWS'.RWST (\r s -> nat (RWS'.runRWST m r s))
instance MFunctor (S.StateT s) where
hoist nat m = S.StateT (\s -> nat (S.runStateT m s))
instance MFunctor (S'.StateT s) where
hoist nat m = S'.StateT (\s -> nat (S'.runStateT m s))
instance MFunctor (W.WriterT w) where
hoist nat m = W.WriterT (nat (W.runWriterT m))
instance MFunctor (W'.WriterT w) where
hoist nat m = W'.WriterT (nat (W'.runWriterT m))
instance Functor f => MFunctor (Compose f) where
hoist nat (Compose f) = Compose (fmap nat f)
instance MFunctor (Product f) where
hoist nat (Pair f g) = Pair f (nat g)
instance MFunctor Backwards where
hoist nat (Backwards f) = Backwards (nat f)
instance MFunctor Lift where
hoist _ (Pure a) = Pure a
hoist nat (Other f) = Other (nat f)
-- | A function that @generalize@s the 'Identity' base monad to be any monad.
generalize :: Monad m => Identity a -> m a
generalize = return . runIdentity
{-# INLINABLE generalize #-}
{-| A monad in the category of monads, using 'lift' from 'MonadTrans' as the
analog of 'return' and 'embed' as the analog of ('=<<'):
> embed lift = id
>
> embed f (lift m) = f m
>
> embed g (embed f t) = embed (\m -> embed g (f m)) t
-}
class (MFunctor t, MonadTrans t) => MMonad t where
{-| Embed a newly created 'MMonad' layer within an existing layer
'embed' is analogous to ('=<<')
-}
embed :: (Monad n) => (forall a . m a -> t n a) -> t m b -> t n b
{-| Squash two 'MMonad' layers into a single layer
'squash' is analogous to 'join'
-}
squash :: (Monad m, MMonad t) => t (t m) a -> t m a
squash = embed id
{-# INLINABLE squash #-}
infixr 2 >|>, =<|
infixl 2 <|<, |>=
{-| Compose two 'MMonad' layer-building functions
('>|>') is analogous to ('>=>')
-}
(>|>)
:: (Monad m3, MMonad t)
=> (forall a . m1 a -> t m2 a)
-> (forall b . m2 b -> t m3 b)
-> m1 c -> t m3 c
(f >|> g) m = embed g (f m)
{-# INLINABLE (>|>) #-}
{-| Equivalent to ('>|>') with the arguments flipped
('<|<') is analogous to ('<=<')
-}
(<|<)
:: (Monad m3, MMonad t)
=> (forall b . m2 b -> t m3 b)
-> (forall a . m1 a -> t m2 a)
-> m1 c -> t m3 c
(g <|< f) m = embed g (f m)
{-# INLINABLE (<|<) #-}
{-| An infix operator equivalent to 'embed'
('=<|') is analogous to ('=<<')
-}
(=<|) :: (Monad n, MMonad t) => (forall a . m a -> t n a) -> t m b -> t n b
(=<|) = embed
{-# INLINABLE (=<|) #-}
{-| Equivalent to ('=<|') with the arguments flipped
('|>=') is analogous to ('>>=')
-}
(|>=) :: (Monad n, MMonad t) => t m b -> (forall a . m a -> t n a) -> t n b
t |>= f = embed f t
{-# INLINABLE (|>=) #-}
instance Monoid w => MMonad (A.AccumT w) where
embed f m = A.AccumT $ \w -> do
((b, wInner), wOuter) <- A.runAccumT (f $ A.runAccumT m w) w
return (b, wInner `mappend` wOuter)
instance MMonad (Ex.ExceptT e) where
embed f m = Ex.ExceptT (do
x <- Ex.runExceptT (f (Ex.runExceptT m))
return (case x of
Left e -> Left e
Right (Left e) -> Left e
Right (Right a) -> Right a ) )
instance MMonad I.IdentityT where
embed f m = f (I.runIdentityT m)
instance MMonad M.MaybeT where
embed f m = M.MaybeT (do
x <- M.runMaybeT (f (M.runMaybeT m))
return (case x of
Nothing -> Nothing
Just Nothing -> Nothing
Just (Just a) -> Just a ) )
instance MMonad (R.ReaderT r) where
embed f m = R.ReaderT (\i -> R.runReaderT (f (R.runReaderT m i)) i)
instance (Monoid w) => MMonad (W.WriterT w) where
embed f m = W.WriterT (do
~((a, w1), w2) <- W.runWriterT (f (W.runWriterT m))
return (a, mappend w1 w2) )
instance (Monoid w) => MMonad (W'.WriterT w) where
embed f m = W'.WriterT (do
((a, w1), w2) <- W'.runWriterT (f (W'.runWriterT m))
return (a, mappend w1 w2) )
{- $tutorial
Monad morphisms solve the common problem of fixing monadic code after the
fact without modifying the original source code or type signatures. The
following sections illustrate various examples of transparently modifying
existing functions.
-}
{- $generalize
Imagine that some library provided the following 'S.State' code:
> import Control.Monad.Trans.State
>
> tick :: State Int ()
> tick = modify (+1)
... but we would prefer to reuse @tick@ within a larger
@('S.StateT' Int 'IO')@ block in order to mix in 'IO' actions.
We could patch the original library to generalize @tick@'s type signature:
> tick :: (Monad m) => StateT Int m ()
... but we would prefer not to fork upstream code if possible. How could
we generalize @tick@'s type without modifying the original code?
We can solve this if we realize that 'S.State' is a type synonym for
'S.StateT' with an 'Identity' base monad:
> type State s = StateT s Identity
... which means that @tick@'s true type is actually:
> tick :: StateT Int Identity ()
Now all we need is a function that @generalize@s the 'Identity' base monad
to be any monad:
> import Data.Functor.Identity
>
> generalize :: (Monad m) => Identity a -> m a
> generalize m = return (runIdentity m)
... which we can 'hoist' to change @tick@'s base monad:
> hoist :: (Monad m, MFunctor t) => (forall a . m a -> n a) -> t m b -> t n b
>
> hoist generalize :: (Monad m, MFunctor t) => t Identity b -> t m b
>
> hoist generalize tick :: (Monad m) => StateT Int m ()
This lets us mix @tick@ alongside 'IO' using 'lift':
> import Control.Monad.Morph
> import Control.Monad.Trans.Class
>
> tock :: StateT Int IO ()
> tock = do
> hoist generalize tick :: (Monad m) => StateT Int m ()
> lift $ putStrLn "Tock!" :: (MonadTrans t) => t IO ()
>>> runStateT tock 0
Tock!
((), 1)
-}
{- $mmorph
Notice that @generalize@ is a monad morphism, and the following two proofs
show how @generalize@ satisfies the monad morphism laws. You can refer to
these proofs as an example for how to prove a function obeys the monad
morphism laws:
> generalize (return x)
>
> -- Definition of 'return' for the Identity monad
> = generalize (Identity x)
>
> -- Definition of 'generalize'
> = return (runIdentity (Identity x))
>
> -- runIdentity (Identity x) = x
> = return x
> generalize $ do x <- m
> f x
>
> -- Definition of (>>=) for the Identity monad
> = generalize (f (runIdentity m))
>
> -- Definition of 'generalize'
> = return (runIdentity (f (runIdentity m)))
>
> -- Monad law: Left identity
> = do x <- return (runIdentity m)
> return (runIdentity (f x))
>
> -- Definition of 'generalize' in reverse
> = do x <- generalize m
> generalize (f x)
-}
{- $interleave
You can combine 'hoist' and 'lift' to insert arbitrary layers anywhere
within a monad transformer stack. This comes in handy when interleaving two
diverse stacks.
For example, we might want to combine the following @save@ function:
> import Control.Monad.Trans.Writer
>
> -- i.e. :: StateT Int (WriterT [Int] Identity) ()
> save :: StateT Int (Writer [Int]) ()
> save = do
> n <- get
> lift $ tell [n]
... with our previous @tock@ function:
> tock :: StateT Int IO ()
However, @save@ and @tock@ differ in two ways:
* @tock@ lacks a 'W.WriterT' layer
* @save@ has an 'Identity' base monad
We can mix the two by inserting a 'W.WriterT' layer for @tock@ and
generalizing @save@'s base monad:
> import Control.Monad
>
> program :: StateT Int (WriterT [Int] IO) ()
> program = replicateM_ 4 $ do
> hoist lift tock
> :: (MonadTrans t) => StateT Int (t IO) ()
> hoist (hoist generalize) save
> :: (Monad m) => StateT Int (WriterT [Int] m ) ()
>>> execWriterT (runStateT program 0)
Tock!
Tock!
Tock!
Tock!
[1,2,3,4]
-}
{- $embed
Suppose we decided to @check@ all 'IOException's using a combination of
'try' and 'ErrorT':
> import Control.Exception
> import Control.Monad.Trans.Class
> import Control.Monad.Trans.Error
>
> check :: IO a -> ErrorT IOException IO a
> check io = ErrorT (try io)
... but then we forget to use @check@ in one spot, mistakenly using 'lift'
instead:
> program :: ErrorT IOException IO ()
> program = do
> str <- lift $ readFile "test.txt"
> check $ putStr str
>>> runErrorT program
*** Exception: test.txt: openFile: does not exist (No such file or directory)
How could we go back and fix 'program' without modifying its source code?
Well, @check@ is a monad morphism, but we can't 'hoist' it to modify the
base monad because then we get two 'E.ErrorT' layers instead of one:
> hoist check :: (MFunctor t) => t IO a -> t (ErrorT IOException IO) a
>
> hoist check program :: ErrorT IOException (ErrorT IOException IO) ()
We'd prefer to 'embed' all newly generated exceptions in the existing
'E.ErrorT' layer:
> embed check :: ErrorT IOException IO a -> ErrorT IOException IO a
>
> embed check program :: ErrorT IOException IO ()
This correctly checks the exceptions that slipped through the cracks:
>>> import Control.Monad.Morph
>>> runErrorT (embed check program)
Left test.txt: openFile: does not exist (No such file or directory)
-}
| Gabriel439/Haskell-MMorph-Library | src/Control/Monad/Morph.hs | bsd-3-clause | 13,247 | 0 | 17 | 3,284 | 2,276 | 1,227 | 1,049 | 124 | 1 |
-- | Parsing Python code.
module Language.Python.TypeInference.Parse (
parse
) where
import Language.Python.Common.AST
import Language.Python.Common.SrcLocation
import Language.Python.TypeInference.Common
import Language.Python.TypeInference.Error
import Language.Python.Version3.Parser
-- | Parse the source code of a Python module.
parse :: SourceCode -> Filename -> TypeInferenceMonad (String, ModuleSpan)
parse code filename = do name <- moduleName filename
case parseModule code filename of
Left err -> throwError (ParseError (show err))
Right (m, _) -> return (name, m)
-- | Infer Python module name from filename.
moduleName :: String -> TypeInferenceMonad String
moduleName filename =
case reverse filename of
'y':'p':'.':cs -> return $ reverse $ takeWhile (`notElem` "/\\") cs
_ -> throwError $ ParseError ("bad filename: " ++ filename)
| lfritz/python-type-inference | python-type-inference/src/Language/Python/TypeInference/Parse.hs | bsd-3-clause | 974 | 0 | 14 | 237 | 237 | 130 | 107 | 17 | 2 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
module Local.Document where
import Control.Monad.Reader (ask)
import Control.Monad.State (get, put)
import Data.Acid
import Data.Aeson
import Data.List (isInfixOf)
import Data.List.Split (splitOn)
import Data.SafeCopy
import Data.Typeable
import GHC.Generics
import System.IO (stdout)
import Text.PrettyPrint.Leijen (Doc, displayIO, linebreak, putDoc,
renderPretty, sep, text, (<+>))
data Document = Document
{ title :: String
, content :: String
, tags :: [String]
} deriving (Eq, Ord, Typeable, ToJSON, FromJSON, Generic)
data Database = Database [Document]
deriveSafeCopy 0 'base ''Database
displayDoc :: Document -> IO ()
displayDoc = putDoc . mainDoc
displayDocWithTags :: Document -> IO ()
displayDocWithTags d = renderWidth 1000 (mainDoc d <+> tagDocs d)
renderWidth :: Int -> Doc -> IO ()
renderWidth w x = displayIO stdout (renderPretty 0.4 w x)
mainDoc :: Document -> Doc
mainDoc d =
text (title d) <+>
text "->" <+>
text (content d) <+>
linebreak
tagDocs :: Document -> Text.PrettyPrint.Leijen.Doc
tagDocs d =
text " tags| " <+>
sep (fmap text (tags d)) <+>
linebreak
instance Show Document where
show (Document title content _) = title ++ " - " ++ content
instance SafeCopy Document where
putCopy Document{..} = contain $ do safePut title; safePut content; safePut tags
getCopy = contain $ Document <$> safeGet <*> safeGet <*> safeGet
hardUpdate :: [Document] -> Update Database ()
hardUpdate docs = put $ Database docs
addDocument :: Document -> Update Database ()
addDocument doc = do
Database documents <- get
put $ Database (doc:documents)
removeDocument :: Document -> Update Database ()
removeDocument doc = do
Database documents <- get
let withoutDoc = filter (/= doc) documents
put (Database withoutDoc)
allDocuments :: Query Database [Document]
allDocuments = do
Database documents <- ask
pure documents
viewDocuments :: Int -> Query Database [Document]
viewDocuments limit = do
Database documents <- ask
pure (take limit documents)
searchDocuments :: [String] -> Query Database [Document]
searchDocuments queries = do
Database documents <- ask
pure (searchDoc queries documents)
searchDoc :: [String] -> [Document] -> [Document]
searchDoc queries = filter filterDoc
where
filterDoc document =
overQueries (title document) queries ||
overQueries (content document) queries ||
any (\a -> overQueries a queries) (tags document)
overQueries :: String -> [String] -> Bool
overQueries content searches = any (\search -> search `isInfixOf` content) searches
buildDocument :: [String] -> Document
buildDocument args = Document {title = _title, tags = _tags, content = _content}
where
_title = head args
_tags = splitOn "," (second args)
_content = unwords (thirdAndOn args)
thirdAndOn :: [String] -> [String]
thirdAndOn args = tail (tail args)
second :: [String] -> String
second ds = head (tail ds)
| tippenein/hasken | lib/Local/Document.hs | bsd-3-clause | 3,264 | 0 | 11 | 667 | 1,083 | 565 | 518 | 89 | 1 |
module Brain.Mirror where
import Logic
import Brain
import MonadBrain
import Data.Maybe
import Control.Monad
mirrorBrain :: Brain
mirrorBrain = toBrain $
forever $ lastOpponentMove >>= move . fromMaybe nop
| sjoerdvisscher/icfp2011 | src/Brain/Mirror.hs | bsd-3-clause | 212 | 0 | 8 | 34 | 54 | 31 | 23 | 9 | 1 |
{-# LANGUAGE
DeriveFoldable
, DeriveFunctor
, DeriveTraversable
, FlexibleContexts
, FlexibleInstances
, LambdaCase
, MultiParamTypeClasses
, RankNTypes
, ScopedTypeVariables
, TemplateHaskell
, TupleSections
#-}
module Simulate
( Event(..)
, JobType(..)
, simulate
) where
import Control.Lens
import Control.Monad.State
import Control.Monad.Writer
import Data.Functor.Compose ( Compose(..) )
import Data.Foldable ( for_, traverse_ )
import Arrival
import Dmrl hiding ( gradeOf )
import qualified Dmrl ( gradeOf )
import Heap
import Job
import Stream ( Stream )
import qualified Stream
data JobType = JtMulti | JtDmrl
deriving (Show, Eq, Ord)
newtype Future a = Future { _fromFuture :: a }
deriving (Show, Eq, Ord)
makeLenses ''Future
data Frames job = Frames{
-- Grade of a frame itself is the current grade of all of its jobs.
-- Within a frame, jobs are keyed by the grade of their next transition.
-- Foreground frame contains active jobs and has minimal current grade.
_foreground :: KeyVal Grade (Heap (Future Grade) job)
, _background :: Maybe (Heap Grade (Heap (Future Grade) job))
} deriving (Show, Foldable, Functor, Traversable)
instance Each (Frames job) (Frames job) job job
makeLenses ''Frames
data Env job = Env{
_timeSinceEvent :: Time
, _arrivals :: Stream (Delayed (Either JobDmrl job))
, _framesq :: Maybe (Frames job)
, _jdsq :: Maybe (Heap Grade JobDmrl)
, _jtqActive :: Maybe JobType
} deriving Show
makeLenses ''Env
fg :: Traversal' (Env job) (KeyVal Grade (Heap (Future Grade) job))
fg = framesq . _Just . foreground
bgq :: Traversal' (Env job) (Maybe (Heap Grade (Heap (Future Grade) job)))
bgq = framesq . _Just . background
data Action = AcArrival | AcTransition JobType | AcSwap JobType
deriving (Show, Eq, Ord)
data Event =
-- Work of entering job.
EvEnter JobType Time
--- Number remaining, total work remaining.
| EvExit JobType Int Time
deriving (Show, Eq, Ord)
simulate ::
IsJob job =>
Stream (Delayed (Either JobDmrl job)) ->
Stream
( Either
(String, Maybe (Frames job), Maybe (Heap Grade JobDmrl))
(Delayed Event)
)
simulate arrs =
Stream.unfold (runState (execWriterT sim)) $
Env 0 arrs Nothing Nothing Nothing
type Simulation job =
WriterT
[ Either
(String, Maybe (Frames job), Maybe (Heap Grade JobDmrl))
(Delayed Event)
] (State (Env job))
sim :: IsJob job => Simulation job ()
sim = do
acq <- argqMin timeq acsAll
case acq of
Nothing -> error "sim: no action, somehow...."
Just ac -> act ac
timeq :: IsJob job => Action -> Simulation job (Maybe Time)
timeq = \case
AcArrival -> do
tEv <- use timeSinceEvent
tArr <- use (arrivals . Stream.head . delay)
return . Just $ tArr - tEv
AcTransition JtMulti ->
ifActive JtMulti $
preuse (fg . val . keyMin) >>= traverse timeUntilGrade
AcTransition JtDmrl ->
ifActive JtDmrl $
preuse (jdsq . _Just . valMin . sizeActual)
AcSwap JtMulti ->
ifActive JtMulti $
preuse (bgq . _Just . keyMin . to Future) >>= traverse timeUntilGrade
AcSwap JtDmrl ->
-- `JtMulti` is correct here: we swap from multitask jobs to DMRL jobs.
ifActive JtMulti $
preuse (jdsq . _Just . keyMin . to Future) >>= traverse timeUntilGrade
act :: IsJob job => Action -> Simulation job ()
act = \case
AcArrival -> do
debug "AcArrival"
jArr <- arrive
case jArr of
Left jd ->
jdsq %= insert (kvf Dmrl.gradeOf jd)
Right j -> do
frameqFg <- preuse fg
case frameqFg of
Nothing ->
framesq ?= Frames (frameOf j) Nothing
Just (Kv gFg _) | gradeOf j > gFg ->
bgq %= insert (frameOf j)
Just frameFg | otherwise -> do
fg .= frameOf j
bgq %= insert frameFg
setJtqActive
AcTransition JtMulti -> do
debug "AcTransition JtMulti"
preuse (fg . val . keyMin) >>= traverse_ serveUntilGrade
frameqFg <- preuse fg
case frameqFg of
Nothing ->
error "act, AcTransition JtMulti: no foreground jobs"
Just (Kv g hPre) -> do
let jqPost = findMin hPre ^. val . to transitioned
hqPost = deleteMin hPre
case hqPost of
Nothing ->
case jqPost of
Nothing -> do
frameqBg <- preuse (bgq . _Just . kvMin)
case frameqBg of
Nothing -> do
framesq .= Nothing
debug "singleton fg, exits, no bg"
Just frameBg -> do
bgq %= (>>= deleteMin)
fg .= frameBg
debug "singleton fg, exits, some bg"
Just jPost -> do
fg .= frameOf jPost
debug "singleton fg, stays"
Just hPost ->
case jqPost of
Nothing -> do
fg . key .= findMin hPost ^. val . grade
fg . val .= hPost
debug "multi fg, exits"
Just jPost -> do
fg .= frameOf jPost
bgq %= insert (Kv g hPost)
debug "multi fg, stays"
when (null jqPost) (depart JtMulti)
AcTransition JtDmrl -> do
debug "AcTransition JtDmrl"
preuse (jdsq . _Just . valMin . sizeActual) >>= traverse_ serveUntilTime
jdsq %= (>>= deleteMin)
depart JtDmrl
AcSwap JtMulti -> do
debug "AcSwap JtMulti"
frameqBgMin <- preuse (bgq . _Just . kvMin)
case frameqBgMin of
Nothing ->
error "act, AcSwap JtMulti: no background jobs"
Just (Kv g h) -> do
serveUntilGrade (Future g)
fg . val %= merge h
bgq %= (>>= deleteMin)
AcSwap JtDmrl -> do
debug "AcSwap JtJtDmrl"
gq <- preuse (jdsq . _Just . keyMin)
case gq of
Nothing ->
error "act, AcSwap JtDmrl: no DMRL jobs"
Just g -> do
serveUntilGrade (Future g)
-- Manually set `jtqActive` to break the grade tie.
jtqActive ?= JtDmrl
arrive :: IsJob job => Simulation job (Either JobDmrl job)
arrive = do
Delayed tArr jArr <- use (arrivals . Stream.head)
tEv <- use timeSinceEvent
serveUntilTime (tArr - tEv)
arrivals %= view Stream.tail
timeSinceEvent .= 0
tell [Right . Delayed tArr $ EvEnter (jtOf jArr) (wOf jArr)]
return jArr
where
jtOf (Left _) = JtDmrl
jtOf (Right _) = JtMulti
wOf = either (view sizeActual) workOf
depart :: IsJob job => JobType -> Simulation job ()
depart jt = do
t <- use timeSinceEvent
arrivals . Stream.head . delay -= t
timeSinceEvent .= 0
n <- get <&> lengthOf (framesq . _Just . each)
w <- get <&> sumOf (framesq . _Just . each . to workOf)
tell [Right . Delayed t $ EvExit jt n w]
setJtqActive
setJtqActive :: IsJob job => Simulation job ()
setJtqActive = do
jtq <- argqMin (preuse . gradeJt) [JtMulti, JtDmrl]
jtqActive .= jtq
where
gradeJt JtMulti = fg . key
gradeJt JtDmrl = jdsq . _Just . keyMin
serveUntilTime :: IsJob job => Time -> Simulation job ()
serveUntilTime t = do
jtq <- use jtqActive
case jtq of
Just JtMulti ->
(preuse fg >>=) . traverse_ $ \frame ->
serveUntilGrade (Future $ gradeAtTime frame t)
_ -> do
timeSinceEvent += t
jdsq . _Just . kvMin %= kvAgeBy t
where
kvAgeBy t (Kv _ jd) = kvf Dmrl.gradeOf $ ageBy jd t
serveUntilGrade :: IsJob job => Future Grade -> Simulation job ()
serveUntilGrade (Future g) = do
jtq <- use jtqActive
when (jtq /= Just JtMulti) $ error "serveUntilGrade: multitask jobs inactive"
tBefore <- totalAgeOf . Compose <$> preuse (fg . val)
fg . key .= g
fg . val . each . grade .= g
tAfter <- totalAgeOf . Compose <$> preuse (fg . val)
timeSinceEvent += tAfter - tBefore
ifActive ::
IsJob job =>
JobType ->
Simulation job (Maybe a) ->
Simulation job (Maybe a)
ifActive jt x = do
jtq <- use jtqActive
if Just jt == jtq then x else return Nothing
timeUntilGrade :: IsJob job => Future Grade -> Simulation job Time
timeUntilGrade (Future g) = do
hq <- preuse (fg . val)
let h = maybe (error "timeUntilGrade: no foreground jobs") id hq
tNow = totalAgeOf h
tFuture = totalAgeOf (h & each . grade .~ g)
return (tFuture - tNow)
debug :: IsJob job => String -> Simulation job ()
debug msg = tell =<< (:[]) . Left <$> ((msg,,) <$> use framesq <*> use jdsq)
frameOf :: IsJob job => job -> KeyVal Grade (Heap (Future Grade) job)
frameOf j = Kv (gradeOf j) (singleton (kvf gradeFuture j))
gradeFuture :: IsJob job => job -> Future Grade
gradeFuture = Future . gradeOf . fst . nextTransition
transitioned :: IsJob job => job -> Maybe job
transitioned = snd . nextTransition
argqMin ::
(Traversable t, Applicative f, Ord b) =>
(a -> f (Maybe b)) -> t a -> f (Maybe a)
argqMin f xs =
fmap (view val) . minimumq . Compose <$> traverse kv xs
where
kv x = fmap (Kv ?? x) <$> f x
minimumq = minimumOf traverse
acsAll :: [Action]
acsAll =
AcArrival : [ac jt | ac <- [AcTransition, AcSwap], jt <- [JtMulti, JtDmrl]]
| vizziv/qsim | src/Simulate.hs | bsd-3-clause | 9,048 | 0 | 29 | 2,524 | 3,211 | 1,557 | 1,654 | -1 | -1 |
{-# LANGUAGE DeriveAnyClass #-}
{-# LANGUAGE DeriveGeneric #-}
module Test.ZM.ADT.Word.Kf92e8339908a (Word(..)) where
import qualified Prelude(Eq,Ord,Show)
import qualified GHC.Generics
import qualified Flat
import qualified Data.Model
import qualified Test.ZM.ADT.LeastSignificantFirst.K20ffacc8f8c9
import qualified Test.ZM.ADT.NonEmptyList.Kbf2d1c86eb20
import qualified Test.ZM.ADT.MostSignificantFirst.K74e2b3b89941
import qualified Test.ZM.ADT.Word7.Kf4c946334a7e
newtype Word = Word (Test.ZM.ADT.LeastSignificantFirst.K20ffacc8f8c9.LeastSignificantFirst (Test.ZM.ADT.NonEmptyList.Kbf2d1c86eb20.NonEmptyList (Test.ZM.ADT.MostSignificantFirst.K74e2b3b89941.MostSignificantFirst Test.ZM.ADT.Word7.Kf4c946334a7e.Word7)))
deriving (Prelude.Eq, Prelude.Ord, Prelude.Show, GHC.Generics.Generic, Flat.Flat)
instance Data.Model.Model Word
| tittoassini/typed | test/Test/ZM/ADT/Word/Kf92e8339908a.hs | bsd-3-clause | 843 | 0 | 12 | 59 | 181 | 121 | 60 | 14 | 0 |
module LinePt2
( LinePt2(..), linePt2, lineP1, lineP2, lineDP
, lineP1X, lineP1Y, lineP2X, lineP2Y, lineToPt2s
, linesCrossed, lineCrossPt2, hasBoundaryOverlap
, crossedLinePairsBrute, crossedLinePairs
, LineSide(..)
, pointLineSide, lineSide
, pt2LineRightCrossingNumber
, module Pt2
) where
import Data.List (foldl')
import Pt2
newtype LinePt2 a = LinePt2 (Pt2 a, Pt2 a) deriving Eq
lineP1, lineP2 :: LinePt2 t -> Pt2 t
lineP1 (LinePt2 (p1,_)) = p1
lineP2 (LinePt2 (_,p2)) = p2
lineP1X, lineP1Y, lineP2X, lineP2Y :: LinePt2 t -> t
lineP1X a = pt2X $ lineP1 a
lineP1Y a = pt2Y $ lineP1 a
lineP2X a = pt2X $ lineP2 a
lineP2Y a = pt2Y $ lineP2 a
lineDP :: Num t => LinePt2 t -> Pt2 t
lineDP (LinePt2 (p1,p2)) = p1 - p2
linePt2 :: a -> a -> a -> a -> LinePt2 a
linePt2 x1 y1 x2 y2 = LinePt2 (pt2 x1 y1, pt2 x2 y2)
lineToPt2s :: LinePt2 a -> [Pt2 a]
lineToPt2s x = [lineP1 x, lineP2 x]
instance Show a => Show (LinePt2 a) where
show (LinePt2 (a,b)) = show a ++ " to " ++ show b
instance Ord a => Ord (LinePt2 a) where
(LinePt2 a) < (LinePt2 b) = a < b
(LinePt2 a) > (LinePt2 b) = a < b
(LinePt2 a) <= (LinePt2 b) = a < b
(LinePt2 a) >= (LinePt2 b) = a < b
compare (LinePt2 a) (LinePt2 b) = compare a b
max (LinePt2 a) (LinePt2 b) = LinePt2 (max a b)
min (LinePt2 a) (LinePt2 b) = LinePt2 (min a b)
data LineSide = LeftSide
| CenterSide
| RightSide
deriving ( Show, Enum, Eq )
pointLineSide :: (Num a, Ord a) => Pt2 a -> LinePt2 a -> LineSide
pointLineSide p line
| d > 0 = LeftSide
| d < 0 = RightSide
| otherwise = CenterSide
where d = lineDP line `crossPt2` ( lineP1 line - p )
lineSide :: (Num a, Ord a) => LinePt2 a -> LinePt2 a -> LineSide
lineSide a b
| b1 /= RightSide && b2 /= RightSide = LeftSide
| b1 /= LeftSide && b2 /= LeftSide = RightSide
| otherwise = CenterSide
where b1 = pointLineSide (lineP1 b) a
b2 = pointLineSide (lineP2 b) a
linesCrossed :: (Num a, Ord a) => LinePt2 a -> LinePt2 a -> Bool
linesCrossed a b = lineSide a b == CenterSide && lineSide b a == CenterSide
type LinePair a = (LinePt2 a, LinePt2 a)
crossedLinePairsBrute :: (Num a, Ord a) => [LinePt2 a] -> [LinePt2 a] -> [LinePair a]
crossedLinePairsBrute x y = concatMap eachCross x
where eachCross x' = (,) x' <$> filter (linesCrossed x') y
crossedLinePairs :: (Num a, Ord a) => [LinePt2 a] -> [LinePt2 a] -> [LinePair a]
crossedLinePairs [] _ = []
crossedLinePairs _ [] = []
crossedLinePairs (x:xs) ys = xx' ++ ls' ++ rs'
where (leftX, centerX, rightX) = lineBuckets x xs
(leftY, centerY, rightY) = lineBuckets x ys
x'xSide = flip lineSide x
x'xCenter x' = x'xSide x' == CenterSide
pairX x' = (x,x')
xx' = map pairX $ filter x'xCenter centerY
ls' = crossedLinePairs (leftX ++ centerX) (leftY ++ centerY)
rs' = crossedLinePairs (rightX ++ centerX) (rightY ++ centerY)
lineBuckets :: (Num a, Ord a) => LinePt2 a -> [LinePt2 a] -> ([LinePt2 a],[LinePt2 a],[LinePt2 a])
lineBuckets x = foldl' intoBucket ([],[],[])
where intoBucket (l,c,r) x' = case lineSide x x' of
LeftSide -> (x':l, c, r )
CenterSide -> ( l, x':c, r )
RightSide -> ( l, c, x':r)
lineCrossPt2 :: Fractional a => LinePt2 a -> LinePt2 a -> Pt2 a
lineCrossPt2 a b = pt2 x y
where da = lineP1 a - lineP2 a
db = lineP1 b - lineP2 b
Pt2 (x1,y1) = lineP1 a
Pt2 (x2,y2) = lineP2 a
Pt2 (x3,y3) = lineP1 b
Pt2 (x4,y4) = lineP2 b
aa = x1 * y2 - y1 * x2
bb = x3 * y4 - y3 * x4
den = da `crossPt2` db
x = ( aa * ( x3 - x4 ) - (x1 - x2 ) * bb ) / den
y = ( aa * ( y3 - y4 ) - (y1 - y2 ) * bb ) / den
hasBoundaryOverlap :: ( Num a, Ord a ) => LinePt2 a -> LinePt2 a -> Bool
hasBoundaryOverlap a b = insideX && insideY
where insideX = overlaps ax1 ax2 bx1 bx2
insideY = overlaps ay1 ay2 by1 by2
(ax1, ay1) = pt2Tuple $ lineP1 a
(ax2, ay2) = pt2Tuple $ lineP2 a
(bx1, by1) = pt2Tuple $ lineP1 b
(bx2, by2) = pt2Tuple $ lineP2 b
overlaps m n p q = m <= q && p <= n
pt2LineRightCrossingNumber :: (Eq a, Ord a, Num a) => Pt2 a -> LinePt2 a -> Int
pt2LineRightCrossingNumber p (LinePt2 (p1,p2))
| y1 == y2 = 0
| y1 < y && y2 < y = 0
| y1 > y && y2 > y = 0
| y1 <= y && side == LeftSide = -1
| y1 > y && side == RightSide = 1
| otherwise = 0
where y = pt2Y p
side = pointLineSide p (LinePt2 (p1,p2))
(y1,y2) = (pt2Y p1, pt2Y p2)
| trenttobler/hs-asteroids | src/LinePt2.hs | bsd-3-clause | 4,758 | 0 | 13 | 1,468 | 2,194 | 1,131 | 1,063 | 110 | 3 |
module Del.Encode.Cpp where
import Del.Encode.Utils
import Del.Syntax
encodeExp :: Exp -> String
encodeExp (Num x) = show x
encodeExp (Sym n _ ds) = n ++ encodeDiff ds
encodeExp (Neg e) = "-" ++ encodeExp e
encodeExp (Mul e1 e2) = encodeExp e1 ++ "*" ++ encodeExp e2
encodeExp (Div e1 e2) = encodeExp e1 ++ "/" ++ encodeExp e2
encodeExp (Add e1 e2) = encodeExp e1 ++ " + " ++ encodeExp e2
encodeExp (Sub e1 e2) = encodeExp e1 ++ " - " ++ encodeExp e2
encodeExp (Pow e1 e2) = "pow(" ++ encodeExp e1 ++ "," ++ encodeExp e2 ++ ")"
| ishiy1993/mk-sode1 | src/Del/Encode/Cpp.hs | bsd-3-clause | 530 | 0 | 9 | 106 | 248 | 121 | 127 | 12 | 1 |
{-# LANGUAGE Trustworthy #-}
-----------------------------------------------------------------------------
-- |
-- Module : Data.Ix
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable
--
-- The 'Ix' class is used to map a contiguous subrange of values in
-- type onto integers. It is used primarily for array indexing
-- (see the array package). 'Ix' uses row-major order.
--
-----------------------------------------------------------------------------
module Data.Ix
(
-- * The 'Ix' class
Ix
( range
, index
, inRange
, rangeSize
)
-- Ix instances:
--
-- Ix Char
-- Ix Int
-- Ix Integer
-- Ix Bool
-- Ix Ordering
-- Ix ()
-- (Ix a, Ix b) => Ix (a, b)
-- ...
-- * Deriving Instances of 'Ix'
-- | Derived instance declarations for the class 'Ix' are only possible
-- for enumerations (i.e. datatypes having only nullary constructors)
-- and single-constructor datatypes, including arbitrarily large tuples,
-- whose constituent types are instances of 'Ix'.
--
-- * For an enumeration, the nullary constructors are assumed to be
-- numbered left-to-right with the indices being 0 to n-1 inclusive. This
-- is the same numbering defined by the 'Enum' class. For example, given
-- the datatype:
--
-- > data Colour = Red | Orange | Yellow | Green | Blue | Indigo | Violet
--
-- we would have:
--
-- > range (Yellow,Blue) == [Yellow,Green,Blue]
-- > index (Yellow,Blue) Green == 1
-- > inRange (Yellow,Blue) Red == False
--
-- * For single-constructor datatypes, the derived instance declarations
-- are as shown for tuples in Figure 1
-- <http://www.haskell.org/onlinelibrary/ix.html#prelude-index>.
) where
-- import Prelude
import GHC.Arr
| spacekitteh/smcghc | libraries/base/Data/Ix.hs | bsd-3-clause | 2,076 | 0 | 5 | 576 | 76 | 69 | 7 | 12 | 0 |
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-name-shadowing #-}
-- | Provides template Haskell code to generate instances for JavaScript
-- object wrappers (<https://github.com/ku-fpg/sunroof-compiler/wiki/JSObject-Wrapper-Types>).
module Language.Sunroof.TH
( deriveJSTuple
) where
import Language.Haskell.TH
import Language.Sunroof.Types as SRT
import Language.Sunroof.Classes
import Language.Sunroof.JS.Object
import Language.Sunroof.JS.Bool
import Data.Boolean
-- | @derive@ derives an incomplete instance for @JSTuple@,
-- as well as completing other classes.
--
-- you write the newtype explictly, and @derive@ does the rest.
--
-- > newtype JSX o = JSX JSObject
--
-- and then the start of the JSTuple instance, and the rest gets filled in
--
-- > derive [d| instance (SunroofArgument o) => JSTuple (JSX o) where
-- > type Internals (JSX o) = (JSString,JSNumber)
-- > |]
--
-- generates
--
-- > instance (SunroofArgument o) => Show (JSX o) where
-- > show (JSX o) = show o
-- >
-- > instance (SunroofArgument o) => Sunroof (JSX o) where
-- > unbox (JSX o) = unbox o
-- > box o = JSX (box o)
-- >
-- > instance (SunroofArgument o) => IfB (JSX o) where
-- > ifB = jsIfB
-- >
-- > type instance BooleanOf (JSX o) = JSBool
-- >
-- > instance (SunroofArgument o) => JSTuple (JSX o) where
-- > type instance Internals (JSX o) = (JSString, JSNumber)
-- > match o = (o ! attr "f1", o ! attr "f2")
-- > tuple (v1,v2) = do
-- > o <- new "Object" ()
-- > o # attr "f1" := v1
-- > o # attr "f2" := v2
-- > return (JSX o)
deriveJSTuple :: Q [Dec] -> Q [Dec]
deriveJSTuple decsQ = do
decs <- decsQ
fmap concat $ mapM complete decs
where
complete :: Dec -> Q [Dec]
complete (InstanceD cxt' (AppT (ConT typeClass) ty) decls) = do
-- Unused: let k decls' = InstanceD cxt' hd (decls ++ decls')
let findClass (ConT t) = t
findClass (AppT t1 _) = findClass t1
findClass _ = error $ "strange instance head found in derive " ++ show ty
let tConTy = findClass ty
-- Next, find the type instance
let internalTy = case decls of
#if MIN_VERSION_template_haskell(2,9,0)
[TySynInstD tyFun (TySynEqn [_arg] internalTy)]
#else
[TySynInstD tyFun [_arg] internalTy]
#endif
| tyFun == ''Internals -> internalTy
_ -> error $ "can not find usable type instance inside JSTuple"
let findInternalStructure (TupleT _n) ts = do
vs <- sequence [ newName "v" | _ <- ts ]
return (TupE,TupP [ VarP v | v <- vs], vs `zip` [ "f" ++ show i | (i::Int) <- [1..]])
findInternalStructure (AppT t1 t2) ts = findInternalStructure t1 (t2 : ts)
findInternalStructure (ConT v) ts = do
info <- reify v
case info of
TyConI (DataD [] _ _ [NormalC internalCons args] []) -> do
vs <- sequence [ newName "v" | _ <- args ]
return ( foldl AppE (ConE internalCons)
, ConP internalCons [ VarP v | v <- vs]
, vs `zip` [ "f" ++ show i | (i::Int) <- [1..]]
)
TyConI (NewtypeD [] _ _ (NormalC internalCons args) []) -> do
vs <- sequence [ newName "v" | _ <- args ]
return ( foldl AppE (ConE internalCons)
, ConP internalCons [ VarP v | v <- vs]
, vs `zip` [ "f" ++ show i | (i::Int) <- [1..]]
)
TyConI (DataD [] _ _ [RecC internalCons args] []) -> do
vs <- sequence [ newName "v" | _ <- args ]
return ( foldl AppE (ConE internalCons)
, ConP internalCons [ VarP v | v <- vs]
, vs `zip` [ nameBase x | (x,_,_) <- args ]
)
_o -> error $ "can not find internal structure of cons " ++ show (v,ts,info)
findInternalStructure o ts = error $ "can not find internal structure of type " ++ show (o,ts)
(builder :: [Exp] -> Exp,unbuilder :: Pat, vars :: [(Name,String)]) <- findInternalStructure internalTy []
-- Now work with the tConTy, to get the tCons
info <- reify tConTy
let tCons = case info of
TyConI (NewtypeD _ _ _ (NormalC tCons [(NotStrict,ConT o)]) [])
| o /= ''JSObject -> error $ "not newtype of JSObject"
| typeClass /= ''JSTuple -> error $ "not instance of JSTuple" ++ show (tConTy,''JSTuple)
| otherwise -> tCons
_ -> error $ "strange info for newtype type " ++ show info
o <- newName "o"
n <- newName "n"
return [ InstanceD cxt' (AppT (ConT ''Show) ty)
[ FunD 'show
[ Clause [ConP tCons [VarP o]]
(NormalB (AppE (VarE 'show) (VarE o))) []]]
, InstanceD cxt' (AppT (ConT ''Sunroof) ty)
[ FunD 'box
[ Clause [VarP n] (NormalB (AppE (ConE tCons)
(AppE (VarE 'box) (VarE n)))) []]
, FunD 'unbox
[ Clause [ConP tCons [VarP o]]
(NormalB (AppE (VarE 'unbox) (VarE o))) []]
]
, InstanceD cxt' (AppT (ConT ''IfB) ty)
[ ValD (VarP 'ifB) (NormalB (VarE 'jsIfB)) [] ]
#if MIN_VERSION_template_haskell(2,9,0)
, TySynInstD ''BooleanOf (TySynEqn [ty] (ConT ''JSBool))
#else
, TySynInstD ''BooleanOf [ty] (ConT ''JSBool)
#endif
, InstanceD cxt' (AppT (ConT ''JSTuple) ty) $ decls ++
[ FunD 'SRT.match
[Clause [VarP o] (NormalB (builder
[ AppE (AppE (VarE $ mkName "!") (VarE o))
(AppE (VarE 'attr) (LitE $ StringL $ s))
| (_,s) <- vars ])) []]
, FunD 'SRT.tuple
[ Clause [unbuilder] (NormalB (DoE (
[ BindS (VarP o) (AppE (AppE (VarE 'new) (LitE $ StringL $ "Object")) (TupE []))
] ++
[ NoBindS $
let assign = AppE (AppE (ConE $ mkName ":=")
(AppE (VarE 'attr) (LitE $ StringL $ s)))
(VarE v)
in AppE (AppE (VarE $ mkName "#")
(VarE o))
(assign)
| (v,s) <- vars
] ++
[ NoBindS $ AppE (VarE 'return) (AppE (ConE tCons) (VarE o))
]))) []
]
]
]
complete _ = error "need instance declaration for derivation of JSTuple."
| ku-fpg/sunroof-th | Language/Sunroof/TH.hs | bsd-3-clause | 8,140 | 0 | 36 | 3,793 | 1,935 | 1,005 | 930 | 96 | 12 |
-- CPP and GeneralizedNewtypeDeriving are needed for IArray UArray instance
-- FFI is for log1p
{-# LANGUAGE CPP, ForeignFunctionInterface, MultiParamTypeClasses #-}
-- We don't put these in LANGUAGE, because it's CPP guarded for GHC only
-- HACK: ScopedTypeVariables and InstanceSigs are for GHC 7.10 only...
{-# OPTIONS_GHC
-XGeneralizedNewtypeDeriving
-XScopedTypeVariables
-XInstanceSigs
#-}
{-# OPTIONS_GHC -Wall -fwarn-tabs #-}
{-# OPTIONS_GHC -O2 -fexcess-precision -fenable-rewrite-rules #-}
----------------------------------------------------------------
-- ~ 2021.10.17
-- |
-- Module : Data.Number.LogFloat
-- Copyright : Copyright (c) 2007--2021 wren gayle romano
-- License : BSD3
-- Maintainer : [email protected]
-- Stability : stable
-- Portability : portable (with CPP, FFI)
--
-- This module presents a type for storing numbers in the log-domain.
-- The main reason for doing this is to prevent underflow when
-- multiplying many small probabilities as is done in Hidden Markov
-- Models and other statistical models often used for natural
-- language processing. The log-domain also helps prevent overflow
-- when multiplying many large numbers. In rare cases it can speed
-- up numerical computation (since addition is faster than
-- multiplication, though logarithms are exceptionally slow), but
-- the primary goal is to improve accuracy of results. A secondary
-- goal has been to maximize efficiency since these computations
-- are frequently done within a /O(n^3)/ loop.
--
-- The 'LogFloat' of this module is restricted to non-negative
-- numbers for efficiency's sake, see "Data.Number.LogFloat.Signed"
-- for doing signed log-domain calculations.
----------------------------------------------------------------
module Data.Number.LogFloat
(
-- * Exceptional numeric values
module Data.Number.Transfinite
-- * @LogFloat@ data type
, LogFloat()
-- ** Isomorphism to normal-domain
, logFloat
, fromLogFloat
-- ** Isomorphism to log-domain
, logToLogFloat
, logFromLogFloat
-- ** Additional operations
, sum, product
, pow
-- * Accurate versions of logarithm\/exponentiation
, log1p, expm1
) where
import Prelude hiding (log, sum, product, isInfinite, isNaN)
import Data.Number.Transfinite
import Data.Number.PartialOrd
import Data.Number.LogFloat.Raw
-- GHC can derive (IArray UArray LogFloat), but Hugs needs to coerce
-- TODO: see about nhc98/yhc, jhc/lhc
import Data.Array.Base (IArray(..))
import Data.Array.Unboxed (UArray)
-- Hugs (Sept 2006) doesn't use the generic wrapper in base:Unsafe.Coerce
-- so we'll just have to go back to the original source.
#ifdef __HUGS__
import Hugs.IOExts (unsafeCoerce)
#elif __NHC__
import NonStdUnsafeCoerce (unsafeCoerce)
#elif __GLASGOW_HASKELL__ >= 710
-- For when the *heap* representations are the same
--import Data.Coerce (coerce)
-- For when the *unboxed array* storage representations are the same
import Unsafe.Coerce (unsafeCoerce)
import Data.Ix (Ix)
#endif
#ifdef __GLASGOW_HASKELL__
import Foreign.Storable (Storable)
#endif
----------------------------------------------------------------
--
-- | A @LogFloat@ is just a 'Double' with a special interpretation.
-- The 'logFloat' function is presented instead of the constructor,
-- in order to ensure semantic conversion. At present the 'Show'
-- instance will convert back to the normal-domain, and hence will
-- underflow at that point. This behavior may change in the future.
-- At present, the 'Read' instance parses things in the normal-domain
-- and then converts them to the log-domain. Again, this behavior
-- may change in the future.
--
-- Because 'logFloat' performs the semantic conversion, we can use
-- operators which say what we /mean/ rather than saying what we're
-- actually doing to the underlying representation. That is,
-- equivalences like the following are true[1] thanks to type-class
-- overloading:
--
-- > logFloat (p + q) == logFloat p + logFloat q
-- > logFloat (p * q) == logFloat p * logFloat q
--
-- (Do note, however, that subtraction can and negation will throw
-- errors: since @LogFloat@ can only represent the positive half of
-- 'Double'. 'Num' is the wrong abstraction to put at the bottom
-- of the numeric type-class hierarchy; but alas, we're stuck with
-- it.)
--
-- Performing operations in the log-domain is cheap, prevents
-- underflow, and is otherwise very nice for dealing with miniscule
-- probabilities. However, crossing into and out of the log-domain
-- is expensive and should be avoided as much as possible. In
-- particular, if you're doing a series of multiplications as in
-- @lp * logFloat q * logFloat r@ it's faster to do @lp * logFloat
-- (q * r)@ if you're reasonably sure the normal-domain multiplication
-- won't underflow; because that way you enter the log-domain only
-- once, instead of twice. Also note that, for precision, if you're
-- doing more than a few multiplications in the log-domain, you
-- should use 'product' rather than using '(*)' repeatedly.
--
-- Even more particularly, you should /avoid addition/ whenever
-- possible. Addition is provided because sometimes we need it, and
-- the proper implementation is not immediately apparent. However,
-- between two @LogFloat@s addition requires crossing the exp\/log
-- boundary twice; with a @LogFloat@ and a 'Double' it's three
-- times, since the regular number needs to enter the log-domain
-- first. This makes addition incredibly slow. Again, if you can
-- parenthesize to do normal-domain operations first, do it!
--
-- [1] That is, true up-to underflow and floating point fuzziness.
-- Which is, of course, the whole point of this module.
newtype LogFloat = LogFloat Double
deriving
( Eq
, Ord -- Should we really perpetuate the Ord lie?
#ifdef __GLASGOW_HASKELL__
-- The H98 Report doesn't include these among the options for
-- automatic derivation. But GHC >= 6.8.2 (at least) can derive
-- them (even without GeneralizedNewtypeDeriving). However,
-- GHC >= 7.10 can't derive @IArray UArray@ thanks to the new
-- type-role stuff! since 'UArray' is declared to be nominal
-- in both arguments... and that seems to be necessary:
-- cf., <https://ghc.haskell.org/trac/ghc/ticket/9220>
#if __GLASGOW_HASKELL__ < 710
, IArray UArray
#endif
, Storable
#endif
)
#if __GLASGOW_HASKELL__ >= 710
-- TODO: this version should also work for NHC and Hugs, I think...
-- HACK: we should be able to just unsafeCoerce the functions
-- themselves, instead of coercing the inputs and the outputs; but,
-- GHC 7.10 seems to get confused about trying to coerce the index
-- types too... To fix this we give explicit signatures, as below,
-- but this requires both ScopedTypeVariables and InstanceSigs; and
-- I'm not sure when InstanceSigs was introduced.
instance IArray UArray LogFloat where
{-# INLINE bounds #-}
bounds :: forall i. Ix i => UArray i LogFloat -> (i, i)
bounds = unsafeCoerce (bounds :: UArray i Double -> (i, i))
{-# INLINE numElements #-}
numElements :: forall i. Ix i => UArray i LogFloat -> Int
numElements = unsafeCoerce (numElements :: UArray i Double -> Int)
{-# INLINE unsafeArray #-}
unsafeArray
:: forall i. Ix i => (i,i) -> [(Int,LogFloat)] -> UArray i LogFloat
unsafeArray = unsafeCoerce (unsafeArray
:: (i,i) -> [(Int,Double)] -> UArray i Double)
{-# INLINE unsafeAt #-}
unsafeAt :: forall i. Ix i => UArray i LogFloat -> Int -> LogFloat
unsafeAt = unsafeCoerce (unsafeAt :: UArray i Double -> Int -> Double)
{-# INLINE unsafeReplace #-}
unsafeReplace
:: forall i. Ix i
=> UArray i LogFloat -> [(Int,LogFloat)] -> UArray i LogFloat
unsafeReplace = unsafeCoerce (unsafeReplace
:: UArray i Double -> [(Int,Double)] -> UArray i Double)
{-# INLINE unsafeAccum #-}
unsafeAccum
:: forall i e. Ix i
=> (LogFloat -> e -> LogFloat)
-> UArray i LogFloat -> [(Int,e)] -> UArray i LogFloat
unsafeAccum = unsafeCoerce (unsafeAccum
:: (Double -> e -> Double)
-> UArray i Double -> [(Int,e)] -> UArray i Double)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray
:: forall i e. Ix i
=> (LogFloat -> e -> LogFloat)
-> LogFloat -> (i,i) -> [(Int,e)] -> UArray i LogFloat
unsafeAccumArray = unsafeCoerce (unsafeAccumArray
:: (Double -> e -> Double)
-> Double -> (i,i) -> [(Int,e)] -> UArray i Double)
#elif __HUGS__ || __NHC__
-- TODO: Storable instance. Though Foreign.Storable isn't in Hugs(Sept06)
-- TODO: depend on my @pointless-fun@ package rather than repeating things here...
-- These two operators make it much easier to read the instance.
-- Hopefully inlining everything will get rid of the eta overhead.
-- <http://matt.immute.net/content/pointless-fun>
(~>) :: (a -> b) -> (d -> c) -> (b -> d) -> a -> c
{-# INLINE (~>) #-}
infixr 2 ~>
f ~> g = (. f) . (g .)
($::) :: a -> (a -> b) -> b
{-# INLINE ($::) #-}
infixl 1 $::
($::) = flip ($)
{-# INLINE logFromLFAssocs #-}
logFromLFAssocs :: [(Int, LogFloat)] -> [(Int, Double)]
#if __GLASGOW_HASKELL__ >= 710
logFromLFAssocs = coerce
#else
logFromLFAssocs = unsafeCoerce
#endif
-- HACK: can't coerce, cf: <https://ghc.haskell.org/trac/ghc/ticket/9220>
{-# INLINE logFromLFUArray #-}
logFromLFUArray :: UArray a LogFloat -> UArray a Double
logFromLFUArray = unsafeCoerce
-- Named unsafe because it could allow injecting NaN if misused
-- HACK: can't coerce, cf: <https://ghc.haskell.org/trac/ghc/ticket/9220>
{-# INLINE unsafeLogToLFUArray #-}
unsafeLogToLFUArray :: UArray a Double -> UArray a LogFloat
unsafeLogToLFUArray = unsafeCoerce
-- Named unsafe because it could allow injecting NaN if misused
{-# INLINE unsafeLogToLFFunc #-}
unsafeLogToLFFunc :: (LogFloat -> a -> LogFloat) -> (Double -> a -> Double)
unsafeLogToLFFunc = ($:: unsafeLogToLogFloat ~> id ~> logFromLogFloat)
-- | Remove the extraneous 'isNaN' test of 'logToLogFloat', when
-- we know it's safe.
{-# INLINE unsafeLogToLogFloat #-}
unsafeLogToLogFloat :: Double -> LogFloat
unsafeLogToLogFloat = LogFloat
instance IArray UArray LogFloat where
{-# INLINE bounds #-}
bounds = bounds . logFromLFUArray
-- Apparently this method was added in base-2.0/GHC-6.6 but Hugs
-- (Sept 2006) doesn't have it. Not sure about NHC's base
#if (!(defined(__HUGS__))) || (__HUGS__ > 200609)
{-# INLINE numElements #-}
numElements = numElements . logFromLFUArray
#endif
{-# INLINE unsafeArray #-}
unsafeArray = unsafeArray $:: id ~> logFromLFAssocs ~> unsafeLogToLFUArray
{-# INLINE unsafeAt #-}
unsafeAt = unsafeAt $:: logFromLFUArray ~> id ~> unsafeLogToLogFloat
{-# INLINE unsafeReplace #-}
unsafeReplace = unsafeReplace
$:: logFromLFUArray ~> logFromLFAssocs ~> unsafeLogToLFUArray
{-# INLINE unsafeAccum #-}
unsafeAccum = unsafeAccum
$:: unsafeLogToLFFunc ~> logFromLFUArray ~> id ~> unsafeLogToLFUArray
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray = unsafeAccumArray
$:: unsafeLogToLFFunc ~> logFromLogFloat ~> id ~> id ~> unsafeLogToLFUArray
#endif
-- TODO: the Nothing branch should never be reachable. Once we get
-- a test suite up and going to /verify/ the never-NaN invariant,
-- we should be able to eliminate the branch and the isNaN checks.
instance PartialOrd LogFloat where
cmp (LogFloat x) (LogFloat y)
| isNaN x || isNaN y = Nothing
| otherwise = Just $! x `compare` y
instance Read LogFloat where
readsPrec p s =
[(LogFloat (log x), r) | (x, r) <- readsPrec p s, not (isNaN x), x >= 0]
----------------------------------------------------------------
-- | Reduce the number of constant string literals we need to store.
errorOutOfRange :: String -> a
{-# NOINLINE errorOutOfRange #-}
errorOutOfRange fun =
error $! "Data.Number.LogFloat."++fun++ ": argument out of range"
-- Both guards are redundant due to the subsequent call to
-- 'Data.Number.Transfinite.log' at all use sites. However we use
-- this function to give local error messages. Perhaps we should
-- catch the exception and throw the new message instead? Portability?
guardNonNegative :: String -> Double -> Double
guardNonNegative fun x
| isNaN x || x < 0 = errorOutOfRange fun
| otherwise = x
guardIsANumber :: String -> Double -> Double
guardIsANumber fun x
| isNaN x = errorOutOfRange fun
| otherwise = x
----------------------------------------------------------------
-- | Constructor which does semantic conversion from normal-domain
-- to log-domain. Throws errors on negative and NaN inputs. If @p@
-- is non-negative, then following equivalence holds:
--
-- > logFloat p == logToLogFloat (log p)
--
-- If @p@ is NaN or negative, then the two sides differ only in
-- which error is thrown.
logFloat :: Double -> LogFloat
{-# INLINE [0] logFloat #-}
-- TODO: should we use NOINLINE or [~0] to avoid the possibility of code bloat?
logFloat = LogFloat . log . guardNonNegative "logFloat"
-- | Constructor which assumes the argument is already in the
-- log-domain. Throws errors on @notANumber@ inputs.
logToLogFloat :: Double -> LogFloat
logToLogFloat = LogFloat . guardIsANumber "logToLogFloat"
-- | Semantically convert our log-domain value back into the
-- normal-domain. Beware of overflow\/underflow. The following
-- equivalence holds (without qualification):
--
-- > fromLogFloat == exp . logFromLogFloat
--
fromLogFloat :: LogFloat -> Double
{-# INLINE [0] fromLogFloat #-}
-- TODO: should we use NOINLINE or [~0] to avoid the possibility of code bloat?
fromLogFloat (LogFloat x) = exp x
-- | Return the log-domain value itself without conversion.
logFromLogFloat :: LogFloat -> Double
logFromLogFloat (LogFloat x) = x
-- These are our module-specific versions of "log\/exp" and "exp\/log";
-- They do the same things but also have a @LogFloat@ in between
-- the logarithm and exponentiation. In order to ensure these rules
-- fire, we have to delay the inlining on two of the four
-- con-\/destructors.
{-# RULES
-- Out of log-domain and back in
"log/fromLogFloat" forall x. log (fromLogFloat x) = logFromLogFloat x
"logFloat/fromLogFloat" forall x. logFloat (fromLogFloat x) = x
-- Into log-domain and back out
"fromLogFloat/logFloat" forall x. fromLogFloat (logFloat x) = x
#-}
----------------------------------------------------------------
-- To show it, we want to show the normal-domain value rather than
-- the log-domain value. Also, if someone managed to break our
-- invariants (e.g. by passing in a negative and noone's pulled on
-- the thunk yet) then we want to crash before printing the
-- constructor, rather than after. N.B. This means the show will
-- underflow\/overflow in the same places as normal doubles since
-- we underflow at the @exp@. Perhaps this means we should show the
-- log-domain value instead.
instance Show LogFloat where
showsPrec p (LogFloat x) =
let y = exp x in y `seq`
showParen (p > 9)
( showString "logFloat "
. showsPrec 11 y
)
----------------------------------------------------------------
-- | A curried function for converting arbitrary pairs into ordered
-- pairs. The continuation recieves the minimum first and the maximum
-- second.
--
-- This combinator is primarily intended to reduce repetition in
-- the source code; but hopefully it should also help reduce bloat
-- in the compiled code, by sharing the continuation and just
-- swapping the variables in place. Of course, if the continuation
-- is very small, then requiring a join point after the conditional
-- swap may end up being more expensive than simply duplicating the
-- continuation. Also, given as we're inlining it, I'm not sure
-- whether GHC will decide to keep the sharing we introduced or
-- whether it'll end up duplicating the continuation into the two
-- call sites.
ordered :: Ord a => a -> a -> (a -> a -> b) -> b
ordered x y k
| x <= y = k x y
| otherwise = k y x
-- N.B., the implementation of @(>=)@ in Hugs (Sept2006) will
-- always returns True if either argument isNaN. This does not
-- constitute a bug for us, since we maintain the invariant that
-- values wrapped by 'LogFloat' are not NaN.
{-# INLINE ordered #-}
-- TODO: Do we need to add explicit INLINE pragmas here? Or will
-- GHC automatically see that they're small enough to want inlining?
--
-- These all work without causing underflow. However, do note that
-- they tend to induce more of the floating-point fuzz than using
-- regular floating numbers because @exp . log@ doesn't really equal
-- @id@. In any case, our main aim is for preventing underflow when
-- multiplying many small numbers (and preventing overflow for
-- multiplying many large numbers) so we're not too worried about
-- +\/- 4e-16.
instance Num LogFloat where
(*) (LogFloat x) (LogFloat y)
| isInfinite x && isInfinite y && x == negate y =
LogFloat negativeInfinity -- @0 * infinity == 0@
| otherwise =
-- This includes the @0 * 0 == 0@ and @infty * infty == infty@
-- cases, since @(+)@ treats them appropriately.
LogFloat (x + y)
(+) (LogFloat x) (LogFloat y)
| isInfinite x && isInfinite y && x == y =
LogFloat x -- @0 + 0 == 0@ and @infty + infty == infty@
| otherwise =
-- This includes the @0 + infinity == infinity@ case,
-- since 'log1pexp' (and 'ordered') treats them appropriately.
ordered x y $ \n m ->
LogFloat (m + log1pexp (n - m))
-- TODO: give a better error message in the (infinity,infinity) case.
-- TODO: does 'log1mexp' handle the (+infty,-infty) cases correctly?
(-) (LogFloat x) (LogFloat y)
| x == negativeInfinity && y == negativeInfinity =
LogFloat negativeInfinity -- @0 - 0 == 0@
| otherwise =
ordered x y $ \n m ->
LogFloat (guardIsANumber "(-)" (m + log1mexp (n - m)))
signum (LogFloat x)
| x == negativeInfinity = 0
| x > negativeInfinity = 1
| otherwise = errorOutOfRange "signum"
-- The extra guard protects against NaN, in case someone
-- broke the invariant. That shouldn't be possible and
-- so noone else bothers to check, but we check here just
-- in case.
-- TODO: wouldn't @not (isNaN x)@ be a better guard to use?
negate _ = errorOutOfRange "negate"
abs = id
fromInteger = LogFloat . log . guardNonNegative "fromInteger" . fromInteger
instance Fractional LogFloat where
-- @n / 0 == infinity@ is handled seamlessly for us. We must catch
-- @0 / 0@ and @infinity / infinity@ NaNs, and handle @0 / infinity@.
(/) (LogFloat x) (LogFloat y)
| isInfinite x && isInfinite y && x == y = errorOutOfRange "(/)"
| x == negativeInfinity = LogFloat negativeInfinity -- @0/infinity == 0@
| otherwise = LogFloat (x - y)
fromRational = LogFloat . log
. guardNonNegative "fromRational" . fromRational
-- Just for fun. The more coercion functions the better. Though
-- Rationals are very buggy when it comes to transfinite values
instance Real LogFloat where
toRational (LogFloat x)
| isInfinite ex || isNaN ex = errorOutOfRange "toRational"
| otherwise = toRational ex
where
ex = exp x
----------------------------------------------------------------
-- | /O(1)/. Compute powers in the log-domain; that is, the following
-- equivalence holds (modulo underflow and all that):
--
-- > logFloat (p ** m) == logFloat p `pow` m
--
-- /Since: 0.13/
pow :: LogFloat -> Double -> LogFloat
{-# INLINE pow #-}
infixr 8 `pow`
pow (LogFloat x) m
| isNaN mx = LogFloat 0
| otherwise = LogFloat mx
where
-- N.B., will be NaN when @x == negativeInfinity && m == 0@
-- (which is true when m is -0 as well as +0). We check for NaN
-- after multiplying, rather than checking this precondition
-- before multiplying, in an attempt to simplify/optimize the
-- generated code.
-- TODO: benchmark.
mx = m * x
-- N.B., the default implementation of (**) for Complex is wrong.
-- It can be fixed by using the definition:
-- > x ** y = if x == 0 then 0 else exp (log x * y)
-- cf., <https://ghc.haskell.org/trac/ghc/ticket/8539>
-- TODO: Is this relevant to us at all?
-- TODO: check out ekmett's compensated library.
-- Some good test cases:
-- for @logsumexp == log . sum . map exp@:
-- logsumexp[0,1,0] should be about 1.55
-- for correctness of avoiding underflow:
-- logsumexp[1000,1001,1000] ~~ 1001.55 == 1000 + 1.55
-- logsumexp[-1000,-999,-1000] ~~ -998.45 == -1000 + 1.55
--
-- | /O(n)/. Compute the sum of a finite list of 'LogFloat's, being
-- careful to avoid underflow issues. That is, the following
-- equivalence holds (modulo underflow and all that):
--
-- > logFloat . sum == sum . map logFloat
--
-- /N.B./, this function requires two passes over the input. Thus,
-- it is not amenable to list fusion, and hence will use a lot of
-- memory when summing long lists.
--
-- /Since: 0.13/
sum :: [LogFloat] -> LogFloat
sum = LogFloat . logSumExp . fmap logFromLogFloat
-- | /O(n)/. Compute the product of a finite list of 'LogFloat's,
-- being careful to avoid numerical error due to loss of precision.
-- That is, the following equivalence holds (modulo underflow and
-- all that):
--
-- > logFloat . product == product . map logFloat
--
-- /Since: 0.13/
product :: [LogFloat] -> LogFloat
product = LogFloat . kahanSum . fmap logFromLogFloat
----------------------------------------------------------------
----------------------------------------------------------- fin.
| wrengr/logfloat | src/Data/Number/LogFloat.hs | bsd-3-clause | 22,006 | 0 | 16 | 4,589 | 2,455 | 1,409 | 1,046 | 120 | 1 |
module Futhark.IR.Prop.RearrangeTests (tests) where
import Control.Applicative
import Futhark.IR.Prop.Rearrange
import Test.Tasty
import Test.Tasty.HUnit
import Test.Tasty.QuickCheck
import Prelude
tests :: TestTree
tests =
testGroup "RearrangeTests" $
isMapTransposeTests
++ [isMapTransposeProp]
isMapTransposeTests :: [TestTree]
isMapTransposeTests =
[ testCase (unwords ["isMapTranspose", show perm, "==", show dres]) $
isMapTranspose perm @?= dres
| (perm, dres) <-
[ ([0, 1, 4, 5, 2, 3], Just (2, 2, 2)),
([1, 0, 4, 5, 2, 3], Nothing),
([1, 0], Just (0, 1, 1)),
([0, 2, 1], Just (1, 1, 1)),
([0, 1, 2], Nothing),
([1, 0, 2], Nothing)
]
]
newtype Permutation = Permutation [Int]
deriving (Eq, Ord, Show)
instance Arbitrary Permutation where
arbitrary = do
Positive n <- arbitrary
Permutation <$> shuffle [0 .. n -1]
isMapTransposeProp :: TestTree
isMapTransposeProp = testProperty "isMapTranspose corresponds to a map of transpose" prop
where
prop :: Permutation -> Bool
prop (Permutation perm) =
case isMapTranspose perm of
Nothing -> True
Just (r1, r2, r3) ->
and
[ r1 >= 0,
r2 > 0,
r3 > 0,
r1 + r2 + r3 == length perm,
let (mapped, notmapped) = splitAt r1 perm
(pretrans, posttrans) = splitAt r2 notmapped
in mapped ++ posttrans ++ pretrans == [0 .. length perm -1]
]
| diku-dk/futhark | unittests/Futhark/IR/Prop/RearrangeTests.hs | isc | 1,540 | 0 | 17 | 464 | 546 | 313 | 233 | 44 | 2 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-matches #-}
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- |
-- Module : Network.AWS.ElastiCache.ListTagsForResource
-- Copyright : (c) 2013-2015 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- The /ListTagsForResource/ action lists all cost allocation tags
-- currently on the named resource. A /cost allocation tag/ is a key-value
-- pair where the key is case-sensitive and the value is optional. Cost
-- allocation tags can be used to categorize and track your AWS costs.
--
-- You can have a maximum of 10 cost allocation tags on an ElastiCache
-- resource. For more information, see
-- <http://docs.aws.amazon.com/AmazonElastiCache/latest/UserGuide/BestPractices.html Using Cost Allocation Tags in Amazon ElastiCache>.
--
-- /See:/ <http://docs.aws.amazon.com/AmazonElastiCache/latest/APIReference/API_ListTagsForResource.html AWS API Reference> for ListTagsForResource.
module Network.AWS.ElastiCache.ListTagsForResource
(
-- * Creating a Request
listTagsForResource
, ListTagsForResource
-- * Request Lenses
, ltfrResourceName
-- * Destructuring the Response
, tagListMessage
, TagListMessage
-- * Response Lenses
, tlmTagList
) where
import Network.AWS.ElastiCache.Types
import Network.AWS.ElastiCache.Types.Product
import Network.AWS.Prelude
import Network.AWS.Request
import Network.AWS.Response
-- | The input parameters for the /ListTagsForResource/ action.
--
-- /See:/ 'listTagsForResource' smart constructor.
newtype ListTagsForResource = ListTagsForResource'
{ _ltfrResourceName :: Text
} deriving (Eq,Read,Show,Data,Typeable,Generic)
-- | Creates a value of 'ListTagsForResource' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltfrResourceName'
listTagsForResource
:: Text -- ^ 'ltfrResourceName'
-> ListTagsForResource
listTagsForResource pResourceName_ =
ListTagsForResource'
{ _ltfrResourceName = pResourceName_
}
-- | The name of the resource for which you want the list of tags, for
-- example 'arn:aws:elasticache:us-west-2:0123456789:cluster:myCluster'.
ltfrResourceName :: Lens' ListTagsForResource Text
ltfrResourceName = lens _ltfrResourceName (\ s a -> s{_ltfrResourceName = a});
instance AWSRequest ListTagsForResource where
type Rs ListTagsForResource = TagListMessage
request = postQuery elastiCache
response
= receiveXMLWrapper "ListTagsForResourceResult"
(\ s h x -> parseXML x)
instance ToHeaders ListTagsForResource where
toHeaders = const mempty
instance ToPath ListTagsForResource where
toPath = const "/"
instance ToQuery ListTagsForResource where
toQuery ListTagsForResource'{..}
= mconcat
["Action" =: ("ListTagsForResource" :: ByteString),
"Version" =: ("2015-02-02" :: ByteString),
"ResourceName" =: _ltfrResourceName]
| fmapfmapfmap/amazonka | amazonka-elasticache/gen/Network/AWS/ElastiCache/ListTagsForResource.hs | mpl-2.0 | 3,503 | 0 | 9 | 681 | 347 | 217 | 130 | 48 | 1 |
{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Ambiata.Cli.Data.Transfer (
TemporaryCreds (..)
, Endpoint (..)
) where
import Mismi.S3.Amazonka (AccessKey, SecretKey (..), SessionToken (..))
import P
data TemporaryCreds =
TemporaryCreds {
tempKey :: AccessKey,
tempSecret :: SecretKey,
sessionToken :: SessionToken
} deriving (Eq, Show)
instance Show SecretKey where
show (SecretKey bs) = show bs
instance Show SessionToken where
show (SessionToken bs) = show bs
newtype Endpoint =
Endpoint {
unEndpoint :: Text
} deriving (Eq, Show)
| ambiata/tatooine-cli | src/Ambiata/Cli/Data/Transfer.hs | apache-2.0 | 642 | 0 | 8 | 152 | 166 | 100 | 66 | 21 | 0 |
{-# LANGUAGE FlexibleInstances, MultiParamTypeClasses #-}
--------------------------------------------------------------------------------
-- This code is generated by util/genC.hs.
--------------------------------------------------------------------------------
module Graphics.UI.GLFW.C where
--------------------------------------------------------------------------------
import Data.Bits ((.&.))
import Data.Char (chr, ord)
import Foreign.C.Types (CDouble, CFloat, CInt, CUChar, CUInt, CUShort)
import Foreign.Ptr (Ptr)
import Bindings.GLFW
import Graphics.UI.GLFW.Types
--------------------------------------------------------------------------------
class C c h where
fromC :: c -> h
toC :: h -> c
--------------------------------------------------------------------------------
instance C CInt Char where
fromC = chr . fromIntegral
toC = fromIntegral . ord
instance C CUInt Char where
fromC = chr . fromIntegral
toC = fromIntegral . ord
instance C CDouble Double where
fromC = realToFrac
toC = realToFrac
instance C CInt Int where
fromC = fromIntegral
toC = fromIntegral
instance C CUInt Int where
fromC = fromIntegral
toC = fromIntegral
instance C CUShort Int where
fromC = fromIntegral
toC = fromIntegral
instance C CFloat Double where
fromC = realToFrac
toC = realToFrac
instance C (Ptr C'GLFWmonitor) Monitor where
fromC = Monitor
toC = unMonitor
instance C (Ptr C'GLFWwindow) Window where
fromC = Window
toC = unWindow
instance C CInt ModifierKeys where
fromC v = ModifierKeys
{ modifierKeysShift = (v .&. c'GLFW_MOD_SHIFT) /= 0
, modifierKeysControl = (v .&. c'GLFW_MOD_CONTROL) /= 0
, modifierKeysAlt = (v .&. c'GLFW_MOD_ALT) /= 0
, modifierKeysSuper = (v .&. c'GLFW_MOD_SUPER) /= 0
}
toC = undefined
instance C C'GLFWvidmode VideoMode where
fromC gvm = VideoMode
{ videoModeWidth = fromIntegral $ c'GLFWvidmode'width gvm
, videoModeHeight = fromIntegral $ c'GLFWvidmode'height gvm
, videoModeRedBits = fromIntegral $ c'GLFWvidmode'redBits gvm
, videoModeGreenBits = fromIntegral $ c'GLFWvidmode'greenBits gvm
, videoModeBlueBits = fromIntegral $ c'GLFWvidmode'blueBits gvm
, videoModeRefreshRate = fromIntegral $ c'GLFWvidmode'refreshRate gvm
}
toC = undefined
--------------------------------------------------------------------------------
instance C CInt Bool where
fromC v
| v == c'GL_FALSE = False
| v == c'GL_TRUE = True
| otherwise = error $ "C CInt Bool fromC: " ++ show v
toC False = c'GL_FALSE
toC True = c'GL_TRUE
instance C CInt Error where
fromC v
| v == c'GLFW_NOT_INITIALIZED = Error'NotInitialized
| v == c'GLFW_NO_CURRENT_CONTEXT = Error'NoCurrentContext
| v == c'GLFW_INVALID_ENUM = Error'InvalidEnum
| v == c'GLFW_INVALID_VALUE = Error'InvalidValue
| v == c'GLFW_OUT_OF_MEMORY = Error'OutOfMemory
| v == c'GLFW_API_UNAVAILABLE = Error'ApiUnavailable
| v == c'GLFW_VERSION_UNAVAILABLE = Error'VersionUnavailable
| v == c'GLFW_PLATFORM_ERROR = Error'PlatformError
| v == c'GLFW_FORMAT_UNAVAILABLE = Error'FormatUnavailable
| otherwise = error $ "C CInt Error fromC: " ++ show v
toC Error'NotInitialized = c'GLFW_NOT_INITIALIZED
toC Error'NoCurrentContext = c'GLFW_NO_CURRENT_CONTEXT
toC Error'InvalidEnum = c'GLFW_INVALID_ENUM
toC Error'InvalidValue = c'GLFW_INVALID_VALUE
toC Error'OutOfMemory = c'GLFW_OUT_OF_MEMORY
toC Error'ApiUnavailable = c'GLFW_API_UNAVAILABLE
toC Error'VersionUnavailable = c'GLFW_VERSION_UNAVAILABLE
toC Error'PlatformError = c'GLFW_PLATFORM_ERROR
toC Error'FormatUnavailable = c'GLFW_FORMAT_UNAVAILABLE
instance C CInt MonitorState where
fromC v
| v == c'GL_TRUE = MonitorState'Connected
| v == c'GL_FALSE = MonitorState'Disconnected
| otherwise = error $ "C CInt MonitorState fromC: " ++ show v
toC MonitorState'Connected = c'GL_TRUE
toC MonitorState'Disconnected = c'GL_FALSE
instance C CInt FocusState where
fromC v
| v == c'GL_TRUE = FocusState'Focused
| v == c'GL_FALSE = FocusState'Defocused
| otherwise = error $ "C CInt FocusState fromC: " ++ show v
toC FocusState'Focused = c'GL_TRUE
toC FocusState'Defocused = c'GL_FALSE
instance C CInt IconifyState where
fromC v
| v == c'GL_TRUE = IconifyState'Iconified
| v == c'GL_FALSE = IconifyState'NotIconified
| otherwise = error $ "C CInt IconifyState fromC: " ++ show v
toC IconifyState'Iconified = c'GL_TRUE
toC IconifyState'NotIconified = c'GL_FALSE
instance C CInt ContextRobustness where
fromC v
| v == c'GLFW_NO_ROBUSTNESS = ContextRobustness'NoRobustness
| v == c'GLFW_NO_RESET_NOTIFICATION = ContextRobustness'NoResetNotification
| v == c'GLFW_LOSE_CONTEXT_ON_RESET = ContextRobustness'LoseContextOnReset
| otherwise = error $ "C CInt ContextRobustness fromC: " ++ show v
toC ContextRobustness'NoRobustness = c'GLFW_NO_ROBUSTNESS
toC ContextRobustness'NoResetNotification = c'GLFW_NO_RESET_NOTIFICATION
toC ContextRobustness'LoseContextOnReset = c'GLFW_LOSE_CONTEXT_ON_RESET
instance C CInt OpenGLProfile where
fromC v
| v == c'GLFW_OPENGL_ANY_PROFILE = OpenGLProfile'Any
| v == c'GLFW_OPENGL_COMPAT_PROFILE = OpenGLProfile'Compat
| v == c'GLFW_OPENGL_CORE_PROFILE = OpenGLProfile'Core
| otherwise = error $ "C CInt OpenGLProfile fromC: " ++ show v
toC OpenGLProfile'Any = c'GLFW_OPENGL_ANY_PROFILE
toC OpenGLProfile'Compat = c'GLFW_OPENGL_COMPAT_PROFILE
toC OpenGLProfile'Core = c'GLFW_OPENGL_CORE_PROFILE
instance C CInt ClientAPI where
fromC v
| v == c'GLFW_OPENGL_API = ClientAPI'OpenGL
| v == c'GLFW_OPENGL_ES_API = ClientAPI'OpenGLES
| otherwise = error $ "C CInt ClientAPI fromC: " ++ show v
toC ClientAPI'OpenGL = c'GLFW_OPENGL_API
toC ClientAPI'OpenGLES = c'GLFW_OPENGL_ES_API
instance C CInt Key where
fromC v
| v == c'GLFW_KEY_UNKNOWN = Key'Unknown
| v == c'GLFW_KEY_SPACE = Key'Space
| v == c'GLFW_KEY_APOSTROPHE = Key'Apostrophe
| v == c'GLFW_KEY_COMMA = Key'Comma
| v == c'GLFW_KEY_MINUS = Key'Minus
| v == c'GLFW_KEY_PERIOD = Key'Period
| v == c'GLFW_KEY_SLASH = Key'Slash
| v == c'GLFW_KEY_0 = Key'0
| v == c'GLFW_KEY_1 = Key'1
| v == c'GLFW_KEY_2 = Key'2
| v == c'GLFW_KEY_3 = Key'3
| v == c'GLFW_KEY_4 = Key'4
| v == c'GLFW_KEY_5 = Key'5
| v == c'GLFW_KEY_6 = Key'6
| v == c'GLFW_KEY_7 = Key'7
| v == c'GLFW_KEY_8 = Key'8
| v == c'GLFW_KEY_9 = Key'9
| v == c'GLFW_KEY_SEMICOLON = Key'Semicolon
| v == c'GLFW_KEY_EQUAL = Key'Equal
| v == c'GLFW_KEY_A = Key'A
| v == c'GLFW_KEY_B = Key'B
| v == c'GLFW_KEY_C = Key'C
| v == c'GLFW_KEY_D = Key'D
| v == c'GLFW_KEY_E = Key'E
| v == c'GLFW_KEY_F = Key'F
| v == c'GLFW_KEY_G = Key'G
| v == c'GLFW_KEY_H = Key'H
| v == c'GLFW_KEY_I = Key'I
| v == c'GLFW_KEY_J = Key'J
| v == c'GLFW_KEY_K = Key'K
| v == c'GLFW_KEY_L = Key'L
| v == c'GLFW_KEY_M = Key'M
| v == c'GLFW_KEY_N = Key'N
| v == c'GLFW_KEY_O = Key'O
| v == c'GLFW_KEY_P = Key'P
| v == c'GLFW_KEY_Q = Key'Q
| v == c'GLFW_KEY_R = Key'R
| v == c'GLFW_KEY_S = Key'S
| v == c'GLFW_KEY_T = Key'T
| v == c'GLFW_KEY_U = Key'U
| v == c'GLFW_KEY_V = Key'V
| v == c'GLFW_KEY_W = Key'W
| v == c'GLFW_KEY_X = Key'X
| v == c'GLFW_KEY_Y = Key'Y
| v == c'GLFW_KEY_Z = Key'Z
| v == c'GLFW_KEY_LEFT_BRACKET = Key'LeftBracket
| v == c'GLFW_KEY_BACKSLASH = Key'Backslash
| v == c'GLFW_KEY_RIGHT_BRACKET = Key'RightBracket
| v == c'GLFW_KEY_GRAVE_ACCENT = Key'GraveAccent
| v == c'GLFW_KEY_WORLD_1 = Key'World1
| v == c'GLFW_KEY_WORLD_2 = Key'World2
| v == c'GLFW_KEY_ESCAPE = Key'Escape
| v == c'GLFW_KEY_ENTER = Key'Enter
| v == c'GLFW_KEY_TAB = Key'Tab
| v == c'GLFW_KEY_BACKSPACE = Key'Backspace
| v == c'GLFW_KEY_INSERT = Key'Insert
| v == c'GLFW_KEY_DELETE = Key'Delete
| v == c'GLFW_KEY_RIGHT = Key'Right
| v == c'GLFW_KEY_LEFT = Key'Left
| v == c'GLFW_KEY_DOWN = Key'Down
| v == c'GLFW_KEY_UP = Key'Up
| v == c'GLFW_KEY_PAGE_UP = Key'PageUp
| v == c'GLFW_KEY_PAGE_DOWN = Key'PageDown
| v == c'GLFW_KEY_HOME = Key'Home
| v == c'GLFW_KEY_END = Key'End
| v == c'GLFW_KEY_CAPS_LOCK = Key'CapsLock
| v == c'GLFW_KEY_SCROLL_LOCK = Key'ScrollLock
| v == c'GLFW_KEY_NUM_LOCK = Key'NumLock
| v == c'GLFW_KEY_PRINT_SCREEN = Key'PrintScreen
| v == c'GLFW_KEY_PAUSE = Key'Pause
| v == c'GLFW_KEY_F1 = Key'F1
| v == c'GLFW_KEY_F2 = Key'F2
| v == c'GLFW_KEY_F3 = Key'F3
| v == c'GLFW_KEY_F4 = Key'F4
| v == c'GLFW_KEY_F5 = Key'F5
| v == c'GLFW_KEY_F6 = Key'F6
| v == c'GLFW_KEY_F7 = Key'F7
| v == c'GLFW_KEY_F8 = Key'F8
| v == c'GLFW_KEY_F9 = Key'F9
| v == c'GLFW_KEY_F10 = Key'F10
| v == c'GLFW_KEY_F11 = Key'F11
| v == c'GLFW_KEY_F12 = Key'F12
| v == c'GLFW_KEY_F13 = Key'F13
| v == c'GLFW_KEY_F14 = Key'F14
| v == c'GLFW_KEY_F15 = Key'F15
| v == c'GLFW_KEY_F16 = Key'F16
| v == c'GLFW_KEY_F17 = Key'F17
| v == c'GLFW_KEY_F18 = Key'F18
| v == c'GLFW_KEY_F19 = Key'F19
| v == c'GLFW_KEY_F20 = Key'F20
| v == c'GLFW_KEY_F21 = Key'F21
| v == c'GLFW_KEY_F22 = Key'F22
| v == c'GLFW_KEY_F23 = Key'F23
| v == c'GLFW_KEY_F24 = Key'F24
| v == c'GLFW_KEY_F25 = Key'F25
| v == c'GLFW_KEY_KP_0 = Key'Pad0
| v == c'GLFW_KEY_KP_1 = Key'Pad1
| v == c'GLFW_KEY_KP_2 = Key'Pad2
| v == c'GLFW_KEY_KP_3 = Key'Pad3
| v == c'GLFW_KEY_KP_4 = Key'Pad4
| v == c'GLFW_KEY_KP_5 = Key'Pad5
| v == c'GLFW_KEY_KP_6 = Key'Pad6
| v == c'GLFW_KEY_KP_7 = Key'Pad7
| v == c'GLFW_KEY_KP_8 = Key'Pad8
| v == c'GLFW_KEY_KP_9 = Key'Pad9
| v == c'GLFW_KEY_KP_DECIMAL = Key'PadDecimal
| v == c'GLFW_KEY_KP_DIVIDE = Key'PadDivide
| v == c'GLFW_KEY_KP_MULTIPLY = Key'PadMultiply
| v == c'GLFW_KEY_KP_SUBTRACT = Key'PadSubtract
| v == c'GLFW_KEY_KP_ADD = Key'PadAdd
| v == c'GLFW_KEY_KP_ENTER = Key'PadEnter
| v == c'GLFW_KEY_KP_EQUAL = Key'PadEqual
| v == c'GLFW_KEY_LEFT_SHIFT = Key'LeftShift
| v == c'GLFW_KEY_LEFT_CONTROL = Key'LeftControl
| v == c'GLFW_KEY_LEFT_ALT = Key'LeftAlt
| v == c'GLFW_KEY_LEFT_SUPER = Key'LeftSuper
| v == c'GLFW_KEY_RIGHT_SHIFT = Key'RightShift
| v == c'GLFW_KEY_RIGHT_CONTROL = Key'RightControl
| v == c'GLFW_KEY_RIGHT_ALT = Key'RightAlt
| v == c'GLFW_KEY_RIGHT_SUPER = Key'RightSuper
| v == c'GLFW_KEY_MENU = Key'Menu
| otherwise = error $ "C CInt Key fromC: " ++ show v
toC Key'Unknown = c'GLFW_KEY_UNKNOWN
toC Key'Space = c'GLFW_KEY_SPACE
toC Key'Apostrophe = c'GLFW_KEY_APOSTROPHE
toC Key'Comma = c'GLFW_KEY_COMMA
toC Key'Minus = c'GLFW_KEY_MINUS
toC Key'Period = c'GLFW_KEY_PERIOD
toC Key'Slash = c'GLFW_KEY_SLASH
toC Key'0 = c'GLFW_KEY_0
toC Key'1 = c'GLFW_KEY_1
toC Key'2 = c'GLFW_KEY_2
toC Key'3 = c'GLFW_KEY_3
toC Key'4 = c'GLFW_KEY_4
toC Key'5 = c'GLFW_KEY_5
toC Key'6 = c'GLFW_KEY_6
toC Key'7 = c'GLFW_KEY_7
toC Key'8 = c'GLFW_KEY_8
toC Key'9 = c'GLFW_KEY_9
toC Key'Semicolon = c'GLFW_KEY_SEMICOLON
toC Key'Equal = c'GLFW_KEY_EQUAL
toC Key'A = c'GLFW_KEY_A
toC Key'B = c'GLFW_KEY_B
toC Key'C = c'GLFW_KEY_C
toC Key'D = c'GLFW_KEY_D
toC Key'E = c'GLFW_KEY_E
toC Key'F = c'GLFW_KEY_F
toC Key'G = c'GLFW_KEY_G
toC Key'H = c'GLFW_KEY_H
toC Key'I = c'GLFW_KEY_I
toC Key'J = c'GLFW_KEY_J
toC Key'K = c'GLFW_KEY_K
toC Key'L = c'GLFW_KEY_L
toC Key'M = c'GLFW_KEY_M
toC Key'N = c'GLFW_KEY_N
toC Key'O = c'GLFW_KEY_O
toC Key'P = c'GLFW_KEY_P
toC Key'Q = c'GLFW_KEY_Q
toC Key'R = c'GLFW_KEY_R
toC Key'S = c'GLFW_KEY_S
toC Key'T = c'GLFW_KEY_T
toC Key'U = c'GLFW_KEY_U
toC Key'V = c'GLFW_KEY_V
toC Key'W = c'GLFW_KEY_W
toC Key'X = c'GLFW_KEY_X
toC Key'Y = c'GLFW_KEY_Y
toC Key'Z = c'GLFW_KEY_Z
toC Key'LeftBracket = c'GLFW_KEY_LEFT_BRACKET
toC Key'Backslash = c'GLFW_KEY_BACKSLASH
toC Key'RightBracket = c'GLFW_KEY_RIGHT_BRACKET
toC Key'GraveAccent = c'GLFW_KEY_GRAVE_ACCENT
toC Key'World1 = c'GLFW_KEY_WORLD_1
toC Key'World2 = c'GLFW_KEY_WORLD_2
toC Key'Escape = c'GLFW_KEY_ESCAPE
toC Key'Enter = c'GLFW_KEY_ENTER
toC Key'Tab = c'GLFW_KEY_TAB
toC Key'Backspace = c'GLFW_KEY_BACKSPACE
toC Key'Insert = c'GLFW_KEY_INSERT
toC Key'Delete = c'GLFW_KEY_DELETE
toC Key'Right = c'GLFW_KEY_RIGHT
toC Key'Left = c'GLFW_KEY_LEFT
toC Key'Down = c'GLFW_KEY_DOWN
toC Key'Up = c'GLFW_KEY_UP
toC Key'PageUp = c'GLFW_KEY_PAGE_UP
toC Key'PageDown = c'GLFW_KEY_PAGE_DOWN
toC Key'Home = c'GLFW_KEY_HOME
toC Key'End = c'GLFW_KEY_END
toC Key'CapsLock = c'GLFW_KEY_CAPS_LOCK
toC Key'ScrollLock = c'GLFW_KEY_SCROLL_LOCK
toC Key'NumLock = c'GLFW_KEY_NUM_LOCK
toC Key'PrintScreen = c'GLFW_KEY_PRINT_SCREEN
toC Key'Pause = c'GLFW_KEY_PAUSE
toC Key'F1 = c'GLFW_KEY_F1
toC Key'F2 = c'GLFW_KEY_F2
toC Key'F3 = c'GLFW_KEY_F3
toC Key'F4 = c'GLFW_KEY_F4
toC Key'F5 = c'GLFW_KEY_F5
toC Key'F6 = c'GLFW_KEY_F6
toC Key'F7 = c'GLFW_KEY_F7
toC Key'F8 = c'GLFW_KEY_F8
toC Key'F9 = c'GLFW_KEY_F9
toC Key'F10 = c'GLFW_KEY_F10
toC Key'F11 = c'GLFW_KEY_F11
toC Key'F12 = c'GLFW_KEY_F12
toC Key'F13 = c'GLFW_KEY_F13
toC Key'F14 = c'GLFW_KEY_F14
toC Key'F15 = c'GLFW_KEY_F15
toC Key'F16 = c'GLFW_KEY_F16
toC Key'F17 = c'GLFW_KEY_F17
toC Key'F18 = c'GLFW_KEY_F18
toC Key'F19 = c'GLFW_KEY_F19
toC Key'F20 = c'GLFW_KEY_F20
toC Key'F21 = c'GLFW_KEY_F21
toC Key'F22 = c'GLFW_KEY_F22
toC Key'F23 = c'GLFW_KEY_F23
toC Key'F24 = c'GLFW_KEY_F24
toC Key'F25 = c'GLFW_KEY_F25
toC Key'Pad0 = c'GLFW_KEY_KP_0
toC Key'Pad1 = c'GLFW_KEY_KP_1
toC Key'Pad2 = c'GLFW_KEY_KP_2
toC Key'Pad3 = c'GLFW_KEY_KP_3
toC Key'Pad4 = c'GLFW_KEY_KP_4
toC Key'Pad5 = c'GLFW_KEY_KP_5
toC Key'Pad6 = c'GLFW_KEY_KP_6
toC Key'Pad7 = c'GLFW_KEY_KP_7
toC Key'Pad8 = c'GLFW_KEY_KP_8
toC Key'Pad9 = c'GLFW_KEY_KP_9
toC Key'PadDecimal = c'GLFW_KEY_KP_DECIMAL
toC Key'PadDivide = c'GLFW_KEY_KP_DIVIDE
toC Key'PadMultiply = c'GLFW_KEY_KP_MULTIPLY
toC Key'PadSubtract = c'GLFW_KEY_KP_SUBTRACT
toC Key'PadAdd = c'GLFW_KEY_KP_ADD
toC Key'PadEnter = c'GLFW_KEY_KP_ENTER
toC Key'PadEqual = c'GLFW_KEY_KP_EQUAL
toC Key'LeftShift = c'GLFW_KEY_LEFT_SHIFT
toC Key'LeftControl = c'GLFW_KEY_LEFT_CONTROL
toC Key'LeftAlt = c'GLFW_KEY_LEFT_ALT
toC Key'LeftSuper = c'GLFW_KEY_LEFT_SUPER
toC Key'RightShift = c'GLFW_KEY_RIGHT_SHIFT
toC Key'RightControl = c'GLFW_KEY_RIGHT_CONTROL
toC Key'RightAlt = c'GLFW_KEY_RIGHT_ALT
toC Key'RightSuper = c'GLFW_KEY_RIGHT_SUPER
toC Key'Menu = c'GLFW_KEY_MENU
instance C CInt KeyState where
fromC v
| v == c'GLFW_PRESS = KeyState'Pressed
| v == c'GLFW_RELEASE = KeyState'Released
| v == c'GLFW_REPEAT = KeyState'Repeating
| otherwise = error $ "C CInt KeyState fromC: " ++ show v
toC KeyState'Pressed = c'GLFW_PRESS
toC KeyState'Released = c'GLFW_RELEASE
toC KeyState'Repeating = c'GLFW_REPEAT
instance C CInt Joystick where
fromC v
| v == c'GLFW_JOYSTICK_1 = Joystick'1
| v == c'GLFW_JOYSTICK_2 = Joystick'2
| v == c'GLFW_JOYSTICK_3 = Joystick'3
| v == c'GLFW_JOYSTICK_4 = Joystick'4
| v == c'GLFW_JOYSTICK_5 = Joystick'5
| v == c'GLFW_JOYSTICK_6 = Joystick'6
| v == c'GLFW_JOYSTICK_7 = Joystick'7
| v == c'GLFW_JOYSTICK_8 = Joystick'8
| v == c'GLFW_JOYSTICK_9 = Joystick'9
| v == c'GLFW_JOYSTICK_10 = Joystick'10
| v == c'GLFW_JOYSTICK_11 = Joystick'11
| v == c'GLFW_JOYSTICK_12 = Joystick'12
| v == c'GLFW_JOYSTICK_13 = Joystick'13
| v == c'GLFW_JOYSTICK_14 = Joystick'14
| v == c'GLFW_JOYSTICK_15 = Joystick'15
| v == c'GLFW_JOYSTICK_16 = Joystick'16
| otherwise = error $ "C CInt Joystick fromC: " ++ show v
toC Joystick'1 = c'GLFW_JOYSTICK_1
toC Joystick'2 = c'GLFW_JOYSTICK_2
toC Joystick'3 = c'GLFW_JOYSTICK_3
toC Joystick'4 = c'GLFW_JOYSTICK_4
toC Joystick'5 = c'GLFW_JOYSTICK_5
toC Joystick'6 = c'GLFW_JOYSTICK_6
toC Joystick'7 = c'GLFW_JOYSTICK_7
toC Joystick'8 = c'GLFW_JOYSTICK_8
toC Joystick'9 = c'GLFW_JOYSTICK_9
toC Joystick'10 = c'GLFW_JOYSTICK_10
toC Joystick'11 = c'GLFW_JOYSTICK_11
toC Joystick'12 = c'GLFW_JOYSTICK_12
toC Joystick'13 = c'GLFW_JOYSTICK_13
toC Joystick'14 = c'GLFW_JOYSTICK_14
toC Joystick'15 = c'GLFW_JOYSTICK_15
toC Joystick'16 = c'GLFW_JOYSTICK_16
instance C CUChar JoystickButtonState where
fromC v
| v == c'GLFW_PRESS = JoystickButtonState'Pressed
| v == c'GLFW_RELEASE = JoystickButtonState'Released
| otherwise = error $ "C CUChar JoystickButtonState fromC: " ++ show v
toC JoystickButtonState'Pressed = c'GLFW_PRESS
toC JoystickButtonState'Released = c'GLFW_RELEASE
instance C CInt MouseButton where
fromC v
| v == c'GLFW_MOUSE_BUTTON_1 = MouseButton'1
| v == c'GLFW_MOUSE_BUTTON_2 = MouseButton'2
| v == c'GLFW_MOUSE_BUTTON_3 = MouseButton'3
| v == c'GLFW_MOUSE_BUTTON_4 = MouseButton'4
| v == c'GLFW_MOUSE_BUTTON_5 = MouseButton'5
| v == c'GLFW_MOUSE_BUTTON_6 = MouseButton'6
| v == c'GLFW_MOUSE_BUTTON_7 = MouseButton'7
| v == c'GLFW_MOUSE_BUTTON_8 = MouseButton'8
| otherwise = error $ "C CInt MouseButton fromC: " ++ show v
toC MouseButton'1 = c'GLFW_MOUSE_BUTTON_1
toC MouseButton'2 = c'GLFW_MOUSE_BUTTON_2
toC MouseButton'3 = c'GLFW_MOUSE_BUTTON_3
toC MouseButton'4 = c'GLFW_MOUSE_BUTTON_4
toC MouseButton'5 = c'GLFW_MOUSE_BUTTON_5
toC MouseButton'6 = c'GLFW_MOUSE_BUTTON_6
toC MouseButton'7 = c'GLFW_MOUSE_BUTTON_7
toC MouseButton'8 = c'GLFW_MOUSE_BUTTON_8
instance C CInt MouseButtonState where
fromC v
| v == c'GLFW_PRESS = MouseButtonState'Pressed
| v == c'GLFW_RELEASE = MouseButtonState'Released
| otherwise = error $ "C CInt MouseButtonState fromC: " ++ show v
toC MouseButtonState'Pressed = c'GLFW_PRESS
toC MouseButtonState'Released = c'GLFW_RELEASE
instance C CInt CursorState where
fromC v
| v == c'GL_TRUE = CursorState'InWindow
| v == c'GL_FALSE = CursorState'NotInWindow
| otherwise = error $ "C CInt CursorState fromC: " ++ show v
toC CursorState'InWindow = c'GL_TRUE
toC CursorState'NotInWindow = c'GL_FALSE
instance C CInt CursorInputMode where
fromC v
| v == c'GLFW_CURSOR_NORMAL = CursorInputMode'Normal
| v == c'GLFW_CURSOR_HIDDEN = CursorInputMode'Hidden
| v == c'GLFW_CURSOR_DISABLED = CursorInputMode'Disabled
| otherwise = error $ "C CInt CursorInputMode fromC: " ++ show v
toC CursorInputMode'Normal = c'GLFW_CURSOR_NORMAL
toC CursorInputMode'Hidden = c'GLFW_CURSOR_HIDDEN
toC CursorInputMode'Disabled = c'GLFW_CURSOR_DISABLED
instance C CInt StickyKeysInputMode where
fromC v
| v == c'GL_TRUE = StickyKeysInputMode'Enabled
| v == c'GL_FALSE = StickyKeysInputMode'Disabled
| otherwise = error $ "C CInt StickyKeysInputMode fromC: " ++ show v
toC StickyKeysInputMode'Enabled = c'GL_TRUE
toC StickyKeysInputMode'Disabled = c'GL_FALSE
instance C CInt StickyMouseButtonsInputMode where
fromC v
| v == c'GL_TRUE = StickyMouseButtonsInputMode'Enabled
| v == c'GL_FALSE = StickyMouseButtonsInputMode'Disabled
| otherwise = error $ "C CInt StickyMouseButtonsInputMode fromC: " ++ show v
toC StickyMouseButtonsInputMode'Enabled = c'GL_TRUE
toC StickyMouseButtonsInputMode'Disabled = c'GL_FALSE
--------------------------------------------------------------------------------
{-# ANN module "HLint: ignore Use camelCase" #-} | phaazon/GLFW-b | Graphics/UI/GLFW/C.hs | bsd-2-clause | 19,563 | 0 | 10 | 3,931 | 5,060 | 2,447 | 2,613 | 481 | 0 |
{-# LANGUAGE TemplateHaskell #-}
--------------------------------------------------------------------------------
-- |
-- Module : Data.Comp.Derive.Traversable
-- Copyright : (c) 2010-2011 Patrick Bahr
-- License : BSD3
-- Maintainer : Patrick Bahr <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC Extensions)
--
-- Automatically derive instances of @Traversable@.
--
--------------------------------------------------------------------------------
module Data.Comp.Derive.Traversable
(
Traversable,
makeTraversable
) where
import Control.Applicative
import Control.Monad hiding (mapM, sequence)
import Data.Comp.Derive.Utils
import Data.Foldable hiding (any, or)
import Data.Maybe
import Data.Traversable
import Language.Haskell.TH
import Prelude hiding (foldl, foldr, mapM, sequence)
import qualified Prelude as P (foldl, foldr, mapM)
iter 0 _ e = e
iter n f e = iter (n-1) f (f `appE` e)
iter' 0 _ e = e
iter' m f e = let f' = iter (m-1) [|fmap|] f
in iter' (m-1) f (f' `appE` e)
{-| Derive an instance of 'Traversable' for a type constructor of any
first-order kind taking at least one argument. -}
makeTraversable :: Name -> Q [Dec]
makeTraversable fname = do
TyConI (DataD _cxt name args constrs _deriving) <- abstractNewtypeQ $ reify fname
let fArg = VarT . tyVarBndrName $ last args
argNames = map (VarT . tyVarBndrName) (init args)
complType = foldl AppT (ConT name) argNames
classType = AppT (ConT ''Traversable) complType
constrs' <- P.mapM (mkPatAndVars . isFarg fArg <=< normalConExp) constrs
traverseDecl <- funD 'traverse (map traverseClause constrs')
sequenceADecl <- funD 'sequenceA (map sequenceAClause constrs')
mapMDecl <- funD 'mapM (map mapMClause constrs')
sequenceDecl <- funD 'sequence (map sequenceClause constrs')
return [InstanceD [] classType [traverseDecl, sequenceADecl, mapMDecl,sequenceDecl]]
where isFarg fArg (constr, args) = (constr, map (`containsType'` fArg) args)
filterVar _ nonFarg [] x = nonFarg x
filterVar farg _ [depth] x = farg depth x
filterVar _ _ _ _ = error "functor variable occurring twice in argument type"
filterVars args varNs farg nonFarg = zipWith (filterVar farg nonFarg) args varNs
mkCPat constr varNs = ConP constr $ map mkPat varNs
mkPat = VarP
mkPatAndVars (constr, args) =
do varNs <- newNames (length args) "x"
return (conE constr, mkCPat constr varNs,
\f g -> filterVars args varNs (\ d x -> f d (varE x)) (g . varE),
any (not . null) args, map varE varNs, catMaybes $ filterVars args varNs (curry Just) (const Nothing))
traverseClause (con, pat,vars',hasFargs,_allVars,_fVars) =
do fn <- newName "f"
let f = varE fn
fp = if hasFargs then VarP fn else WildP
vars = vars' (\d x -> iter d [|traverse|] f `appE` x) (\x -> [|pure $x|])
body <- P.foldl (\ x y -> [|$x <*> $y|]) [|pure $con|] vars
return $ Clause [fp, pat] (NormalB body) []
sequenceAClause (con, pat,vars',_hasFargs,_,_) =
do let vars = vars' (\d x -> iter' d [|sequenceA|] x) (\x -> [|pure $x|])
body <- P.foldl (\ x y -> [|$x <*> $y|]) [|pure $con|] vars
return $ Clause [pat] (NormalB body) []
-- Note: the monadic versions are not defined
-- applicatively, as this results in a considerable
-- performance penalty (by factor 2)!
mapMClause (con, pat,_,hasFargs,allVars, fvars) =
do fn <- newName "f"
let f = varE fn
fp = if hasFargs then VarP fn else WildP
conAp = P.foldl appE con allVars
conBind (d,x) y = [| $(iter d [|mapM|] f) $(varE x) >>= $(lamE [varP x] y)|]
body <- P.foldr conBind [|return $conAp|] fvars
return $ Clause [fp, pat] (NormalB body) []
sequenceClause (con, pat,_vars',_hasFargs,allVars, fvars) =
do let conAp = P.foldl appE con allVars
conBind (d, x) y = [| $(iter' d [|sequence|] (varE x)) >>= $(lamE [varP x] y)|]
body <- P.foldr conBind [|return $conAp|] fvars
return $ Clause [pat] (NormalB body) []
| spacekitteh/compdata | src/Data/Comp/Derive/Traversable.hs | bsd-3-clause | 4,538 | 8 | 18 | 1,343 | 1,415 | 772 | 643 | -1 | -1 |
{-# LANGUAGE DeriveTraversable #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeSynonymInstances #-}
module List
(
main
) where
import Prelude hiding (reverse, splitAt)
import Data.Foldable (find)
import Data.Function (on)
import qualified Data.List
import Data.Maybe (isNothing)
import Data.Monoid (Endo(..))
import Data.Proxy
import Data.Semigroup (Semigroup((<>)))
import qualified Data.Sequence as Seq
import qualified Data.Vector as V
import Lens.Micro
import Test.QuickCheck
import Brick.Util (clamp)
import Brick.Widgets.List
instance (Arbitrary n, Arbitrary a) => Arbitrary (List n a) where
arbitrary = list <$> arbitrary <*> (V.fromList <$> arbitrary) <*> pure 1
-- List move operations that never modify the underlying list
data ListMoveOp a
= MoveUp
| MoveDown
| MoveBy Int
| MoveTo Int
| MoveToElement a
| FindElement a
deriving (Show)
instance Arbitrary a => Arbitrary (ListMoveOp a) where
arbitrary = oneof
[ pure MoveUp
, pure MoveDown
, MoveBy <$> arbitrary
, MoveTo <$> arbitrary
, MoveToElement <$> arbitrary
, FindElement <$> arbitrary
]
-- List operations. We don't have "page"-based movement operations
-- because these depend on render context (i.e. effect in EventM)
data ListOp a
= Insert Int a
| Remove Int
| Replace Int [a]
| Clear
| Reverse
| ListMoveOp (ListMoveOp a)
deriving (Show)
instance Arbitrary a => Arbitrary (ListOp a) where
arbitrary = frequency
[ (1, Insert <$> arbitrary <*> arbitrary)
, (1, Remove <$> arbitrary)
, (1, Replace <$> arbitrary <*> arbitrary)
, (1, pure Clear)
, (1, pure Reverse)
, (6, arbitrary)
]
-- Turn a ListOp into a List endomorphism
op :: Eq a => ListOp a -> List n a -> List n a
op (Insert i a) = listInsert i a
op (Remove i) = listRemove i
op (Replace i xs) =
-- avoid setting index to Nothing
listReplace (V.fromList xs) (Just i)
op Clear = listClear
op Reverse = listReverse
op (ListMoveOp mo) = moveOp mo
-- Turn a ListMoveOp into a List endomorphism
moveOp :: (Eq a) => ListMoveOp a -> List n a -> List n a
moveOp MoveUp = listMoveUp
moveOp MoveDown = listMoveDown
moveOp (MoveBy n) = listMoveBy n
moveOp (MoveTo n) = listMoveTo n
moveOp (MoveToElement a) = listMoveToElement a
moveOp (FindElement a) = listFindBy (== a)
applyListOps
:: (Foldable t)
=> (op a -> List n a -> List n a) -> t (op a) -> List n a -> List n a
applyListOps f = appEndo . foldMap (Endo . f)
-- | Initial selection is always 0 (or Nothing for empty list)
prop_initialSelection :: [a] -> Bool
prop_initialSelection xs =
list () (V.fromList xs) 1 ^. listSelectedL ==
if null xs then Nothing else Just 0
-- list operations keep the selected index in bounds
prop_listOpsMaintainSelectedValid
:: (Eq a) => [ListOp a] -> List n a -> Bool
prop_listOpsMaintainSelectedValid ops l =
let l' = applyListOps op ops l
in
case l' ^. listSelectedL of
-- either there is no selection and list is empty
Nothing -> null l'
-- or the selected index is valid
Just i -> i >= 0 && i < length l'
-- reversing a list keeps the selected element the same
prop_reverseMaintainsSelectedElement
:: (Eq a) => [ListOp a] -> List n a -> Bool
prop_reverseMaintainsSelectedElement ops l =
let
-- apply some random list ops to (probably) set a selected element
l' = applyListOps op ops l
l'' = listReverse l'
in
fmap snd (listSelectedElement l') == fmap snd (listSelectedElement l'')
-- reversing maintains size of list
prop_reverseMaintainsSizeOfList :: List n a -> Bool
prop_reverseMaintainsSizeOfList l =
length l == length (listReverse l)
-- an inserted element may always be found at the given index
-- (when target index is clamped to 0 <= n <= len)
prop_insert :: (Eq a) => Int -> a -> List n a -> Bool
prop_insert i a l =
let
l' = listInsert i a l
i' = clamp 0 (length l) i
in
listSelectedElement (listMoveTo i' l') == Just (i', a)
-- inserting anywhere always increases size of list by 1
prop_insertSize :: (Eq a) => Int -> a -> List n a -> Bool
prop_insertSize i a l =
let
l' = listInsert i a l
in
length l' == length l + 1
-- inserting an element and moving to it always succeeds and
-- the selected element is the one we inserted.
--
-- The index is not necessarily the index we inserted at, because
-- the element could be present in the original list. So we don't
-- check that.
--
prop_insertMoveTo :: (Eq a) => [ListOp a] -> List n a -> Int -> a -> Bool
prop_insertMoveTo ops l i a =
let
l' = listInsert i a (applyListOps op ops l)
sel = listSelectedElement (listMoveToElement a l')
in
fmap snd sel == Just a
-- inserting an element and repeatedly seeking it always
-- reaches the element we inserted, at the index where we
-- inserted it.
--
prop_insertFindBy :: (Eq a) => [ListOp a] -> List n a -> Int -> a -> Bool
prop_insertFindBy ops l i a =
let
l' = applyListOps op ops l
l'' = set listSelectedL Nothing . listInsert i a $ l'
seeks = converging ((==) `on` (^. listSelectedL)) (listFindBy (== a)) l''
i' = clamp 0 (length l') i -- we can't have inserted past len
in
(find ((== Just i') . (^. listSelectedL)) seeks >>= listSelectedElement)
== Just (i', a)
-- inserting then deleting always yields a list with the original elems
prop_insertRemove :: (Eq a) => Int -> a -> List n a -> Bool
prop_insertRemove i a l =
let
i' = clamp 0 (length l) i
l' = listInsert i' a l -- pre-clamped
l'' = listRemove i' l'
in
l'' ^. listElementsL == l ^. listElementsL
-- deleting in-bounds always reduces size of list by 1
-- deleting out-of-bounds never changes list size
prop_remove :: Int -> List n a -> Bool
prop_remove i l =
let
len = length l
i' = clamp 0 (len - 1) i
test
| len > 0 && i == i' = (== len - 1) -- i is in bounds
| otherwise = (== len) -- i is out of bounds
in
test (length (listRemove i l))
-- deleting an element and re-inserting it at same position
-- gives the original list elements
prop_removeInsert :: (Eq a) => Int -> List n a -> Bool
prop_removeInsert i l =
let
sel = listSelectedElement (listMoveTo i l)
l' = maybe id (\(i', a) -> listInsert i' a . listRemove i') sel l
in
l' ^. listElementsL == l ^. listElementsL
-- Apply @f@ until @test a (f a) == True@, then return @a@.
converge :: (a -> a -> Bool) -> (a -> a) -> a -> a
converge test f = last . converging test f
-- Apply @f@ until @test a (f a) == True@, returning the start,
-- intermediate and final values as a list.
converging :: (a -> a -> Bool) -> (a -> a) -> a -> [a]
converging test f a
| test a (f a) = [a]
| otherwise = a : converging test f (f a)
-- listMoveUp always reaches 0 (or list is empty)
prop_moveUp :: (Eq a) => [ListOp a] -> List n a -> Bool
prop_moveUp ops l =
let
l' = applyListOps op ops l
l'' = converge ((==) `on` (^. listSelectedL)) listMoveUp l'
len = length l''
in
maybe (len == 0) (== 0) (l'' ^. listSelectedL)
-- listMoveDown always reaches end of list (or list is empty)
prop_moveDown :: (Eq a) => [ListOp a] -> List n a -> Bool
prop_moveDown ops l =
let
l' = applyListOps op ops l
l'' = converge ((==) `on` (^. listSelectedL)) listMoveDown l'
len = length l''
in
maybe (len == 0) (== len - 1) (l'' ^. listSelectedL)
-- move ops never change the list
prop_moveOpsNeverChangeList :: (Eq a) => [ListMoveOp a] -> List n a -> Bool
prop_moveOpsNeverChangeList ops l =
let
l' = applyListOps moveOp ops l
in
l' ^. listElementsL == l ^. listElementsL
-- If the list is empty, empty selection is used.
-- Otherwise, if the specified selected index is not in list bounds,
-- zero is used instead.
prop_replaceSetIndex
:: (Eq a)
=> [ListOp a] -> List n a -> [a] -> Int -> Bool
prop_replaceSetIndex ops l xs i =
let
v = V.fromList xs
l' = applyListOps op ops l
l'' = listReplace v (Just i) l'
i' = clamp 0 (length v - 1) i
inBounds = i == i'
in
l'' ^. listSelectedL == case (null v, inBounds) of
(True, _) -> Nothing
(False, True) -> Just i
(False, False) -> Just 0
-- Replacing with no index always clears the index
prop_replaceNoIndex :: (Eq a) => [ListOp a] -> List n a -> [a] -> Bool
prop_replaceNoIndex ops l xs =
let
v = V.fromList xs
l' = applyListOps op ops l
in
isNothing (listReplace v Nothing l' ^. listSelectedL)
-- | Move the list selected index. If the index is `Just x`, adjust by the
-- specified amount; if it is `Nothing` (i.e. there is no selection) and the
-- direction is positive, set to `Just 0` (first element), otherwise set to
-- `Just (length - 1)` (last element). Subject to validation.
prop_moveByWhenNoSelection :: List n a -> Int -> Property
prop_moveByWhenNoSelection l amt =
let
l' = l & listSelectedL .~ Nothing
len = length l
expected = if amt > 0 then 0 else len - 1
in
len > 0 ==> listMoveBy amt l' ^. listSelectedL == Just expected
splitAtLength :: (Foldable t, Splittable t) => t a -> Int -> Bool
splitAtLength l i =
let
len = length l
(h, t) = splitAt i l
in
length h + length t == len
&& length h == clamp 0 len i
splitAtAppend
:: (Splittable t, Semigroup (t a), Eq (t a))
=> t a -> Int -> Bool
splitAtAppend l i = uncurry (<>) (splitAt i l) == l
prop_splitAtLength_Vector :: [a] -> Int -> Bool
prop_splitAtLength_Vector = splitAtLength . V.fromList
prop_splitAtAppend_Vector :: (Eq a) => [a] -> Int -> Bool
prop_splitAtAppend_Vector = splitAtAppend . V.fromList
prop_splitAtLength_Seq :: [a] -> Int -> Bool
prop_splitAtLength_Seq = splitAtLength . Seq.fromList
prop_splitAtAppend_Seq :: (Eq a) => [a] -> Int -> Bool
prop_splitAtAppend_Seq = splitAtAppend . Seq.fromList
reverseSingleton
:: forall t a. (Reversible t, Applicative t, Eq (t a))
=> Proxy t -> a -> Bool
reverseSingleton _ a =
let l = pure a :: t a
in reverse l == l
reverseAppend
:: (Reversible t, Semigroup (t a), Eq (t a))
=> t a -> t a -> Bool
reverseAppend l1 l2 =
reverse (l1 <> l2) == reverse l2 <> reverse l1
prop_reverseSingleton_Vector :: (Eq a) => a -> Bool
prop_reverseSingleton_Vector = reverseSingleton (Proxy :: Proxy V.Vector)
prop_reverseAppend_Vector :: (Eq a) => [a] -> [a] -> Bool
prop_reverseAppend_Vector l1 l2 =
reverseAppend (V.fromList l1) (V.fromList l2)
prop_reverseSingleton_Seq :: (Eq a) => a -> Bool
prop_reverseSingleton_Seq = reverseSingleton (Proxy :: Proxy Seq.Seq)
prop_reverseAppend_Seq :: (Eq a) => [a] -> [a] -> Bool
prop_reverseAppend_Seq l1 l2 =
reverseAppend (Seq.fromList l1) (Seq.fromList l2)
-- Laziness tests. Here we create a custom container type
-- that we use to ensure certain operations do not cause the
-- whole container to be evaluated.
--
newtype L a = L [a]
deriving (Functor, Foldable, Traversable)
instance Splittable L where
splitAt i (L xs) = over both L (Data.List.splitAt i xs)
-- moveBy positive amount does not evaluate 'length'
prop_moveByPosLazy :: Bool
prop_moveByPosLazy =
let
v = L (1:2:3:4:undefined) :: L Int
l = list () v 1
l' = listMoveBy 1 l
in
l' ^. listSelectedL == Just 1
-- listFindBy is lazy
prop_findByLazy :: Bool
prop_findByLazy =
let
v = L (1:2:3:4:undefined) :: L Int
l = list () v 1 & listSelectedL .~ Nothing
l' = listFindBy even l
l'' = listFindBy even l'
in
l' ^. listSelectedL == Just 1
&& l'' ^. listSelectedL == Just 3
return []
main :: IO Bool
main = $quickCheckAll
| sjakobi/brick | tests/List.hs | bsd-3-clause | 11,624 | 0 | 14 | 2,650 | 3,815 | 1,993 | 1,822 | -1 | -1 |
{-
(c) The University of Glasgow, 2000-2006
\section[Finder]{Module Finder}
-}
{-# LANGUAGE CPP #-}
module ETA.Main.Finder (
flushFinderCaches,
FindResult(..),
findImportedModule,
findExactModule,
findHomeModule,
findExposedPackageModule,
mkHomeModLocation,
mkHomeModLocation2,
mkHiOnlyModLocation,
addHomeModuleToFinder,
uncacheModule,
mkStubPaths,
findObjectLinkableMaybe,
findObjectLinkable,
cannotFindModule,
cannotFindInterface,
) where
#include "HsVersions.h"
import ETA.BasicTypes.Module
import ETA.Main.HscTypes
import ETA.Main.Packages
import ETA.Utils.FastString
import ETA.Utils.Util
import ETA.Prelude.PrelNames ( gHC_PRIM )
import ETA.Main.DynFlags
import ETA.Utils.Outputable
import qualified ETA.Utils.Outputable as Outputable
import ETA.Utils.UniqFM
import ETA.Utils.Maybes ( expectJust )
import ETA.Utils.Exception ( evaluate )
import Data.IORef ( IORef, writeIORef, readIORef, atomicModifyIORef )
import System.Directory
import System.FilePath
import Control.Monad
import Data.Time
import Data.List ( foldl' )
type FileExt = String -- Filename extension
type BaseName = String -- Basename of file
-- -----------------------------------------------------------------------------
-- The Finder
-- The Finder provides a thin filesystem abstraction to the rest of
-- the compiler. For a given module, it can tell you where the
-- source, interface, and object files for that module live.
-- It does *not* know which particular package a module lives in. Use
-- Packages.lookupModuleInAllPackages for that.
-- -----------------------------------------------------------------------------
-- The finder's cache
-- remove all the home modules from the cache; package modules are
-- assumed to not move around during a session.
flushFinderCaches :: HscEnv -> IO ()
flushFinderCaches hsc_env = do
-- Ideally the update to both caches be a single atomic operation.
writeIORef fc_ref emptyUFM
flushModLocationCache this_pkg mlc_ref
where
this_pkg = thisPackage (hsc_dflags hsc_env)
fc_ref = hsc_FC hsc_env
mlc_ref = hsc_MLC hsc_env
flushModLocationCache :: UnitId -> IORef ModLocationCache -> IO ()
flushModLocationCache this_pkg ref = do
atomicModifyIORef ref $ \fm -> (filterModuleEnv is_ext fm, ())
_ <- evaluate =<< readIORef ref
return ()
where is_ext mod _ | moduleUnitId mod /= this_pkg = True
| otherwise = False
addToFinderCache :: IORef FinderCache -> ModuleName -> FindResult -> IO ()
addToFinderCache ref key val =
atomicModifyIORef ref $ \c -> (addToUFM c key val, ())
addToModLocationCache :: IORef ModLocationCache -> Module -> ModLocation -> IO ()
addToModLocationCache ref key val =
atomicModifyIORef ref $ \c -> (extendModuleEnv c key val, ())
removeFromFinderCache :: IORef FinderCache -> ModuleName -> IO ()
removeFromFinderCache ref key =
atomicModifyIORef ref $ \c -> (delFromUFM c key, ())
removeFromModLocationCache :: IORef ModLocationCache -> Module -> IO ()
removeFromModLocationCache ref key =
atomicModifyIORef ref $ \c -> (delModuleEnv c key, ())
lookupFinderCache :: IORef FinderCache -> ModuleName -> IO (Maybe FindResult)
lookupFinderCache ref key = do
c <- readIORef ref
return $! lookupUFM c key
lookupModLocationCache :: IORef ModLocationCache -> Module
-> IO (Maybe ModLocation)
lookupModLocationCache ref key = do
c <- readIORef ref
return $! lookupModuleEnv c key
-- -----------------------------------------------------------------------------
-- The two external entry points
-- | Locate a module that was imported by the user. We have the
-- module's name, and possibly a package name. Without a package
-- name, this function will use the search path and the known exposed
-- packages to find the module, if a package is specified then only
-- that package is searched for the module.
findImportedModule :: HscEnv -> ModuleName -> Maybe FastString -> IO FindResult
findImportedModule hsc_env mod_name mb_pkg =
case mb_pkg of
Nothing -> unqual_import
Just pkg | pkg == fsLit "this" -> home_import -- "this" is special
| otherwise -> pkg_import
where
home_import = findHomeModule hsc_env mod_name
pkg_import = findExposedPackageModule hsc_env mod_name mb_pkg
unqual_import = home_import
`orIfNotFound`
findExposedPackageModule hsc_env mod_name Nothing
-- | Locate a specific 'Module'. The purpose of this function is to
-- create a 'ModLocation' for a given 'Module', that is to find out
-- where the files associated with this module live. It is used when
-- reading the interface for a module mentioned by another interface,
-- for example (a "system import").
findExactModule :: HscEnv -> Module -> IO FindResult
findExactModule hsc_env mod =
let dflags = hsc_dflags hsc_env
in if moduleUnitId mod == thisPackage dflags
then findHomeModule hsc_env (moduleName mod)
else findPackageModule hsc_env mod
-- -----------------------------------------------------------------------------
-- Helpers
orIfNotFound :: IO FindResult -> IO FindResult -> IO FindResult
orIfNotFound this or_this = do
res <- this
case res of
NotFound { fr_paths = paths1, fr_mods_hidden = mh1
, fr_pkgs_hidden = ph1, fr_suggestions = s1 }
-> do res2 <- or_this
case res2 of
NotFound { fr_paths = paths2, fr_pkg = mb_pkg2, fr_mods_hidden = mh2
, fr_pkgs_hidden = ph2, fr_suggestions = s2 }
-> return (NotFound { fr_paths = paths1 ++ paths2
, fr_pkg = mb_pkg2 -- snd arg is the package search
, fr_mods_hidden = mh1 ++ mh2
, fr_pkgs_hidden = ph1 ++ ph2
, fr_suggestions = s1 ++ s2 })
_other -> return res2
_other -> return res
-- | Helper function for 'findHomeModule': this function wraps an IO action
-- which would look up @mod_name@ in the file system (the home package),
-- and first consults the 'hsc_FC' cache to see if the lookup has already
-- been done. Otherwise, do the lookup (with the IO action) and save
-- the result in the finder cache and the module location cache (if it
-- was successful.)
homeSearchCache :: HscEnv -> ModuleName -> IO FindResult -> IO FindResult
homeSearchCache hsc_env mod_name do_this = do
m <- lookupFinderCache (hsc_FC hsc_env) mod_name
case m of
Just result -> return result
Nothing -> do
result <- do_this
addToFinderCache (hsc_FC hsc_env) mod_name result
case result of
Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
_other -> return ()
return result
findExposedPackageModule :: HscEnv -> ModuleName -> Maybe FastString
-> IO FindResult
findExposedPackageModule hsc_env mod_name mb_pkg
= case lookupModuleWithSuggestions (hsc_dflags hsc_env) mod_name mb_pkg of
LookupFound m pkg_conf ->
findPackageModule_ hsc_env m pkg_conf
LookupMultiple rs ->
return (FoundMultiple rs)
LookupHidden pkg_hiddens mod_hiddens ->
return (NotFound{ fr_paths = [], fr_pkg = Nothing
, fr_pkgs_hidden = map (moduleUnitId.fst) pkg_hiddens
, fr_mods_hidden = map (moduleUnitId.fst) mod_hiddens
, fr_suggestions = [] })
LookupNotFound suggest ->
return (NotFound{ fr_paths = [], fr_pkg = Nothing
, fr_pkgs_hidden = []
, fr_mods_hidden = []
, fr_suggestions = suggest })
modLocationCache :: HscEnv -> Module -> IO FindResult -> IO FindResult
modLocationCache hsc_env mod do_this = do
mb_loc <- lookupModLocationCache mlc mod
case mb_loc of
Just loc -> return (Found loc mod)
Nothing -> do
result <- do_this
case result of
Found loc mod -> addToModLocationCache (hsc_MLC hsc_env) mod loc
_other -> return ()
return result
where
mlc = hsc_MLC hsc_env
addHomeModuleToFinder :: HscEnv -> ModuleName -> ModLocation -> IO Module
addHomeModuleToFinder hsc_env mod_name loc = do
let mod = mkModule (thisPackage (hsc_dflags hsc_env)) mod_name
addToFinderCache (hsc_FC hsc_env) mod_name (Found loc mod)
addToModLocationCache (hsc_MLC hsc_env) mod loc
return mod
uncacheModule :: HscEnv -> ModuleName -> IO ()
uncacheModule hsc_env mod = do
let this_pkg = thisPackage (hsc_dflags hsc_env)
removeFromFinderCache (hsc_FC hsc_env) mod
removeFromModLocationCache (hsc_MLC hsc_env) (mkModule this_pkg mod)
-- -----------------------------------------------------------------------------
-- The internal workers
-- | Implements the search for a module name in the home package only. Calling
-- this function directly is usually *not* what you want; currently, it's used
-- as a building block for the following operations:
--
-- 1. When you do a normal package lookup, we first check if the module
-- is available in the home module, before looking it up in the package
-- database.
--
-- 2. When you have a package qualified import with package name "this",
-- we shortcut to the home module.
--
-- 3. When we look up an exact 'Module', if the package key associated with
-- the module is the current home module do a look up in the home module.
--
-- 4. Some special-case code in GHCi (ToDo: Figure out why that needs to
-- call this.)
findHomeModule :: HscEnv -> ModuleName -> IO FindResult
findHomeModule hsc_env mod_name =
homeSearchCache hsc_env mod_name $
let
dflags = hsc_dflags hsc_env
home_path = importPaths dflags
hisuf = hiSuf dflags
mod = mkModule (thisPackage dflags) mod_name
source_exts =
[ ("hs", mkHomeModLocationSearched dflags mod_name "hs")
, ("lhs", mkHomeModLocationSearched dflags mod_name "lhs")
, ("hsig", mkHomeModLocationSearched dflags mod_name "hsig")
, ("lhsig", mkHomeModLocationSearched dflags mod_name "lhsig")
]
hi_exts = [ (hisuf, mkHiOnlyModLocation dflags hisuf)
, (addBootSuffix hisuf, mkHiOnlyModLocation dflags hisuf)
]
-- In compilation manager modes, we look for source files in the home
-- package because we can compile these automatically. In one-shot
-- compilation mode we look for .hi and .hi-boot files only.
exts | isOneShot (ghcMode dflags) = hi_exts
| otherwise = source_exts
in
-- special case for GHC.Prim; we won't find it in the filesystem.
-- This is important only when compiling the base package (where GHC.Prim
-- is a home module).
if mod == gHC_PRIM
then return (Found (error "GHC.Prim ModLocation") mod)
else searchPathExts home_path mod exts
-- | Search for a module in external packages only.
findPackageModule :: HscEnv -> Module -> IO FindResult
findPackageModule hsc_env mod = do
let
dflags = hsc_dflags hsc_env
pkg_id = moduleUnitId mod
--
case lookupPackage dflags pkg_id of
Nothing -> return (NoPackage pkg_id)
Just pkg_conf -> findPackageModule_ hsc_env mod pkg_conf
-- | Look up the interface file associated with module @mod@. This function
-- requires a few invariants to be upheld: (1) the 'Module' in question must
-- be the module identifier of the *original* implementation of a module,
-- not a reexport (this invariant is upheld by @Packages.lhs@) and (2)
-- the 'PackageConfig' must be consistent with the package key in the 'Module'.
-- The redundancy is to avoid an extra lookup in the package state
-- for the appropriate config.
findPackageModule_ :: HscEnv -> Module -> PackageConfig -> IO FindResult
findPackageModule_ hsc_env mod pkg_conf =
ASSERT( moduleUnitId mod == packageConfigId pkg_conf )
modLocationCache hsc_env mod $
-- special case for GHC.Prim; we won't find it in the filesystem.
if mod == gHC_PRIM
then return (Found (error "GHC.Prim ModLocation") mod)
else
let
dflags = hsc_dflags hsc_env
tag = buildTag dflags
-- hi-suffix for packages depends on the build tag.
package_hisuf | null tag = "hi"
| otherwise = tag ++ "_hi"
mk_hi_loc = mkHiOnlyModLocation dflags package_hisuf
import_dirs = importDirs pkg_conf
-- we never look for a .hi-boot file in an external package;
-- .hi-boot files only make sense for the home package.
in
case import_dirs of
[one] | MkDepend <- ghcMode dflags -> do
-- there's only one place that this .hi file can be, so
-- don't bother looking for it.
let basename = moduleNameSlashes (moduleName mod)
loc <- mk_hi_loc one basename
return (Found loc mod)
_otherwise ->
searchPathExts import_dirs mod [(package_hisuf, mk_hi_loc)]
-- -----------------------------------------------------------------------------
-- General path searching
searchPathExts
:: [FilePath] -- paths to search
-> Module -- module name
-> [ (
FileExt, -- suffix
FilePath -> BaseName -> IO ModLocation -- action
)
]
-> IO FindResult
searchPathExts paths mod exts
= do result <- search to_search
{-
hPutStrLn stderr (showSDoc $
vcat [text "Search" <+> ppr mod <+> sep (map (text. fst) exts)
, nest 2 (vcat (map text paths))
, case result of
Succeeded (loc, p) -> text "Found" <+> ppr loc
Failed fs -> text "not found"])
-}
return result
where
basename = moduleNameSlashes (moduleName mod)
to_search :: [(FilePath, IO ModLocation)]
to_search = [ (file, fn path basename)
| path <- paths,
(ext,fn) <- exts,
let base | path == "." = basename
| otherwise = path </> basename
file = base <.> ext
]
search [] = return (NotFound { fr_paths = map fst to_search
, fr_pkg = Just (moduleUnitId mod)
, fr_mods_hidden = [], fr_pkgs_hidden = []
, fr_suggestions = [] })
search ((file, mk_result) : rest) = do
b <- doesFileExist file
if b
then do { loc <- mk_result; return (Found loc mod) }
else search rest
mkHomeModLocationSearched :: DynFlags -> ModuleName -> FileExt
-> FilePath -> BaseName -> IO ModLocation
mkHomeModLocationSearched dflags mod suff path basename = do
mkHomeModLocation2 dflags mod (path </> basename) suff
-- -----------------------------------------------------------------------------
-- Constructing a home module location
-- This is where we construct the ModLocation for a module in the home
-- package, for which we have a source file. It is called from three
-- places:
--
-- (a) Here in the finder, when we are searching for a module to import,
-- using the search path (-i option).
--
-- (b) The compilation manager, when constructing the ModLocation for
-- a "root" module (a source file named explicitly on the command line
-- or in a :load command in GHCi).
--
-- (c) The driver in one-shot mode, when we need to construct a
-- ModLocation for a source file named on the command-line.
--
-- Parameters are:
--
-- mod
-- The name of the module
--
-- path
-- (a): The search path component where the source file was found.
-- (b) and (c): "."
--
-- src_basename
-- (a): (moduleNameSlashes mod)
-- (b) and (c): The filename of the source file, minus its extension
--
-- ext
-- The filename extension of the source file (usually "hs" or "lhs").
mkHomeModLocation :: DynFlags -> ModuleName -> FilePath -> IO ModLocation
mkHomeModLocation dflags mod src_filename = do
let (basename,extension) = splitExtension src_filename
mkHomeModLocation2 dflags mod basename extension
mkHomeModLocation2 :: DynFlags
-> ModuleName
-> FilePath -- Of source module, without suffix
-> String -- Suffix
-> IO ModLocation
mkHomeModLocation2 dflags mod src_basename ext = do
let mod_basename = moduleNameSlashes mod
obj_fn = mkObjPath dflags src_basename mod_basename
hi_fn = mkHiPath dflags src_basename mod_basename
return (ModLocation{ ml_hs_file = Just (src_basename <.> ext),
ml_hi_file = hi_fn,
ml_obj_file = obj_fn })
mkHiOnlyModLocation :: DynFlags -> Suffix -> FilePath -> String
-> IO ModLocation
mkHiOnlyModLocation dflags hisuf path basename
= do let full_basename = path </> basename
obj_fn = mkObjPath dflags full_basename basename
return ModLocation{ ml_hs_file = Nothing,
ml_hi_file = full_basename <.> hisuf,
-- Remove the .hi-boot suffix from
-- hi_file, if it had one. We always
-- want the name of the real .hi file
-- in the ml_hi_file field.
ml_obj_file = obj_fn
}
-- | Constructs the filename of a .o file for a given source file.
-- Does /not/ check whether the .o file exists
mkObjPath
:: DynFlags
-> FilePath -- the filename of the source file, minus the extension
-> String -- the module name with dots replaced by slashes
-> FilePath
mkObjPath dflags basename mod_basename = obj_basename <.> osuf
where
odir = objectDir dflags
osuf = objectSuf dflags
obj_basename | Just dir <- odir = dir </> mod_basename
| otherwise = basename
-- | Constructs the filename of a .hi file for a given source file.
-- Does /not/ check whether the .hi file exists
mkHiPath
:: DynFlags
-> FilePath -- the filename of the source file, minus the extension
-> String -- the module name with dots replaced by slashes
-> FilePath
mkHiPath dflags basename mod_basename = hi_basename <.> hisuf
where
hidir = hiDir dflags
hisuf = hiSuf dflags
hi_basename | Just dir <- hidir = dir </> mod_basename
| otherwise = basename
-- -----------------------------------------------------------------------------
-- Filenames of the stub files
-- We don't have to store these in ModLocations, because they can be derived
-- from other available information, and they're only rarely needed.
mkStubPaths
:: DynFlags
-> ModuleName
-> ModLocation
-> FilePath
mkStubPaths dflags mod location
= let
stubdir = stubDir dflags
mod_basename = moduleNameSlashes mod
src_basename = dropExtension $ expectJust "mkStubPaths"
(ml_hs_file location)
stub_basename0
| Just dir <- stubdir = dir </> mod_basename
| otherwise = src_basename
stub_basename = stub_basename0 ++ "_stub"
in
stub_basename <.> "h"
-- -----------------------------------------------------------------------------
-- findLinkable isn't related to the other stuff in here,
-- but there's no other obvious place for it
findObjectLinkableMaybe :: Module -> ModLocation -> IO (Maybe Linkable)
findObjectLinkableMaybe mod locn
= do let obj_fn = ml_obj_file locn
maybe_obj_time <- modificationTimeIfExists obj_fn
case maybe_obj_time of
Nothing -> return Nothing
Just obj_time -> liftM Just (findObjectLinkable mod obj_fn obj_time)
-- Make an object linkable when we know the object file exists, and we know
-- its modification time.
findObjectLinkable :: Module -> FilePath -> UTCTime -> IO Linkable
findObjectLinkable mod obj_fn obj_time = return (LM obj_time mod [DotO obj_fn])
-- We used to look for _stub.o files here, but that was a bug (#706)
-- Now GHC merges the stub.o into the main .o (#3687)
-- -----------------------------------------------------------------------------
-- Error messages
cannotFindModule :: DynFlags -> ModuleName -> FindResult -> SDoc
cannotFindModule = cantFindErr (sLit "Could not find module")
(sLit "Ambiguous module name")
cannotFindInterface :: DynFlags -> ModuleName -> FindResult -> SDoc
cannotFindInterface = cantFindErr (sLit "Failed to load interface for")
(sLit "Ambiguous interface for")
cantFindErr :: LitString -> LitString -> DynFlags -> ModuleName -> FindResult
-> SDoc
cantFindErr _ multiple_found _ mod_name (FoundMultiple mods)
| Just pkgs <- unambiguousPackages
= hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 (
sep [ptext (sLit "it was found in multiple packages:"),
hsep (map ppr pkgs) ]
)
| otherwise
= hang (ptext multiple_found <+> quotes (ppr mod_name) <> colon) 2 (
vcat (map pprMod mods)
)
where
unambiguousPackages = foldl' unambiguousPackage (Just []) mods
unambiguousPackage (Just xs) (m, ModOrigin (Just _) _ _ _)
= Just (moduleUnitId m : xs)
unambiguousPackage _ _ = Nothing
pprMod (m, o) = ptext (sLit "it is bound as") <+> ppr m <+>
ptext (sLit "by") <+> pprOrigin m o
pprOrigin _ ModHidden = panic "cantFindErr: bound by mod hidden"
pprOrigin m (ModOrigin e res _ f) = sep $ punctuate comma (
if e == Just True
then [ptext (sLit "package") <+> ppr (moduleUnitId m)]
else [] ++
map ((ptext (sLit "a reexport in package") <+>)
.ppr.packageConfigId) res ++
if f then [ptext (sLit "a package flag")] else []
)
cantFindErr cannot_find _ dflags mod_name find_result
= ptext cannot_find <+> quotes (ppr mod_name)
$$ more_info
where
more_info
= case find_result of
NoPackage pkg
-> ptext (sLit "no package key matching") <+> quotes (ppr pkg) <+>
ptext (sLit "was found") $$ looks_like_srcpkgid pkg
NotFound { fr_paths = files, fr_pkg = mb_pkg
, fr_mods_hidden = mod_hiddens, fr_pkgs_hidden = pkg_hiddens
, fr_suggestions = suggest }
| Just pkg <- mb_pkg, pkg /= thisPackage dflags
-> not_found_in_package pkg files
| not (null suggest)
-> pp_suggestions suggest $$ tried_these files
| null files && null mod_hiddens && null pkg_hiddens
-> ptext (sLit "It is not a module in the current program, or in any known package.")
| otherwise
-> vcat (map pkg_hidden pkg_hiddens) $$
vcat (map mod_hidden mod_hiddens) $$
tried_these files
_ -> panic "cantFindErr"
build_tag = buildTag dflags
not_found_in_package pkg files
| build_tag /= ""
= let
build = if build_tag == "p" then "profiling"
else "\"" ++ build_tag ++ "\""
in
ptext (sLit "Perhaps you haven't installed the ") <> text build <>
ptext (sLit " libraries for package ") <> quotes (ppr pkg) <> char '?' $$
tried_these files
| otherwise
= ptext (sLit "There are files missing in the ") <> quotes (ppr pkg) <>
ptext (sLit " package,") $$
ptext (sLit "try running 'eta-pkg check'.") $$
tried_these files
tried_these files
| null files = Outputable.empty
| verbosity dflags < 3 =
ptext (sLit "Use -v to see a list of the files searched for.")
| otherwise =
hang (ptext (sLit "Locations searched:")) 2 $ vcat (map text files)
pkg_hidden :: UnitId -> SDoc
pkg_hidden pkgid =
ptext (sLit "It is a member of the hidden package")
<+> quotes (ppr pkgid)
--FIXME: we don't really want to show the package key here we should
-- show the source package id or installed package id if it's ambiguous
<> dot $$ cabal_pkg_hidden_hint pkgid
cabal_pkg_hidden_hint pkgid
| gopt Opt_BuildingCabalPackage dflags
= let pkg = expectJust "pkg_hidden" (lookupPackage dflags pkgid)
in ptext (sLit "Perhaps you need to add") <+>
quotes (ppr (packageName pkg)) <+>
ptext (sLit "to the build-depends in your .cabal file.")
| otherwise = Outputable.empty
looks_like_srcpkgid :: UnitId -> SDoc
looks_like_srcpkgid pk
-- Unsafely coerce a package key FastString into a source package ID
-- FastString and see if it means anything.
| (pkg:pkgs) <- searchPackageId dflags (SourcePackageId (unitIdFS pk))
= parens (text "This package key looks like the source package ID;" $$
text "the real package key is" <+> quotes (ftext (installedUnitIdFS (unitId pkg))) $$
(if null pkgs then Outputable.empty
else text "and" <+> int (length pkgs) <+> text "other candidates"))
-- Todo: also check if it looks like a package name!
| otherwise = Outputable.empty
mod_hidden pkg =
ptext (sLit "it is a hidden module in the package") <+> quotes (ppr pkg)
pp_suggestions :: [ModuleSuggestion] -> SDoc
pp_suggestions sugs
| null sugs = Outputable.empty
| otherwise = hang (ptext (sLit "Perhaps you meant"))
2 (vcat (map pp_sugg sugs))
-- NB: Prefer the *original* location, and then reexports, and then
-- package flags when making suggestions. ToDo: if the original package
-- also has a reexport, prefer that one
pp_sugg (SuggestVisible m mod o) = ppr m <+> provenance o
where provenance ModHidden = Outputable.empty
provenance (ModOrigin{ fromOrigPackage = e,
fromExposedReexport = res,
fromPackageFlag = f })
| Just True <- e
= parens (ptext (sLit "from") <+> ppr (moduleUnitId mod))
| f && moduleName mod == m
= parens (ptext (sLit "from") <+> ppr (moduleUnitId mod))
| (pkg:_) <- res
= parens (ptext (sLit "from") <+> ppr (packageConfigId pkg)
<> comma <+> ptext (sLit "reexporting") <+> ppr mod)
| f
= parens (ptext (sLit "defined via package flags to be")
<+> ppr mod)
| otherwise = Outputable.empty
pp_sugg (SuggestHidden m mod o) = ppr m <+> provenance o
where provenance ModHidden = Outputable.empty
provenance (ModOrigin{ fromOrigPackage = e,
fromHiddenReexport = rhs })
| Just False <- e
= parens (ptext (sLit "needs flag -package-key")
<+> ppr (moduleUnitId mod))
| (pkg:_) <- rhs
= parens (ptext (sLit "needs flag -package-key")
<+> ppr (packageConfigId pkg))
| otherwise = Outputable.empty
| pparkkin/eta | compiler/ETA/Main/Finder.hs | bsd-3-clause | 27,697 | 1 | 20 | 7,899 | 5,572 | 2,825 | 2,747 | 434 | 12 |
{-# LANGUAGE CPP, GADTs #-}
-- |
-- Module : Data.Array.Accelerate.CUDA
-- Copyright : [2008..2011] Manuel M T Chakravarty, Gabriele Keller, Sean Lee, Trevor L. McDonell
-- License : BSD3
--
-- Maintainer : Manuel M T Chakravarty <[email protected]>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- This module implements the CUDA backend for the embedded array language.
--
module Data.Array.Accelerate.CUDA (
-- * Generate and execute CUDA code for an array expression
Arrays, run, stream
) where
-- standard library
import Prelude hiding (catch)
import Data.Record.Label
import Control.Exception
import Control.Applicative
import System.IO.Unsafe
import qualified Data.HashTable as Hash
-- CUDA binding
import Foreign.CUDA.Driver.Error
import qualified Foreign.CUDA.Driver as CUDA
-- friends
import Data.Array.Accelerate.AST (Arrays(..), ArraysR(..))
import Data.Array.Accelerate.Smart (Acc, convertAcc, convertAccFun1)
import Data.Array.Accelerate.Array.Representation (size)
import Data.Array.Accelerate.Array.Sugar (Array(..))
import Data.Array.Accelerate.CUDA.Array.Data
import Data.Array.Accelerate.CUDA.State
import Data.Array.Accelerate.CUDA.Compile
import Data.Array.Accelerate.CUDA.Execute
#include "accelerate.h"
-- Accelerate: CUDA
-- ----------------
-- | Compile and run a complete embedded array program using the CUDA backend
--
run :: Arrays a => Acc a -> a
{-# NOINLINE run #-}
run a = unsafePerformIO execute
where
acc = convertAcc a
execute = evalCUDA (compileAcc acc >>= executeAcc >>= collect)
`catch`
\e -> INTERNAL_ERROR(error) "unhandled" (show (e :: CUDAException))
-- | Stream a lazily read list of input arrays through the given program,
-- collecting results as we go
--
stream :: (Arrays a, Arrays b) => (Acc a -> Acc b) -> [a] -> [b]
{-# NOINLINE stream #-}
stream f arrs = unsafePerformIO $ uncurry (execute arrs) =<< runCUDA (compileAfun1 acc)
where
acc = convertAccFun1 f
execute [] _ state = finalise state >> return [] -- release all constant arrays
execute (a:as) afun state = do
(b,s) <- runCUDAWith state (executeAfun1 afun a >>= collect)
`catch`
\e -> INTERNAL_ERROR(error) "unhandled" (show (e :: CUDAException))
bs <- unsafeInterleaveIO (execute as afun s)
return (b:bs)
--
finalise state = do
mem <- Hash.toList (getL memoryTable state)
mapM_ (\(_,MemoryEntry _ p) -> CUDA.free (CUDA.castDevPtr p)) mem
-- Copy from device to host, and decrement the usage counter. This last step
-- should result in all transient arrays having been removed from the device.
--
collect :: Arrays arrs => arrs -> CIO arrs
collect arrs = collectR arrays arrs
where
collectR :: ArraysR arrs -> arrs -> CIO arrs
collectR ArraysRunit () = return ()
collectR ArraysRarray arr@(Array sh ad) = peekArray ad (size sh) >> freeArray ad >> return arr
collectR (ArraysRpair r1 r2) (arrs1, arrs2) = (,) <$> collectR r1 arrs1 <*> collectR r2 arrs2
| wilbowma/accelerate | Data/Array/Accelerate/CUDA.hs | bsd-3-clause | 3,221 | 0 | 15 | 743 | 767 | 434 | 333 | 46 | 3 |
-- | Contains version information for Haste.
module Haste.Version (
BootVer (..),
hasteVersion, intVersion, ghcVersion, bootVersion,
showBootVersion, parseBootVersion,
showVersion
) where
import Data.Version
import Config (cProjectVersion)
import Text.ParserCombinators.ReadP
import Data.Maybe (listToMaybe)
-- | Current Haste version.
hasteVersion :: Version
hasteVersion = Version [0,5,4] []
-- | Current Haste version as an Int. The format of this version number is
-- MAJOR*10 000 + MINOR*100 + MICRO.
-- Version 1.2.3 would thus be represented as 10203.
intVersion :: Int
intVersion = foldl (\a x -> a*100+x) 0 $ take 3 ver
where Version ver _ = hasteVersion
-- | The version of GHC used to build this binary.
ghcVersion :: Version
ghcVersion =
fst $ head $ filter (\(_,s) -> null s) parses
where
parses = readP_to_S parseVersion cProjectVersion
-- | Haste + GHC version combo.
bootVersion :: BootVer
bootVersion = BootVer hasteVersion ghcVersion
data BootVer = BootVer {
bootHasteVersion :: !Version,
bootGhcVersion :: !Version
} deriving (Show, Read)
showBootVersion :: BootVer -> String
showBootVersion (BootVer ver ghcver) =
"haste-" ++ showVersion ver ++ "-ghc-" ++ showVersion ghcver
parseBootVersion :: String -> Maybe BootVer
parseBootVersion =
fmap fst . listToMaybe . filter (\(_,s) -> null s) . parse
where
parse = readP_to_S $ do
_ <- string "haste-"
hastever <- parseVersion
_ <- string "-ghc-"
ghcver <- parseVersion
return $ BootVer hastever ghcver
| nyson/haste-compiler | src/Haste/Version.hs | bsd-3-clause | 1,564 | 0 | 11 | 317 | 406 | 220 | 186 | 40 | 1 |
-- | Build instance tycons for the PData and PDatas type families.
--
-- TODO: the PData and PDatas cases are very similar.
-- We should be able to factor out the common parts.
module Vectorise.Generic.PData
( buildPDataTyCon
, buildPDatasTyCon )
where
import Vectorise.Monad
import Vectorise.Builtins
import Vectorise.Generic.Description
import Vectorise.Utils
import Vectorise.Env( GlobalEnv( global_fam_inst_env ) )
import BasicTypes
import BuildTyCl
import DataCon
import TyCon
import Type
import FamInst
import FamInstEnv
import TcMType
import Name
import Util
import MonadUtils
import Control.Monad
-- buildPDataTyCon ------------------------------------------------------------
-- | Build the PData instance tycon for a given type constructor.
buildPDataTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDataTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDataTyConOcc orig_name
rhs <- buildPDataTyConRhs orig_name vect_tc repr_tc repr
pdata <- builtin pdataTyCon
buildDataFamInst name' pdata vect_tc rhs
where
orig_name = tyConName orig_tc
buildDataFamInst :: Name -> TyCon -> TyCon -> AlgTyConRhs -> VM FamInst
buildDataFamInst name' fam_tc vect_tc rhs
= do { axiom_name <- mkDerivedName mkInstTyCoOcc name'
; (_, tyvars') <- liftDs $ tcInstSigTyVarsLoc (getSrcSpan name') tyvars
; let ax = mkSingleCoAxiom Representational axiom_name tyvars' fam_tc pat_tys rep_ty
tys' = mkTyVarTys tyvars'
rep_ty = mkTyConApp rep_tc tys'
pat_tys = [mkTyConApp vect_tc tys']
rep_tc = buildAlgTyCon name'
tyvars'
(map (const Nominal) tyvars')
Nothing
[] -- no stupid theta
rhs
rec_flag -- FIXME: is this ok?
False -- Not promotable
False -- not GADT syntax
(FamInstTyCon ax fam_tc pat_tys)
; liftDs $ newFamInst (DataFamilyInst rep_tc) ax }
where
tyvars = tyConTyVars vect_tc
rec_flag = boolToRecFlag (isRecursiveTyCon vect_tc)
buildPDataTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDataTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDataDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDataDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDataDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDataDataConOcc orig_name
comp_tys <- mkSumTys repr_sel_ty mkPDataType repr
fam_envs <- readGEnv global_fam_inst_env
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
where
no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict
-- buildPDatasTyCon -----------------------------------------------------------
-- | Build the PDatas instance tycon for a given type constructor.
buildPDatasTyCon :: TyCon -> TyCon -> SumRepr -> VM FamInst
buildPDatasTyCon orig_tc vect_tc repr
= fixV $ \fam_inst ->
do let repr_tc = dataFamInstRepTyCon fam_inst
name' <- mkLocalisedName mkPDatasTyConOcc orig_name
rhs <- buildPDatasTyConRhs orig_name vect_tc repr_tc repr
pdatas <- builtin pdatasTyCon
buildDataFamInst name' pdatas vect_tc rhs
where
orig_name = tyConName orig_tc
buildPDatasTyConRhs :: Name -> TyCon -> TyCon -> SumRepr -> VM AlgTyConRhs
buildPDatasTyConRhs orig_name vect_tc repr_tc repr
= do data_con <- buildPDatasDataCon orig_name vect_tc repr_tc repr
return $ DataTyCon { data_cons = [data_con], is_enum = False }
buildPDatasDataCon :: Name -> TyCon -> TyCon -> SumRepr -> VM DataCon
buildPDatasDataCon orig_name vect_tc repr_tc repr
= do let tvs = tyConTyVars vect_tc
dc_name <- mkLocalisedName mkPDatasDataConOcc orig_name
comp_tys <- mkSumTys repr_sels_ty mkPDatasType repr
fam_envs <- readGEnv global_fam_inst_env
liftDs $ buildDataCon fam_envs dc_name
False -- not infix
(map (const no_bang) comp_tys)
(Just $ map (const HsLazy) comp_tys)
[] -- no field labels
tvs
[] -- no existentials
[] -- no eq spec
[] -- no context
comp_tys
(mkFamilyTyConApp repr_tc (mkTyVarTys tvs))
repr_tc
where
no_bang = HsSrcBang Nothing NoSrcUnpack NoSrcStrict
-- Utils ----------------------------------------------------------------------
-- | Flatten a SumRepr into a list of data constructor types.
mkSumTys
:: (SumRepr -> Type)
-> (Type -> VM Type)
-> SumRepr
-> VM [Type]
mkSumTys repr_selX_ty mkTc repr
= sum_tys repr
where
sum_tys EmptySum = return []
sum_tys (UnarySum r) = con_tys r
sum_tys d@(Sum { repr_cons = cons })
= liftM (repr_selX_ty d :) (concatMapM con_tys cons)
con_tys (ConRepr _ r) = prod_tys r
prod_tys EmptyProd = return []
prod_tys (UnaryProd r) = liftM singleton (comp_ty r)
prod_tys (Prod { repr_comps = comps }) = mapM comp_ty comps
comp_ty r = mkTc (compOrigType r)
{-
mk_fam_inst :: TyCon -> TyCon -> (TyCon, [Type])
mk_fam_inst fam_tc arg_tc
= (fam_tc, [mkTyConApp arg_tc . mkTyVarTys $ tyConTyVars arg_tc])
-}
| acowley/ghc | compiler/vectorise/Vectorise/Generic/PData.hs | bsd-3-clause | 6,448 | 0 | 14 | 2,170 | 1,330 | 673 | 657 | 121 | 5 |
module Goober () where
import Language.Haskell.Liquid.Prelude (isEven)
{-@ takeEvens :: [Int] -> [{v: Int | v mod 2 = 0}] @-}
takeEvens :: [Int] -> [Int]
takeEvens [] = []
takeEvens (x:xs) = if isEven x
then x : takeEvens xs
else takeEvens xs
| mightymoose/liquidhaskell | tests/pos/modTest.hs | bsd-3-clause | 293 | 0 | 7 | 94 | 83 | 47 | 36 | 7 | 2 |
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Compat.SnocList
-- License : BSD3
--
-- Maintainer : [email protected]
-- Stability : experimental
-- Portability : portable
--
-- A very reversed list. Has efficient `snoc`
module Distribution.Compat.SnocList (
SnocList,
runSnocList,
snoc,
) where
import Prelude ()
import Distribution.Compat.Prelude
newtype SnocList a = SnocList [a]
snoc :: SnocList a -> a -> SnocList a
snoc (SnocList xs) x = SnocList (x : xs)
runSnocList :: SnocList a -> [a]
runSnocList (SnocList xs) = reverse xs
instance Semigroup (SnocList a) where
SnocList xs <> SnocList ys = SnocList (ys <> xs)
instance Monoid (SnocList a) where
mempty = SnocList []
mappend = (<>)
| themoritz/cabal | Cabal/Distribution/Compat/SnocList.hs | bsd-3-clause | 804 | 0 | 8 | 156 | 202 | 113 | 89 | 16 | 1 |
module T10083 where
import T10083a
data RSR = MkRSR SR
eqRSR (MkRSR s1) (MkRSR s2) = (eqSR s1 s2)
foo x y = not (eqRSR x y)
| ezyang/ghc | testsuite/tests/simplCore/should_compile/T10083.hs | bsd-3-clause | 132 | 0 | 7 | 35 | 67 | 35 | 32 | 5 | 1 |
-- !!! ds001 -- simple function and pattern bindings
--
-- this tests ultra-simple function and pattern bindings (no patterns)
module ShouldCompile where
-- simple function bindings
f x = x
g x y z = f z
j w x y z = g w x z
h x y = f y
where
f a b = a
-- simple pattern bindings
a = b
b = f
c = c
| wxwxwwxxx/ghc | testsuite/tests/deSugar/should_compile/ds001.hs | bsd-3-clause | 313 | 0 | 7 | 89 | 93 | 50 | 43 | 9 | 1 |
{-# LANGUAGE GADTs #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE NoMonomorphismRestriction #-}
module Ref ( Col(..), Row(..), Ref(..), toCoords, fromCoords, refAdd, rLeft, rRight, rUp, rDown, rZero, readRef ) where
import Text.PrettyPrint hiding ((<>))
import Data.Map as M hiding (map, foldl, (!))
import Data.Maybe
import Data.List hiding (and)
import Data.Monoid
import Data.Function
import Data.Array
import Data.String
import Data.Char
import Cat
-- This file has all the stuff to do with references/addresses in spreadsheets
-- Absolute, relative, adding them, using them as indices etc.
-- This is for array types
data Col = CRel {x::Int} | CAbs {x::Int} deriving (Eq)
data Row = RRel {y::Int} | RAbs {y::Int} deriving (Eq)
data Ref = Ref {cRef::Col, rRef::Row} deriving (Eq)
-- Col 'A' is 1, so show adds 64 to get 'A'
instance Show Col where
show (CRel x) = [chr (64+x)]
show (CAbs x) = [chr (64+x)]
instance Show Row where
show (RRel x) = show x
show (RAbs x) = show x
-- Assumes counting starts at 1, so the 'A' column is 1
cMod :: Col -> Col -> Col
cMod (CAbs n) (CRel x) = CRel $ 1 + ((x-1) `mod` n)
cMod (CAbs n) (CAbs x) = CAbs $ 1 + ((x-1) `mod` n)
cMod (CRel n) (CRel x) = CRel $ 1 + ((x-1) `mod` n)
cMod (CRel n) (CAbs x) = CAbs $ 1 + ((x-1) `mod` n)
rMod :: Row -> Row -> Row
rMod (RAbs n) (RRel x) = RRel $ 1 + ((x-1) `mod` n)
rMod (RAbs n) (RAbs x) = RAbs $ 1 + ((x-1) `mod` n)
rMod (RRel n) (RRel x) = RRel $ 1 + ((x-1) `mod` n)
rMod (RRel n) (RAbs x) = RAbs $ 1 + ((x-1) `mod` n)
refMod :: Ref -> Ref -> Ref
refMod (Ref cmax rmax) (Ref c r) = Ref (cMod cmax c) (rMod rmax r)
instance Show Ref where
show (Ref c r) = show c ++ show r
instance Monoid Ref where
mempty = rZero
mappend = refAdd (Ref (CAbs 10) (RAbs 10))
rLeft :: Ref
rLeft = Ref (CRel $ -1) (RRel 0)
rRight :: Ref
rRight = Ref (CRel 1) (RRel 0)
rUp :: Ref
rUp = Ref (CRel 0) (RRel $ -1)
rDown :: Ref
rDown = Ref (CRel 0) (RRel 1)
rZero :: Ref
rZero = Ref (CRel 0) (RRel 0)
toCoords :: Ref -> (Int, Int)
toCoords ref = (x $ cRef ref, y $ rRef ref)
fromCoords :: (Int, Int) -> Ref
fromCoords (x,y) = Ref (CRel $ x) (RRel $ y)
-- toCoords . fromCoords = id
data Arr e = Arr { arrFrom ::Ref, arrTo::Ref}
-- | Addition of references
-- If either of the y corrds are Abs then it's just them
-- The final Ref uses the types of the y
-- This will be used for copying cells and things like that.
cadd:: Col -> Col -> Col -> Col
cadd cmax c1 c2@(CAbs c) = cMod cmax c2
cadd cmax c1@(CRel c) c2 = cMod cmax $ CRel $ (x c1) + (x c2)
cadd cmax c1@(CAbs c) c2 = cMod cmax $ CAbs $ (x c1) + (x c2)
radd :: Row -> Row -> Row -> Row
radd rmax c1 c2@(RAbs _) = rMod rmax c2
radd rmax c1 c2 = rMod rmax $ RRel $ (y c1) + (y c2)
-- This is bad - we need to disallow adding to absolute references in the type system
refAdd :: Ref -> Ref -> Ref -> Ref
refAdd (Ref cmax rmax) r1 (r2@(Ref (CAbs _) (RAbs _))) = r2
refAdd (Ref cmax rmax) r1 (r2@(Ref (CAbs _) (RRel _))) = Ref (cRef r2) $ radd rmax (rRef r1) (rRef r2)
refAdd (Ref cmax rmax) r1 (r2@(Ref (CRel _) (RAbs _))) = Ref (cadd cmax (cRef r1) $ cRef r2) (rRef r2)
refAdd (Ref cmax rmax) r1 (r2@(Ref (CRel _) (RRel _))) = Ref (cadd cmax (cRef r1) $ cRef r2) (radd rmax (rRef r1) $ rRef r2)
-- toCoords/fromCoords defines the ordering
instance Ord Ref where
compare x y = compare (toCoords x) $ toCoords y
instance Ix Ref where
range (a, b) = fmap fromCoords $ range (toCoords a, toCoords b)
inRange (a, b) c = inRange (toCoords a, toCoords b) $ toCoords c
index (m,n) p = index (toCoords m, toCoords n) $ toCoords p
readRef :: String -> Ref
readRef ss = fromCoords (col, row)
where
col = (ord $ head ss) - 64
row = read $ tail ss
| b1g3ar5/Spreadsheet | Ref.hs | mit | 4,034 | 0 | 11 | 879 | 1,883 | 1,015 | 868 | 86 | 1 |
{-# LANGUAGE MultiParamTypeClasses #-}
module Utils.Tuplify
( Tuplify (..)
) where
class Tuplify a b where
toTuple :: a -> b
fromTuple :: b -> a
| AndrewRademacher/scotty-cass-test | src/Utils/Tuplify.hs | mit | 165 | 0 | 7 | 46 | 45 | 26 | 19 | 6 | 0 |
transpose [] = []
transpose (xs:xss) =
let h = head xs
tss = map (\x -> [x]) (tail xs)
yss = transpose xss
in
case yss of
[] -> [h]:tss
(zs:zss) -> (h:zs):map (\(ts, zs') -> (head ts):zs') (zip tss zss)
| harryxp/haskell-things | misc/transpose.hs | mit | 241 | 0 | 16 | 80 | 157 | 82 | 75 | 8 | 2 |
{-# OPTIONS_GHC -fno-warn-type-defaults #-}
module Main where
import Numeric.MCMC.Flat
import qualified Data.Vector.Unboxed as U (unsafeIndex)
bnn :: Particle -> Double
bnn xs = -0.5 * (x0 ^ 2 * x1 ^ 2 + x0 ^ 2 + x1 ^ 2 - 8 * x0 - 8 * x1) where
x0 = U.unsafeIndex xs 0
x1 = U.unsafeIndex xs 1
origin :: Ensemble
origin = ensemble [
particle [negate 1.0, negate 1.0]
, particle [negate 1.0, 1.0]
, particle [1.0, negate 1.0]
, particle [1.0, 1.0]
]
main :: IO ()
main = withSystemRandom . asGenIO $ mcmc 100 origin bnn
| jtobin/flat-mcmc | test/BNN.hs | mit | 540 | 0 | 17 | 122 | 224 | 121 | 103 | 16 | 1 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.MediaStreamAudioSourceNode
(js_getMediaStream, getMediaStream, MediaStreamAudioSourceNode,
castToMediaStreamAudioSourceNode, gTypeMediaStreamAudioSourceNode)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSVal(..), JSString)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSVal(..), FromJSVal(..))
import GHCJS.Marshal.Pure (PToJSVal(..), PFromJSVal(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.JSFFI.Generated.Enums
foreign import javascript unsafe "$1[\"mediaStream\"]"
js_getMediaStream ::
MediaStreamAudioSourceNode -> IO (Nullable MediaStream)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/MediaStreamAudioSourceNode.mediaStream Mozilla MediaStreamAudioSourceNode.mediaStream documentation>
getMediaStream ::
(MonadIO m) => MediaStreamAudioSourceNode -> m (Maybe MediaStream)
getMediaStream self
= liftIO (nullableToMaybe <$> (js_getMediaStream (self))) | manyoo/ghcjs-dom | ghcjs-dom-jsffi/src/GHCJS/DOM/JSFFI/Generated/MediaStreamAudioSourceNode.hs | mit | 1,528 | 6 | 10 | 176 | 371 | 236 | 135 | 25 | 1 |
{-# LANGUAGE FlexibleContexts #-}
{-# OPTIONS_GHC -freduction-depth=50 #-}
module CoqLNOutputThmSubst where
import Data.Maybe ( catMaybes )
import Text.Printf ( printf )
import AST
import ASTAnalysis
import ComputationMonad
import CoqLNOutputCommon
import CoqLNOutputCombinators
import MyLibrary ( sepStrings )
substThms :: ASTAnalysis -> [[NtRoot]] -> M String
substThms aa nts =
do { subst_close_recs <- mapM (local . subst_close_rec aa) nts
; subst_closes <- mapM (local . subst_close aa) nts
; subst_close_open_recs <- mapM (local . subst_close_open_rec aa) nts
; subst_close_opens <- mapM (local . subst_close_open aa) nts
; subst_constrs <- mapM (local . subst_constr aa) nts
; subst_degrees <- mapM (local . subst_degree aa) nts
; subst_fresh_eqs <- mapM (local . subst_fresh_eq aa) nts
; subst_fresh_sames <- mapM (local . subst_fresh_same aa) nts
; subst_freshs <- mapM (local . subst_fresh aa) nts
; subst_intro_recs <- mapM (local . subst_intro_rec aa) nts
; subst_intros <- mapM (local . subst_intro aa) nts
; subst_lcs <- mapM (local . subst_lc aa) nts
; subst_open_recs <- mapM (local . subst_open_rec aa) nts
; subst_opens <- mapM (local . subst_open aa) nts
; subst_open_vars <- mapM (local . subst_open_var aa) nts
; subst_spec_recs <- mapM (local . subst_spec_rec aa) nts
; subst_specs <- mapM (local . subst_spec aa) nts
; subst_substs <- mapM (local . subst_subst aa) nts
; return $ printf "Ltac %s ::= auto with %s %s; tauto.\n\
\Ltac %s ::= autorewrite with %s.\n\
\\n"
defaultAuto hintDb bruteDb
defaultAutoRewr hintDb++
concat subst_close_recs ++
concat subst_closes ++
concat subst_degrees ++
concat subst_fresh_eqs ++
concat subst_fresh_sames ++
concat subst_freshs ++
concat subst_lcs ++
concat subst_open_recs ++
concat subst_opens ++
concat subst_open_vars ++
concat subst_spec_recs ++
concat subst_specs ++
concat subst_substs ++
concat subst_close_open_recs ++
concat subst_close_opens ++
(concat $ concat subst_constrs) ++
concat subst_intro_recs ++
concat subst_intros ++ "\n"
}
{- | @subxt u x (close_rec k y e) = close_rec k y (subst u x e)@
when @x <> y@ and @y `notin` fv u@ and @degree k u@. -}
subst_close_rec :: ASTAnalysis -> [NtRoot] -> M String
subst_close_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2' aaa nt1s thm
; names <- processNt1Nt2Mv2' aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeRecName aa nt1 mv2'
; return $ subst_fn ++ "_" ++ close_fn
}
neq mv2 mv2' x y | mv2 == mv2' = printf " %s <> %s ->\n" x y
| otherwise = ""
fv nt2 nt2' y fv_fn u
| canBindIn aaa nt2' nt2 = printf " %s %s %s %s ->\n" y mvSetNotin fv_fn u
| otherwise = ""
deg nt2 nt2' d k u
| canBindIn aaa nt2' nt2 = printf " %s %s %s ->\n" d k u
| otherwise = ""
thm aa nt1 nt2 mv2 nt2' mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeRecName aa nt1 mv2'
; fv_fn <- fvName aa nt2 mv2'
; degree <- degreeName aa nt2 mv2'
; x <- newName mv2'
; y <- newName mv2
; k <- newName bvarRoot
; u <- newName nt2
; e <- newName nt1
; return $ printf "forall %s %s %s %s %s,\n\
\%s\
\%s\
\%s\
\ %s %s %s (%s %s %s %s) = %s %s %s (%s %s %s %s)"
e u x y k
(deg nt2 nt2' degree k u)
(neq mv2 mv2' x y)
(fv nt2 nt2' y fv_fn u)
subst_fn u x close_fn k y e
close_fn k y subst_fn u x e
}
{- | @subxt u x (close y e) = close y (subst u x e)@
when @x <> y@ and @y `notin` fv u@ and @lc u@. -}
subst_close :: ASTAnalysis -> [NtRoot] -> M String
subst_close aaa nt1s =
do { gens <- processNt1Nt2Mv2' aaa nt1s gen
; names <- processNt1Nt2Mv2' aaa nt1s name
; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeName aa nt1 mv2'
; return $ subst_fn ++ "_" ++ close_fn
}
neq mv2 mv2' x y | mv2 == mv2' = printf " %s <> %s ->\n" x y
| otherwise = ""
fv nt2 nt2' y fv_fn u
| canBindIn aaa nt2' nt2 = printf " %s %s %s %s ->\n" y mvSetNotin fv_fn u
| otherwise = ""
gen aa nt1 nt2 mv2 nt2' mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeName aa nt1 mv2'
; fv_fn <- fvName aa nt2 mv2'
; lc <- lcName aa nt2
; x <- newName mv2'
; y <- newName mv2
; u <- newName nt2
; e <- newName nt1
; let stmt = printf "forall %s %s %s %s,\n\
\ %s %s ->\
\%s\
\%s\
\ %s %s %s (%s %s %s) = %s %s (%s %s %s %s)"
e u x y
lc u
(neq mv2 mv2' x y)
(fv nt2 nt2' y fv_fn u)
subst_fn u x close_fn y e
close_fn y subst_fn u x e
; let proof = printf "unfold %s; %s." close_fn defaultSimp
; return (stmt, proof)
}
{- | @subst u x e@ = @close_rec k z (subst u x (open_rec k (var z) e))@
when @z `notin` fv u `union` fv e `union` { x }@ and @degree k u@. -}
subst_close_open_rec :: ASTAnalysis -> [NtRoot] -> M String
subst_close_open_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2' aaa nt1s thm
; names <- processNt1Nt2Mv2' aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Set types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite Hide [hintDb] Set names thms proof
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeRecName aa nt1 mv2'
; open_fn <- openRecName aa nt1 mv2'
; return $ sepStrings "_" [subst_fn, close_fn, open_fn]
}
neq mv2 mv2' z x | mv2 == mv2' = printf " %s <> %s ->\n" z x
| otherwise = ""
fv nt nt' z fv_fn t
| canBindIn aaa nt' nt = printf " %s %s %s %s ->\n" z mvSetNotin fv_fn t
| otherwise = ""
deg nt nt' d k t
| canBindIn aaa nt' nt = printf " %s %s %s ->\n" d k t
| otherwise = ""
thm aa nt1 nt2 mv2 nt2' mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeRecName aa nt1 mv2'
; open_fn <- openRecName aa nt1 mv2'
; degree <- degreeName aa nt2 mv2'
; u <- newName nt2
; x <- newName mv2
; z <- newName mv2'
; e <- newName nt1
; k <- newName bvarRoot
; fv_fn <- fvName aa nt1 mv2'
; fv_fn' <- fvName aa nt2 mv2'
; constr <- getFreeVarConstr aa nt2' mv2'
; return $ printf "forall %s %s %s %s %s,\n\
\%s\
\%s\
\%s\
\%s\
\ %s %s %s %s = %s %s %s (%s %s %s (%s %s (%s %s) %s))"
e u x z k
(fv nt1 nt2' z fv_fn e)
(fv nt2 nt2' z fv_fn' u)
(neq mv2 mv2' z x)
(deg nt2 nt2' degree k u)
subst_fn u x e
close_fn k z subst_fn u x open_fn k (toName constr) z e
}
{- | @subst u x e@ = @close_rec k z (subst u x (open_rec k (var z) e))@
when @z `notin` fv u `union` fv e `union` { x }@ and @lc u@. -}
subst_close_open :: ASTAnalysis -> [NtRoot] -> M String
subst_close_open aaa nt1s =
do { gens <- processNt1Nt2Mv2' aaa nt1s gen
; names <- processNt1Nt2Mv2' aaa nt1s name
; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeName aa nt1 mv2'
; open_fn <- openName aa nt1 mv2'
; return $ sepStrings "_" [subst_fn, close_fn, open_fn]
}
neq mv2 mv2' z x | mv2 == mv2' = printf " %s <> %s ->\n" z x
| otherwise = ""
fv nt nt' z fv_fn t
| canBindIn aaa nt' nt = printf " %s %s %s %s ->\n" z mvSetNotin fv_fn t
| otherwise = ""
lcHyp nt lc t | isOpenable aaa nt = printf " %s %s ->\n" lc t
| otherwise = ""
gen aa nt1 nt2 mv2 nt2' mv2' =
do { subst_fn <- substName aa nt1 mv2
; close_fn <- closeName aa nt1 mv2'
; open_fn <- openName aa nt1 mv2'
; lc <- lcName aa nt2
; u <- newName nt2
; x <- newName mv2
; z <- newName mv2'
; e <- newName nt1
; fv_fn <- fvName aa nt1 mv2'
; fv_fn' <- fvName aa nt2 mv2'
; constr <- getFreeVarConstr aa nt2' mv2'
-- ORDER TO OPEN
; let stmt = printf "forall %s %s %s %s,\n\
\%s\
\%s\
\%s\
\%s\
\ %s %s %s %s = %s %s (%s %s %s (%s %s (%s %s)))"
e u x z
(fv nt1 nt2' z fv_fn e)
(fv nt2 nt2' z fv_fn' u)
(neq mv2 mv2' z x)
(lcHyp nt2 lc u)
subst_fn u x e
close_fn z subst_fn u x open_fn e (toName constr) z
; let proof = printf "unfold %s; unfold %s; %s." close_fn open_fn defaultSimp
; return (stmt, proof)
}
{- | How @subst@ commutes with binding constructors. -}
subst_constr :: ASTAnalysis -> [NtRoot] -> M [String]
subst_constr aaa nt1s =
sequence $ do { nt1 <- nt1s
; nt2 <- filter (canBindOver aaa nt1) (ntRoots aaa)
; mv2 <- mvsOfNt aaa nt2
; (Syntax _ _ cs) <- [runM [] $ getSyntax aaa nt1]
; c <- [c | c <- cs, hasBindingArg c]
; return $ local $ thm aaa nt1 nt2 mv2 c
}
where
thm aa nt1 nt2 mv2 c@(SConstr pos _ _ args _) =
do { subst_fn <- substName aa nt1 mv2
; lc <- lcName aa nt2
; u <- newName nt2
; x <- newName mv2
; glomps <- mapM (glomp aa pos nt2 mv2 u x) args
; let (mvs, nts, args', freshes) = unzip4 glomps
; let stmt = printf "forall %s %s %s %s,\n\
\%s\
\%s\
\ %s %s %s (%s %s) = %s %s"
(sepStrings " " $ catMaybes mvs) (sepStrings " " nts) u x
(lcHyp nt2 lc u)
(concat $ catMaybes freshes)
subst_fn u x (toName c) (sepStrings " " nts)
(toName c) (sepStrings " " $ map wrap args')
; let proof = defaultSimp ++ "."
; let name = subst_fn ++ "_" ++ (toName c)
; lemmaText Resolve NoRewrite NoHide [hintDb] name stmt proof
}
unzip4 [] = ([], [], [], [])
unzip4 ((a,b,c,d):xs) = (a:as,b:bs,c:cs,d:ds)
where
(as,bs,cs,ds) = unzip4 xs
wrap s = "(" ++ s ++ ")"
lcHyp nt2 lc u | isOpenable aaa nt2 = printf " %s %s ->\n" lc u
| otherwise = ""
glomp _ pos _ _ _ _ IndexArg = error $ show pos ++ ": Internal error (subst_constr / IndexArg)."
glomp _ _ _ _ _ _ (MvArg nt) =
do { n <- newName nt
; return $ (Nothing, n, n, Nothing)
}
glomp aa _ nt2 mv2 u x (NtArg nt)
| canBindIn aa nt2 nt =
do { n <- newName nt
; subst_fn <- substName aa nt mv2
; return $ (Nothing, n, printf "%s %s %s %s" subst_fn u x n, Nothing)
}
| otherwise =
do { n <- newName nt
; return $ (Nothing, n, n, Nothing)
}
glomp aa _ nt2 mv2 u x (BindingArg mv' nt' nt)
| canBindIn aa nt2 nt =
do { n <- newName nt
; z <- newName mv'
; close_fn <- closeName aa nt mv'
; open_fn <- openName aa nt mv'
; subst_fn <- substName aa nt mv2
; constr <- getFreeVarConstr aa nt' mv'
; fv_fnu <- fvName aa nt2 mv'
; fv_fnn <- fvName aa nt mv'
; let fvu = if canBindIn aa nt' nt2
then Just (printf "%s %s" fv_fnu u)
else Nothing
; let fvn = if canBindIn aa nt' nt
then Just (printf "%s %s" fv_fnn n)
else Nothing
; let fvz = if canonRoot aa mv' == canonRoot aa mv2
then Just (printf "%s %s" mvSetSingleton x)
else Nothing
; let fresh = catMaybes [fvu, fvn, fvz]
; let hyp = if null fresh
then ""
else printf " %s %s %s ->\n" z mvSetNotin (sepStrings (" " ++ mvSetUnion ++ " ") fresh)
-- ORDER TO OPEN
; return $ (Just z, n, printf "%s %s (%s %s %s (%s %s (%s %s)))"
close_fn z
subst_fn u x
open_fn n (toName constr) z,
Just hyp)
}
| otherwise =
do { n <- newName nt
; return $ (Nothing, n, n, Nothing)
}
{- | @degree n (subst u x e)@ when @degree n u@ and @degree n e@. -}
subst_degree :: ASTAnalysis -> [NtRoot] -> M String
subst_degree aaa nt1s =
do { thms <- processNt1Nt2Mv2' aaa nt1s thm
; names <- processNt1Nt2Mv2' aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; degree <- degreeName aa nt1 mv2'
; return $ subst_fn ++ "_" ++ degree
}
thm aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2' nt2 =
do { k <- newName bvarRoot
; e1 <- newName nt1
; e2 <- newName nt2
; x <- newName mv2
; subst_fn <- substName aa nt1 mv2
; degree <- degreeName aa nt1 mv2'
; degree' <- degreeName aa nt2 mv2'
; return $ printf "forall %s %s %s %s,\n\
\ %s %s %s ->\n\
\ %s %s %s ->\n\
\ %s %s (%s %s %s %s)"
e1 e2 x k
degree k e1
degree' k e2
degree k subst_fn e2 x e1
}
thm aa nt1 nt2 mv2 _ mv2' | otherwise =
do { k <- newName bvarRoot
; e1 <- newName nt1
; e2 <- newName nt2
; x <- newName mv2
; subst_fn <- substName aa nt1 mv2
; degree <- degreeName aa nt1 mv2'
; return $ printf "forall %s %s %s %s,\n\
\ %s %s %s ->\n\
\ %s %s (%s %s %s %s)"
e1 e2 x k
degree k e1
degree k subst_fn e2 x e1
}
{- | @subst u x e = e@ when @x `notin` fv e@. -}
subst_fresh_eq :: ASTAnalysis -> [NtRoot] -> M String
subst_fresh_eq aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve Rewrite NoHide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 =
do { subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_fresh_eq"
}
thm aa nt1 nt2 mv2 =
do { subst_fn <- substName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; u <- newName nt2
; x <- newName mv2
; e <- newName nt1
; return $ printf "forall %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s %s = %s"
e u x
x mvSetNotin fv_fn e
subst_fn u x e e
}
{- | @x `notin` subst u x e@ when @x `notin` fv u@. -}
subst_fresh_same :: ASTAnalysis -> [NtRoot] -> M String
subst_fresh_same aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 =
do { subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_fresh_same"
}
thm aa nt1 nt2 mv2 =
do { subst_fn <- substName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; fv_fn' <- fvName aa nt2 mv2
; u <- newName nt2
; x <- newName mv2
; e <- newName nt1
; return $ printf "forall %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s (%s %s %s %s)"
e u x
x mvSetNotin fv_fn' u
x mvSetNotin fv_fn subst_fn u x e
}
{- | @x `notin` subst u y e@ when @x `notin` fv u `union` fv e@. -}
subst_fresh :: ASTAnalysis -> [NtRoot] -> M String
subst_fresh aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 =
do { subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_fresh"
}
thm aa nt1 nt2 mv2 =
do { subst_fn <- substName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; fv_fn' <- fvName aa nt2 mv2
; u <- newName nt2
; x <- newName mv2
; y <- newName mv2
; e <- newName nt1
; return $ printf "forall %s %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s %s ->\n\
\ %s %s %s (%s %s %s %s)"
e u x y
x mvSetNotin fv_fn e
x mvSetNotin fv_fn' u
x mvSetNotin fv_fn subst_fn u y e
}
{- | @open_rec k u e = subst u x (open_rec k x e)@ when @x `notin` fv e@. -}
subst_intro_rec :: ASTAnalysis -> [NtRoot] -> M String
subst_intro_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve Rewrite NoHide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 =
do { subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_intro_rec"
}
thm aa nt1 nt2 mv2 =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; constr <- getFreeVarConstr aa nt2 mv2
; k <- newName bvarRoot
; e <- newName nt1
; u <- newName nt2
; x <- newName mv2
; return $ printf "forall %s %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s %s = %s %s %s (%s %s (%s %s) %s)"
e x u k
x mvSetNotin fv_fn e
open_fn k u e
subst_fn u x open_fn k (toName constr) x e
}
{- | @open_rec k u e = subst u x (open_rec e x)@ when @x `notin` fv e@. -}
subst_intro :: ASTAnalysis -> [NtRoot] -> M String
subst_intro aaa nt1s =
do { gens <- processNt1Nt2Mv2 aaa nt1s gen
; names <- processNt1Nt2Mv2 aaa nt1s name
; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 =
do { subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_intro"
}
gen aa nt1 nt2 mv2 =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openName aa nt1 mv2
; fv_fn <- fvName aa nt1 mv2
; constr <- getFreeVarConstr aa nt2 mv2
; e <- newName nt1
; u <- newName nt2
; x <- newName mv2
; let stmt = printf "forall %s %s %s,\n\
\ %s %s %s %s ->\n\
\ %s %s %s = %s %s %s (%s %s (%s %s))"
x e u
x mvSetNotin fv_fn e
open_fn e u
subst_fn u x open_fn e (toName constr) x
; let proof = printf "unfold %s; %s." open_fn defaultSimp
; return (stmt, proof)
}
{- | @lc (subst u x e)@ when @lc u@ and @lc e@. -}
subst_lc :: ASTAnalysis -> [NtRoot] -> M String
subst_lc aaa nt1s =
do { gens <- processNt1Nt2Mv2 aaa nt1s gen
; names <- processNt1Nt2Mv2 aaa nt1s name
; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 =
do { lc <- lcName aa nt1
; subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_" ++ lc
}
gen aa nt1 nt2 mv2 =
do { e1 <- newName nt1
; e2 <- newName nt2
; x <- newName mv2
; lc <- lcName aa nt1
; lc' <- lcName aa nt2
; subst_fn <- substName aa nt1 mv2
; let stmt = printf "forall %s %s %s,\n\
\ %s %s ->\n\
\ %s %s ->\n\
\ %s (%s %s %s %s)"
e1 e2 x
lc e1
lc' e2
lc subst_fn e2 x e1
; let proof = printf "%s." defaultSimp
; return (stmt, proof)
}
{- | @subst u x (open_rec n v e) = open_rec n (subst u x v) (subst u x e)@
when @lc u@. -}
subst_open_rec :: ASTAnalysis -> [NtRoot] -> M String
subst_open_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2' aaa nt1s thm
; names <- processNt1Nt2Mv2' aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite Hide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2'
; return $ subst_fn ++ "_" ++ open_fn
}
lcHyp nt2 nt2' lc u
| canBindIn aaa nt2' nt2 = printf " %s %s ->\n" lc u
| otherwise = ""
thm aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2 nt2' =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2'
; u <- newName nt2
; v <- newName nt2'
; x <- newName mv2
; e <- newName nt1
; k <- newName bvarRoot
; subst_fn' <- substName aa nt2' mv2
; lc <- lcName aa nt2
; return $ printf "forall %s %s %s %s %s,\n\
\%s\
\ %s %s %s (%s %s %s %s) = %s %s (%s %s %s %s) (%s %s %s %s)"
e u v x k
(lcHyp nt2 nt2' lc u)
subst_fn u x open_fn k v e
open_fn k subst_fn' u x v subst_fn u x e
}
thm aa nt1 nt2 mv2 nt2' mv2' | otherwise =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2'
; u <- newName nt2
; v <- newName nt2'
; x <- newName mv2
; e <- newName nt1
; k <- newName bvarRoot
; lc <- lcName aa nt2
; return $ printf "forall %s %s %s %s %s,\n\
\%s\
\ %s %s %s (%s %s %s %s) = %s %s %s (%s %s %s %s)"
e u v x k
(lcHyp nt2 nt2' lc u)
subst_fn u x open_fn k v e
open_fn k v subst_fn u x e
}
{- | @subst u x (open e v) = open (subst u x e) (subst u x v)@
when @lc u@. -}
subst_open :: ASTAnalysis -> [NtRoot] -> M String
subst_open aaa nt1s =
do { gens <- processNt1Nt2Mv2' aaa nt1s gen
; names <- processNt1Nt2Mv2' aaa nt1s name
; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openName aa nt1 mv2'
; return $ subst_fn ++ "_" ++ open_fn
}
lcHyp nt2 nt2' lc u
| canBindIn aaa nt2' nt2 = printf " %s %s ->\n" lc u
| otherwise = ""
gen aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2 nt2' =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openName aa nt1 mv2'
; u <- newName nt2
; v <- newName nt2'
; x <- newName mv2
; e <- newName nt1
; subst_fn' <- substName aa nt2' mv2
; lc <- lcName aa nt2
-- ORDER TO OPEN
; let stmt = printf "forall %s %s %s %s,\n\
\%s\
\ %s %s %s (%s %s %s) = %s (%s %s %s %s) (%s %s %s %s)"
e u v x
(lcHyp nt2 nt2' lc u)
subst_fn u x open_fn e v
open_fn subst_fn u x e subst_fn' u x v
; let proof = printf "unfold %s; %s." open_fn defaultSimp
; return (stmt, proof)
}
gen aa nt1 nt2 mv2 nt2' mv2' | otherwise =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openName aa nt1 mv2'
; u <- newName nt2
; v <- newName nt2'
; x <- newName mv2
; e <- newName nt1
; lc <- lcName aa nt2
-- ORDER TO OPEN
; let stmt = printf "forall %s %s %s %s,\n\
\%s\
\ %s %s %s (%s %s %s) = %s (%s %s %s %s) %s"
e u v x
(lcHyp nt2 nt2' lc u)
subst_fn u x open_fn e v
open_fn subst_fn u x e v
; let proof = printf "unfold %s; %s." open_fn defaultSimp
; return (stmt, proof)
}
{- | @subst u x (open e (var y)) = open (subst u x e) (var y)@
when @lc u@ and @x <> y@. -}
subst_open_var :: ASTAnalysis -> [NtRoot] -> M String
subst_open_var aaa nt1s =
do { gens <- processNt1Nt2Mv2' aaa nt1s gen
; names <- processNt1Nt2Mv2' aaa nt1s name
; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openName aa nt1 mv2'
; return $ subst_fn ++ "_" ++ open_fn ++ "_var"
}
lcHyp nt2 nt2' lc u
| canBindIn aaa nt2' nt2 = printf " %s %s ->\n" lc u
| otherwise = ""
neq mv2 mv2' x y | mv2 == mv2' = printf " %s <> %s ->\n" x y
| otherwise = ""
gen aa nt1 nt2 mv2 nt2' mv2' =
do { subst_fn <- substName aa nt1 mv2
; open_fn <- openName aa nt1 mv2'
; u <- newName nt2
; x <- newName mv2
; y <- newName mv2'
; constr <- getFreeVarConstr aa nt2' mv2'
; e <- newName nt1
; lc <- lcName aa nt2
-- ORDER TO OPEN
; let stmt = printf "forall %s %s %s %s,\n\
\%s\
\%s\
\ %s (%s %s %s %s) (%s %s) = %s %s %s (%s %s (%s %s))"
e u x y
(neq mv2 mv2' x y)
(lcHyp nt2 nt2' lc u)
open_fn subst_fn u x e (toName constr) y
subst_fn u x open_fn e (toName constr) y
; let rw = subst_fn ++ "_" ++ open_fn
; let proof = printf "intros; rewrite %s; %s." rw defaultSimp
; return (stmt, proof)
}
{- | @subst e2 x e1 = open_rec k e2 (close_rec k x e1)@. -}
subst_spec_rec :: ASTAnalysis -> [NtRoot] -> M String
subst_spec_rec aaa nt1s =
do { thms <- processNt1Nt2Mv2 aaa nt1s thm
; names <- processNt1Nt2Mv2 aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite Hide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 =
do { subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_spec_rec"
}
thm aa nt1 nt2 mv2 =
do { k <- newName bvarRoot
; e1 <- newName nt1
; e2 <- newName nt2
; x <- newName mv2
; close_fn <- closeRecName aa nt1 mv2
; open_fn <- openRecName aa nt1 mv2
; subst_fn <- substName aa nt1 mv2
; return $ printf "forall %s %s %s %s,\n\
\ %s %s %s %s = %s %s %s (%s %s %s %s)"
e1 e2 x k
subst_fn e2 x e1 open_fn k e2 close_fn k x e1
}
{- | @subst e2 x e1 = open (close x e1) e2@. -}
subst_spec :: ASTAnalysis -> [NtRoot] -> M String
subst_spec aaa nt1s =
do { gens <- processNt1Nt2Mv2 aaa nt1s gen
; names <- processNt1Nt2Mv2 aaa nt1s name
; lemmaText2 Resolve NoRewrite NoHide [hintDb] names gens
}
where
name aa nt1 _ mv2 =
do { subst_fn <- substName aa nt1 mv2
; return $ subst_fn ++ "_spec"
}
gen aa nt1 nt2 mv2 =
do { e1 <- newName nt1
; e2 <- newName nt2
; x <- newName mv2
; close_fn <- closeName aa nt1 mv2
; open_fn <- openName aa nt1 mv2
; subst_fn <- substName aa nt1 mv2
-- ORDER TO OPEN
; let stmt = printf "forall %s %s %s,\n\
\ %s %s %s %s = %s (%s %s %s) %s"
e1 e2 x
subst_fn e2 x e1 open_fn close_fn x e1 e2
; let proof = printf "unfold %s; unfold %s; %s."
close_fn open_fn defaultSimp
; return (stmt, proof)
}
{- | @subst u y (subst u' x e) = subst (subst u y u') x (subst u y e)@
when @x `notin` fv u@.
Implementation note (BEA): The case analysis in the function is
somewhat intense. Maybe there's a simpler way? -}
subst_subst :: ASTAnalysis -> [NtRoot] -> M String
subst_subst aaa nt1s =
do { thms <- processNt1Nt2Mv2' aaa nt1s thm
; names <- processNt1Nt2Mv2' aaa nt1s name
; types <- processNt1 aaa nt1s ntType
; let proof = repeat (mutPfStart Prop types ++ defaultSimp ++ ".")
; mutualLemmaText2 Resolve NoRewrite NoHide [hintDb] Prop names thms proof
}
where
name aa nt1 _ mv2 _ mv2' =
do { subst_out <- substName aa nt1 mv2
; subst_in <- substName aa nt1 mv2'
; return $ subst_out ++ "_" ++ subst_in
}
neq x y mv2 mv2' | mv2 == mv2' = " " ++ x ++ " <> " ++ y ++ " ->\n"
neq _ _ _ _ | otherwise = ""
thm aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2 nt2' && canBindIn aa nt2' nt2 =
do { subst_out <- substName aa nt1 mv2
; subst_in <- substName aa nt1 mv2'
; subst_new <- substName aa nt2' mv2
; fv_fn <- fvName aa nt2 mv2'
; e <- newName nt1
; u <- newName nt2
; y <- newName mv2
; u' <- newName nt2'
; x <- newName mv2'
; return $ printf "forall %s %s %s %s %s,\n\
\ %s %s %s %s ->\n\
\%s\
\ %s %s %s (%s %s %s %s) = %s (%s %s %s %s) %s (%s %s %s %s)"
e u u' x y
x mvSetNotin fv_fn u
(neq x y mv2 mv2')
subst_out u y subst_in u' x e
subst_in subst_new u y u' x subst_out u y e
}
thm aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2 nt2' =
do { subst_out <- substName aa nt1 mv2
; subst_in <- substName aa nt1 mv2'
; subst_new <- substName aa nt2' mv2
; e <- newName nt1
; u <- newName nt2
; y <- newName mv2
; u' <- newName nt2'
; x <- newName mv2'
; return $ printf "forall %s %s %s %s %s,\n\
\%s\
\ %s %s %s (%s %s %s %s) = %s (%s %s %s %s) %s (%s %s %s %s)"
e u u' x y
(neq x y mv2 mv2')
subst_out u y subst_in u' x e
subst_in subst_new u y u' x subst_out u y e
}
thm aa nt1 nt2 mv2 nt2' mv2' | canBindIn aa nt2' nt2 =
do { subst_out <- substName aa nt1 mv2
; subst_in <- substName aa nt1 mv2'
; fv_fn <- fvName aa nt2 mv2'
; e <- newName nt1
; u <- newName nt2
; y <- newName mv2
; u' <- newName nt2'
; x <- newName mv2'
; return $ printf "forall %s %s %s %s %s,\n\
\ %s %s %s %s ->\n\
\%s\
\ %s %s %s (%s %s %s %s) = %s %s %s (%s %s %s %s)"
e u u' x y
x mvSetNotin fv_fn u
(neq x y mv2 mv2')
subst_out u y subst_in u' x e
subst_in u' x subst_out u y e
}
thm aa nt1 nt2 mv2 nt2' mv2' | otherwise =
do { subst_out <- substName aa nt1 mv2
; subst_in <- substName aa nt1 mv2'
; e <- newName nt1
; u <- newName nt2
; y <- newName mv2
; u' <- newName nt2'
; x <- newName mv2'
; return $ printf "forall %s %s %s %s %s,\n\
\ %s %s %s %s ->\n\
\%s\
\ %s %s %s (%s %s %s %s) = %s %s %s (%s %s %s %s)"
e u u' x y
(neq x y mv2 mv2')
subst_out u y subst_in u' x e
subst_in u' x subst_out u y e
}
| plclub/lngen | src/CoqLNOutputThmSubst.hs | mit | 39,755 | 0 | 27 | 19,520 | 10,063 | 4,885 | 5,178 | 673 | 9 |
module Fass.TestHelper where
import Test.Hspec
import Text.Parsec
import Text.Parsec.String
testParser :: Parser a -> String -> Either ParseError a
testParser parser = parse parser "test parser"
matchRight :: (Show a, Show b, Eq b) => Either a b -> b -> IO ()
matchRight ex y = case ex of
Left x -> fail $ show x
Right x -> x `shouldBe` y
testParserEqual :: Parser String -> String -> IO ()
testParserEqual parser input = testParser parser input `matchRight` input
(|@|) :: (Eq a, Show a) => a -> a -> Expectation
(|@|) = shouldBe
| darthdeus/fass | test/Fass/TestHelper.hs | mit | 544 | 0 | 9 | 109 | 224 | 117 | 107 | 14 | 2 |
{-# LANGUAGE PatternSynonyms, ForeignFunctionInterface, JavaScriptFFI #-}
module GHCJS.DOM.JSFFI.Generated.IDBRequest
(js_getResult, getResult, js_getError, getError, js_getSource,
getSource, js_getTransaction, getTransaction, js_getReadyState,
getReadyState, success, error, IDBRequest, castToIDBRequest,
gTypeIDBRequest, IsIDBRequest, toIDBRequest)
where
import Prelude ((.), (==), (>>=), return, IO, Int, Float, Double, Bool(..), Maybe, maybe, fromIntegral, round, fmap, Show, Read, Eq, Ord)
import Data.Typeable (Typeable)
import GHCJS.Types (JSRef(..), JSString, castRef)
import GHCJS.Foreign (jsNull)
import GHCJS.Foreign.Callback (syncCallback, asyncCallback, syncCallback1, asyncCallback1, syncCallback2, asyncCallback2, OnBlocked(..))
import GHCJS.Marshal (ToJSRef(..), FromJSRef(..))
import GHCJS.Marshal.Pure (PToJSRef(..), PFromJSRef(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Int (Int64)
import Data.Word (Word, Word64)
import GHCJS.DOM.Types
import Control.Applicative ((<$>))
import GHCJS.DOM.EventTargetClosures (EventName, unsafeEventName)
import GHCJS.DOM.Enums
foreign import javascript unsafe "$1[\"result\"]" js_getResult ::
JSRef IDBRequest -> IO (JSRef IDBAny)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.result Mozilla IDBRequest.result documentation>
getResult ::
(MonadIO m, IsIDBRequest self) => self -> m (Maybe IDBAny)
getResult self
= liftIO
((js_getResult (unIDBRequest (toIDBRequest self))) >>= fromJSRef)
foreign import javascript unsafe "$1[\"error\"]" js_getError ::
JSRef IDBRequest -> IO (JSRef DOMError)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.error Mozilla IDBRequest.error documentation>
getError ::
(MonadIO m, IsIDBRequest self) => self -> m (Maybe DOMError)
getError self
= liftIO
((js_getError (unIDBRequest (toIDBRequest self))) >>= fromJSRef)
foreign import javascript unsafe "$1[\"source\"]" js_getSource ::
JSRef IDBRequest -> IO (JSRef IDBAny)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.source Mozilla IDBRequest.source documentation>
getSource ::
(MonadIO m, IsIDBRequest self) => self -> m (Maybe IDBAny)
getSource self
= liftIO
((js_getSource (unIDBRequest (toIDBRequest self))) >>= fromJSRef)
foreign import javascript unsafe "$1[\"transaction\"]"
js_getTransaction :: JSRef IDBRequest -> IO (JSRef IDBTransaction)
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.transaction Mozilla IDBRequest.transaction documentation>
getTransaction ::
(MonadIO m, IsIDBRequest self) => self -> m (Maybe IDBTransaction)
getTransaction self
= liftIO
((js_getTransaction (unIDBRequest (toIDBRequest self))) >>=
fromJSRef)
foreign import javascript unsafe "$1[\"readyState\"]"
js_getReadyState :: JSRef IDBRequest -> IO JSString
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.readyState Mozilla IDBRequest.readyState documentation>
getReadyState ::
(MonadIO m, IsIDBRequest self, FromJSString result) =>
self -> m result
getReadyState self
= liftIO
(fromJSString <$>
(js_getReadyState (unIDBRequest (toIDBRequest self))))
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.onsuccess Mozilla IDBRequest.onsuccess documentation>
success ::
(IsIDBRequest self, IsEventTarget self) => EventName self Event
success = unsafeEventName (toJSString "success")
-- | <https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest.onerror Mozilla IDBRequest.onerror documentation>
error ::
(IsIDBRequest self, IsEventTarget self) => EventName self Event
error = unsafeEventName (toJSString "error") | plow-technologies/ghcjs-dom | src/GHCJS/DOM/JSFFI/Generated/IDBRequest.hs | mit | 3,809 | 30 | 13 | 589 | 899 | 511 | 388 | 64 | 1 |
module Game.Output.Util
( unmanagedSurface
) where
import Foreign.Ptr (Ptr)
import SDL
import SDL.Raw.Types
-- | A helper for unmanaged 'Surface's, since it is not exposed by SDL itself.
unmanagedSurface :: Ptr SDL.Raw.Types.Surface -> SDL.Surface
unmanagedSurface p = SDL.Surface p Nothing
| flomerz/SchaffschNie | src/Game/Output/Util.hs | mit | 301 | 0 | 7 | 50 | 65 | 38 | 27 | 7 | 1 |
{-# LANGUAGE NoImplicitPrelude, OverloadedStrings, TupleSections, GADTs #-}
module DayX where
import AdventPrelude2
input :: IO Text
input = readFile "data/dayX.txt"
parser = letter
result1 =
runEitherT $
do i <- EitherT (parseOnly (parser `sepBy` endOfLine) <$> input)
pure (take 5 i)
| farrellm/advent-2016 | src/DayX.hs | mit | 300 | 0 | 14 | 55 | 81 | 43 | 38 | 10 | 1 |
{-# LANGUAGE CPP #-}
module GHCJS.DOM.StringCallback (
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
module GHCJS.DOM.JSFFI.Generated.StringCallback
#else
#endif
) where
#if (defined(ghcjs_HOST_OS) && defined(USE_JAVASCRIPTFFI)) || !defined(USE_WEBKIT)
import GHCJS.DOM.JSFFI.Generated.StringCallback
#else
#endif
| plow-technologies/ghcjs-dom | src/GHCJS/DOM/StringCallback.hs | mit | 355 | 0 | 5 | 33 | 33 | 26 | 7 | 4 | 0 |
{-# LANGUAGE OverloadedStrings #-}
module ClientSpec (spec) where
import Helper
import HTTP
import Client
spec :: Spec
spec = do
describe "client" $ do
it "does a HTTP request via a Unix domain socket" $ do
inTempDirectory $ do
withServer (return (True, "hello")) $ do
client `shouldReturn` (True, "hello")
it "indicates failure" $ do
inTempDirectory $ do
withServer (return (False, "hello")) $ do
client `shouldReturn` (False, "hello")
context "when server socket is missing" $ do
it "reports error" $ do
inTempDirectory $ do
client `shouldReturn` (False, "could not connect to .sensei.sock\n")
| hspec/sensei | test/ClientSpec.hs | mit | 717 | 0 | 20 | 212 | 189 | 97 | 92 | 20 | 1 |
laste = head . reverse
| zseymour/latex-repo | CS 571/assignment3/code/laste.hs | mit | 23 | 0 | 5 | 5 | 10 | 5 | 5 | 1 | 1 |
module Paths_Verba where
-- This is here only for ease of testing
-- for unpackaged builds. It will be replaced
-- by the custom generated one automatically.
getDataFileName :: FilePath -> IO FilePath
getDataFileName = return
| Jefffrey/Verba | src/Paths_Verba.hs | mit | 227 | 0 | 6 | 37 | 24 | 15 | 9 | 3 | 1 |
{-
see Chapter 41 of the Haskell 2010 Language Report
-}
module System.IO where
| evilcandybag/JSHC | hslib/System/IO.hs | mit | 83 | 0 | 3 | 16 | 7 | 5 | 2 | 1 | 0 |
{-|
Module : Example.Mnist
Description : MNIST traning example
Copyright : (c) Anatoly Yakovenko, 2015-2016
License : MIT
Maintainer : [email protected]
Stability : experimental
Portability : POSIX
This module implements an example traning the MNIST data set. Using
the dataset parsing code from:
<https://github.com/mhwombat/backprop-example/blob/master/Mnist.hs>
-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
module Examples.Mnist (generateTrainBatches
,generateTrainLabels
,generateTestBatches
,mnist
)where
import Control.Applicative((<|>))
import Control.Monad.Trans(liftIO)
import Control.Monad(when,forever,forM_, foldM_)
import qualified Data.ByteString.Lazy as BL
import Data.Binary.Get hiding(label)
import qualified Data.Binary as B
import Data.Word
import qualified Data.List.Split as S
import qualified Data.Array.Repa as R
import Codec.Compression.GZip as GZ
import Data.List.Split(chunksOf)
import Statistics.LinearRegression as S
import qualified Data.DNN.Trainer as T
import qualified Data.RBM as RB
import qualified Data.Matrix as M
import qualified Data.ImageUtils as I
import Data.Matrix(Matrix(..)
,U
,B
,I
,H
)
{-|
Train a network to recognize digits from the MNIST dataset. Start by training
each layer as an RBM with the Contrastive Divergence algorithm. Then finish
up the traning with Back-propagation. Animate the weights as the traning
progresses.
-}
mnist :: IO ()
mnist = do
let r1 = RB.new 0 785 530 --dimentions include the bias node
r2 = RB.new 0 530 530 --sqrt(529) == 23
r3 = RB.new 0 530 11
-- train the first layer
tr1 <- B.decodeFile "dist/rbm1" --decode if this layer is already been trained
<|> do tr1 <- snd <$> (T.run [r1] $ trainCD "dist/rbm1.gif" 0.01)
B.encodeFile "dist/rbm1" tr1 --save the layer to a file
return tr1
-- train the second layer
tr2 <- B.decodeFile "dist/rbm2"
<|> do tr2 <- snd <$> (T.run (tr1++[r2]) $ trainCD "dist/rbm2.gif" 0.001)
B.encodeFile "dist/rbm2" tr2
return tr2
-- train the third layer
tr3 <- B.decodeFile "dist/rbm3"
<|> do tr3 <- snd <$> (T.run (tr2++[r3]) $ trainCD "dist/rbm3.gif" 0.001)
B.encodeFile "dist/rbm3" tr3
return tr3
-- backprop
let train pbp xx = do
let name = "dist/bp" ++ (show xx)
gif = name ++ ".gif"
bp <- B.decodeFile name
<|> do bp <- snd <$> (T.run pbp $ trainBP gif 0.01 0.001)
B.encodeFile name bp
return bp
mapM_ (testBatch bp) [0..9] --print how well our network recognizes the images
return bp
foldM_ train tr3 [1::Int ..] --train forever
-- max number of minibatches
maxCount :: Int
maxCount = 25000
-- how often to check the progress
testCount :: Int
testCount = 1000
-- size of the minibatch
rowCount :: Int
rowCount = 5
-- |train the last layer in the DNN via the CD algorithm
trainCD :: String -> Double -> T.Trainer IO ()
trainCD file mine = forever $ do
T.setLearnRate 0.001
let batchids = [0..468::Int]
forM_ batchids $ \ ix -> do
big <- liftIO $ readBatch ix
small <- mapM M.d2u $ M.splitRows rowCount big
forM_ small $ \ batch -> do
T.contraDiv batch
cnt <- T.getCount
when (0 == cnt `mod` testCount) $ do
nns <- T.getDNN
ww <- M.cast1 <$> M.transpose (last nns)
liftIO $ I.appendGIF file ww
when (0 == cnt `mod` testCount) $ do
err <- T.reconErr big
liftIO $ print (cnt, err)
when (cnt >= maxCount || err < mine) $ T.finish_
-- |train the entire DNN via backprop
trainBP :: String -> Double -> Double -> T.Trainer IO ()
trainBP file lr mine = forever $ do
T.setLearnRate lr
let batchids = [0..468::Int]
forM_ batchids $ \ ix -> do
bbatch <- liftIO $ readBatch ix
blabel <- liftIO $ readLabel ix
sbatch <- mapM M.d2u $ M.splitRows rowCount bbatch
slabel <- mapM M.d2u $ M.splitRows rowCount blabel
forM_ (zip sbatch slabel) $ \ (batch,label) -> do
T.backProp batch label
cnt <- T.getCount
when (0 == cnt `mod` testCount) $ do
gen <- T.backward (Matrix $ toLabelM [0..9])
liftIO $ I.appendGIF file gen
when (0 == cnt `mod` testCount) $ do
err <- T.forwardErr bbatch blabel
liftIO $ print (cnt, err)
when (cnt >= maxCount || err < mine) $ T.finish_
-- |compute the correlation between the labels and the DNN output
testBatch :: [Matrix U I H] -> Int -> IO ()
testBatch nns ix = do
let name = "dist/test" ++ (show ix)
bxi <- Matrix <$> readArray name
let bxh = M.fromList (M.row bxi, 11) $ concat $ replicate (M.row bxi) $ labelVector ix
(bxh',_) <- T.run nns $ T.feedForward bxi
let cor = S.correl (M.toUnboxed bxh') (M.toUnboxed bxh)
print (ix, cor)
-- |Generate a batch of images with bias values for training.
generateTrainBatches :: IO ()
generateTrainBatches = do
images <- readImages "dist/train-images-idx3-ubyte.gz"
let batches = map toMatrix $ chunksOf 128 images
(flip mapM_) (zip [0::Integer ..] batches) $ \ (ix, bb) -> do
let name = "dist/train" ++ (show ix)
writeArray name bb
-- |Generate a batch of of matching labels with bias values.
generateTrainLabels :: IO ()
generateTrainLabels = do
labels <- readLabels "dist/train-labels-idx1-ubyte.gz"
let batches = map toLabelM $ chunksOf 128 labels
(flip mapM_) (zip [0::Integer ..] batches) $ \ (ix, bb) -> do
let name = "dist/label" ++ (show ix)
writeArray name bb
-- |Generate a the test images with bias values sorted by label.
generateTestBatches :: IO ()
generateTestBatches = do
images <- readImages "dist/t10k-images-idx3-ubyte.gz"
labels <- readLabels "dist/t10k-labels-idx1-ubyte.gz"
(flip mapM_) ([0..9]) $ \ ix -> do
let name = "dist/test" ++ (show ix)
let batch = filter (((==) ix) . fst) $ zip labels images
let bb = toMatrix $ snd $ unzip batch
writeArray name bb
-- |generate a 2d array from the list of images
-- |add the bias node as the first node to each image
toMatrix :: [Image] -> R.Array R.U R.DIM2 Double
toMatrix images = m
where
m = R.fromListUnboxed (R.Z R.:. len R.:. maxsz) (concatMap pixels images)
maxsz = 1 + (maximum $ map (\ ii -> (iRows ii) * (iColumns ii)) images)
len = length images
pixels im = take maxsz $ 1:((normalisedData im) ++ [0..])
-- |file IO utils
readImages :: FilePath -> IO [Image]
readImages filename = do
content <- GZ.decompress <$> BL.readFile filename
let (_, _, r, c, unpackedData) = runGet deserialiseHeader content
return (map (Image (fromIntegral r) (fromIntegral c)) unpackedData)
writeArray :: String -> R.Array R.U R.DIM2 Double -> IO ()
writeArray fileName array = do
let (R.Z R.:. r R.:. c) = R.extent array
B.encodeFile fileName (r,c,R.toList array)
readArray ::String -> IO (R.Array R.U R.DIM2 Double)
readArray fileName = do
(r,c,ls) <- B.decodeFile fileName
return $ R.fromListUnboxed (R.Z R.:. r R.:. c) ls
readBatch :: Int -> IO (Matrix U B I)
readBatch ix = Matrix <$> readArray name
where name = "dist/train" ++ (show ix)
readLabel :: Int -> IO (Matrix U B H)
readLabel ix = Matrix <$> readArray name
where name = "dist/label" ++ (show ix)
-- |MNIST image parsing code
-- |from https://github.com/mhwombat/backprop-example/blob/master/Mnist.hs
data Image = Image {
iRows :: Int
, iColumns :: Int
, iPixels :: [Word8]
} deriving (Eq, Show)
normalisedData :: Image -> [Double]
normalisedData image = map normalisePixel (iPixels image)
normalisePixel :: Word8 -> Double
normalisePixel p = (fromIntegral p) / 255.0
toLabelM :: [Int] -> R.Array R.U R.DIM2 Double
toLabelM labels = m
where
m = R.fromListUnboxed (R.Z R.:. len R.:. 11) (concatMap labelVector labels)
len = length labels
labelVector :: Int -> [Double]
labelVector ll = take 11 $ 1.0:(start ++ end)
where start = take ll $ repeat 0.0
end = 1.0 : repeat 0.0
{-|
MNIST label file format
[offset] [type] [value] [description]
0000 32 bit integer 0x00000801(2049) magic number (MSB first)
0004 32 bit integer 10000 number of items
0008 unsigned byte ?? label
0009 unsigned byte ?? label
........
xxxx unsigned byte ?? label
The labels values are 0 to 9.
-}
deserialiseLabels :: Get (Word32, Word32, [Word8])
deserialiseLabels = do
magicNumber <- getWord32be
count <- getWord32be
labelData <- getRemainingLazyByteString
let labels = BL.unpack labelData
return (magicNumber, count, labels)
readLabels :: FilePath -> IO [Int]
readLabels filename = do
content <- GZ.decompress <$> BL.readFile filename
let (_, _, labels) = runGet deserialiseLabels content
return (map fromIntegral labels)
{-|
MNIST Image file format
[offset] [type] [value] [description]
0000 32 bit integer 0x00000803(2051) magic number
0004 32 bit integer ?? number of images
0008 32 bit integer 28 number of rows
0012 32 bit integer 28 number of columns
0016 unsigned byte ?? pixel
0017 unsigned byte ?? pixel
........
xxxx unsigned byte ?? pixel
Pixels are organized row-wise. Pixel values are 0 to 255. 0 means background (white), 255
means foreground (black).
-}
deserialiseHeader :: Get (Word32, Word32, Word32, Word32, [[Word8]])
deserialiseHeader = do
magicNumber <- getWord32be
imageCount <- getWord32be
r <- getWord32be
c <- getWord32be
packedData <- getRemainingLazyByteString
let len = fromIntegral (r * c)
let unpackedData = S.chunksOf len (BL.unpack packedData)
return (magicNumber, imageCount, r, c, unpackedData)
| aeyakovenko/rbm | Examples/Mnist.hs | mit | 10,131 | 0 | 24 | 2,639 | 2,971 | 1,506 | 1,465 | 192 | 1 |
{-# LANGUAGE CPP #-}
module Cabal
( getPackageGhcOpts
, findCabalFile
) where
#ifdef ENABLE_CABAL
import Stack
import Control.Exception (IOException, catch)
import Control.Monad (when)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.State (execStateT, modify)
import Data.Char (isSpace)
import Data.List (foldl', nub, sort, find, isPrefixOf, isSuffixOf)
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative ((<$>))
import Data.Monoid (Monoid(..))
#endif
import Distribution.Package (PackageIdentifier(..), PackageName)
import Distribution.PackageDescription (PackageDescription(..), Executable(..), TestSuite(..), Benchmark(..), emptyHookedBuildInfo, buildable, libBuildInfo)
import Distribution.PackageDescription.Parse (readPackageDescription)
import Distribution.Simple.Configure (configure)
import Distribution.Simple.LocalBuildInfo (LocalBuildInfo(..), ComponentLocalBuildInfo(..),
Component(..), ComponentName(..),
#if __GLASGOW_HASKELL__ < 707
allComponentsBy,
#endif
componentBuildInfo, foldComponent)
import Distribution.Simple.Compiler (PackageDB(..))
import Distribution.Simple.Command (CommandParse(..), commandParseArgs)
import Distribution.Simple.GHC (componentGhcOptions)
import Distribution.Simple.Program (defaultProgramConfiguration)
import Distribution.Simple.Program.Db (lookupProgram)
import Distribution.Simple.Program.Types (ConfiguredProgram(programVersion), simpleProgram)
import Distribution.Simple.Program.GHC (GhcOptions(..), renderGhcOptions)
import Distribution.Simple.Setup (ConfigFlags(..), defaultConfigFlags, configureCommand, toFlag)
#if __GLASGOW_HASKELL__ >= 709
import Distribution.Utils.NubList
import qualified Distribution.Simple.GHC as GHC(configure)
#endif
import Distribution.Verbosity (silent)
import Distribution.Version (Version(..))
import System.IO.Error (ioeGetErrorString)
import System.Directory (doesFileExist, getDirectoryContents)
import System.FilePath (takeDirectory, splitFileName, (</>))
componentName :: Component -> ComponentName
componentName =
foldComponent (const CLibName)
(CExeName . exeName)
(CTestName . testName)
(CBenchName . benchmarkName)
getComponentLocalBuildInfo :: LocalBuildInfo -> ComponentName -> ComponentLocalBuildInfo
#if __GLASGOW_HASKELL__ >= 707
getComponentLocalBuildInfo lbi cname = getLocalBuildInfo cname $ componentsConfigs lbi
where getLocalBuildInfo cname' ((cname'', clbi, _):cfgs) =
if cname' == cname'' then clbi else getLocalBuildInfo cname' cfgs
getLocalBuildInfo _ [] = error $ "internal error: missing config"
#else
getComponentLocalBuildInfo lbi CLibName =
case libraryConfig lbi of
Nothing -> error $ "internal error: missing library config"
Just clbi -> clbi
getComponentLocalBuildInfo lbi (CExeName name) =
case lookup name (executableConfigs lbi) of
Nothing -> error $ "internal error: missing config for executable " ++ name
Just clbi -> clbi
getComponentLocalBuildInfo lbi (CTestName name) =
case lookup name (testSuiteConfigs lbi) of
Nothing -> error $ "internal error: missing config for test suite " ++ name
Just clbi -> clbi
getComponentLocalBuildInfo lbi (CBenchName name) =
case lookup name (testSuiteConfigs lbi) of
Nothing -> error $ "internal error: missing config for benchmark " ++ name
Just clbi -> clbi
#endif
#if __GLASGOW_HASKELL__ >= 707
-- TODO: Fix callsites so we don't need `allComponentsBy`. It was taken from
-- http://hackage.haskell.org/package/Cabal-1.16.0.3/docs/src/Distribution-Simple-LocalBuildInfo.html#allComponentsBy
-- since it doesn't exist in Cabal 1.18.*
--
-- | Obtains all components (libs, exes, or test suites), transformed by the
-- given function. Useful for gathering dependencies with component context.
allComponentsBy :: PackageDescription
-> (Component -> a)
-> [a]
allComponentsBy pkg_descr f =
[ f (CLib lib) | Just lib <- [library pkg_descr]
, buildable (libBuildInfo lib) ]
++ [ f (CExe exe) | exe <- executables pkg_descr
, buildable (buildInfo exe) ]
++ [ f (CTest tst) | tst <- testSuites pkg_descr
, buildable (testBuildInfo tst)
, testEnabled tst ]
++ [ f (CBench bm) | bm <- benchmarks pkg_descr
, buildable (benchmarkBuildInfo bm)
, benchmarkEnabled bm ]
#endif
stackifyFlags :: ConfigFlags -> Maybe StackConfig -> ConfigFlags
stackifyFlags cfg Nothing = cfg
stackifyFlags cfg (Just si) = cfg { configDistPref = toFlag dist
, configPackageDBs = pdbs
}
where
pdbs = [Nothing, Just GlobalPackageDB] ++ pdbs'
pdbs' = Just . SpecificPackageDB <$> stackDbs si
dist = stackDist si
-- via: https://groups.google.com/d/msg/haskell-stack/8HJ6DHAinU0/J68U6AXTsasJ
-- cabal configure --package-db=clear --package-db=global --package-db=$(stack path --snapshot-pkg-db) --package-db=$(stack path --local-pkg-db)
getPackageGhcOpts :: FilePath -> Maybe StackConfig -> [String] -> IO (Either String [String])
getPackageGhcOpts path mbStack opts = do
getPackageGhcOpts' `catch` (\e -> do
return $ Left $ "Cabal error: " ++ (ioeGetErrorString (e :: IOException)))
where
getPackageGhcOpts' :: IO (Either String [String])
getPackageGhcOpts' = do
genPkgDescr <- readPackageDescription silent path
distDir <- getDistDir
let programCfg = defaultProgramConfiguration
let initCfgFlags = (defaultConfigFlags programCfg)
{ configDistPref = toFlag distDir
-- TODO: figure out how to find out this flag
, configUserInstall = toFlag True
-- configure with --enable-tests to include test dependencies/modules
, configTests = toFlag True
-- configure with --enable-benchmarks to include benchmark dependencies/modules
, configBenchmarks = toFlag True
}
let initCfgFlags' = stackifyFlags initCfgFlags mbStack
cfgFlags <- flip execStateT initCfgFlags' $ do
let sandboxConfig = takeDirectory path </> "cabal.sandbox.config"
exists <- lift $ doesFileExist sandboxConfig
when (exists) $ do
sandboxPackageDb <- lift $ getSandboxPackageDB sandboxConfig
modify $ \x -> x { configPackageDBs = [Just sandboxPackageDb] }
let cmdUI = configureCommand programCfg
case commandParseArgs cmdUI True opts of
CommandReadyToGo (modFlags, _) -> modify modFlags
CommandErrors (e:_) -> error e
_ -> return ()
localBuildInfo <- configure (genPkgDescr, emptyHookedBuildInfo) cfgFlags
let pkgDescr = localPkgDescr localBuildInfo
let baseDir = fst . splitFileName $ path
case getGhcVersion localBuildInfo of
Nothing -> return $ Left "GHC is not configured"
#if __GLASGOW_HASKELL__ >= 709
Just _ -> do
let mbLibName = pkgLibName pkgDescr
let ghcOpts' = foldl' mappend mempty $ map (getComponentGhcOptions localBuildInfo) $ flip allComponentsBy (\c -> c) . localPkgDescr $ localBuildInfo
-- FIX bug in GhcOptions' `mappend`
ghcOpts = ghcOpts' { ghcOptExtra = overNubListR (filter (/= "-Werror")) $ ghcOptExtra ghcOpts'
, ghcOptPackageDBs = sort $ nub (ghcOptPackageDBs ghcOpts')
, ghcOptPackages = overNubListR (filter (\(_, pkgId, _) -> Just (pkgName pkgId) /= mbLibName)) $ (ghcOptPackages ghcOpts')
, ghcOptSourcePath = overNubListR (map (baseDir </>)) (ghcOptSourcePath ghcOpts')
}
putStrLn "configuring"
(ghcInfo,_,_) <- GHC.configure silent Nothing Nothing defaultProgramConfiguration
return $ Right $ renderGhcOptions ghcInfo ghcOpts
#else
Just ghcVersion -> do
let mbLibName = pkgLibName pkgDescr
let ghcOpts' = foldl' mappend mempty $ map (getComponentGhcOptions localBuildInfo) $ flip allComponentsBy (\c -> c) . localPkgDescr $ localBuildInfo
ghcOpts = ghcOpts' { ghcOptExtra = filter (/= "-Werror") $ nub $ ghcOptExtra ghcOpts'
, ghcOptPackages = filter (\(_, pkgId) -> Just (pkgName pkgId) /= mbLibName) $ nub (ghcOptPackages ghcOpts')
, ghcOptSourcePath = map (baseDir </>) (ghcOptSourcePath ghcOpts')
}
return $ Right $ renderGhcOptions ghcVersion ghcOpts
#endif
-- returns the right 'dist' directory in the case of a sandbox
getDistDir = do
let dir = takeDirectory path </> "dist"
contents <- getDirectoryContents dir
return $ case find ("dist-sandbox-" `isPrefixOf`) contents of
Just sbdir -> dir </> sbdir
Nothing -> dir
pkgLibName :: PackageDescription -> Maybe PackageName
pkgLibName pkgDescr = if hasLibrary pkgDescr
then Just $ pkgName . package $ pkgDescr
else Nothing
hasLibrary :: PackageDescription -> Bool
hasLibrary = maybe False (\_ -> True) . library
getComponentGhcOptions :: LocalBuildInfo -> Component -> GhcOptions
getComponentGhcOptions lbi comp =
componentGhcOptions silent lbi bi clbi (buildDir lbi)
where bi = componentBuildInfo comp
clbi = getComponentLocalBuildInfo lbi (componentName comp)
getGhcVersion :: LocalBuildInfo -> Maybe Version
getGhcVersion lbi = let db = withPrograms lbi
in do ghc <- lookupProgram (simpleProgram "ghc") db
programVersion ghc
getSandboxPackageDB :: FilePath -> IO PackageDB
getSandboxPackageDB sandboxPath = do
contents <- readFile sandboxPath
return $ SpecificPackageDB $ extractValue . parse $ contents
where
pkgDbKey = "package-db:"
parse = head . filter (pkgDbKey `isPrefixOf`) . lines
extractValue = fst . break isSpace . dropWhile isSpace . drop (length pkgDbKey)
findCabalFile :: FilePath -> IO (Maybe FilePath)
findCabalFile dir = do
allFiles <- getDirectoryContents dir
let mbCabalFile = find (isCabalFile) allFiles
case mbCabalFile of
Just cabalFile -> return $ Just $ dir </> cabalFile
Nothing ->
let parentDir = takeDirectory dir
in if parentDir == dir
then return Nothing
else findCabalFile parentDir
where
isCabalFile :: FilePath -> Bool
isCabalFile path = cabalExtension `isSuffixOf` path
&& length path > length cabalExtension
where cabalExtension = ".cabal"
# else
getPackageGhcOpts :: FilePath -> [String] -> IO (Either String [String])
getPackageGhcOpts _ _ = return $ Right []
findCabalFile :: FilePath -> IO (Maybe FilePath)
findCabalFile _ = return Nothing
#endif
| schell/hdevtools | src/Cabal.hs | mit | 11,366 | 0 | 28 | 2,978 | 2,292 | 1,229 | 1,063 | 8 | 1 |
module Ternary.Examples where
import Ternary.Core.Digit
import Ternary.List.Exact
import Ternary.List.FiniteExact
import Ternary.List.FiniteExactNum
import Ternary.Util.Triad
x = Exact [P1,O0,undefined] 0
y = Exact [P2,P2,undefined] 0
z = Exact (cycle allT2) 0
-- x+x, x*x, y*y
z2 = z * z
as = streamDigits z2
slow = take 400 as
fast = take 401 as -- incremental computation
a,b :: Integer
a = 5458086354678022563255767332088955423567
b = 686633208503168754901134087608765434678992253678865
c,d :: Exact
c = fromInteger a
d = fromInteger b
trunc :: FiniteExact
trunc = takeFinite 200 (c*d)
cd :: Triad
cd = finiteExactToTriad trunc
check = let u = a*b
v = triadNumerator cd
in print u >> print v >> print (u == v)
| jeroennoels/exact-real | test/Ternary/Examples.hs | mit | 773 | 0 | 10 | 170 | 256 | 143 | 113 | 26 | 1 |
module Data.Dar.Put
(
putDARFile, putDARHeader, putINDEXHeader, calcINDEXHeader,
putINDEXNode, putDATANode
) where
import Data.Binary.Put
import qualified Data.ByteString.Lazy.Char8 as BC
import Data.Word
import Data.Dar.Types
--
-- **************************************************
-- Functions for putting DataNodes into DAR a file and than into a ByteStrings.
putDARFile :: [DataNode] -> BC.ByteString
putDARFile = runPut . putDARFile'
putDARFile' :: [DataNode] -> Put
putDARFile' nodes = do
let index = calcINDEXHeader
(map identifyDNode nodes)
(map identifyDNodeLen nodes)
(map contentDNodeLen nodes)
putDARHeader . fromIntegral . length $ nodes
putINDEXHeader index
putDATAHeader nodes
putDARHeader :: Word64 -> Put
putDARHeader nodeN = do
let header = headerDAR defaultDar
putLazyByteString $ identifyDAR header -- 3 bytes that identify this as a DAR file.
putWord8 $ majorV header -- Major Version of the DAR file.
putWord8 $ minorV header -- Minor Version of the DAR file.
putWord64le nodeN -- Number of DataNodes in the DAR file.
putWord32le 0 -- Checksum (not used).
putINDEXHeader :: IndexHeader -> Put
putINDEXHeader iNodes = do
-- let nSizeAndName = reverse . fst . foldl (\(acc,p) (i,x) -> ((i,p):acc, p+x)) ([],0)
-- $ zip
-- (map (\x -> (identifyDNodeLen x, identifyDNode x) ) nodes)
-- (map getsize nodes)
-- getsize x = 4 + (fromIntegral $ identifyDNodeLen x)
-- + 8 + (fromIntegral $ contentDNodeLen x)
-- -- The size (everything preceding DataNode block)
-- -- the DAR header (17 bytes), ".index" (6 bytes), ".data" (5 bytes),
-- --
-- -- offset (8 bytes)). Total 28 bytes + ()
-- preSize = 28 + (sum $ map ((+) 12 . fromIntegral . identifyDNodeLen) nodes)
putLazyByteString $ identifyINDEX iNodes
mapM_ putINDEXNode $ indexNodes iNodes
-- Calculates the index and offsets for DataNodes
calcINDEXHeader :: [BC.ByteString] -> [Word32] -> [Word64] -> IndexHeader
calcINDEXHeader names nameLens dataSizes = IndexH
(identifyINDEX $ indexDAR defaultDar)
iNodes
where -- Offsets needs to know about the header for each data Node
-- 4 bytes, nameLen bytes, 8 bytes
sizeBeforeData = 28 + (sum $ map ((+) 12 . fromIntegral) nameLens)
offsets = reverse . fst $
foldr (\off (acc,prevOff) -> (prevOff:acc, prevOff + off))
([], sizeBeforeData) dataSizes
iNodes = zipWith3 IndexN nameLens names offsets
putINDEXNode :: IndexNode -> Put
putINDEXNode iNode = do
putWord32le $ identifyINodeLen iNode
putLazyByteString $ identifyINode iNode
putWord64le $ nodePosition iNode
putDATAHeader :: [DataNode] -> Put
putDATAHeader nodes = do
putLazyByteString . identifyDATA $ dataDAR defaultDar -- 5 bytes start data block.
mapM_ putDATANode nodes
putDATANode :: DataNode -> Put
putDATANode node = do
-- Length of the DataNode's name in bytes.
putWord32le . fromIntegral $ identifyDNodeLen node
-- The DataNode's name.
putLazyByteString $ identifyDNode node
-- Length of the DataNode's data in bytes.
putWord64le . fromIntegral $ contentDNodeLen node
-- The DataNode's data.
putLazyByteString $ contentDNode node
| blockynight/hdarchiver | Data/Dar/Put.hs | mit | 3,524 | 0 | 13 | 960 | 618 | 324 | 294 | 55 | 1 |
{-
Parser.hs: Parser for the Flounder interface definition language
Part of Flounder: a strawman device definition DSL for Barrelfish
Copyright (c) 2009, ETH Zurich.
All rights reserved.
This file is distributed under the terms in the attached LICENSE file.
If you do not find this file, copies can be found by writing to:
ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group.
-}
module Parser where
import Syntax
import Prelude
import qualified System
import Text.ParserCombinators.Parsec as Parsec
import Text.ParserCombinators.Parsec.Expr
import Text.ParserCombinators.Parsec.Pos
import qualified Text.ParserCombinators.Parsec.Token as P
import Text.ParserCombinators.Parsec.Language( javaStyle )
import Char
import Numeric
import Data.List
import Text.Printf
parse_intf predefDecls filename = parseFromFile (intffile predefDecls) filename
parse_include predefDecls filename = parseFromFile (includefile predefDecls) filename
lexer = P.makeTokenParser (javaStyle
{ P.reservedNames = [ "interface",
"message",
"rpc",
"in",
"out"
]
, P.reservedOpNames = ["*","/","+","-"]
, P.commentStart = "/*"
, P.commentEnd = "*/"
})
whiteSpace = P.whiteSpace lexer
reserved = P.reserved lexer
identifier = P.identifier lexer
stringLit = P.stringLiteral lexer
comma = P.comma lexer
commaSep = P.commaSep lexer
commaSep1 = P.commaSep1 lexer
parens = P.parens lexer
braces = P.braces lexer
squares = P.squares lexer
semiSep = P.semiSep lexer
symbol = P.symbol lexer
natural = P.natural lexer
builtinTypes = map show [UInt8 ..] ++ ["int"] -- int is legacy -AB
-- identifyBuiltin :: [(String, Declaration)] -> String -> TypeRef
identifyBuiltin typeDcls typeName =
do {
if typeName `elem` builtinTypes then
return $ Builtin $ (read typeName::TypeBuiltin)
else
case typeName `lookup` typeDcls of
Just (Typedef (TAliasT new orig)) -> return $ TypeAlias new orig
Just _ -> return $ TypeVar typeName
Nothing ->
do {
; pos <- getPosition
-- This is ugly, I agree:
; return $ error ("Use of undeclared type '" ++ typeName ++ "' in "
++ show (sourceName pos) ++ " at l. "
++ show (sourceLine pos) ++ " col. "
++ show (sourceColumn pos))
}
}
intffile predefDecls = do { whiteSpace
; i <- iface predefDecls
; return i
}
includefile predefDecls = do { whiteSpace
; typeDecls <- typeDeclaration predefDecls
; return typeDecls
}
iface predefDecls = do { reserved "interface"
; name <- identifier
; descr <- option name stringLit
; decls <- braces $ do {
; typeDecls <- typeDeclaration predefDecls
; msgDecls <- many1 $ mesg typeDecls
; return ((map snd typeDecls) ++ msgDecls)
}
; symbol ";" <?> " ';' missing from end of " ++ name ++ " interface specification"
; return (Interface name (Just descr) decls)
}
typeDeclaration typeDcls = do {
; decl <- try (do {
; x <- transparentAlias
; return $ Just x
})
<|> try (do {
; x <- typedefinition typeDcls
; return $ Just x
})
<|> return Nothing
; case decl of
Nothing -> return typeDcls
Just x -> typeDeclaration (x : typeDcls)
}
mesg typeDcls = do { bckArgs <- many backendParams
; def <- msg typeDcls bckArgs <|> rpc typeDcls bckArgs
; return $ Messagedef def
}
msg typeDcls bckArgs = do { t <- msgtype
; i <- identifier
; a <- parens $ commaSep (marg typeDcls)
; symbol ";"
; return $ Message t i a bckArgs
}
rpc typeDcls bckArgs= do { _ <- rpctype
; i <- identifier
; a <- parens $ commaSep (rpcArg typeDcls)
; symbol ";"
; return $ RPC i a bckArgs
}
rpctype = do { reserved "rpc"
; return () }
rpcArg typeDcls = do { reserved "in"
; Arg b n <- marg typeDcls
; return $ RPCArgIn b n
}
<|> do { reserved "out"
; Arg b n <- marg typeDcls
; return $ RPCArgOut b n
}
backendParams = do { char '@'
; i <- identifier
; p <- parens $ commaSep backendParam
; return (i, p)
}
backendParam = do { name <- identifier
; symbol "="
; do { num <- natural ; return $ (name, BackendInt num) }
<|> do { arg <- identifier ; return $ (name, BackendMsgArg arg) }
}
msgtype = do { reserved "message"; return MMessage }
<|> do { reserved "call"; return MCall }
<|> do { reserved "response"; return MResponse }
marg typeDcls = try (marg_array typeDcls)
<|> (marg_simple typeDcls)
marg_simple typeDcls = do { t <- identifier
; n <- identifier
; b <- identifyBuiltin typeDcls t
; return (Arg b (Name n))
}
marg_array typeDcls = do { t <- identifier
; n <- identifier
; symbol "["
; l <- identifier
; symbol "]"
; bType <- identifyBuiltin typeDcls t
; return (Arg bType (DynamicArray n l))
}
transparentAlias = do { whiteSpace
; reserved "alias"
; newType <- identifier
; originType <- identifier
; symbol ";"
; return (newType, Typedef $ TAliasT newType
(read originType::TypeBuiltin))
}
typedefinition typeDcls = do { whiteSpace
; reserved "typedef"
; (name, typeDef) <- typedef_body typeDcls
; symbol ";"
; return (name, Typedef typeDef)
}
typedef_body typeDcls = try (struct_typedef typeDcls)
<|> try (array_typedef typeDcls)
<|> try enum_typedef
<|> (alias_typedef typeDcls)
struct_typedef typeDcls = do { reserved "struct"
; f <- braces $ many1 (struct_field typeDcls)
; i <- identifier
; return (i, (TStruct i f))
}
struct_field typeDcls = do { t <- identifier
; i <- identifier
; symbol ";"
; b <- identifyBuiltin typeDcls t
; return (TStructField b i)
}
array_typedef typeDcls = do { t <- identifier
; i <- identifier
; symbol "["
; sz <- integer
; symbol "]"
; b <- identifyBuiltin typeDcls t
; return (i, (TArray b i sz))
}
enum_typedef = do { reserved "enum"
; v <- braces $ commaSep1 identifier
; i <- identifier
; return (i, (TEnum i v))
}
alias_typedef typeDcls = do { t <- identifier
; i <- identifier
; b <- identifyBuiltin typeDcls t
; return (i, (TAlias i b))
}
integer = P.integer lexer
| modeswitch/barrelfish | tools/flounder/Parser.hs | mit | 9,156 | 5 | 23 | 4,501 | 2,037 | 1,033 | 1,004 | 164 | 4 |
module Fitness where
-- | Conversion helper
toFloat :: Int -> Float
toFloat = fromIntegral . toInteger
fitness :: Float -> Int -> Int -> Float
fitness coverage towersUsed _ = if k == 0 then 0 else coverage / k
where
k = toFloat towersUsed | NCrashed/radio-problem | scripts/InvalidFitness2.hs | mit | 246 | 0 | 7 | 53 | 78 | 43 | 35 | 6 | 2 |
-- Copyright 2015 Mitchell Kember. Subject to the MIT License.
-- Project Euler: Problem 15
-- Lattice paths
module Problem15 where
import Common (combinations)
routes :: Int -> Int -> Int
routes w h = fromIntegral result
where
ww = toInteger w
hh = toInteger h
result = combinations ww (ww + hh)
solve :: Int
solve = routes 20 20
| mk12/euler | haskell/Problem15.hs | mit | 349 | 0 | 9 | 79 | 91 | 50 | 41 | 9 | 1 |
module Storyfragment where
import Data.Char
isNotAlpha = not . isAlpha
hasAlpha = any isAlpha
nonPunctuationError xs = error (show xs ++ " is not all punctuation")
nonLetterError x = error (show x ++ " is not a letter")
data Fragment = Fragment String Char
deriving (Show)
fragment punctuation letter | isNotAlpha letter = nonLetterError letter
| hasAlpha punctuation = nonPunctuationError punctuation
| otherwise = Fragment punctuation letter
data Story = Tail String | Fragment :-> Story
deriving (Show)
infixr :->
story :: String -> Story
story "" = Tail ""
story (x:"") | isAlpha x = (Fragment "" x) :-> (Tail "")
| otherwise = Tail [x]
story (x:xs) = story [x] +++ story xs
(+++) :: Story -> Story -> Story
Tail xs +++ Tail ys | hasAlpha xs = nonPunctuationError xs
| hasAlpha ys = nonPunctuationError ys
| otherwise = Tail (xs ++ ys)
Tail xs +++ (Fragment ys y :-> z) | hasAlpha xs = nonPunctuationError xs
| hasAlpha ys = nonPunctuationError ys
| isNotAlpha y = nonLetterError y
| otherwise = (Fragment (xs ++ ys) y) :-> z
(x :-> y) +++ z = x :-> (y +++ z)
reverseStory l = rev l (Tail "")
where
rev (Fragment xs x :-> ys) (Tail "") = rev (Fragment "" x :-> ys) (Tail (reverse xs))
rev (Fragment xs x :-> ys) (Fragment "" a :-> b) = rev (Fragment "" x :-> ys) (Fragment (reverse xs) a :-> b)
rev (x :-> ys) a = rev ys (x :-> a)
rev (Tail xs) (Fragment "" a :-> b) = rev (Tail "") (Fragment (reverse xs) a :-> b)
rev (Tail "") a = a
toString :: Story -> String
toString (Tail xs) = xs
toString (Fragment xs x :-> y) = xs ++ [x] ++ (toString y)
symbols :: Story -> String
symbols (Tail xs) = ""
symbols (Fragment xs x :-> y) = (toLower x):(symbols y)
| akaihola/palindromi-haskell | src/Storyfragment.hs | mit | 1,925 | 0 | 12 | 590 | 839 | 408 | 431 | 40 | 5 |
module Items where
import Data.Map (adjust)
import Properties
data Item = Item { itemName :: String,
itemInfo :: Properties,
itemActions :: [String]
} deriving (Eq)
instance Show Item where
show (Item name info actions) = name
class Inv a where
findItem :: String -> a -> Maybe Item
removeItem :: Item -> a -> a
addItem :: Item -> a -> a
-- | Change a property of an item.
changeItem :: String -- ^ Name of the property to be changed
-> (String -> String) -- ^ A function to change the property
-> Item -- The item to change
-> Item -- The resulting item
changeItem string f item =
item { itemInfo = adjust f string (itemInfo item) }
-- | Use it this way:
-- | changeItem "attack" (show $ (* 3) read) sword
-- | where sword is a named item representing a sword with a property called
-- "attack". Using changeItem this way will multiply that property by 3.
-- More simply, one can also supply a new value instead of a function, simply
-- by using const:
-- changeItem "attack" (const "15") sword
-- Now the sword's "attack" property is simply "15".
| emhoracek/explora | library/Items.hs | gpl-2.0 | 1,175 | 0 | 9 | 325 | 201 | 116 | 85 | 19 | 1 |
{-# LANGUAGE DeriveDataTypeable, GeneralizedNewtypeDeriving #-}
-- Copyright (C) 2008 JP Bernardy
module Yi.TextCompletion (
-- * Word completion
wordComplete,
wordComplete',
wordCompleteString,
wordCompleteString',
mkWordComplete,
resetComplete,
completeWordB,
) where
import Prelude ()
import Yi.Completion
import Data.Char
import Data.List (filter, drop, isPrefixOf, reverse, findIndex, length, groupBy)
import Data.Maybe
import Yi.Core
-- ---------------------------------------------------------------------
-- | Word completion
--
-- when doing keyword completion, we need to keep track of the word
-- we're trying to complete.
newtype Completion = Completion
-- Point -- beginning of the thing we try to complete
[String] -- the list of all possible things we can complete to.
-- (this seems very inefficient; but we use lazyness to our advantage)
deriving Typeable
-- TODO: put this in keymap state instead
instance Initializable Completion where
initial = Completion []
-- | Switch out of completion mode.
resetComplete :: EditorM ()
resetComplete = setDynamic (Completion [])
-- | Try to complete the current word with occurences found elsewhere in the
-- editor. Further calls try other options.
mkWordComplete :: YiM String -> (String -> YiM [String]) -> ([String] -> YiM () ) -> (String -> String -> Bool) -> YiM String
mkWordComplete extractFn sourceFn msgFn predMatch = do
Completion complList <- withEditor getDynamic
case complList of
(x:xs) -> do -- more alternatives, use them.
msgFn (x:xs)
withEditor $ setDynamic (Completion xs)
return x
[] -> do -- no alternatives, build them.
w <- extractFn
ws <- sourceFn w
withEditor $ setDynamic (Completion $ (nubSet $ filter (matches w) ws) ++ [w])
-- We put 'w' back at the end so we go back to it after seeing
-- all possibilities.
mkWordComplete extractFn sourceFn msgFn predMatch -- to pick the 1st possibility.
where matches x y = x `predMatch` y && x/=y
wordCompleteString' :: Bool -> YiM String
wordCompleteString' caseSensitive = mkWordComplete
(withEditor $ withBuffer0 $ do readRegionB =<< regionOfPartB unitWord Backward)
(\_ -> withEditor wordsForCompletion)
(\_ -> return ())
(mkIsPrefixOf caseSensitive)
wordCompleteString :: YiM String
wordCompleteString = wordCompleteString' True
wordComplete' :: Bool -> YiM ()
wordComplete' caseSensitive = do
x <- wordCompleteString' caseSensitive
withEditor $ withBuffer0 $ flip replaceRegionB x =<< regionOfPartB unitWord Backward
wordComplete :: YiM ()
wordComplete = wordComplete' True
----------------------------
-- Alternative Word Completion
{-
'completeWordB' is an alternative to 'wordCompleteB'.
'completeWordB' offers a slightly different interface. The user
completes the word using the mini-buffer in the same way a user
completes a buffer or file name when switching buffers or opening a
file. This means that it never guesses and completes only as much as
it can without guessing.
I think there is room for both approaches. The 'wordCompleteB' approach
which just guesses the completion from a list of possible completion
and then re-hitting the key-binding will cause it to guess again.
I think this is very nice for things such as completing a word within
a TeX-buffer. However using the mini-buffer might be nicer when we allow
syntax knowledge to allow completion for example we may complete from
a Hoogle database.
-}
completeWordB :: EditorM ()
completeWordB = veryQuickCompleteWord
{-
This is a very quick and dirty way to complete the current word.
It works in a similar way to the completion of words in the mini-buffer
it uses the message buffer to give simple feedback such as,
"Matches:" and "Complete, but not unique:"
It is by no means perfect but it's also not bad, pretty usable.
-}
veryQuickCompleteWord :: EditorM ()
veryQuickCompleteWord =
do (curWord, curWords) <- withBuffer0 wordsAndCurrentWord
let match :: String -> Maybe String
match x = if (isPrefixOf curWord x) && (x /= curWord) then Just x else Nothing
preText <- completeInList curWord match curWords
if curWord == ""
then printMsg "No word to complete"
else withBuffer0 $ insertN $ drop (length curWord) preText
wordsAndCurrentWord :: BufferM (String, [String])
wordsAndCurrentWord =
do curText <- readRegionB =<< regionOfB Document
curWord <- readRegionB =<< regionOfPartB unitWord Backward
return (curWord, words' curText)
wordsForCompletionInBuffer :: BufferM [String]
wordsForCompletionInBuffer = do
above <- readRegionB =<< regionOfPartB Document Backward
below <- readRegionB =<< regionOfPartB Document Forward
return (reverse (words' above) ++ words' below)
wordsForCompletion :: EditorM [String]
wordsForCompletion = do
(_b:bs) <- fmap bkey <$> getBufferStack
w0 <- withBuffer0 $ wordsForCompletionInBuffer
contents <- forM bs $ \b->withGivenBuffer0 b elemsB
return $ w0 ++ concatMap words' contents
words' :: String -> [String]
words' = filter (not . isNothing . charClass . head) . groupBy ((==) `on` charClass)
charClass :: Char -> Maybe Int
charClass c = findIndex (generalCategory c `elem`)
[[UppercaseLetter, LowercaseLetter, TitlecaseLetter, ModifierLetter, OtherLetter,
ConnectorPunctuation,
NonSpacingMark, SpacingCombiningMark, EnclosingMark, DecimalNumber, LetterNumber, OtherNumber],
[MathSymbol, CurrencySymbol, ModifierSymbol, OtherSymbol]
]
{-
Finally obviously we wish to have a much more sophisticated completeword.
One which spawns a mini-buffer and allows searching in Hoogle databases
or in other files etc.
-}
| codemac/yi-editor | src/Yi/TextCompletion.hs | gpl-2.0 | 6,052 | 0 | 21 | 1,388 | 1,113 | 584 | 529 | 85 | 3 |
module CountingChange where
import Data.List
countchange :: Int -> [Int] -> Int
countchange m c = countChange m $ (reverse . sort) c
countChange :: Int -> [Int] -> Int
countChange _ [] = 0
countChange 0 _ = 1
countChange m c@(x:xs) = if m < 0
then 0
else countChange m xs + countChange (m - x) c
-- *CountingChange> countchange 300 [5,10,20,50,100,200,500] -- 1022
-- 1022
-- *CountingChange> countchange 301 [5,10,20,50,100,200,500] -- 1022
-- 0
-- *CountingChange> countchange 4 [5,10,20,50,100,200,500] -- 1022
-- 0
-- *CountingChange> countchange 4 [1,2] -- 1022
-- 3
-- *CountingChange> countchange 4 [] -- 1022
-- 0
-- *CountingChange> countchange 0 [1,2] -- 1022
-- 1
-- *CountingChange> countchange 100 [50,25,10,5,1]
-- 292
| ardumont/haskell-lab | src/CountingChange.hs | gpl-2.0 | 800 | 0 | 9 | 188 | 157 | 90 | 67 | 10 | 2 |
{-# LANGUAGE OverloadedStrings #-}
module Ssh.Cryption.Tests (
tests
) where
import Test.Framework
import Test.QuickCheck
import qualified Test.HUnit as H
import Test.Framework.Providers.HUnit
import Test.Framework.Providers.QuickCheck2
import Data.Word
import Control.Monad.State
import qualified Data.ByteString.Lazy as B
import Ssh.Cryption
import Ssh.String
import Ssh.Debug
encryptThenDecryptTest enc dec ks plain key iv =
let encrypted = evalState (enc ks key plain) $ CryptionInfo iv
decrypted = evalState (dec ks key encrypted) $ CryptionInfo iv
in (length key >= 16 && length iv >= 16 && length plain `mod` 16 == 0) ==> plain == decrypted
encryptThenDecrypt name enc dec keysizes =
map (\ks -> testProperty (name ++ show ks ++ ": Encrypt then Decrypt == plaintext") $ encryptThenDecryptTest enc dec ks) keysizes
tests :: [Test]
tests = concat
[
encryptThenDecrypt "AES CBC" cbcAesEncrypt cbcAesDecrypt [ 256 ]
, encryptThenDecrypt "AES CTR" ctrAesEncrypt ctrAesDecrypt [ 256 ]
]
| bcoppens/HaskellSshClient | tests/Ssh/Cryption/Tests.hs | gpl-3.0 | 1,044 | 0 | 16 | 196 | 301 | 164 | 137 | 25 | 1 |
import Graphics.UI.GLUT
import Control.Monad.Cont
import Data.IORef(IORef)
import qualified Data.IORef as IORef
import qualified Foreign.C.Types
import LiveSource
newIORef x = lift (IORef.newIORef x)
writeIORef x y = lift (IORef.writeIORef x y)
readIORef x = lift (IORef.readIORef x)
modifyIORef x y = lift (IORef.modifyIORef x y)
type GLFloat = Foreign.C.Types.CFloat
type ContIO r a = ContT r IO a
defines :: ContIO r (IORef.IORef (() -> ContIO GLFloat GLFloat), ContIO GLFloat GLFloat)
defines = do
contref <- newIORef undefined
let test = do
i <- newIORef 0
callCC (\k -> writeIORef contref k)
modifyIORef i (+ 1)
readIORef i
return (contref, test)
run :: ContIO a a -> IO a
run m = runContT m return
main = do
(contref, test) <- run defines
run test >>= print
getArgsAndInitialize
createAWindow "points"
mainLoop
createAWindow windowName = do
(contref, test) <- run defines
run test
initialDisplayMode $= [ DoubleBuffered, RGBAMode, WithDepthBuffer,
WithAlphaComponent ]
createWindow windowName
displayCallback $= display contref
idleCallback $= Just (display contref)
axis = (Vector3 1 1 (1::GLfloat))
list = [-0.5,-0.45..0.5]
display thingy = do
clear [ColorBuffer , DepthBuffer]
loadIdentity
x1 <- run (readIORef thingy >>= \k -> k())
maybeFunction <- loadAndRunFilePrintingErrorMessageUnsafeWithCache "live_code.hs"
case maybeFunction of
(Just function,cached) -> function Nothing
_ -> return ()
{-
renderPrimitive Points $
sequence $ interleave rainbow grid
-}
swapBuffers
flush
{-
interleave = (concat .) . zipWith (\x y-> [x,y])
rainbow = cycle $ liftM3 to_color colors colors colors
to_color x y z = do currentColor $= Color4 x y z 1
colors = [0,0.25..1]
grid = do (x,y,z) <- liftM3 (,,) list list list
return (vertex (Vertex3 (x::GLfloat) y z))
-}
| xpika/live-source | examples/live-glut-test/example.hs | gpl-3.0 | 1,943 | 0 | 15 | 448 | 572 | 284 | 288 | 49 | 2 |
{-# LANGUAGE StandaloneDeriving, FlexibleInstances #-}
module Pseudoterminal w3here
import System.Posix.Pty
import System.Process
import Data.ByteString.Char8 (pack)
-- | Spawn in my regular env
spawnWithEnv :: FilePath -> [String] ->
(Int, Int) -> IO (Pty, ProcessHandle)
spawnWithEnv = spawnWithPty Nothing True
deriving instance Show BaudRate
-- deriving instance Show (Either [PtyControlCode] ByteString)
data Attributes = Attributes { inSpeed :: BaudRate
, outSpeed :: BaudRate
, bitsInByte :: Int
, inTime :: Int
, minIn :: Int } deriving Show
-- , termMode :: TerminalMode}
getAttributes :: TerminalAttributes -> Attributes
getAttributes = Attributes <$>
inputSpeed <*>
outputSpeed <*>
bitsPerByte <*>
inputTime <*>
minInput
main :: IO ()
main = do
(pty, shellHandle) <-
spawnWithEnv "bash" [] (20, 10)
getTerminalName pty >>= print
getSlaveTerminalName pty >>= print
tryReadPty pty >>= print
writePty pty $ pack "ls\n"
tryReadPty pty >>= print
tryReadPty pty >>= print
tryReadPty pty >>= print
tryReadPty pty >>= print
tryReadPty pty >>= print
tryReadPty pty >>= print
tryReadPty pty >>= print
attrs <- getTerminalAttributes pty >>= return . getAttributes
print $ attrs
| pscollins/Termonoid | src/Pseudoterm.hs | gpl-3.0 | 1,460 | 1 | 10 | 453 | 343 | 174 | 169 | -1 | -1 |
module Format where
import System.Console.ANSI
import Data.List
import Data.Time.Clock (UTCTime)
import qualified Data.Time.Format as F
import Text.Printf (printf)
import WeatherParse
import WeatherFetch
-- how do we want to display something?
data OutputFormat
= Plaintext
| Pango
| ANSI
deriving (Show, Read, Eq)
-- format a forecast object
formatForecast :: OutputFormat -> Unit -> Forecast -> String
formatForecast outFormat unit (Forecast c fD) =
formatCity outFormat c ++ concatMap (formatWeather outFormat unit) fD
-- format a city object
formatCity :: OutputFormat -> WeatherParse.City -> String
formatCity outFormat (WeatherParse.City n c) =
format outFormat "Weather for " ++ n ++ ", " ++ c ++ "\n"
-- format a weather object
formatWeather :: OutputFormat -> Unit -> Weather -> String
formatWeather outFormat u w = intercalate "\n" ls
where ls = [ fF (formatTime (time w) ++ " - " ++ descs ++ " ") ++
fF ("[" ++ show (clouds w) ++ "% clouds]")
, fF (fTU (temp w) ++ " (" ++ fTU (tempMin w) ++
"/" ++ fTU (tempMax w) ++ ")")
, fF (show (pressure w) ++ "hPa, " ++ show (humidity w) ++
"% humidity" ++ rain'' ++ snow'')
, fF ("Wind from " ++ show (windDir w) ++ "°, at " ++
fSU (windSpeed w))
, "\n"
]
descs = unwords $ map (\(Description s) -> s) (description w)
fF = format outFormat
fTU = formatTemp u
fSU = formatSpeed u
rain' = formatMm (rain w)
rain''
| rain' /= "" = rain' ++ " rain"
| otherwise = ""
snow' = formatMm (snow w)
snow''
| snow' /= "" = snow' ++ " snow"
| otherwise = ""
-- format a temperature according to unit system
formatTemp :: Unit -> Double -> String
formatTemp u v = show v ++ f u
where f Metric = "°C"
f Imperial = "°F"
f Default = "°K"
-- format a windspeed according to unit system
formatSpeed :: Unit -> Double -> String
formatSpeed u v = show v ++ f u
where f Imperial = "mph"
f _ = "m/s"
-- format a rain / snow value, in millimeters
formatMm :: Precipitation -> String
formatMm (Precipitation (Just d)) = printf ", %.2f" d ++ "mm"
formatMm _ = ""
-- format a timestamp as saved in a Weather object
formatTime :: Maybe UTCTime -> String
formatTime = maybe "" (F.formatTime F.defaultTimeLocale "%A, %d.%m.%Y %H:%M")
-- format a string according to args:
format :: OutputFormat -> String -> String
format Plaintext s = s
format Pango s
| head s == '[' = yellow
| "hPa" `isInfixOf` s = red
| otherwise = lightBlue
where cS = "</span>"
lightBlue = "<span color=\"lightblue\">" ++ s ++ "</span>"
red = "<span color=\"red\">" ++ s ++ cS
yellow = "<span color=\"yellow\">" ++ s ++ cS
format ANSI s
| head s == '[' = yellow
| "hPa" `isInfixOf` s = red
| otherwise = lightBlue
where cS = setSGRCode []
lightBlue = setSGRCode
[SetColor Foreground Vivid Cyan] ++ s ++ cS
red = setSGRCode
[SetColor Foreground Vivid Red] ++ s ++ cS
yellow = setSGRCode
[SetColor Foreground Vivid Yellow] ++ s ++ cS
| ibabushkin/hweather | Format.hs | gpl-3.0 | 3,342 | 0 | 17 | 1,032 | 1,031 | 526 | 505 | 77 | 3 |
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.AndroidPublisher.Edits.APKListings.Get
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Fetches the APK-specific localized listing for a specified APK and
-- language code.
--
-- /See:/ <https://developers.google.com/android-publisher Google Play Developer API Reference> for @androidpublisher.edits.apklistings.get@.
module Network.Google.Resource.AndroidPublisher.Edits.APKListings.Get
(
-- * REST Resource
EditsAPKListingsGetResource
-- * Creating a Request
, editsAPKListingsGet
, EditsAPKListingsGet
-- * Request Lenses
, eapklgPackageName
, eapklgAPKVersionCode
, eapklgLanguage
, eapklgEditId
) where
import Network.Google.AndroidPublisher.Types
import Network.Google.Prelude
-- | A resource alias for @androidpublisher.edits.apklistings.get@ method which the
-- 'EditsAPKListingsGet' request conforms to.
type EditsAPKListingsGetResource =
"androidpublisher" :>
"v2" :>
"applications" :>
Capture "packageName" Text :>
"edits" :>
Capture "editId" Text :>
"apks" :>
Capture "apkVersionCode" (Textual Int32) :>
"listings" :>
Capture "language" Text :>
QueryParam "alt" AltJSON :> Get '[JSON] APKListing
-- | Fetches the APK-specific localized listing for a specified APK and
-- language code.
--
-- /See:/ 'editsAPKListingsGet' smart constructor.
data EditsAPKListingsGet = EditsAPKListingsGet'
{ _eapklgPackageName :: !Text
, _eapklgAPKVersionCode :: !(Textual Int32)
, _eapklgLanguage :: !Text
, _eapklgEditId :: !Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'EditsAPKListingsGet' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eapklgPackageName'
--
-- * 'eapklgAPKVersionCode'
--
-- * 'eapklgLanguage'
--
-- * 'eapklgEditId'
editsAPKListingsGet
:: Text -- ^ 'eapklgPackageName'
-> Int32 -- ^ 'eapklgAPKVersionCode'
-> Text -- ^ 'eapklgLanguage'
-> Text -- ^ 'eapklgEditId'
-> EditsAPKListingsGet
editsAPKListingsGet pEapklgPackageName_ pEapklgAPKVersionCode_ pEapklgLanguage_ pEapklgEditId_ =
EditsAPKListingsGet'
{ _eapklgPackageName = pEapklgPackageName_
, _eapklgAPKVersionCode = _Coerce # pEapklgAPKVersionCode_
, _eapklgLanguage = pEapklgLanguage_
, _eapklgEditId = pEapklgEditId_
}
-- | Unique identifier for the Android app that is being updated; for
-- example, \"com.spiffygame\".
eapklgPackageName :: Lens' EditsAPKListingsGet Text
eapklgPackageName
= lens _eapklgPackageName
(\ s a -> s{_eapklgPackageName = a})
-- | The APK version code whose APK-specific listings should be read or
-- modified.
eapklgAPKVersionCode :: Lens' EditsAPKListingsGet Int32
eapklgAPKVersionCode
= lens _eapklgAPKVersionCode
(\ s a -> s{_eapklgAPKVersionCode = a})
. _Coerce
-- | The language code (a BCP-47 language tag) of the APK-specific localized
-- listing to read or modify. For example, to select Austrian German, pass
-- \"de-AT\".
eapklgLanguage :: Lens' EditsAPKListingsGet Text
eapklgLanguage
= lens _eapklgLanguage
(\ s a -> s{_eapklgLanguage = a})
-- | Unique identifier for this edit.
eapklgEditId :: Lens' EditsAPKListingsGet Text
eapklgEditId
= lens _eapklgEditId (\ s a -> s{_eapklgEditId = a})
instance GoogleRequest EditsAPKListingsGet where
type Rs EditsAPKListingsGet = APKListing
type Scopes EditsAPKListingsGet =
'["https://www.googleapis.com/auth/androidpublisher"]
requestClient EditsAPKListingsGet'{..}
= go _eapklgPackageName _eapklgEditId
_eapklgAPKVersionCode
_eapklgLanguage
(Just AltJSON)
androidPublisherService
where go
= buildClient
(Proxy :: Proxy EditsAPKListingsGetResource)
mempty
| rueshyna/gogol | gogol-android-publisher/gen/Network/Google/Resource/AndroidPublisher/Edits/APKListings/Get.hs | mpl-2.0 | 4,764 | 0 | 18 | 1,095 | 566 | 336 | 230 | 91 | 1 |
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.BigtableAdmin.Types.Product
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <[email protected]>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
module Network.Google.BigtableAdmin.Types.Product where
import Network.Google.BigtableAdmin.Types.Sum
import Network.Google.Prelude
-- | Unconditionally routes all read\/write requests to a specific cluster.
-- This option preserves read-your-writes consistency but does not improve
-- availability.
--
-- /See:/ 'singleClusterRouting' smart constructor.
data SingleClusterRouting =
SingleClusterRouting'
{ _scrAllowTransactionalWrites :: !(Maybe Bool)
, _scrClusterId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SingleClusterRouting' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'scrAllowTransactionalWrites'
--
-- * 'scrClusterId'
singleClusterRouting
:: SingleClusterRouting
singleClusterRouting =
SingleClusterRouting'
{_scrAllowTransactionalWrites = Nothing, _scrClusterId = Nothing}
-- | Whether or not \`CheckAndMutateRow\` and \`ReadModifyWriteRow\` requests
-- are allowed by this app profile. It is unsafe to send these requests to
-- the same table\/row\/column in multiple clusters.
scrAllowTransactionalWrites :: Lens' SingleClusterRouting (Maybe Bool)
scrAllowTransactionalWrites
= lens _scrAllowTransactionalWrites
(\ s a -> s{_scrAllowTransactionalWrites = a})
-- | The cluster to which read\/write requests should be routed.
scrClusterId :: Lens' SingleClusterRouting (Maybe Text)
scrClusterId
= lens _scrClusterId (\ s a -> s{_scrClusterId = a})
instance FromJSON SingleClusterRouting where
parseJSON
= withObject "SingleClusterRouting"
(\ o ->
SingleClusterRouting' <$>
(o .:? "allowTransactionalWrites") <*>
(o .:? "clusterId"))
instance ToJSON SingleClusterRouting where
toJSON SingleClusterRouting'{..}
= object
(catMaybes
[("allowTransactionalWrites" .=) <$>
_scrAllowTransactionalWrites,
("clusterId" .=) <$> _scrClusterId])
-- | Required. Labels are a flexible and lightweight mechanism for organizing
-- cloud resources into groups that reflect a customer\'s organizational
-- needs and deployment strategies. They can be used to filter resources
-- and aggregate metrics. * Label keys must be between 1 and 63 characters
-- long and must conform to the regular expression:
-- \`\\p{Ll}\\p{Lo}{0,62}\`. * Label values must be between 0 and 63
-- characters long and must conform to the regular expression:
-- \`[\\p{Ll}\\p{Lo}\\p{N}_-]{0,63}\`. * No more than 64 labels can be
-- associated with a given resource. * Keys and values must both be under
-- 128 bytes.
--
-- /See:/ 'instanceLabels' smart constructor.
newtype InstanceLabels =
InstanceLabels'
{ _ilAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'InstanceLabels' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ilAddtional'
instanceLabels
:: HashMap Text Text -- ^ 'ilAddtional'
-> InstanceLabels
instanceLabels pIlAddtional_ =
InstanceLabels' {_ilAddtional = _Coerce # pIlAddtional_}
ilAddtional :: Lens' InstanceLabels (HashMap Text Text)
ilAddtional
= lens _ilAddtional (\ s a -> s{_ilAddtional = a}) .
_Coerce
instance FromJSON InstanceLabels where
parseJSON
= withObject "InstanceLabels"
(\ o -> InstanceLabels' <$> (parseJSONObject o))
instance ToJSON InstanceLabels where
toJSON = toJSON . _ilAddtional
-- | The response for ListBackups.
--
-- /See:/ 'listBackupsResponse' smart constructor.
data ListBackupsResponse =
ListBackupsResponse'
{ _lbrNextPageToken :: !(Maybe Text)
, _lbrBackups :: !(Maybe [Backup])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListBackupsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lbrNextPageToken'
--
-- * 'lbrBackups'
listBackupsResponse
:: ListBackupsResponse
listBackupsResponse =
ListBackupsResponse' {_lbrNextPageToken = Nothing, _lbrBackups = Nothing}
-- | \`next_page_token\` can be sent in a subsequent ListBackups call to
-- fetch more of the matching backups.
lbrNextPageToken :: Lens' ListBackupsResponse (Maybe Text)
lbrNextPageToken
= lens _lbrNextPageToken
(\ s a -> s{_lbrNextPageToken = a})
-- | The list of matching backups.
lbrBackups :: Lens' ListBackupsResponse [Backup]
lbrBackups
= lens _lbrBackups (\ s a -> s{_lbrBackups = a}) .
_Default
. _Coerce
instance FromJSON ListBackupsResponse where
parseJSON
= withObject "ListBackupsResponse"
(\ o ->
ListBackupsResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "backups" .!= mempty))
instance ToJSON ListBackupsResponse where
toJSON ListBackupsResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lbrNextPageToken,
("backups" .=) <$> _lbrBackups])
-- | The \`Status\` type defines a logical error model that is suitable for
-- different programming environments, including REST APIs and RPC APIs. It
-- is used by [gRPC](https:\/\/github.com\/grpc). Each \`Status\` message
-- contains three pieces of data: error code, error message, and error
-- details. You can find out more about this error model and how to work
-- with it in the [API Design
-- Guide](https:\/\/cloud.google.com\/apis\/design\/errors).
--
-- /See:/ 'status' smart constructor.
data Status =
Status'
{ _sDetails :: !(Maybe [StatusDetailsItem])
, _sCode :: !(Maybe (Textual Int32))
, _sMessage :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Status' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sDetails'
--
-- * 'sCode'
--
-- * 'sMessage'
status
:: Status
status = Status' {_sDetails = Nothing, _sCode = Nothing, _sMessage = Nothing}
-- | A list of messages that carry the error details. There is a common set
-- of message types for APIs to use.
sDetails :: Lens' Status [StatusDetailsItem]
sDetails
= lens _sDetails (\ s a -> s{_sDetails = a}) .
_Default
. _Coerce
-- | The status code, which should be an enum value of google.rpc.Code.
sCode :: Lens' Status (Maybe Int32)
sCode
= lens _sCode (\ s a -> s{_sCode = a}) .
mapping _Coerce
-- | A developer-facing error message, which should be in English. Any
-- user-facing error message should be localized and sent in the
-- google.rpc.Status.details field, or localized by the client.
sMessage :: Lens' Status (Maybe Text)
sMessage = lens _sMessage (\ s a -> s{_sMessage = a})
instance FromJSON Status where
parseJSON
= withObject "Status"
(\ o ->
Status' <$>
(o .:? "details" .!= mempty) <*> (o .:? "code") <*>
(o .:? "message"))
instance ToJSON Status where
toJSON Status'{..}
= object
(catMaybes
[("details" .=) <$> _sDetails,
("code" .=) <$> _sCode,
("message" .=) <$> _sMessage])
-- | Request message for BigtableInstanceAdmin.CreateInstance.
--
-- /See:/ 'createInstanceRequest' smart constructor.
data CreateInstanceRequest =
CreateInstanceRequest'
{ _cirParent :: !(Maybe Text)
, _cirInstanceId :: !(Maybe Text)
, _cirClusters :: !(Maybe CreateInstanceRequestClusters)
, _cirInstance :: !(Maybe Instance)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateInstanceRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cirParent'
--
-- * 'cirInstanceId'
--
-- * 'cirClusters'
--
-- * 'cirInstance'
createInstanceRequest
:: CreateInstanceRequest
createInstanceRequest =
CreateInstanceRequest'
{ _cirParent = Nothing
, _cirInstanceId = Nothing
, _cirClusters = Nothing
, _cirInstance = Nothing
}
-- | Required. The unique name of the project in which to create the new
-- instance. Values are of the form \`projects\/{project}\`.
cirParent :: Lens' CreateInstanceRequest (Maybe Text)
cirParent
= lens _cirParent (\ s a -> s{_cirParent = a})
-- | Required. The ID to be used when referring to the new instance within
-- its project, e.g., just \`myinstance\` rather than
-- \`projects\/myproject\/instances\/myinstance\`.
cirInstanceId :: Lens' CreateInstanceRequest (Maybe Text)
cirInstanceId
= lens _cirInstanceId
(\ s a -> s{_cirInstanceId = a})
-- | Required. The clusters to be created within the instance, mapped by
-- desired cluster ID, e.g., just \`mycluster\` rather than
-- \`projects\/myproject\/instances\/myinstance\/clusters\/mycluster\`.
-- Fields marked \`OutputOnly\` must be left blank. Currently, at most four
-- clusters can be specified.
cirClusters :: Lens' CreateInstanceRequest (Maybe CreateInstanceRequestClusters)
cirClusters
= lens _cirClusters (\ s a -> s{_cirClusters = a})
-- | Required. The instance to create. Fields marked \`OutputOnly\` must be
-- left blank.
cirInstance :: Lens' CreateInstanceRequest (Maybe Instance)
cirInstance
= lens _cirInstance (\ s a -> s{_cirInstance = a})
instance FromJSON CreateInstanceRequest where
parseJSON
= withObject "CreateInstanceRequest"
(\ o ->
CreateInstanceRequest' <$>
(o .:? "parent") <*> (o .:? "instanceId") <*>
(o .:? "clusters")
<*> (o .:? "instance"))
instance ToJSON CreateInstanceRequest where
toJSON CreateInstanceRequest'{..}
= object
(catMaybes
[("parent" .=) <$> _cirParent,
("instanceId" .=) <$> _cirInstanceId,
("clusters" .=) <$> _cirClusters,
("instance" .=) <$> _cirInstance])
-- | Specifies the audit configuration for a service. The configuration
-- determines which permission types are logged, and what identities, if
-- any, are exempted from logging. An AuditConfig must have one or more
-- AuditLogConfigs. If there are AuditConfigs for both \`allServices\` and
-- a specific service, the union of the two AuditConfigs is used for that
-- service: the log_types specified in each AuditConfig are enabled, and
-- the exempted_members in each AuditLogConfig are exempted. Example Policy
-- with multiple AuditConfigs: { \"audit_configs\": [ { \"service\":
-- \"allServices\", \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\",
-- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\":
-- \"DATA_WRITE\" }, { \"log_type\": \"ADMIN_READ\" } ] }, { \"service\":
-- \"sampleservice.googleapis.com\", \"audit_log_configs\": [ {
-- \"log_type\": \"DATA_READ\" }, { \"log_type\": \"DATA_WRITE\",
-- \"exempted_members\": [ \"user:aliya\'example.com\" ] } ] } ] } For
-- sampleservice, this policy enables DATA_READ, DATA_WRITE and ADMIN_READ
-- logging. It also exempts jose\'example.com from DATA_READ logging, and
-- aliya\'example.com from DATA_WRITE logging.
--
-- /See:/ 'auditConfig' smart constructor.
data AuditConfig =
AuditConfig'
{ _acService :: !(Maybe Text)
, _acAuditLogConfigs :: !(Maybe [AuditLogConfig])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AuditConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'acService'
--
-- * 'acAuditLogConfigs'
auditConfig
:: AuditConfig
auditConfig = AuditConfig' {_acService = Nothing, _acAuditLogConfigs = Nothing}
-- | Specifies a service that will be enabled for audit logging. For example,
-- \`storage.googleapis.com\`, \`cloudsql.googleapis.com\`. \`allServices\`
-- is a special value that covers all services.
acService :: Lens' AuditConfig (Maybe Text)
acService
= lens _acService (\ s a -> s{_acService = a})
-- | The configuration for logging of each type of permission.
acAuditLogConfigs :: Lens' AuditConfig [AuditLogConfig]
acAuditLogConfigs
= lens _acAuditLogConfigs
(\ s a -> s{_acAuditLogConfigs = a})
. _Default
. _Coerce
instance FromJSON AuditConfig where
parseJSON
= withObject "AuditConfig"
(\ o ->
AuditConfig' <$>
(o .:? "service") <*>
(o .:? "auditLogConfigs" .!= mempty))
instance ToJSON AuditConfig where
toJSON AuditConfig'{..}
= object
(catMaybes
[("service" .=) <$> _acService,
("auditLogConfigs" .=) <$> _acAuditLogConfigs])
-- | Request message for
-- google.bigtable.admin.v2.BigtableTableAdmin.GenerateConsistencyToken
--
-- /See:/ 'generateConsistencyTokenRequest' smart constructor.
data GenerateConsistencyTokenRequest =
GenerateConsistencyTokenRequest'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GenerateConsistencyTokenRequest' with the minimum fields required to make a request.
--
generateConsistencyTokenRequest
:: GenerateConsistencyTokenRequest
generateConsistencyTokenRequest = GenerateConsistencyTokenRequest'
instance FromJSON GenerateConsistencyTokenRequest
where
parseJSON
= withObject "GenerateConsistencyTokenRequest"
(\ o -> pure GenerateConsistencyTokenRequest')
instance ToJSON GenerateConsistencyTokenRequest where
toJSON = const emptyObject
-- | Request message for
-- google.bigtable.admin.v2.BigtableTableAdmin.ModifyColumnFamilies
--
-- /See:/ 'modifyColumnFamiliesRequest' smart constructor.
newtype ModifyColumnFamiliesRequest =
ModifyColumnFamiliesRequest'
{ _mcfrModifications :: Maybe [Modification]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ModifyColumnFamiliesRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mcfrModifications'
modifyColumnFamiliesRequest
:: ModifyColumnFamiliesRequest
modifyColumnFamiliesRequest =
ModifyColumnFamiliesRequest' {_mcfrModifications = Nothing}
-- | Required. Modifications to be atomically applied to the specified
-- table\'s families. Entries are applied in order, meaning that earlier
-- modifications can be masked by later ones (in the case of repeated
-- updates to the same family, for example).
mcfrModifications :: Lens' ModifyColumnFamiliesRequest [Modification]
mcfrModifications
= lens _mcfrModifications
(\ s a -> s{_mcfrModifications = a})
. _Default
. _Coerce
instance FromJSON ModifyColumnFamiliesRequest where
parseJSON
= withObject "ModifyColumnFamiliesRequest"
(\ o ->
ModifyColumnFamiliesRequest' <$>
(o .:? "modifications" .!= mempty))
instance ToJSON ModifyColumnFamiliesRequest where
toJSON ModifyColumnFamiliesRequest'{..}
= object
(catMaybes
[("modifications" .=) <$> _mcfrModifications])
-- | Represents a textual expression in the Common Expression Language (CEL)
-- syntax. CEL is a C-like expression language. The syntax and semantics of
-- CEL are documented at https:\/\/github.com\/google\/cel-spec. Example
-- (Comparison): title: \"Summary size limit\" description: \"Determines if
-- a summary is less than 100 chars\" expression: \"document.summary.size()
-- \< 100\" Example (Equality): title: \"Requestor is owner\" description:
-- \"Determines if requestor is the document owner\" expression:
-- \"document.owner == request.auth.claims.email\" Example (Logic): title:
-- \"Public documents\" description: \"Determine whether the document
-- should be publicly visible\" expression: \"document.type != \'private\'
-- && document.type != \'internal\'\" Example (Data Manipulation): title:
-- \"Notification string\" description: \"Create a notification string with
-- a timestamp.\" expression: \"\'New message received at \' +
-- string(document.create_time)\" The exact variables and functions that
-- may be referenced within an expression are determined by the service
-- that evaluates it. See the service documentation for additional
-- information.
--
-- /See:/ 'expr' smart constructor.
data Expr =
Expr'
{ _eLocation :: !(Maybe Text)
, _eExpression :: !(Maybe Text)
, _eTitle :: !(Maybe Text)
, _eDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Expr' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eLocation'
--
-- * 'eExpression'
--
-- * 'eTitle'
--
-- * 'eDescription'
expr
:: Expr
expr =
Expr'
{ _eLocation = Nothing
, _eExpression = Nothing
, _eTitle = Nothing
, _eDescription = Nothing
}
-- | Optional. String indicating the location of the expression for error
-- reporting, e.g. a file name and a position in the file.
eLocation :: Lens' Expr (Maybe Text)
eLocation
= lens _eLocation (\ s a -> s{_eLocation = a})
-- | Textual representation of an expression in Common Expression Language
-- syntax.
eExpression :: Lens' Expr (Maybe Text)
eExpression
= lens _eExpression (\ s a -> s{_eExpression = a})
-- | Optional. Title for the expression, i.e. a short string describing its
-- purpose. This can be used e.g. in UIs which allow to enter the
-- expression.
eTitle :: Lens' Expr (Maybe Text)
eTitle = lens _eTitle (\ s a -> s{_eTitle = a})
-- | Optional. Description of the expression. This is a longer text which
-- describes the expression, e.g. when hovered over it in a UI.
eDescription :: Lens' Expr (Maybe Text)
eDescription
= lens _eDescription (\ s a -> s{_eDescription = a})
instance FromJSON Expr where
parseJSON
= withObject "Expr"
(\ o ->
Expr' <$>
(o .:? "location") <*> (o .:? "expression") <*>
(o .:? "title")
<*> (o .:? "description"))
instance ToJSON Expr where
toJSON Expr'{..}
= object
(catMaybes
[("location" .=) <$> _eLocation,
("expression" .=) <$> _eExpression,
("title" .=) <$> _eTitle,
("description" .=) <$> _eDescription])
-- | The response message for Locations.ListLocations.
--
-- /See:/ 'listLocationsResponse' smart constructor.
data ListLocationsResponse =
ListLocationsResponse'
{ _llrNextPageToken :: !(Maybe Text)
, _llrLocations :: !(Maybe [Location])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListLocationsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'llrNextPageToken'
--
-- * 'llrLocations'
listLocationsResponse
:: ListLocationsResponse
listLocationsResponse =
ListLocationsResponse' {_llrNextPageToken = Nothing, _llrLocations = Nothing}
-- | The standard List next-page token.
llrNextPageToken :: Lens' ListLocationsResponse (Maybe Text)
llrNextPageToken
= lens _llrNextPageToken
(\ s a -> s{_llrNextPageToken = a})
-- | A list of locations that matches the specified filter in the request.
llrLocations :: Lens' ListLocationsResponse [Location]
llrLocations
= lens _llrLocations (\ s a -> s{_llrLocations = a})
. _Default
. _Coerce
instance FromJSON ListLocationsResponse where
parseJSON
= withObject "ListLocationsResponse"
(\ o ->
ListLocationsResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "locations" .!= mempty))
instance ToJSON ListLocationsResponse where
toJSON ListLocationsResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _llrNextPageToken,
("locations" .=) <$> _llrLocations])
-- | The response message for Operations.ListOperations.
--
-- /See:/ 'listOperationsResponse' smart constructor.
data ListOperationsResponse =
ListOperationsResponse'
{ _lorNextPageToken :: !(Maybe Text)
, _lorOperations :: !(Maybe [Operation])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListOperationsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lorNextPageToken'
--
-- * 'lorOperations'
listOperationsResponse
:: ListOperationsResponse
listOperationsResponse =
ListOperationsResponse'
{_lorNextPageToken = Nothing, _lorOperations = Nothing}
-- | The standard List next-page token.
lorNextPageToken :: Lens' ListOperationsResponse (Maybe Text)
lorNextPageToken
= lens _lorNextPageToken
(\ s a -> s{_lorNextPageToken = a})
-- | A list of operations that matches the specified filter in the request.
lorOperations :: Lens' ListOperationsResponse [Operation]
lorOperations
= lens _lorOperations
(\ s a -> s{_lorOperations = a})
. _Default
. _Coerce
instance FromJSON ListOperationsResponse where
parseJSON
= withObject "ListOperationsResponse"
(\ o ->
ListOperationsResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "operations" .!= mempty))
instance ToJSON ListOperationsResponse where
toJSON ListOperationsResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lorNextPageToken,
("operations" .=) <$> _lorOperations])
-- | Request message for BigtableInstanceAdmin.CreateCluster.
--
-- /See:/ 'createClusterRequest' smart constructor.
data CreateClusterRequest =
CreateClusterRequest'
{ _ccrParent :: !(Maybe Text)
, _ccrCluster :: !(Maybe Cluster)
, _ccrClusterId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateClusterRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccrParent'
--
-- * 'ccrCluster'
--
-- * 'ccrClusterId'
createClusterRequest
:: CreateClusterRequest
createClusterRequest =
CreateClusterRequest'
{_ccrParent = Nothing, _ccrCluster = Nothing, _ccrClusterId = Nothing}
-- | Required. The unique name of the instance in which to create the new
-- cluster. Values are of the form
-- \`projects\/{project}\/instances\/{instance}\`.
ccrParent :: Lens' CreateClusterRequest (Maybe Text)
ccrParent
= lens _ccrParent (\ s a -> s{_ccrParent = a})
-- | Required. The cluster to be created. Fields marked \`OutputOnly\` must
-- be left blank.
ccrCluster :: Lens' CreateClusterRequest (Maybe Cluster)
ccrCluster
= lens _ccrCluster (\ s a -> s{_ccrCluster = a})
-- | Required. The ID to be used when referring to the new cluster within its
-- instance, e.g., just \`mycluster\` rather than
-- \`projects\/myproject\/instances\/myinstance\/clusters\/mycluster\`.
ccrClusterId :: Lens' CreateClusterRequest (Maybe Text)
ccrClusterId
= lens _ccrClusterId (\ s a -> s{_ccrClusterId = a})
instance FromJSON CreateClusterRequest where
parseJSON
= withObject "CreateClusterRequest"
(\ o ->
CreateClusterRequest' <$>
(o .:? "parent") <*> (o .:? "cluster") <*>
(o .:? "clusterId"))
instance ToJSON CreateClusterRequest where
toJSON CreateClusterRequest'{..}
= object
(catMaybes
[("parent" .=) <$> _ccrParent,
("cluster" .=) <$> _ccrCluster,
("clusterId" .=) <$> _ccrClusterId])
-- | Request message for \`GetIamPolicy\` method.
--
-- /See:/ 'getIAMPolicyRequest' smart constructor.
newtype GetIAMPolicyRequest =
GetIAMPolicyRequest'
{ _giprOptions :: Maybe GetPolicyOptions
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GetIAMPolicyRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'giprOptions'
getIAMPolicyRequest
:: GetIAMPolicyRequest
getIAMPolicyRequest = GetIAMPolicyRequest' {_giprOptions = Nothing}
-- | OPTIONAL: A \`GetPolicyOptions\` object for specifying options to
-- \`GetIamPolicy\`.
giprOptions :: Lens' GetIAMPolicyRequest (Maybe GetPolicyOptions)
giprOptions
= lens _giprOptions (\ s a -> s{_giprOptions = a})
instance FromJSON GetIAMPolicyRequest where
parseJSON
= withObject "GetIAMPolicyRequest"
(\ o -> GetIAMPolicyRequest' <$> (o .:? "options"))
instance ToJSON GetIAMPolicyRequest where
toJSON GetIAMPolicyRequest'{..}
= object
(catMaybes [("options" .=) <$> _giprOptions])
-- | A resizable group of nodes in a particular cloud location, capable of
-- serving all Tables in the parent Instance.
--
-- /See:/ 'cluster' smart constructor.
data Cluster =
Cluster'
{ _cState :: !(Maybe ClusterType)
, _cDefaultStorageType :: !(Maybe ClusterDefaultStorageType)
, _cLocation :: !(Maybe Text)
, _cServeNodes :: !(Maybe (Textual Int32))
, _cName :: !(Maybe Text)
, _cEncryptionConfig :: !(Maybe EncryptionConfig)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Cluster' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cState'
--
-- * 'cDefaultStorageType'
--
-- * 'cLocation'
--
-- * 'cServeNodes'
--
-- * 'cName'
--
-- * 'cEncryptionConfig'
cluster
:: Cluster
cluster =
Cluster'
{ _cState = Nothing
, _cDefaultStorageType = Nothing
, _cLocation = Nothing
, _cServeNodes = Nothing
, _cName = Nothing
, _cEncryptionConfig = Nothing
}
-- | Output only. The current state of the cluster.
cState :: Lens' Cluster (Maybe ClusterType)
cState = lens _cState (\ s a -> s{_cState = a})
-- | Immutable. The type of storage used by this cluster to serve its parent
-- instance\'s tables, unless explicitly overridden.
cDefaultStorageType :: Lens' Cluster (Maybe ClusterDefaultStorageType)
cDefaultStorageType
= lens _cDefaultStorageType
(\ s a -> s{_cDefaultStorageType = a})
-- | Immutable. The location where this cluster\'s nodes and storage reside.
-- For best performance, clients should be located as close as possible to
-- this cluster. Currently only zones are supported, so values should be of
-- the form \`projects\/{project}\/locations\/{zone}\`.
cLocation :: Lens' Cluster (Maybe Text)
cLocation
= lens _cLocation (\ s a -> s{_cLocation = a})
-- | Required. The number of nodes allocated to this cluster. More nodes
-- enable higher throughput and more consistent performance.
cServeNodes :: Lens' Cluster (Maybe Int32)
cServeNodes
= lens _cServeNodes (\ s a -> s{_cServeNodes = a}) .
mapping _Coerce
-- | The unique name of the cluster. Values are of the form
-- \`projects\/{project}\/instances\/{instance}\/clusters\/a-z*\`.
cName :: Lens' Cluster (Maybe Text)
cName = lens _cName (\ s a -> s{_cName = a})
-- | Immutable. The encryption configuration for CMEK-protected clusters.
cEncryptionConfig :: Lens' Cluster (Maybe EncryptionConfig)
cEncryptionConfig
= lens _cEncryptionConfig
(\ s a -> s{_cEncryptionConfig = a})
instance FromJSON Cluster where
parseJSON
= withObject "Cluster"
(\ o ->
Cluster' <$>
(o .:? "state") <*> (o .:? "defaultStorageType") <*>
(o .:? "location")
<*> (o .:? "serveNodes")
<*> (o .:? "name")
<*> (o .:? "encryptionConfig"))
instance ToJSON Cluster where
toJSON Cluster'{..}
= object
(catMaybes
[("state" .=) <$> _cState,
("defaultStorageType" .=) <$> _cDefaultStorageType,
("location" .=) <$> _cLocation,
("serveNodes" .=) <$> _cServeNodes,
("name" .=) <$> _cName,
("encryptionConfig" .=) <$> _cEncryptionConfig])
-- | An initial split point for a newly created table.
--
-- /See:/ 'split' smart constructor.
newtype Split =
Split'
{ _sKey :: Maybe Bytes
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Split' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sKey'
split
:: Split
split = Split' {_sKey = Nothing}
-- | Row key to use as an initial tablet boundary.
sKey :: Lens' Split (Maybe ByteString)
sKey
= lens _sKey (\ s a -> s{_sKey = a}) . mapping _Bytes
instance FromJSON Split where
parseJSON
= withObject "Split"
(\ o -> Split' <$> (o .:? "key"))
instance ToJSON Split where
toJSON Split'{..}
= object (catMaybes [("key" .=) <$> _sKey])
-- | Read\/write requests are routed to the nearest cluster in the instance,
-- and will fail over to the nearest cluster that is available in the event
-- of transient errors or delays. Clusters in a region are considered
-- equidistant. Choosing this option sacrifices read-your-writes
-- consistency to improve availability.
--
-- /See:/ 'multiClusterRoutingUseAny' smart constructor.
data MultiClusterRoutingUseAny =
MultiClusterRoutingUseAny'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'MultiClusterRoutingUseAny' with the minimum fields required to make a request.
--
multiClusterRoutingUseAny
:: MultiClusterRoutingUseAny
multiClusterRoutingUseAny = MultiClusterRoutingUseAny'
instance FromJSON MultiClusterRoutingUseAny where
parseJSON
= withObject "MultiClusterRoutingUseAny"
(\ o -> pure MultiClusterRoutingUseAny')
instance ToJSON MultiClusterRoutingUseAny where
toJSON = const emptyObject
-- | The state of a table\'s data in a particular cluster.
--
-- /See:/ 'clusterState' smart constructor.
data ClusterState =
ClusterState'
{ _csReplicationState :: !(Maybe ClusterStateReplicationState)
, _csEncryptionInfo :: !(Maybe [EncryptionInfo])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ClusterState' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'csReplicationState'
--
-- * 'csEncryptionInfo'
clusterState
:: ClusterState
clusterState =
ClusterState' {_csReplicationState = Nothing, _csEncryptionInfo = Nothing}
-- | Output only. The state of replication for the table in this cluster.
csReplicationState :: Lens' ClusterState (Maybe ClusterStateReplicationState)
csReplicationState
= lens _csReplicationState
(\ s a -> s{_csReplicationState = a})
-- | Output only. The encryption information for the table in this cluster.
-- If the encryption key protecting this resource is customer managed, then
-- its version can be rotated in Cloud Key Management Service (Cloud KMS).
-- The primary version of the key and its status will be reflected here
-- when changes propagate from Cloud KMS.
csEncryptionInfo :: Lens' ClusterState [EncryptionInfo]
csEncryptionInfo
= lens _csEncryptionInfo
(\ s a -> s{_csEncryptionInfo = a})
. _Default
. _Coerce
instance FromJSON ClusterState where
parseJSON
= withObject "ClusterState"
(\ o ->
ClusterState' <$>
(o .:? "replicationState") <*>
(o .:? "encryptionInfo" .!= mempty))
instance ToJSON ClusterState where
toJSON ClusterState'{..}
= object
(catMaybes
[("replicationState" .=) <$> _csReplicationState,
("encryptionInfo" .=) <$> _csEncryptionInfo])
-- | A resource that represents Google Cloud Platform location.
--
-- /See:/ 'location' smart constructor.
data Location =
Location'
{ _lName :: !(Maybe Text)
, _lMetadata :: !(Maybe LocationMetadata)
, _lDisplayName :: !(Maybe Text)
, _lLabels :: !(Maybe LocationLabels)
, _lLocationId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Location' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lName'
--
-- * 'lMetadata'
--
-- * 'lDisplayName'
--
-- * 'lLabels'
--
-- * 'lLocationId'
location
:: Location
location =
Location'
{ _lName = Nothing
, _lMetadata = Nothing
, _lDisplayName = Nothing
, _lLabels = Nothing
, _lLocationId = Nothing
}
-- | Resource name for the location, which may vary between implementations.
-- For example: \`\"projects\/example-project\/locations\/us-east1\"\`
lName :: Lens' Location (Maybe Text)
lName = lens _lName (\ s a -> s{_lName = a})
-- | Service-specific metadata. For example the available capacity at the
-- given location.
lMetadata :: Lens' Location (Maybe LocationMetadata)
lMetadata
= lens _lMetadata (\ s a -> s{_lMetadata = a})
-- | The friendly name for this location, typically a nearby city name. For
-- example, \"Tokyo\".
lDisplayName :: Lens' Location (Maybe Text)
lDisplayName
= lens _lDisplayName (\ s a -> s{_lDisplayName = a})
-- | Cross-service attributes for the location. For example
-- {\"cloud.googleapis.com\/region\": \"us-east1\"}
lLabels :: Lens' Location (Maybe LocationLabels)
lLabels = lens _lLabels (\ s a -> s{_lLabels = a})
-- | The canonical id for this location. For example: \`\"us-east1\"\`.
lLocationId :: Lens' Location (Maybe Text)
lLocationId
= lens _lLocationId (\ s a -> s{_lLocationId = a})
instance FromJSON Location where
parseJSON
= withObject "Location"
(\ o ->
Location' <$>
(o .:? "name") <*> (o .:? "metadata") <*>
(o .:? "displayName")
<*> (o .:? "labels")
<*> (o .:? "locationId"))
instance ToJSON Location where
toJSON Location'{..}
= object
(catMaybes
[("name" .=) <$> _lName,
("metadata" .=) <$> _lMetadata,
("displayName" .=) <$> _lDisplayName,
("labels" .=) <$> _lLabels,
("locationId" .=) <$> _lLocationId])
-- | This resource represents a long-running operation that is the result of
-- a network API call.
--
-- /See:/ 'operation' smart constructor.
data Operation =
Operation'
{ _oDone :: !(Maybe Bool)
, _oError :: !(Maybe Status)
, _oResponse :: !(Maybe OperationResponse)
, _oName :: !(Maybe Text)
, _oMetadata :: !(Maybe OperationMetadata)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Operation' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'oDone'
--
-- * 'oError'
--
-- * 'oResponse'
--
-- * 'oName'
--
-- * 'oMetadata'
operation
:: Operation
operation =
Operation'
{ _oDone = Nothing
, _oError = Nothing
, _oResponse = Nothing
, _oName = Nothing
, _oMetadata = Nothing
}
-- | If the value is \`false\`, it means the operation is still in progress.
-- If \`true\`, the operation is completed, and either \`error\` or
-- \`response\` is available.
oDone :: Lens' Operation (Maybe Bool)
oDone = lens _oDone (\ s a -> s{_oDone = a})
-- | The error result of the operation in case of failure or cancellation.
oError :: Lens' Operation (Maybe Status)
oError = lens _oError (\ s a -> s{_oError = a})
-- | The normal response of the operation in case of success. If the original
-- method returns no data on success, such as \`Delete\`, the response is
-- \`google.protobuf.Empty\`. If the original method is standard
-- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource.
-- For other methods, the response should have the type \`XxxResponse\`,
-- where \`Xxx\` is the original method name. For example, if the original
-- method name is \`TakeSnapshot()\`, the inferred response type is
-- \`TakeSnapshotResponse\`.
oResponse :: Lens' Operation (Maybe OperationResponse)
oResponse
= lens _oResponse (\ s a -> s{_oResponse = a})
-- | The server-assigned name, which is only unique within the same service
-- that originally returns it. If you use the default HTTP mapping, the
-- \`name\` should be a resource name ending with
-- \`operations\/{unique_id}\`.
oName :: Lens' Operation (Maybe Text)
oName = lens _oName (\ s a -> s{_oName = a})
-- | Service-specific metadata associated with the operation. It typically
-- contains progress information and common metadata such as create time.
-- Some services might not provide such metadata. Any method that returns a
-- long-running operation should document the metadata type, if any.
oMetadata :: Lens' Operation (Maybe OperationMetadata)
oMetadata
= lens _oMetadata (\ s a -> s{_oMetadata = a})
instance FromJSON Operation where
parseJSON
= withObject "Operation"
(\ o ->
Operation' <$>
(o .:? "done") <*> (o .:? "error") <*>
(o .:? "response")
<*> (o .:? "name")
<*> (o .:? "metadata"))
instance ToJSON Operation where
toJSON Operation'{..}
= object
(catMaybes
[("done" .=) <$> _oDone, ("error" .=) <$> _oError,
("response" .=) <$> _oResponse,
("name" .=) <$> _oName,
("metadata" .=) <$> _oMetadata])
-- | A generic empty message that you can re-use to avoid defining duplicated
-- empty messages in your APIs. A typical example is to use it as the
-- request or the response type of an API method. For instance: service Foo
-- { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } The
-- JSON representation for \`Empty\` is empty JSON object \`{}\`.
--
-- /See:/ 'empty' smart constructor.
data Empty =
Empty'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Empty' with the minimum fields required to make a request.
--
empty
:: Empty
empty = Empty'
instance FromJSON Empty where
parseJSON = withObject "Empty" (\ o -> pure Empty')
instance ToJSON Empty where
toJSON = const emptyObject
-- | Response message for BigtableInstanceAdmin.ListAppProfiles.
--
-- /See:/ 'listAppProFilesResponse' smart constructor.
data ListAppProFilesResponse =
ListAppProFilesResponse'
{ _lapfrNextPageToken :: !(Maybe Text)
, _lapfrFailedLocations :: !(Maybe [Text])
, _lapfrAppProFiles :: !(Maybe [AppProFile])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListAppProFilesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lapfrNextPageToken'
--
-- * 'lapfrFailedLocations'
--
-- * 'lapfrAppProFiles'
listAppProFilesResponse
:: ListAppProFilesResponse
listAppProFilesResponse =
ListAppProFilesResponse'
{ _lapfrNextPageToken = Nothing
, _lapfrFailedLocations = Nothing
, _lapfrAppProFiles = Nothing
}
-- | Set if not all app profiles could be returned in a single response. Pass
-- this value to \`page_token\` in another request to get the next page of
-- results.
lapfrNextPageToken :: Lens' ListAppProFilesResponse (Maybe Text)
lapfrNextPageToken
= lens _lapfrNextPageToken
(\ s a -> s{_lapfrNextPageToken = a})
-- | Locations from which AppProfile information could not be retrieved, due
-- to an outage or some other transient condition. AppProfiles from these
-- locations may be missing from \`app_profiles\`. Values are of the form
-- \`projects\/\/locations\/\`
lapfrFailedLocations :: Lens' ListAppProFilesResponse [Text]
lapfrFailedLocations
= lens _lapfrFailedLocations
(\ s a -> s{_lapfrFailedLocations = a})
. _Default
. _Coerce
-- | The list of requested app profiles.
lapfrAppProFiles :: Lens' ListAppProFilesResponse [AppProFile]
lapfrAppProFiles
= lens _lapfrAppProFiles
(\ s a -> s{_lapfrAppProFiles = a})
. _Default
. _Coerce
instance FromJSON ListAppProFilesResponse where
parseJSON
= withObject "ListAppProFilesResponse"
(\ o ->
ListAppProFilesResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "failedLocations" .!= mempty)
<*> (o .:? "appProfiles" .!= mempty))
instance ToJSON ListAppProFilesResponse where
toJSON ListAppProFilesResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lapfrNextPageToken,
("failedLocations" .=) <$> _lapfrFailedLocations,
("appProfiles" .=) <$> _lapfrAppProFiles])
-- | Encapsulates progress related information for a Cloud Bigtable long
-- running operation.
--
-- /See:/ 'operationProgress' smart constructor.
data OperationProgress =
OperationProgress'
{ _opStartTime :: !(Maybe DateTime')
, _opProgressPercent :: !(Maybe (Textual Int32))
, _opEndTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationProgress' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'opStartTime'
--
-- * 'opProgressPercent'
--
-- * 'opEndTime'
operationProgress
:: OperationProgress
operationProgress =
OperationProgress'
{_opStartTime = Nothing, _opProgressPercent = Nothing, _opEndTime = Nothing}
-- | Time the request was received.
opStartTime :: Lens' OperationProgress (Maybe UTCTime)
opStartTime
= lens _opStartTime (\ s a -> s{_opStartTime = a}) .
mapping _DateTime
-- | Percent completion of the operation. Values are between 0 and 100
-- inclusive.
opProgressPercent :: Lens' OperationProgress (Maybe Int32)
opProgressPercent
= lens _opProgressPercent
(\ s a -> s{_opProgressPercent = a})
. mapping _Coerce
-- | If set, the time at which this operation failed or was completed
-- successfully.
opEndTime :: Lens' OperationProgress (Maybe UTCTime)
opEndTime
= lens _opEndTime (\ s a -> s{_opEndTime = a}) .
mapping _DateTime
instance FromJSON OperationProgress where
parseJSON
= withObject "OperationProgress"
(\ o ->
OperationProgress' <$>
(o .:? "startTime") <*> (o .:? "progressPercent") <*>
(o .:? "endTime"))
instance ToJSON OperationProgress where
toJSON OperationProgress'{..}
= object
(catMaybes
[("startTime" .=) <$> _opStartTime,
("progressPercent" .=) <$> _opProgressPercent,
("endTime" .=) <$> _opEndTime])
-- | Output only. Map from cluster ID to per-cluster table state. If it could
-- not be determined whether or not the table has data in a particular
-- cluster (for example, if its zone is unavailable), then there will be an
-- entry for the cluster with UNKNOWN \`replication_status\`. Views:
-- \`REPLICATION_VIEW\`, \`ENCRYPTION_VIEW\`, \`FULL\`
--
-- /See:/ 'tableClusterStates' smart constructor.
newtype TableClusterStates =
TableClusterStates'
{ _tcsAddtional :: HashMap Text ClusterState
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableClusterStates' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcsAddtional'
tableClusterStates
:: HashMap Text ClusterState -- ^ 'tcsAddtional'
-> TableClusterStates
tableClusterStates pTcsAddtional_ =
TableClusterStates' {_tcsAddtional = _Coerce # pTcsAddtional_}
tcsAddtional :: Lens' TableClusterStates (HashMap Text ClusterState)
tcsAddtional
= lens _tcsAddtional (\ s a -> s{_tcsAddtional = a})
. _Coerce
instance FromJSON TableClusterStates where
parseJSON
= withObject "TableClusterStates"
(\ o -> TableClusterStates' <$> (parseJSONObject o))
instance ToJSON TableClusterStates where
toJSON = toJSON . _tcsAddtional
-- | The column families configured for this table, mapped by column family
-- ID. Views: \`SCHEMA_VIEW\`, \`FULL\`
--
-- /See:/ 'tableColumnFamilies' smart constructor.
newtype TableColumnFamilies =
TableColumnFamilies'
{ _tcfAddtional :: HashMap Text ColumnFamily
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableColumnFamilies' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tcfAddtional'
tableColumnFamilies
:: HashMap Text ColumnFamily -- ^ 'tcfAddtional'
-> TableColumnFamilies
tableColumnFamilies pTcfAddtional_ =
TableColumnFamilies' {_tcfAddtional = _Coerce # pTcfAddtional_}
tcfAddtional :: Lens' TableColumnFamilies (HashMap Text ColumnFamily)
tcfAddtional
= lens _tcfAddtional (\ s a -> s{_tcfAddtional = a})
. _Coerce
instance FromJSON TableColumnFamilies where
parseJSON
= withObject "TableColumnFamilies"
(\ o -> TableColumnFamilies' <$> (parseJSONObject o))
instance ToJSON TableColumnFamilies where
toJSON = toJSON . _tcfAddtional
-- | Request message for
-- google.bigtable.admin.v2.BigtableTableAdmin.CreateTable
--
-- /See:/ 'createTableRequest' smart constructor.
data CreateTableRequest =
CreateTableRequest'
{ _ctrInitialSplits :: !(Maybe [Split])
, _ctrTableId :: !(Maybe Text)
, _ctrTable :: !(Maybe Table)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateTableRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ctrInitialSplits'
--
-- * 'ctrTableId'
--
-- * 'ctrTable'
createTableRequest
:: CreateTableRequest
createTableRequest =
CreateTableRequest'
{_ctrInitialSplits = Nothing, _ctrTableId = Nothing, _ctrTable = Nothing}
-- | The optional list of row keys that will be used to initially split the
-- table into several tablets (tablets are similar to HBase regions). Given
-- two split keys, \`s1\` and \`s2\`, three tablets will be created,
-- spanning the key ranges: \`[, s1), [s1, s2), [s2, )\`. Example: * Row
-- keys := \`[\"a\", \"apple\", \"custom\", \"customer_1\",
-- \"customer_2\",\` \`\"other\", \"zz\"]\` * initial_split_keys :=
-- \`[\"apple\", \"customer_1\", \"customer_2\", \"other\"]\` * Key
-- assignment: - Tablet 1 \`[, apple) => {\"a\"}.\` - Tablet 2 \`[apple,
-- customer_1) => {\"apple\", \"custom\"}.\` - Tablet 3 \`[customer_1,
-- customer_2) => {\"customer_1\"}.\` - Tablet 4 \`[customer_2, other) =>
-- {\"customer_2\"}.\` - Tablet 5 \`[other, ) => {\"other\", \"zz\"}.\`
ctrInitialSplits :: Lens' CreateTableRequest [Split]
ctrInitialSplits
= lens _ctrInitialSplits
(\ s a -> s{_ctrInitialSplits = a})
. _Default
. _Coerce
-- | Required. The name by which the new table should be referred to within
-- the parent instance, e.g., \`foobar\` rather than
-- \`{parent}\/tables\/foobar\`. Maximum 50 characters.
ctrTableId :: Lens' CreateTableRequest (Maybe Text)
ctrTableId
= lens _ctrTableId (\ s a -> s{_ctrTableId = a})
-- | Required. The Table to create.
ctrTable :: Lens' CreateTableRequest (Maybe Table)
ctrTable = lens _ctrTable (\ s a -> s{_ctrTable = a})
instance FromJSON CreateTableRequest where
parseJSON
= withObject "CreateTableRequest"
(\ o ->
CreateTableRequest' <$>
(o .:? "initialSplits" .!= mempty) <*>
(o .:? "tableId")
<*> (o .:? "table"))
instance ToJSON CreateTableRequest where
toJSON CreateTableRequest'{..}
= object
(catMaybes
[("initialSplits" .=) <$> _ctrInitialSplits,
("tableId" .=) <$> _ctrTableId,
("table" .=) <$> _ctrTable])
-- | The metadata for the Operation returned by CreateCluster.
--
-- /See:/ 'createClusterMetadata' smart constructor.
data CreateClusterMetadata =
CreateClusterMetadata'
{ _ccmRequestTime :: !(Maybe DateTime')
, _ccmTables :: !(Maybe CreateClusterMetadataTables)
, _ccmOriginalRequest :: !(Maybe CreateClusterRequest)
, _ccmFinishTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateClusterMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccmRequestTime'
--
-- * 'ccmTables'
--
-- * 'ccmOriginalRequest'
--
-- * 'ccmFinishTime'
createClusterMetadata
:: CreateClusterMetadata
createClusterMetadata =
CreateClusterMetadata'
{ _ccmRequestTime = Nothing
, _ccmTables = Nothing
, _ccmOriginalRequest = Nothing
, _ccmFinishTime = Nothing
}
-- | The time at which the original request was received.
ccmRequestTime :: Lens' CreateClusterMetadata (Maybe UTCTime)
ccmRequestTime
= lens _ccmRequestTime
(\ s a -> s{_ccmRequestTime = a})
. mapping _DateTime
-- | Keys: the full \`name\` of each table that existed in the instance when
-- CreateCluster was first called, i.e.
-- \`projects\/\/instances\/\/tables\/\`. Any table added to the instance
-- by a later API call will be created in the new cluster by that API call,
-- not this one. Values: information on how much of a table\'s data has
-- been copied to the newly-created cluster so far.
ccmTables :: Lens' CreateClusterMetadata (Maybe CreateClusterMetadataTables)
ccmTables
= lens _ccmTables (\ s a -> s{_ccmTables = a})
-- | The request that prompted the initiation of this CreateCluster
-- operation.
ccmOriginalRequest :: Lens' CreateClusterMetadata (Maybe CreateClusterRequest)
ccmOriginalRequest
= lens _ccmOriginalRequest
(\ s a -> s{_ccmOriginalRequest = a})
-- | The time at which the operation failed or was completed successfully.
ccmFinishTime :: Lens' CreateClusterMetadata (Maybe UTCTime)
ccmFinishTime
= lens _ccmFinishTime
(\ s a -> s{_ccmFinishTime = a})
. mapping _DateTime
instance FromJSON CreateClusterMetadata where
parseJSON
= withObject "CreateClusterMetadata"
(\ o ->
CreateClusterMetadata' <$>
(o .:? "requestTime") <*> (o .:? "tables") <*>
(o .:? "originalRequest")
<*> (o .:? "finishTime"))
instance ToJSON CreateClusterMetadata where
toJSON CreateClusterMetadata'{..}
= object
(catMaybes
[("requestTime" .=) <$> _ccmRequestTime,
("tables" .=) <$> _ccmTables,
("originalRequest" .=) <$> _ccmOriginalRequest,
("finishTime" .=) <$> _ccmFinishTime])
-- | Progress info for copying a table\'s data to the new cluster.
--
-- /See:/ 'tableProgress' smart constructor.
data TableProgress =
TableProgress'
{ _tpState :: !(Maybe TableProgressState)
, _tpEstimatedSizeBytes :: !(Maybe (Textual Int64))
, _tpEstimatedCopiedBytes :: !(Maybe (Textual Int64))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TableProgress' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tpState'
--
-- * 'tpEstimatedSizeBytes'
--
-- * 'tpEstimatedCopiedBytes'
tableProgress
:: TableProgress
tableProgress =
TableProgress'
{ _tpState = Nothing
, _tpEstimatedSizeBytes = Nothing
, _tpEstimatedCopiedBytes = Nothing
}
tpState :: Lens' TableProgress (Maybe TableProgressState)
tpState = lens _tpState (\ s a -> s{_tpState = a})
-- | Estimate of the size of the table to be copied.
tpEstimatedSizeBytes :: Lens' TableProgress (Maybe Int64)
tpEstimatedSizeBytes
= lens _tpEstimatedSizeBytes
(\ s a -> s{_tpEstimatedSizeBytes = a})
. mapping _Coerce
-- | Estimate of the number of bytes copied so far for this table. This will
-- eventually reach \'estimated_size_bytes\' unless the table copy is
-- CANCELLED.
tpEstimatedCopiedBytes :: Lens' TableProgress (Maybe Int64)
tpEstimatedCopiedBytes
= lens _tpEstimatedCopiedBytes
(\ s a -> s{_tpEstimatedCopiedBytes = a})
. mapping _Coerce
instance FromJSON TableProgress where
parseJSON
= withObject "TableProgress"
(\ o ->
TableProgress' <$>
(o .:? "state") <*> (o .:? "estimatedSizeBytes") <*>
(o .:? "estimatedCopiedBytes"))
instance ToJSON TableProgress where
toJSON TableProgress'{..}
= object
(catMaybes
[("state" .=) <$> _tpState,
("estimatedSizeBytes" .=) <$> _tpEstimatedSizeBytes,
("estimatedCopiedBytes" .=) <$>
_tpEstimatedCopiedBytes])
-- | A GcRule which deletes cells matching any of the given rules.
--
-- /See:/ 'union' smart constructor.
newtype Union =
Union'
{ _uRules :: Maybe [GcRule]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Union' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uRules'
union
:: Union
union = Union' {_uRules = Nothing}
-- | Delete cells which would be deleted by any element of \`rules\`.
uRules :: Lens' Union [GcRule]
uRules
= lens _uRules (\ s a -> s{_uRules = a}) . _Default .
_Coerce
instance FromJSON Union where
parseJSON
= withObject "Union"
(\ o -> Union' <$> (o .:? "rules" .!= mempty))
instance ToJSON Union where
toJSON Union'{..}
= object (catMaybes [("rules" .=) <$> _uRules])
--
-- /See:/ 'statusDetailsItem' smart constructor.
newtype StatusDetailsItem =
StatusDetailsItem'
{ _sdiAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'StatusDetailsItem' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'sdiAddtional'
statusDetailsItem
:: HashMap Text JSONValue -- ^ 'sdiAddtional'
-> StatusDetailsItem
statusDetailsItem pSdiAddtional_ =
StatusDetailsItem' {_sdiAddtional = _Coerce # pSdiAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
sdiAddtional :: Lens' StatusDetailsItem (HashMap Text JSONValue)
sdiAddtional
= lens _sdiAddtional (\ s a -> s{_sdiAddtional = a})
. _Coerce
instance FromJSON StatusDetailsItem where
parseJSON
= withObject "StatusDetailsItem"
(\ o -> StatusDetailsItem' <$> (parseJSONObject o))
instance ToJSON StatusDetailsItem where
toJSON = toJSON . _sdiAddtional
-- | Keys: the full \`name\` of each table that existed in the instance when
-- CreateCluster was first called, i.e.
-- \`projects\/\/instances\/\/tables\/\`. Any table added to the instance
-- by a later API call will be created in the new cluster by that API call,
-- not this one. Values: information on how much of a table\'s data has
-- been copied to the newly-created cluster so far.
--
-- /See:/ 'createClusterMetadataTables' smart constructor.
newtype CreateClusterMetadataTables =
CreateClusterMetadataTables'
{ _ccmtAddtional :: HashMap Text TableProgress
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateClusterMetadataTables' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccmtAddtional'
createClusterMetadataTables
:: HashMap Text TableProgress -- ^ 'ccmtAddtional'
-> CreateClusterMetadataTables
createClusterMetadataTables pCcmtAddtional_ =
CreateClusterMetadataTables' {_ccmtAddtional = _Coerce # pCcmtAddtional_}
ccmtAddtional :: Lens' CreateClusterMetadataTables (HashMap Text TableProgress)
ccmtAddtional
= lens _ccmtAddtional
(\ s a -> s{_ccmtAddtional = a})
. _Coerce
instance FromJSON CreateClusterMetadataTables where
parseJSON
= withObject "CreateClusterMetadataTables"
(\ o ->
CreateClusterMetadataTables' <$> (parseJSONObject o))
instance ToJSON CreateClusterMetadataTables where
toJSON = toJSON . _ccmtAddtional
-- | The metadata for the Operation returned by UpdateAppProfile.
--
-- /See:/ 'updateAppProFileMetadata' smart constructor.
data UpdateAppProFileMetadata =
UpdateAppProFileMetadata'
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateAppProFileMetadata' with the minimum fields required to make a request.
--
updateAppProFileMetadata
:: UpdateAppProFileMetadata
updateAppProFileMetadata = UpdateAppProFileMetadata'
instance FromJSON UpdateAppProFileMetadata where
parseJSON
= withObject "UpdateAppProFileMetadata"
(\ o -> pure UpdateAppProFileMetadata')
instance ToJSON UpdateAppProFileMetadata where
toJSON = const emptyObject
-- | Encapsulates settings provided to GetIamPolicy.
--
-- /See:/ 'getPolicyOptions' smart constructor.
newtype GetPolicyOptions =
GetPolicyOptions'
{ _gpoRequestedPolicyVersion :: Maybe (Textual Int32)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GetPolicyOptions' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gpoRequestedPolicyVersion'
getPolicyOptions
:: GetPolicyOptions
getPolicyOptions = GetPolicyOptions' {_gpoRequestedPolicyVersion = Nothing}
-- | Optional. The policy format version to be returned. Valid values are 0,
-- 1, and 3. Requests specifying an invalid value will be rejected.
-- Requests for policies with any conditional bindings must specify version
-- 3. Policies without any conditional bindings may specify any valid value
-- or leave the field unset. To learn which resources support conditions in
-- their IAM policies, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
gpoRequestedPolicyVersion :: Lens' GetPolicyOptions (Maybe Int32)
gpoRequestedPolicyVersion
= lens _gpoRequestedPolicyVersion
(\ s a -> s{_gpoRequestedPolicyVersion = a})
. mapping _Coerce
instance FromJSON GetPolicyOptions where
parseJSON
= withObject "GetPolicyOptions"
(\ o ->
GetPolicyOptions' <$>
(o .:? "requestedPolicyVersion"))
instance ToJSON GetPolicyOptions where
toJSON GetPolicyOptions'{..}
= object
(catMaybes
[("requestedPolicyVersion" .=) <$>
_gpoRequestedPolicyVersion])
-- | A backup of a Cloud Bigtable table.
--
-- /See:/ 'backup' smart constructor.
data Backup =
Backup'
{ _bSizeBytes :: !(Maybe (Textual Int64))
, _bState :: !(Maybe BackupState)
, _bStartTime :: !(Maybe DateTime')
, _bSourceTable :: !(Maybe Text)
, _bName :: !(Maybe Text)
, _bEndTime :: !(Maybe DateTime')
, _bExpireTime :: !(Maybe DateTime')
, _bEncryptionInfo :: !(Maybe EncryptionInfo)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Backup' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bSizeBytes'
--
-- * 'bState'
--
-- * 'bStartTime'
--
-- * 'bSourceTable'
--
-- * 'bName'
--
-- * 'bEndTime'
--
-- * 'bExpireTime'
--
-- * 'bEncryptionInfo'
backup
:: Backup
backup =
Backup'
{ _bSizeBytes = Nothing
, _bState = Nothing
, _bStartTime = Nothing
, _bSourceTable = Nothing
, _bName = Nothing
, _bEndTime = Nothing
, _bExpireTime = Nothing
, _bEncryptionInfo = Nothing
}
-- | Output only. Size of the backup in bytes.
bSizeBytes :: Lens' Backup (Maybe Int64)
bSizeBytes
= lens _bSizeBytes (\ s a -> s{_bSizeBytes = a}) .
mapping _Coerce
-- | Output only. The current state of the backup.
bState :: Lens' Backup (Maybe BackupState)
bState = lens _bState (\ s a -> s{_bState = a})
-- | Output only. \`start_time\` is the time that the backup was started
-- (i.e. approximately the time the CreateBackup request is received). The
-- row data in this backup will be no older than this timestamp.
bStartTime :: Lens' Backup (Maybe UTCTime)
bStartTime
= lens _bStartTime (\ s a -> s{_bStartTime = a}) .
mapping _DateTime
-- | Required. Immutable. Name of the table from which this backup was
-- created. This needs to be in the same instance as the backup. Values are
-- of the form
-- \`projects\/{project}\/instances\/{instance}\/tables\/{source_table}\`.
bSourceTable :: Lens' Backup (Maybe Text)
bSourceTable
= lens _bSourceTable (\ s a -> s{_bSourceTable = a})
-- | A globally unique identifier for the backup which cannot be changed.
-- Values are of the form
-- \`projects\/{project}\/instances\/{instance}\/clusters\/{cluster}\/
-- backups\/_a-zA-Z0-9*\` The final segment of the name must be between 1
-- and 50 characters in length. The backup is stored in the cluster
-- identified by the prefix of the backup name of the form
-- \`projects\/{project}\/instances\/{instance}\/clusters\/{cluster}\`.
bName :: Lens' Backup (Maybe Text)
bName = lens _bName (\ s a -> s{_bName = a})
-- | Output only. \`end_time\` is the time that the backup was finished. The
-- row data in the backup will be no newer than this timestamp.
bEndTime :: Lens' Backup (Maybe UTCTime)
bEndTime
= lens _bEndTime (\ s a -> s{_bEndTime = a}) .
mapping _DateTime
-- | Required. The expiration time of the backup, with microseconds
-- granularity that must be at least 6 hours and at most 30 days from the
-- time the request is received. Once the \`expire_time\` has passed, Cloud
-- Bigtable will delete the backup and free the resources used by the
-- backup.
bExpireTime :: Lens' Backup (Maybe UTCTime)
bExpireTime
= lens _bExpireTime (\ s a -> s{_bExpireTime = a}) .
mapping _DateTime
-- | Output only. The encryption information for the backup.
bEncryptionInfo :: Lens' Backup (Maybe EncryptionInfo)
bEncryptionInfo
= lens _bEncryptionInfo
(\ s a -> s{_bEncryptionInfo = a})
instance FromJSON Backup where
parseJSON
= withObject "Backup"
(\ o ->
Backup' <$>
(o .:? "sizeBytes") <*> (o .:? "state") <*>
(o .:? "startTime")
<*> (o .:? "sourceTable")
<*> (o .:? "name")
<*> (o .:? "endTime")
<*> (o .:? "expireTime")
<*> (o .:? "encryptionInfo"))
instance ToJSON Backup where
toJSON Backup'{..}
= object
(catMaybes
[("sizeBytes" .=) <$> _bSizeBytes,
("state" .=) <$> _bState,
("startTime" .=) <$> _bStartTime,
("sourceTable" .=) <$> _bSourceTable,
("name" .=) <$> _bName, ("endTime" .=) <$> _bEndTime,
("expireTime" .=) <$> _bExpireTime,
("encryptionInfo" .=) <$> _bEncryptionInfo])
-- | The metadata for the Operation returned by UpdateCluster.
--
-- /See:/ 'updateClusterMetadata' smart constructor.
data UpdateClusterMetadata =
UpdateClusterMetadata'
{ _ucmRequestTime :: !(Maybe DateTime')
, _ucmOriginalRequest :: !(Maybe Cluster)
, _ucmFinishTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateClusterMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ucmRequestTime'
--
-- * 'ucmOriginalRequest'
--
-- * 'ucmFinishTime'
updateClusterMetadata
:: UpdateClusterMetadata
updateClusterMetadata =
UpdateClusterMetadata'
{ _ucmRequestTime = Nothing
, _ucmOriginalRequest = Nothing
, _ucmFinishTime = Nothing
}
-- | The time at which the original request was received.
ucmRequestTime :: Lens' UpdateClusterMetadata (Maybe UTCTime)
ucmRequestTime
= lens _ucmRequestTime
(\ s a -> s{_ucmRequestTime = a})
. mapping _DateTime
-- | The request that prompted the initiation of this UpdateCluster
-- operation.
ucmOriginalRequest :: Lens' UpdateClusterMetadata (Maybe Cluster)
ucmOriginalRequest
= lens _ucmOriginalRequest
(\ s a -> s{_ucmOriginalRequest = a})
-- | The time at which the operation failed or was completed successfully.
ucmFinishTime :: Lens' UpdateClusterMetadata (Maybe UTCTime)
ucmFinishTime
= lens _ucmFinishTime
(\ s a -> s{_ucmFinishTime = a})
. mapping _DateTime
instance FromJSON UpdateClusterMetadata where
parseJSON
= withObject "UpdateClusterMetadata"
(\ o ->
UpdateClusterMetadata' <$>
(o .:? "requestTime") <*> (o .:? "originalRequest")
<*> (o .:? "finishTime"))
instance ToJSON UpdateClusterMetadata where
toJSON UpdateClusterMetadata'{..}
= object
(catMaybes
[("requestTime" .=) <$> _ucmRequestTime,
("originalRequest" .=) <$> _ucmOriginalRequest,
("finishTime" .=) <$> _ucmFinishTime])
-- | Request message for \`SetIamPolicy\` method.
--
-- /See:/ 'setIAMPolicyRequest' smart constructor.
data SetIAMPolicyRequest =
SetIAMPolicyRequest'
{ _siprUpdateMask :: !(Maybe GFieldMask)
, _siprPolicy :: !(Maybe Policy)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'SetIAMPolicyRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'siprUpdateMask'
--
-- * 'siprPolicy'
setIAMPolicyRequest
:: SetIAMPolicyRequest
setIAMPolicyRequest =
SetIAMPolicyRequest' {_siprUpdateMask = Nothing, _siprPolicy = Nothing}
-- | OPTIONAL: A FieldMask specifying which fields of the policy to modify.
-- Only the fields in the mask will be modified. If no mask is provided,
-- the following default mask is used: \`paths: \"bindings, etag\"\`
siprUpdateMask :: Lens' SetIAMPolicyRequest (Maybe GFieldMask)
siprUpdateMask
= lens _siprUpdateMask
(\ s a -> s{_siprUpdateMask = a})
-- | REQUIRED: The complete policy to be applied to the \`resource\`. The
-- size of the policy is limited to a few 10s of KB. An empty policy is a
-- valid policy but certain Cloud Platform services (such as Projects)
-- might reject them.
siprPolicy :: Lens' SetIAMPolicyRequest (Maybe Policy)
siprPolicy
= lens _siprPolicy (\ s a -> s{_siprPolicy = a})
instance FromJSON SetIAMPolicyRequest where
parseJSON
= withObject "SetIAMPolicyRequest"
(\ o ->
SetIAMPolicyRequest' <$>
(o .:? "updateMask") <*> (o .:? "policy"))
instance ToJSON SetIAMPolicyRequest where
toJSON SetIAMPolicyRequest'{..}
= object
(catMaybes
[("updateMask" .=) <$> _siprUpdateMask,
("policy" .=) <$> _siprPolicy])
-- | Added to the error payload.
--
-- /See:/ 'failureTrace' smart constructor.
newtype FailureTrace =
FailureTrace'
{ _ftFrames :: Maybe [Frame]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'FailureTrace' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ftFrames'
failureTrace
:: FailureTrace
failureTrace = FailureTrace' {_ftFrames = Nothing}
ftFrames :: Lens' FailureTrace [Frame]
ftFrames
= lens _ftFrames (\ s a -> s{_ftFrames = a}) .
_Default
. _Coerce
instance FromJSON FailureTrace where
parseJSON
= withObject "FailureTrace"
(\ o ->
FailureTrace' <$> (o .:? "frames" .!= mempty))
instance ToJSON FailureTrace where
toJSON FailureTrace'{..}
= object (catMaybes [("frames" .=) <$> _ftFrames])
-- | Request message for
-- google.bigtable.admin.v2.BigtableTableAdmin.CheckConsistency
--
-- /See:/ 'checkConsistencyRequest' smart constructor.
newtype CheckConsistencyRequest =
CheckConsistencyRequest'
{ _ccrConsistencyToken :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CheckConsistencyRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccrConsistencyToken'
checkConsistencyRequest
:: CheckConsistencyRequest
checkConsistencyRequest =
CheckConsistencyRequest' {_ccrConsistencyToken = Nothing}
-- | Required. The token created using GenerateConsistencyToken for the
-- Table.
ccrConsistencyToken :: Lens' CheckConsistencyRequest (Maybe Text)
ccrConsistencyToken
= lens _ccrConsistencyToken
(\ s a -> s{_ccrConsistencyToken = a})
instance FromJSON CheckConsistencyRequest where
parseJSON
= withObject "CheckConsistencyRequest"
(\ o ->
CheckConsistencyRequest' <$>
(o .:? "consistencyToken"))
instance ToJSON CheckConsistencyRequest where
toJSON CheckConsistencyRequest'{..}
= object
(catMaybes
[("consistencyToken" .=) <$> _ccrConsistencyToken])
-- | Response message for
-- google.bigtable.admin.v2.BigtableTableAdmin.ListTables
--
-- /See:/ 'listTablesResponse' smart constructor.
data ListTablesResponse =
ListTablesResponse'
{ _ltrNextPageToken :: !(Maybe Text)
, _ltrTables :: !(Maybe [Table])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListTablesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ltrNextPageToken'
--
-- * 'ltrTables'
listTablesResponse
:: ListTablesResponse
listTablesResponse =
ListTablesResponse' {_ltrNextPageToken = Nothing, _ltrTables = Nothing}
-- | Set if not all tables could be returned in a single response. Pass this
-- value to \`page_token\` in another request to get the next page of
-- results.
ltrNextPageToken :: Lens' ListTablesResponse (Maybe Text)
ltrNextPageToken
= lens _ltrNextPageToken
(\ s a -> s{_ltrNextPageToken = a})
-- | The tables present in the requested instance.
ltrTables :: Lens' ListTablesResponse [Table]
ltrTables
= lens _ltrTables (\ s a -> s{_ltrTables = a}) .
_Default
. _Coerce
instance FromJSON ListTablesResponse where
parseJSON
= withObject "ListTablesResponse"
(\ o ->
ListTablesResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "tables" .!= mempty))
instance ToJSON ListTablesResponse where
toJSON ListTablesResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _ltrNextPageToken,
("tables" .=) <$> _ltrTables])
-- | The request for RestoreTable.
--
-- /See:/ 'restoreTableRequest' smart constructor.
data RestoreTableRequest =
RestoreTableRequest'
{ _rtrBackup :: !(Maybe Text)
, _rtrTableId :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RestoreTableRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rtrBackup'
--
-- * 'rtrTableId'
restoreTableRequest
:: RestoreTableRequest
restoreTableRequest =
RestoreTableRequest' {_rtrBackup = Nothing, _rtrTableId = Nothing}
-- | Name of the backup from which to restore. Values are of the form
-- \`projects\/\/instances\/\/clusters\/\/backups\/\`.
rtrBackup :: Lens' RestoreTableRequest (Maybe Text)
rtrBackup
= lens _rtrBackup (\ s a -> s{_rtrBackup = a})
-- | Required. The id of the table to create and restore to. This table must
-- not already exist. The \`table_id\` appended to \`parent\` forms the
-- full table name of the form \`projects\/\/instances\/\/tables\/\`.
rtrTableId :: Lens' RestoreTableRequest (Maybe Text)
rtrTableId
= lens _rtrTableId (\ s a -> s{_rtrTableId = a})
instance FromJSON RestoreTableRequest where
parseJSON
= withObject "RestoreTableRequest"
(\ o ->
RestoreTableRequest' <$>
(o .:? "backup") <*> (o .:? "tableId"))
instance ToJSON RestoreTableRequest where
toJSON RestoreTableRequest'{..}
= object
(catMaybes
[("backup" .=) <$> _rtrBackup,
("tableId" .=) <$> _rtrTableId])
-- | Metadata type for the operation returned by CreateBackup.
--
-- /See:/ 'createBackupMetadata' smart constructor.
data CreateBackupMetadata =
CreateBackupMetadata'
{ _cbmStartTime :: !(Maybe DateTime')
, _cbmSourceTable :: !(Maybe Text)
, _cbmName :: !(Maybe Text)
, _cbmEndTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateBackupMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cbmStartTime'
--
-- * 'cbmSourceTable'
--
-- * 'cbmName'
--
-- * 'cbmEndTime'
createBackupMetadata
:: CreateBackupMetadata
createBackupMetadata =
CreateBackupMetadata'
{ _cbmStartTime = Nothing
, _cbmSourceTable = Nothing
, _cbmName = Nothing
, _cbmEndTime = Nothing
}
-- | The time at which this operation started.
cbmStartTime :: Lens' CreateBackupMetadata (Maybe UTCTime)
cbmStartTime
= lens _cbmStartTime (\ s a -> s{_cbmStartTime = a})
. mapping _DateTime
-- | The name of the table the backup is created from.
cbmSourceTable :: Lens' CreateBackupMetadata (Maybe Text)
cbmSourceTable
= lens _cbmSourceTable
(\ s a -> s{_cbmSourceTable = a})
-- | The name of the backup being created.
cbmName :: Lens' CreateBackupMetadata (Maybe Text)
cbmName = lens _cbmName (\ s a -> s{_cbmName = a})
-- | If set, the time at which this operation finished or was cancelled.
cbmEndTime :: Lens' CreateBackupMetadata (Maybe UTCTime)
cbmEndTime
= lens _cbmEndTime (\ s a -> s{_cbmEndTime = a}) .
mapping _DateTime
instance FromJSON CreateBackupMetadata where
parseJSON
= withObject "CreateBackupMetadata"
(\ o ->
CreateBackupMetadata' <$>
(o .:? "startTime") <*> (o .:? "sourceTable") <*>
(o .:? "name")
<*> (o .:? "endTime"))
instance ToJSON CreateBackupMetadata where
toJSON CreateBackupMetadata'{..}
= object
(catMaybes
[("startTime" .=) <$> _cbmStartTime,
("sourceTable" .=) <$> _cbmSourceTable,
("name" .=) <$> _cbmName,
("endTime" .=) <$> _cbmEndTime])
-- | Request message for BigtableInstanceAdmin.PartialUpdateInstance.
--
-- /See:/ 'partialUpdateInstanceRequest' smart constructor.
data PartialUpdateInstanceRequest =
PartialUpdateInstanceRequest'
{ _puirUpdateMask :: !(Maybe GFieldMask)
, _puirInstance :: !(Maybe Instance)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'PartialUpdateInstanceRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'puirUpdateMask'
--
-- * 'puirInstance'
partialUpdateInstanceRequest
:: PartialUpdateInstanceRequest
partialUpdateInstanceRequest =
PartialUpdateInstanceRequest'
{_puirUpdateMask = Nothing, _puirInstance = Nothing}
-- | Required. The subset of Instance fields which should be replaced. Must
-- be explicitly set.
puirUpdateMask :: Lens' PartialUpdateInstanceRequest (Maybe GFieldMask)
puirUpdateMask
= lens _puirUpdateMask
(\ s a -> s{_puirUpdateMask = a})
-- | Required. The Instance which will (partially) replace the current value.
puirInstance :: Lens' PartialUpdateInstanceRequest (Maybe Instance)
puirInstance
= lens _puirInstance (\ s a -> s{_puirInstance = a})
instance FromJSON PartialUpdateInstanceRequest where
parseJSON
= withObject "PartialUpdateInstanceRequest"
(\ o ->
PartialUpdateInstanceRequest' <$>
(o .:? "updateMask") <*> (o .:? "instance"))
instance ToJSON PartialUpdateInstanceRequest where
toJSON PartialUpdateInstanceRequest'{..}
= object
(catMaybes
[("updateMask" .=) <$> _puirUpdateMask,
("instance" .=) <$> _puirInstance])
-- | Rule for determining which cells to delete during garbage collection.
--
-- /See:/ 'gcRule' smart constructor.
data GcRule =
GcRule'
{ _grMaxAge :: !(Maybe GDuration)
, _grUnion :: !(Maybe Union)
, _grIntersection :: !(Maybe Intersection)
, _grMaxNumVersions :: !(Maybe (Textual Int32))
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GcRule' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'grMaxAge'
--
-- * 'grUnion'
--
-- * 'grIntersection'
--
-- * 'grMaxNumVersions'
gcRule
:: GcRule
gcRule =
GcRule'
{ _grMaxAge = Nothing
, _grUnion = Nothing
, _grIntersection = Nothing
, _grMaxNumVersions = Nothing
}
-- | Delete cells in a column older than the given age. Values must be at
-- least one millisecond, and will be truncated to microsecond granularity.
grMaxAge :: Lens' GcRule (Maybe Scientific)
grMaxAge
= lens _grMaxAge (\ s a -> s{_grMaxAge = a}) .
mapping _GDuration
-- | Delete cells that would be deleted by any nested rule.
grUnion :: Lens' GcRule (Maybe Union)
grUnion = lens _grUnion (\ s a -> s{_grUnion = a})
-- | Delete cells that would be deleted by every nested rule.
grIntersection :: Lens' GcRule (Maybe Intersection)
grIntersection
= lens _grIntersection
(\ s a -> s{_grIntersection = a})
-- | Delete all cells in a column except the most recent N.
grMaxNumVersions :: Lens' GcRule (Maybe Int32)
grMaxNumVersions
= lens _grMaxNumVersions
(\ s a -> s{_grMaxNumVersions = a})
. mapping _Coerce
instance FromJSON GcRule where
parseJSON
= withObject "GcRule"
(\ o ->
GcRule' <$>
(o .:? "maxAge") <*> (o .:? "union") <*>
(o .:? "intersection")
<*> (o .:? "maxNumVersions"))
instance ToJSON GcRule where
toJSON GcRule'{..}
= object
(catMaybes
[("maxAge" .=) <$> _grMaxAge,
("union" .=) <$> _grUnion,
("intersection" .=) <$> _grIntersection,
("maxNumVersions" .=) <$> _grMaxNumVersions])
-- | Request message for \`TestIamPermissions\` method.
--
-- /See:/ 'testIAMPermissionsRequest' smart constructor.
newtype TestIAMPermissionsRequest =
TestIAMPermissionsRequest'
{ _tiprPermissions :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TestIAMPermissionsRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiprPermissions'
testIAMPermissionsRequest
:: TestIAMPermissionsRequest
testIAMPermissionsRequest =
TestIAMPermissionsRequest' {_tiprPermissions = Nothing}
-- | The set of permissions to check for the \`resource\`. Permissions with
-- wildcards (such as \'*\' or \'storage.*\') are not allowed. For more
-- information see [IAM
-- Overview](https:\/\/cloud.google.com\/iam\/docs\/overview#permissions).
tiprPermissions :: Lens' TestIAMPermissionsRequest [Text]
tiprPermissions
= lens _tiprPermissions
(\ s a -> s{_tiprPermissions = a})
. _Default
. _Coerce
instance FromJSON TestIAMPermissionsRequest where
parseJSON
= withObject "TestIAMPermissionsRequest"
(\ o ->
TestIAMPermissionsRequest' <$>
(o .:? "permissions" .!= mempty))
instance ToJSON TestIAMPermissionsRequest where
toJSON TestIAMPermissionsRequest'{..}
= object
(catMaybes [("permissions" .=) <$> _tiprPermissions])
-- | A configuration object describing how Cloud Bigtable should treat
-- traffic from a particular end user application.
--
-- /See:/ 'appProFile' smart constructor.
data AppProFile =
AppProFile'
{ _apfSingleClusterRouting :: !(Maybe SingleClusterRouting)
, _apfEtag :: !(Maybe Text)
, _apfMultiClusterRoutingUseAny :: !(Maybe MultiClusterRoutingUseAny)
, _apfName :: !(Maybe Text)
, _apfDescription :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AppProFile' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'apfSingleClusterRouting'
--
-- * 'apfEtag'
--
-- * 'apfMultiClusterRoutingUseAny'
--
-- * 'apfName'
--
-- * 'apfDescription'
appProFile
:: AppProFile
appProFile =
AppProFile'
{ _apfSingleClusterRouting = Nothing
, _apfEtag = Nothing
, _apfMultiClusterRoutingUseAny = Nothing
, _apfName = Nothing
, _apfDescription = Nothing
}
-- | Use a single-cluster routing policy.
apfSingleClusterRouting :: Lens' AppProFile (Maybe SingleClusterRouting)
apfSingleClusterRouting
= lens _apfSingleClusterRouting
(\ s a -> s{_apfSingleClusterRouting = a})
-- | Strongly validated etag for optimistic concurrency control. Preserve the
-- value returned from \`GetAppProfile\` when calling \`UpdateAppProfile\`
-- to fail the request if there has been a modification in the mean time.
-- The \`update_mask\` of the request need not include \`etag\` for this
-- protection to apply. See
-- [Wikipedia](https:\/\/en.wikipedia.org\/wiki\/HTTP_ETag) and [RFC
-- 7232](https:\/\/tools.ietf.org\/html\/rfc7232#section-2.3) for more
-- details.
apfEtag :: Lens' AppProFile (Maybe Text)
apfEtag = lens _apfEtag (\ s a -> s{_apfEtag = a})
-- | Use a multi-cluster routing policy.
apfMultiClusterRoutingUseAny :: Lens' AppProFile (Maybe MultiClusterRoutingUseAny)
apfMultiClusterRoutingUseAny
= lens _apfMultiClusterRoutingUseAny
(\ s a -> s{_apfMultiClusterRoutingUseAny = a})
-- | The unique name of the app profile. Values are of the form
-- \`projects\/{project}\/instances\/{instance}\/appProfiles\/_a-zA-Z0-9*\`.
apfName :: Lens' AppProFile (Maybe Text)
apfName = lens _apfName (\ s a -> s{_apfName = a})
-- | Long form description of the use case for this AppProfile.
apfDescription :: Lens' AppProFile (Maybe Text)
apfDescription
= lens _apfDescription
(\ s a -> s{_apfDescription = a})
instance FromJSON AppProFile where
parseJSON
= withObject "AppProFile"
(\ o ->
AppProFile' <$>
(o .:? "singleClusterRouting") <*> (o .:? "etag") <*>
(o .:? "multiClusterRoutingUseAny")
<*> (o .:? "name")
<*> (o .:? "description"))
instance ToJSON AppProFile where
toJSON AppProFile'{..}
= object
(catMaybes
[("singleClusterRouting" .=) <$>
_apfSingleClusterRouting,
("etag" .=) <$> _apfEtag,
("multiClusterRoutingUseAny" .=) <$>
_apfMultiClusterRoutingUseAny,
("name" .=) <$> _apfName,
("description" .=) <$> _apfDescription])
--
-- /See:/ 'frame' smart constructor.
data Frame =
Frame'
{ _fWorkflowGuid :: !(Maybe Text)
, _fZoneId :: !(Maybe Text)
, _fTargetName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Frame' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'fWorkflowGuid'
--
-- * 'fZoneId'
--
-- * 'fTargetName'
frame
:: Frame
frame =
Frame' {_fWorkflowGuid = Nothing, _fZoneId = Nothing, _fTargetName = Nothing}
fWorkflowGuid :: Lens' Frame (Maybe Text)
fWorkflowGuid
= lens _fWorkflowGuid
(\ s a -> s{_fWorkflowGuid = a})
fZoneId :: Lens' Frame (Maybe Text)
fZoneId = lens _fZoneId (\ s a -> s{_fZoneId = a})
fTargetName :: Lens' Frame (Maybe Text)
fTargetName
= lens _fTargetName (\ s a -> s{_fTargetName = a})
instance FromJSON Frame where
parseJSON
= withObject "Frame"
(\ o ->
Frame' <$>
(o .:? "workflowGuid") <*> (o .:? "zoneId") <*>
(o .:? "targetName"))
instance ToJSON Frame where
toJSON Frame'{..}
= object
(catMaybes
[("workflowGuid" .=) <$> _fWorkflowGuid,
("zoneId" .=) <$> _fZoneId,
("targetName" .=) <$> _fTargetName])
-- | Required. The clusters to be created within the instance, mapped by
-- desired cluster ID, e.g., just \`mycluster\` rather than
-- \`projects\/myproject\/instances\/myinstance\/clusters\/mycluster\`.
-- Fields marked \`OutputOnly\` must be left blank. Currently, at most four
-- clusters can be specified.
--
-- /See:/ 'createInstanceRequestClusters' smart constructor.
newtype CreateInstanceRequestClusters =
CreateInstanceRequestClusters'
{ _circAddtional :: HashMap Text Cluster
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateInstanceRequestClusters' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'circAddtional'
createInstanceRequestClusters
:: HashMap Text Cluster -- ^ 'circAddtional'
-> CreateInstanceRequestClusters
createInstanceRequestClusters pCircAddtional_ =
CreateInstanceRequestClusters' {_circAddtional = _Coerce # pCircAddtional_}
circAddtional :: Lens' CreateInstanceRequestClusters (HashMap Text Cluster)
circAddtional
= lens _circAddtional
(\ s a -> s{_circAddtional = a})
. _Coerce
instance FromJSON CreateInstanceRequestClusters where
parseJSON
= withObject "CreateInstanceRequestClusters"
(\ o ->
CreateInstanceRequestClusters' <$>
(parseJSONObject o))
instance ToJSON CreateInstanceRequestClusters where
toJSON = toJSON . _circAddtional
-- | Response message for
-- google.bigtable.admin.v2.BigtableTableAdmin.GenerateConsistencyToken
--
-- /See:/ 'generateConsistencyTokenResponse' smart constructor.
newtype GenerateConsistencyTokenResponse =
GenerateConsistencyTokenResponse'
{ _gctrConsistencyToken :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'GenerateConsistencyTokenResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'gctrConsistencyToken'
generateConsistencyTokenResponse
:: GenerateConsistencyTokenResponse
generateConsistencyTokenResponse =
GenerateConsistencyTokenResponse' {_gctrConsistencyToken = Nothing}
-- | The generated consistency token.
gctrConsistencyToken :: Lens' GenerateConsistencyTokenResponse (Maybe Text)
gctrConsistencyToken
= lens _gctrConsistencyToken
(\ s a -> s{_gctrConsistencyToken = a})
instance FromJSON GenerateConsistencyTokenResponse
where
parseJSON
= withObject "GenerateConsistencyTokenResponse"
(\ o ->
GenerateConsistencyTokenResponse' <$>
(o .:? "consistencyToken"))
instance ToJSON GenerateConsistencyTokenResponse
where
toJSON GenerateConsistencyTokenResponse'{..}
= object
(catMaybes
[("consistencyToken" .=) <$> _gctrConsistencyToken])
-- | Cloud Key Management Service (Cloud KMS) settings for a CMEK-protected
-- cluster.
--
-- /See:/ 'encryptionConfig' smart constructor.
newtype EncryptionConfig =
EncryptionConfig'
{ _ecKmsKeyName :: Maybe Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EncryptionConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ecKmsKeyName'
encryptionConfig
:: EncryptionConfig
encryptionConfig = EncryptionConfig' {_ecKmsKeyName = Nothing}
-- | Describes the Cloud KMS encryption key that will be used to protect the
-- destination Bigtable cluster. The requirements for this key are: 1) The
-- Cloud Bigtable service account associated with the project that contains
-- this cluster must be granted the
-- \`cloudkms.cryptoKeyEncrypterDecrypter\` role on the CMEK key. 2) Only
-- regional keys can be used and the region of the CMEK key must match the
-- region of the cluster. 3) All clusters within an instance must use the
-- same CMEK key. Values are of the form
-- \`projects\/{project}\/locations\/{location}\/keyRings\/{keyring}\/cryptoKeys\/{key}\`
ecKmsKeyName :: Lens' EncryptionConfig (Maybe Text)
ecKmsKeyName
= lens _ecKmsKeyName (\ s a -> s{_ecKmsKeyName = a})
instance FromJSON EncryptionConfig where
parseJSON
= withObject "EncryptionConfig"
(\ o -> EncryptionConfig' <$> (o .:? "kmsKeyName"))
instance ToJSON EncryptionConfig where
toJSON EncryptionConfig'{..}
= object
(catMaybes [("kmsKeyName" .=) <$> _ecKmsKeyName])
-- | Request message for
-- google.bigtable.admin.v2.BigtableTableAdmin.DropRowRange
--
-- /See:/ 'dropRowRangeRequest' smart constructor.
data DropRowRangeRequest =
DropRowRangeRequest'
{ _drrrRowKeyPrefix :: !(Maybe Bytes)
, _drrrDeleteAllDataFromTable :: !(Maybe Bool)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'DropRowRangeRequest' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'drrrRowKeyPrefix'
--
-- * 'drrrDeleteAllDataFromTable'
dropRowRangeRequest
:: DropRowRangeRequest
dropRowRangeRequest =
DropRowRangeRequest'
{_drrrRowKeyPrefix = Nothing, _drrrDeleteAllDataFromTable = Nothing}
-- | Delete all rows that start with this row key prefix. Prefix cannot be
-- zero length.
drrrRowKeyPrefix :: Lens' DropRowRangeRequest (Maybe ByteString)
drrrRowKeyPrefix
= lens _drrrRowKeyPrefix
(\ s a -> s{_drrrRowKeyPrefix = a})
. mapping _Bytes
-- | Delete all rows in the table. Setting this to false is a no-op.
drrrDeleteAllDataFromTable :: Lens' DropRowRangeRequest (Maybe Bool)
drrrDeleteAllDataFromTable
= lens _drrrDeleteAllDataFromTable
(\ s a -> s{_drrrDeleteAllDataFromTable = a})
instance FromJSON DropRowRangeRequest where
parseJSON
= withObject "DropRowRangeRequest"
(\ o ->
DropRowRangeRequest' <$>
(o .:? "rowKeyPrefix") <*>
(o .:? "deleteAllDataFromTable"))
instance ToJSON DropRowRangeRequest where
toJSON DropRowRangeRequest'{..}
= object
(catMaybes
[("rowKeyPrefix" .=) <$> _drrrRowKeyPrefix,
("deleteAllDataFromTable" .=) <$>
_drrrDeleteAllDataFromTable])
-- | The metadata for the Operation returned by UpdateInstance.
--
-- /See:/ 'updateInstanceMetadata' smart constructor.
data UpdateInstanceMetadata =
UpdateInstanceMetadata'
{ _uimRequestTime :: !(Maybe DateTime')
, _uimOriginalRequest :: !(Maybe PartialUpdateInstanceRequest)
, _uimFinishTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'UpdateInstanceMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'uimRequestTime'
--
-- * 'uimOriginalRequest'
--
-- * 'uimFinishTime'
updateInstanceMetadata
:: UpdateInstanceMetadata
updateInstanceMetadata =
UpdateInstanceMetadata'
{ _uimRequestTime = Nothing
, _uimOriginalRequest = Nothing
, _uimFinishTime = Nothing
}
-- | The time at which the original request was received.
uimRequestTime :: Lens' UpdateInstanceMetadata (Maybe UTCTime)
uimRequestTime
= lens _uimRequestTime
(\ s a -> s{_uimRequestTime = a})
. mapping _DateTime
-- | The request that prompted the initiation of this UpdateInstance
-- operation.
uimOriginalRequest :: Lens' UpdateInstanceMetadata (Maybe PartialUpdateInstanceRequest)
uimOriginalRequest
= lens _uimOriginalRequest
(\ s a -> s{_uimOriginalRequest = a})
-- | The time at which the operation failed or was completed successfully.
uimFinishTime :: Lens' UpdateInstanceMetadata (Maybe UTCTime)
uimFinishTime
= lens _uimFinishTime
(\ s a -> s{_uimFinishTime = a})
. mapping _DateTime
instance FromJSON UpdateInstanceMetadata where
parseJSON
= withObject "UpdateInstanceMetadata"
(\ o ->
UpdateInstanceMetadata' <$>
(o .:? "requestTime") <*> (o .:? "originalRequest")
<*> (o .:? "finishTime"))
instance ToJSON UpdateInstanceMetadata where
toJSON UpdateInstanceMetadata'{..}
= object
(catMaybes
[("requestTime" .=) <$> _uimRequestTime,
("originalRequest" .=) <$> _uimOriginalRequest,
("finishTime" .=) <$> _uimFinishTime])
-- | A GcRule which deletes cells matching all of the given rules.
--
-- /See:/ 'intersection' smart constructor.
newtype Intersection =
Intersection'
{ _iRules :: Maybe [GcRule]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Intersection' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iRules'
intersection
:: Intersection
intersection = Intersection' {_iRules = Nothing}
-- | Only delete cells which would be deleted by every element of \`rules\`.
iRules :: Lens' Intersection [GcRule]
iRules
= lens _iRules (\ s a -> s{_iRules = a}) . _Default .
_Coerce
instance FromJSON Intersection where
parseJSON
= withObject "Intersection"
(\ o -> Intersection' <$> (o .:? "rules" .!= mempty))
instance ToJSON Intersection where
toJSON Intersection'{..}
= object (catMaybes [("rules" .=) <$> _iRules])
-- | A set of columns within a table which share a common configuration.
--
-- /See:/ 'columnFamily' smart constructor.
newtype ColumnFamily =
ColumnFamily'
{ _cfGcRule :: Maybe GcRule
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ColumnFamily' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cfGcRule'
columnFamily
:: ColumnFamily
columnFamily = ColumnFamily' {_cfGcRule = Nothing}
-- | Garbage collection rule specified as a protobuf. Must serialize to at
-- most 500 bytes. NOTE: Garbage collection executes opportunistically in
-- the background, and so it\'s possible for reads to return a cell even if
-- it matches the active GC expression for its family.
cfGcRule :: Lens' ColumnFamily (Maybe GcRule)
cfGcRule = lens _cfGcRule (\ s a -> s{_cfGcRule = a})
instance FromJSON ColumnFamily where
parseJSON
= withObject "ColumnFamily"
(\ o -> ColumnFamily' <$> (o .:? "gcRule"))
instance ToJSON ColumnFamily where
toJSON ColumnFamily'{..}
= object (catMaybes [("gcRule" .=) <$> _cfGcRule])
-- | Response message for \`TestIamPermissions\` method.
--
-- /See:/ 'testIAMPermissionsResponse' smart constructor.
newtype TestIAMPermissionsResponse =
TestIAMPermissionsResponse'
{ _tiamprPermissions :: Maybe [Text]
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'TestIAMPermissionsResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tiamprPermissions'
testIAMPermissionsResponse
:: TestIAMPermissionsResponse
testIAMPermissionsResponse =
TestIAMPermissionsResponse' {_tiamprPermissions = Nothing}
-- | A subset of \`TestPermissionsRequest.permissions\` that the caller is
-- allowed.
tiamprPermissions :: Lens' TestIAMPermissionsResponse [Text]
tiamprPermissions
= lens _tiamprPermissions
(\ s a -> s{_tiamprPermissions = a})
. _Default
. _Coerce
instance FromJSON TestIAMPermissionsResponse where
parseJSON
= withObject "TestIAMPermissionsResponse"
(\ o ->
TestIAMPermissionsResponse' <$>
(o .:? "permissions" .!= mempty))
instance ToJSON TestIAMPermissionsResponse where
toJSON TestIAMPermissionsResponse'{..}
= object
(catMaybes
[("permissions" .=) <$> _tiamprPermissions])
-- | Response message for BigtableInstanceAdmin.ListClusters.
--
-- /See:/ 'listClustersResponse' smart constructor.
data ListClustersResponse =
ListClustersResponse'
{ _lcrNextPageToken :: !(Maybe Text)
, _lcrFailedLocations :: !(Maybe [Text])
, _lcrClusters :: !(Maybe [Cluster])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListClustersResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lcrNextPageToken'
--
-- * 'lcrFailedLocations'
--
-- * 'lcrClusters'
listClustersResponse
:: ListClustersResponse
listClustersResponse =
ListClustersResponse'
{ _lcrNextPageToken = Nothing
, _lcrFailedLocations = Nothing
, _lcrClusters = Nothing
}
-- | DEPRECATED: This field is unused and ignored.
lcrNextPageToken :: Lens' ListClustersResponse (Maybe Text)
lcrNextPageToken
= lens _lcrNextPageToken
(\ s a -> s{_lcrNextPageToken = a})
-- | Locations from which Cluster information could not be retrieved, due to
-- an outage or some other transient condition. Clusters from these
-- locations may be missing from \`clusters\`, or may only have partial
-- information returned. Values are of the form \`projects\/\/locations\/\`
lcrFailedLocations :: Lens' ListClustersResponse [Text]
lcrFailedLocations
= lens _lcrFailedLocations
(\ s a -> s{_lcrFailedLocations = a})
. _Default
. _Coerce
-- | The list of requested clusters.
lcrClusters :: Lens' ListClustersResponse [Cluster]
lcrClusters
= lens _lcrClusters (\ s a -> s{_lcrClusters = a}) .
_Default
. _Coerce
instance FromJSON ListClustersResponse where
parseJSON
= withObject "ListClustersResponse"
(\ o ->
ListClustersResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "failedLocations" .!= mempty)
<*> (o .:? "clusters" .!= mempty))
instance ToJSON ListClustersResponse where
toJSON ListClustersResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lcrNextPageToken,
("failedLocations" .=) <$> _lcrFailedLocations,
("clusters" .=) <$> _lcrClusters])
-- | Information about a backup.
--
-- /See:/ 'backupInfo' smart constructor.
data BackupInfo =
BackupInfo'
{ _biStartTime :: !(Maybe DateTime')
, _biSourceTable :: !(Maybe Text)
, _biBackup :: !(Maybe Text)
, _biEndTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'BackupInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'biStartTime'
--
-- * 'biSourceTable'
--
-- * 'biBackup'
--
-- * 'biEndTime'
backupInfo
:: BackupInfo
backupInfo =
BackupInfo'
{ _biStartTime = Nothing
, _biSourceTable = Nothing
, _biBackup = Nothing
, _biEndTime = Nothing
}
-- | Output only. The time that the backup was started. Row data in the
-- backup will be no older than this timestamp.
biStartTime :: Lens' BackupInfo (Maybe UTCTime)
biStartTime
= lens _biStartTime (\ s a -> s{_biStartTime = a}) .
mapping _DateTime
-- | Output only. Name of the table the backup was created from.
biSourceTable :: Lens' BackupInfo (Maybe Text)
biSourceTable
= lens _biSourceTable
(\ s a -> s{_biSourceTable = a})
-- | Output only. Name of the backup.
biBackup :: Lens' BackupInfo (Maybe Text)
biBackup = lens _biBackup (\ s a -> s{_biBackup = a})
-- | Output only. This time that the backup was finished. Row data in the
-- backup will be no newer than this timestamp.
biEndTime :: Lens' BackupInfo (Maybe UTCTime)
biEndTime
= lens _biEndTime (\ s a -> s{_biEndTime = a}) .
mapping _DateTime
instance FromJSON BackupInfo where
parseJSON
= withObject "BackupInfo"
(\ o ->
BackupInfo' <$>
(o .:? "startTime") <*> (o .:? "sourceTable") <*>
(o .:? "backup")
<*> (o .:? "endTime"))
instance ToJSON BackupInfo where
toJSON BackupInfo'{..}
= object
(catMaybes
[("startTime" .=) <$> _biStartTime,
("sourceTable" .=) <$> _biSourceTable,
("backup" .=) <$> _biBackup,
("endTime" .=) <$> _biEndTime])
-- | An Identity and Access Management (IAM) policy, which specifies access
-- controls for Google Cloud resources. A \`Policy\` is a collection of
-- \`bindings\`. A \`binding\` binds one or more \`members\` to a single
-- \`role\`. Members can be user accounts, service accounts, Google groups,
-- and domains (such as G Suite). A \`role\` is a named list of
-- permissions; each \`role\` can be an IAM predefined role or a
-- user-created custom role. For some types of Google Cloud resources, a
-- \`binding\` can also specify a \`condition\`, which is a logical
-- expression that allows access to a resource only if the expression
-- evaluates to \`true\`. A condition can add constraints based on
-- attributes of the request, the resource, or both. To learn which
-- resources support conditions in their IAM policies, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
-- **JSON example:** { \"bindings\": [ { \"role\":
-- \"roles\/resourcemanager.organizationAdmin\", \"members\": [
-- \"user:mike\'example.com\", \"group:admins\'example.com\",
-- \"domain:google.com\",
-- \"serviceAccount:my-project-id\'appspot.gserviceaccount.com\" ] }, {
-- \"role\": \"roles\/resourcemanager.organizationViewer\", \"members\": [
-- \"user:eve\'example.com\" ], \"condition\": { \"title\": \"expirable
-- access\", \"description\": \"Does not grant access after Sep 2020\",
-- \"expression\": \"request.time \<
-- timestamp(\'2020-10-01T00:00:00.000Z\')\", } } ], \"etag\":
-- \"BwWWja0YfJA=\", \"version\": 3 } **YAML example:** bindings: -
-- members: - user:mike\'example.com - group:admins\'example.com -
-- domain:google.com -
-- serviceAccount:my-project-id\'appspot.gserviceaccount.com role:
-- roles\/resourcemanager.organizationAdmin - members: -
-- user:eve\'example.com role: roles\/resourcemanager.organizationViewer
-- condition: title: expirable access description: Does not grant access
-- after Sep 2020 expression: request.time \<
-- timestamp(\'2020-10-01T00:00:00.000Z\') - etag: BwWWja0YfJA= - version:
-- 3 For a description of IAM and its features, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/docs\/).
--
-- /See:/ 'policy' smart constructor.
data Policy =
Policy'
{ _pAuditConfigs :: !(Maybe [AuditConfig])
, _pEtag :: !(Maybe Bytes)
, _pVersion :: !(Maybe (Textual Int32))
, _pBindings :: !(Maybe [Binding])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Policy' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'pAuditConfigs'
--
-- * 'pEtag'
--
-- * 'pVersion'
--
-- * 'pBindings'
policy
:: Policy
policy =
Policy'
{ _pAuditConfigs = Nothing
, _pEtag = Nothing
, _pVersion = Nothing
, _pBindings = Nothing
}
-- | Specifies cloud audit logging configuration for this policy.
pAuditConfigs :: Lens' Policy [AuditConfig]
pAuditConfigs
= lens _pAuditConfigs
(\ s a -> s{_pAuditConfigs = a})
. _Default
. _Coerce
-- | \`etag\` is used for optimistic concurrency control as a way to help
-- prevent simultaneous updates of a policy from overwriting each other. It
-- is strongly suggested that systems make use of the \`etag\` in the
-- read-modify-write cycle to perform policy updates in order to avoid race
-- conditions: An \`etag\` is returned in the response to \`getIamPolicy\`,
-- and systems are expected to put that etag in the request to
-- \`setIamPolicy\` to ensure that their change will be applied to the same
-- version of the policy. **Important:** If you use IAM Conditions, you
-- must include the \`etag\` field whenever you call \`setIamPolicy\`. If
-- you omit this field, then IAM allows you to overwrite a version \`3\`
-- policy with a version \`1\` policy, and all of the conditions in the
-- version \`3\` policy are lost.
pEtag :: Lens' Policy (Maybe ByteString)
pEtag
= lens _pEtag (\ s a -> s{_pEtag = a}) .
mapping _Bytes
-- | Specifies the format of the policy. Valid values are \`0\`, \`1\`, and
-- \`3\`. Requests that specify an invalid value are rejected. Any
-- operation that affects conditional role bindings must specify version
-- \`3\`. This requirement applies to the following operations: * Getting a
-- policy that includes a conditional role binding * Adding a conditional
-- role binding to a policy * Changing a conditional role binding in a
-- policy * Removing any role binding, with or without a condition, from a
-- policy that includes conditions **Important:** If you use IAM
-- Conditions, you must include the \`etag\` field whenever you call
-- \`setIamPolicy\`. If you omit this field, then IAM allows you to
-- overwrite a version \`3\` policy with a version \`1\` policy, and all of
-- the conditions in the version \`3\` policy are lost. If a policy does
-- not include any conditions, operations on that policy may specify any
-- valid version or leave the field unset. To learn which resources support
-- conditions in their IAM policies, see the [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
pVersion :: Lens' Policy (Maybe Int32)
pVersion
= lens _pVersion (\ s a -> s{_pVersion = a}) .
mapping _Coerce
-- | Associates a list of \`members\` to a \`role\`. Optionally, may specify
-- a \`condition\` that determines how and when the \`bindings\` are
-- applied. Each of the \`bindings\` must contain at least one member.
pBindings :: Lens' Policy [Binding]
pBindings
= lens _pBindings (\ s a -> s{_pBindings = a}) .
_Default
. _Coerce
instance FromJSON Policy where
parseJSON
= withObject "Policy"
(\ o ->
Policy' <$>
(o .:? "auditConfigs" .!= mempty) <*> (o .:? "etag")
<*> (o .:? "version")
<*> (o .:? "bindings" .!= mempty))
instance ToJSON Policy where
toJSON Policy'{..}
= object
(catMaybes
[("auditConfigs" .=) <$> _pAuditConfigs,
("etag" .=) <$> _pEtag, ("version" .=) <$> _pVersion,
("bindings" .=) <$> _pBindings])
-- | Cross-service attributes for the location. For example
-- {\"cloud.googleapis.com\/region\": \"us-east1\"}
--
-- /See:/ 'locationLabels' smart constructor.
newtype LocationLabels =
LocationLabels'
{ _llAddtional :: HashMap Text Text
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LocationLabels' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'llAddtional'
locationLabels
:: HashMap Text Text -- ^ 'llAddtional'
-> LocationLabels
locationLabels pLlAddtional_ =
LocationLabels' {_llAddtional = _Coerce # pLlAddtional_}
llAddtional :: Lens' LocationLabels (HashMap Text Text)
llAddtional
= lens _llAddtional (\ s a -> s{_llAddtional = a}) .
_Coerce
instance FromJSON LocationLabels where
parseJSON
= withObject "LocationLabels"
(\ o -> LocationLabels' <$> (parseJSONObject o))
instance ToJSON LocationLabels where
toJSON = toJSON . _llAddtional
-- | The metadata for the Operation returned by CreateInstance.
--
-- /See:/ 'createInstanceMetadata' smart constructor.
data CreateInstanceMetadata =
CreateInstanceMetadata'
{ _cimRequestTime :: !(Maybe DateTime')
, _cimOriginalRequest :: !(Maybe CreateInstanceRequest)
, _cimFinishTime :: !(Maybe DateTime')
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CreateInstanceMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'cimRequestTime'
--
-- * 'cimOriginalRequest'
--
-- * 'cimFinishTime'
createInstanceMetadata
:: CreateInstanceMetadata
createInstanceMetadata =
CreateInstanceMetadata'
{ _cimRequestTime = Nothing
, _cimOriginalRequest = Nothing
, _cimFinishTime = Nothing
}
-- | The time at which the original request was received.
cimRequestTime :: Lens' CreateInstanceMetadata (Maybe UTCTime)
cimRequestTime
= lens _cimRequestTime
(\ s a -> s{_cimRequestTime = a})
. mapping _DateTime
-- | The request that prompted the initiation of this CreateInstance
-- operation.
cimOriginalRequest :: Lens' CreateInstanceMetadata (Maybe CreateInstanceRequest)
cimOriginalRequest
= lens _cimOriginalRequest
(\ s a -> s{_cimOriginalRequest = a})
-- | The time at which the operation failed or was completed successfully.
cimFinishTime :: Lens' CreateInstanceMetadata (Maybe UTCTime)
cimFinishTime
= lens _cimFinishTime
(\ s a -> s{_cimFinishTime = a})
. mapping _DateTime
instance FromJSON CreateInstanceMetadata where
parseJSON
= withObject "CreateInstanceMetadata"
(\ o ->
CreateInstanceMetadata' <$>
(o .:? "requestTime") <*> (o .:? "originalRequest")
<*> (o .:? "finishTime"))
instance ToJSON CreateInstanceMetadata where
toJSON CreateInstanceMetadata'{..}
= object
(catMaybes
[("requestTime" .=) <$> _cimRequestTime,
("originalRequest" .=) <$> _cimOriginalRequest,
("finishTime" .=) <$> _cimFinishTime])
-- | Service-specific metadata. For example the available capacity at the
-- given location.
--
-- /See:/ 'locationMetadata' smart constructor.
newtype LocationMetadata =
LocationMetadata'
{ _lmAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'LocationMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lmAddtional'
locationMetadata
:: HashMap Text JSONValue -- ^ 'lmAddtional'
-> LocationMetadata
locationMetadata pLmAddtional_ =
LocationMetadata' {_lmAddtional = _Coerce # pLmAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
lmAddtional :: Lens' LocationMetadata (HashMap Text JSONValue)
lmAddtional
= lens _lmAddtional (\ s a -> s{_lmAddtional = a}) .
_Coerce
instance FromJSON LocationMetadata where
parseJSON
= withObject "LocationMetadata"
(\ o -> LocationMetadata' <$> (parseJSONObject o))
instance ToJSON LocationMetadata where
toJSON = toJSON . _lmAddtional
-- | Service-specific metadata associated with the operation. It typically
-- contains progress information and common metadata such as create time.
-- Some services might not provide such metadata. Any method that returns a
-- long-running operation should document the metadata type, if any.
--
-- /See:/ 'operationMetadata' smart constructor.
newtype OperationMetadata =
OperationMetadata'
{ _omAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'omAddtional'
operationMetadata
:: HashMap Text JSONValue -- ^ 'omAddtional'
-> OperationMetadata
operationMetadata pOmAddtional_ =
OperationMetadata' {_omAddtional = _Coerce # pOmAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
omAddtional :: Lens' OperationMetadata (HashMap Text JSONValue)
omAddtional
= lens _omAddtional (\ s a -> s{_omAddtional = a}) .
_Coerce
instance FromJSON OperationMetadata where
parseJSON
= withObject "OperationMetadata"
(\ o -> OperationMetadata' <$> (parseJSONObject o))
instance ToJSON OperationMetadata where
toJSON = toJSON . _omAddtional
-- | Provides the configuration for logging a type of permissions. Example: {
-- \"audit_log_configs\": [ { \"log_type\": \"DATA_READ\",
-- \"exempted_members\": [ \"user:jose\'example.com\" ] }, { \"log_type\":
-- \"DATA_WRITE\" } ] } This enables \'DATA_READ\' and \'DATA_WRITE\'
-- logging, while exempting jose\'example.com from DATA_READ logging.
--
-- /See:/ 'auditLogConfig' smart constructor.
data AuditLogConfig =
AuditLogConfig'
{ _alcLogType :: !(Maybe AuditLogConfigLogType)
, _alcExemptedMembers :: !(Maybe [Text])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'AuditLogConfig' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'alcLogType'
--
-- * 'alcExemptedMembers'
auditLogConfig
:: AuditLogConfig
auditLogConfig =
AuditLogConfig' {_alcLogType = Nothing, _alcExemptedMembers = Nothing}
-- | The log type that this config enables.
alcLogType :: Lens' AuditLogConfig (Maybe AuditLogConfigLogType)
alcLogType
= lens _alcLogType (\ s a -> s{_alcLogType = a})
-- | Specifies the identities that do not cause logging for this type of
-- permission. Follows the same format of Binding.members.
alcExemptedMembers :: Lens' AuditLogConfig [Text]
alcExemptedMembers
= lens _alcExemptedMembers
(\ s a -> s{_alcExemptedMembers = a})
. _Default
. _Coerce
instance FromJSON AuditLogConfig where
parseJSON
= withObject "AuditLogConfig"
(\ o ->
AuditLogConfig' <$>
(o .:? "logType") <*>
(o .:? "exemptedMembers" .!= mempty))
instance ToJSON AuditLogConfig where
toJSON AuditLogConfig'{..}
= object
(catMaybes
[("logType" .=) <$> _alcLogType,
("exemptedMembers" .=) <$> _alcExemptedMembers])
-- | Response message for BigtableInstanceAdmin.ListInstances.
--
-- /See:/ 'listInstancesResponse' smart constructor.
data ListInstancesResponse =
ListInstancesResponse'
{ _lirNextPageToken :: !(Maybe Text)
, _lirFailedLocations :: !(Maybe [Text])
, _lirInstances :: !(Maybe [Instance])
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'ListInstancesResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'lirNextPageToken'
--
-- * 'lirFailedLocations'
--
-- * 'lirInstances'
listInstancesResponse
:: ListInstancesResponse
listInstancesResponse =
ListInstancesResponse'
{ _lirNextPageToken = Nothing
, _lirFailedLocations = Nothing
, _lirInstances = Nothing
}
-- | DEPRECATED: This field is unused and ignored.
lirNextPageToken :: Lens' ListInstancesResponse (Maybe Text)
lirNextPageToken
= lens _lirNextPageToken
(\ s a -> s{_lirNextPageToken = a})
-- | Locations from which Instance information could not be retrieved, due to
-- an outage or some other transient condition. Instances whose Clusters
-- are all in one of the failed locations may be missing from
-- \`instances\`, and Instances with at least one Cluster in a failed
-- location may only have partial information returned. Values are of the
-- form \`projects\/\/locations\/\`
lirFailedLocations :: Lens' ListInstancesResponse [Text]
lirFailedLocations
= lens _lirFailedLocations
(\ s a -> s{_lirFailedLocations = a})
. _Default
. _Coerce
-- | The list of requested instances.
lirInstances :: Lens' ListInstancesResponse [Instance]
lirInstances
= lens _lirInstances (\ s a -> s{_lirInstances = a})
. _Default
. _Coerce
instance FromJSON ListInstancesResponse where
parseJSON
= withObject "ListInstancesResponse"
(\ o ->
ListInstancesResponse' <$>
(o .:? "nextPageToken") <*>
(o .:? "failedLocations" .!= mempty)
<*> (o .:? "instances" .!= mempty))
instance ToJSON ListInstancesResponse where
toJSON ListInstancesResponse'{..}
= object
(catMaybes
[("nextPageToken" .=) <$> _lirNextPageToken,
("failedLocations" .=) <$> _lirFailedLocations,
("instances" .=) <$> _lirInstances])
-- | Metadata type for the long-running operation returned by RestoreTable.
--
-- /See:/ 'restoreTableMetadata' smart constructor.
data RestoreTableMetadata =
RestoreTableMetadata'
{ _rtmOptimizeTableOperationName :: !(Maybe Text)
, _rtmSourceType :: !(Maybe RestoreTableMetadataSourceType)
, _rtmProgress :: !(Maybe OperationProgress)
, _rtmName :: !(Maybe Text)
, _rtmBackupInfo :: !(Maybe BackupInfo)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RestoreTableMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rtmOptimizeTableOperationName'
--
-- * 'rtmSourceType'
--
-- * 'rtmProgress'
--
-- * 'rtmName'
--
-- * 'rtmBackupInfo'
restoreTableMetadata
:: RestoreTableMetadata
restoreTableMetadata =
RestoreTableMetadata'
{ _rtmOptimizeTableOperationName = Nothing
, _rtmSourceType = Nothing
, _rtmProgress = Nothing
, _rtmName = Nothing
, _rtmBackupInfo = Nothing
}
-- | If exists, the name of the long-running operation that will be used to
-- track the post-restore optimization process to optimize the performance
-- of the restored table. The metadata type of the long-running operation
-- is OptimizeRestoreTableMetadata. The response type is Empty. This
-- long-running operation may be automatically created by the system if
-- applicable after the RestoreTable long-running operation completes
-- successfully. This operation may not be created if the table is already
-- optimized or the restore was not successful.
rtmOptimizeTableOperationName :: Lens' RestoreTableMetadata (Maybe Text)
rtmOptimizeTableOperationName
= lens _rtmOptimizeTableOperationName
(\ s a -> s{_rtmOptimizeTableOperationName = a})
-- | The type of the restore source.
rtmSourceType :: Lens' RestoreTableMetadata (Maybe RestoreTableMetadataSourceType)
rtmSourceType
= lens _rtmSourceType
(\ s a -> s{_rtmSourceType = a})
-- | The progress of the RestoreTable operation.
rtmProgress :: Lens' RestoreTableMetadata (Maybe OperationProgress)
rtmProgress
= lens _rtmProgress (\ s a -> s{_rtmProgress = a})
-- | Name of the table being created and restored to.
rtmName :: Lens' RestoreTableMetadata (Maybe Text)
rtmName = lens _rtmName (\ s a -> s{_rtmName = a})
rtmBackupInfo :: Lens' RestoreTableMetadata (Maybe BackupInfo)
rtmBackupInfo
= lens _rtmBackupInfo
(\ s a -> s{_rtmBackupInfo = a})
instance FromJSON RestoreTableMetadata where
parseJSON
= withObject "RestoreTableMetadata"
(\ o ->
RestoreTableMetadata' <$>
(o .:? "optimizeTableOperationName") <*>
(o .:? "sourceType")
<*> (o .:? "progress")
<*> (o .:? "name")
<*> (o .:? "backupInfo"))
instance ToJSON RestoreTableMetadata where
toJSON RestoreTableMetadata'{..}
= object
(catMaybes
[("optimizeTableOperationName" .=) <$>
_rtmOptimizeTableOperationName,
("sourceType" .=) <$> _rtmSourceType,
("progress" .=) <$> _rtmProgress,
("name" .=) <$> _rtmName,
("backupInfo" .=) <$> _rtmBackupInfo])
-- | Response message for
-- google.bigtable.admin.v2.BigtableTableAdmin.CheckConsistency
--
-- /See:/ 'checkConsistencyResponse' smart constructor.
newtype CheckConsistencyResponse =
CheckConsistencyResponse'
{ _ccrConsistent :: Maybe Bool
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'CheckConsistencyResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ccrConsistent'
checkConsistencyResponse
:: CheckConsistencyResponse
checkConsistencyResponse = CheckConsistencyResponse' {_ccrConsistent = Nothing}
-- | True only if the token is consistent. A token is consistent if
-- replication has caught up with the restrictions specified in the
-- request.
ccrConsistent :: Lens' CheckConsistencyResponse (Maybe Bool)
ccrConsistent
= lens _ccrConsistent
(\ s a -> s{_ccrConsistent = a})
instance FromJSON CheckConsistencyResponse where
parseJSON
= withObject "CheckConsistencyResponse"
(\ o ->
CheckConsistencyResponse' <$> (o .:? "consistent"))
instance ToJSON CheckConsistencyResponse where
toJSON CheckConsistencyResponse'{..}
= object
(catMaybes [("consistent" .=) <$> _ccrConsistent])
-- | A create, update, or delete of a particular column family.
--
-- /See:/ 'modification' smart constructor.
data Modification =
Modification'
{ _mDrop :: !(Maybe Bool)
, _mCreate :: !(Maybe ColumnFamily)
, _mId :: !(Maybe Text)
, _mUpdate :: !(Maybe ColumnFamily)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Modification' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'mDrop'
--
-- * 'mCreate'
--
-- * 'mId'
--
-- * 'mUpdate'
modification
:: Modification
modification =
Modification'
{_mDrop = Nothing, _mCreate = Nothing, _mId = Nothing, _mUpdate = Nothing}
-- | Drop (delete) the column family with the given ID, or fail if no such
-- family exists.
mDrop :: Lens' Modification (Maybe Bool)
mDrop = lens _mDrop (\ s a -> s{_mDrop = a})
-- | Create a new column family with the specified schema, or fail if one
-- already exists with the given ID.
mCreate :: Lens' Modification (Maybe ColumnFamily)
mCreate = lens _mCreate (\ s a -> s{_mCreate = a})
-- | The ID of the column family to be modified.
mId :: Lens' Modification (Maybe Text)
mId = lens _mId (\ s a -> s{_mId = a})
-- | Update an existing column family to the specified schema, or fail if no
-- column family exists with the given ID.
mUpdate :: Lens' Modification (Maybe ColumnFamily)
mUpdate = lens _mUpdate (\ s a -> s{_mUpdate = a})
instance FromJSON Modification where
parseJSON
= withObject "Modification"
(\ o ->
Modification' <$>
(o .:? "drop") <*> (o .:? "create") <*> (o .:? "id")
<*> (o .:? "update"))
instance ToJSON Modification where
toJSON Modification'{..}
= object
(catMaybes
[("drop" .=) <$> _mDrop, ("create" .=) <$> _mCreate,
("id" .=) <$> _mId, ("update" .=) <$> _mUpdate])
-- | A collection of user data indexed by row, column, and timestamp. Each
-- table is served using the resources of its parent cluster.
--
-- /See:/ 'table' smart constructor.
data Table =
Table'
{ _tGranularity :: !(Maybe TableGranularity)
, _tName :: !(Maybe Text)
, _tRestoreInfo :: !(Maybe RestoreInfo)
, _tClusterStates :: !(Maybe TableClusterStates)
, _tColumnFamilies :: !(Maybe TableColumnFamilies)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Table' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'tGranularity'
--
-- * 'tName'
--
-- * 'tRestoreInfo'
--
-- * 'tClusterStates'
--
-- * 'tColumnFamilies'
table
:: Table
table =
Table'
{ _tGranularity = Nothing
, _tName = Nothing
, _tRestoreInfo = Nothing
, _tClusterStates = Nothing
, _tColumnFamilies = Nothing
}
-- | Immutable. The granularity (i.e. \`MILLIS\`) at which timestamps are
-- stored in this table. Timestamps not matching the granularity will be
-- rejected. If unspecified at creation time, the value will be set to
-- \`MILLIS\`. Views: \`SCHEMA_VIEW\`, \`FULL\`.
tGranularity :: Lens' Table (Maybe TableGranularity)
tGranularity
= lens _tGranularity (\ s a -> s{_tGranularity = a})
-- | The unique name of the table. Values are of the form
-- \`projects\/{project}\/instances\/{instance}\/tables\/_a-zA-Z0-9*\`.
-- Views: \`NAME_ONLY\`, \`SCHEMA_VIEW\`, \`REPLICATION_VIEW\`, \`FULL\`
tName :: Lens' Table (Maybe Text)
tName = lens _tName (\ s a -> s{_tName = a})
-- | Output only. If this table was restored from another data source (e.g. a
-- backup), this field will be populated with information about the
-- restore.
tRestoreInfo :: Lens' Table (Maybe RestoreInfo)
tRestoreInfo
= lens _tRestoreInfo (\ s a -> s{_tRestoreInfo = a})
-- | Output only. Map from cluster ID to per-cluster table state. If it could
-- not be determined whether or not the table has data in a particular
-- cluster (for example, if its zone is unavailable), then there will be an
-- entry for the cluster with UNKNOWN \`replication_status\`. Views:
-- \`REPLICATION_VIEW\`, \`ENCRYPTION_VIEW\`, \`FULL\`
tClusterStates :: Lens' Table (Maybe TableClusterStates)
tClusterStates
= lens _tClusterStates
(\ s a -> s{_tClusterStates = a})
-- | The column families configured for this table, mapped by column family
-- ID. Views: \`SCHEMA_VIEW\`, \`FULL\`
tColumnFamilies :: Lens' Table (Maybe TableColumnFamilies)
tColumnFamilies
= lens _tColumnFamilies
(\ s a -> s{_tColumnFamilies = a})
instance FromJSON Table where
parseJSON
= withObject "Table"
(\ o ->
Table' <$>
(o .:? "granularity") <*> (o .:? "name") <*>
(o .:? "restoreInfo")
<*> (o .:? "clusterStates")
<*> (o .:? "columnFamilies"))
instance ToJSON Table where
toJSON Table'{..}
= object
(catMaybes
[("granularity" .=) <$> _tGranularity,
("name" .=) <$> _tName,
("restoreInfo" .=) <$> _tRestoreInfo,
("clusterStates" .=) <$> _tClusterStates,
("columnFamilies" .=) <$> _tColumnFamilies])
-- | Metadata type for the long-running operation used to track the progress
-- of optimizations performed on a newly restored table. This long-running
-- operation is automatically created by the system after the successful
-- completion of a table restore, and cannot be cancelled.
--
-- /See:/ 'optimizeRestoredTableMetadata' smart constructor.
data OptimizeRestoredTableMetadata =
OptimizeRestoredTableMetadata'
{ _ortmProgress :: !(Maybe OperationProgress)
, _ortmName :: !(Maybe Text)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OptimizeRestoredTableMetadata' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'ortmProgress'
--
-- * 'ortmName'
optimizeRestoredTableMetadata
:: OptimizeRestoredTableMetadata
optimizeRestoredTableMetadata =
OptimizeRestoredTableMetadata' {_ortmProgress = Nothing, _ortmName = Nothing}
-- | The progress of the post-restore optimizations.
ortmProgress :: Lens' OptimizeRestoredTableMetadata (Maybe OperationProgress)
ortmProgress
= lens _ortmProgress (\ s a -> s{_ortmProgress = a})
-- | Name of the restored table being optimized.
ortmName :: Lens' OptimizeRestoredTableMetadata (Maybe Text)
ortmName = lens _ortmName (\ s a -> s{_ortmName = a})
instance FromJSON OptimizeRestoredTableMetadata where
parseJSON
= withObject "OptimizeRestoredTableMetadata"
(\ o ->
OptimizeRestoredTableMetadata' <$>
(o .:? "progress") <*> (o .:? "name"))
instance ToJSON OptimizeRestoredTableMetadata where
toJSON OptimizeRestoredTableMetadata'{..}
= object
(catMaybes
[("progress" .=) <$> _ortmProgress,
("name" .=) <$> _ortmName])
-- | Information about a table restore.
--
-- /See:/ 'restoreInfo' smart constructor.
data RestoreInfo =
RestoreInfo'
{ _riSourceType :: !(Maybe RestoreInfoSourceType)
, _riBackupInfo :: !(Maybe BackupInfo)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'RestoreInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'riSourceType'
--
-- * 'riBackupInfo'
restoreInfo
:: RestoreInfo
restoreInfo = RestoreInfo' {_riSourceType = Nothing, _riBackupInfo = Nothing}
-- | The type of the restore source.
riSourceType :: Lens' RestoreInfo (Maybe RestoreInfoSourceType)
riSourceType
= lens _riSourceType (\ s a -> s{_riSourceType = a})
-- | Information about the backup used to restore the table. The backup may
-- no longer exist.
riBackupInfo :: Lens' RestoreInfo (Maybe BackupInfo)
riBackupInfo
= lens _riBackupInfo (\ s a -> s{_riBackupInfo = a})
instance FromJSON RestoreInfo where
parseJSON
= withObject "RestoreInfo"
(\ o ->
RestoreInfo' <$>
(o .:? "sourceType") <*> (o .:? "backupInfo"))
instance ToJSON RestoreInfo where
toJSON RestoreInfo'{..}
= object
(catMaybes
[("sourceType" .=) <$> _riSourceType,
("backupInfo" .=) <$> _riBackupInfo])
-- | The normal response of the operation in case of success. If the original
-- method returns no data on success, such as \`Delete\`, the response is
-- \`google.protobuf.Empty\`. If the original method is standard
-- \`Get\`\/\`Create\`\/\`Update\`, the response should be the resource.
-- For other methods, the response should have the type \`XxxResponse\`,
-- where \`Xxx\` is the original method name. For example, if the original
-- method name is \`TakeSnapshot()\`, the inferred response type is
-- \`TakeSnapshotResponse\`.
--
-- /See:/ 'operationResponse' smart constructor.
newtype OperationResponse =
OperationResponse'
{ _orAddtional :: HashMap Text JSONValue
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'OperationResponse' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'orAddtional'
operationResponse
:: HashMap Text JSONValue -- ^ 'orAddtional'
-> OperationResponse
operationResponse pOrAddtional_ =
OperationResponse' {_orAddtional = _Coerce # pOrAddtional_}
-- | Properties of the object. Contains field \'type with type URL.
orAddtional :: Lens' OperationResponse (HashMap Text JSONValue)
orAddtional
= lens _orAddtional (\ s a -> s{_orAddtional = a}) .
_Coerce
instance FromJSON OperationResponse where
parseJSON
= withObject "OperationResponse"
(\ o -> OperationResponse' <$> (parseJSONObject o))
instance ToJSON OperationResponse where
toJSON = toJSON . _orAddtional
-- | Encryption information for a given resource. If this resource is
-- protected with customer managed encryption, the in-use Cloud Key
-- Management Service (Cloud KMS) key version is specified along with its
-- status.
--
-- /See:/ 'encryptionInfo' smart constructor.
data EncryptionInfo =
EncryptionInfo'
{ _eiEncryptionType :: !(Maybe EncryptionInfoEncryptionType)
, _eiKmsKeyVersion :: !(Maybe Text)
, _eiEncryptionStatus :: !(Maybe Status)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'EncryptionInfo' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'eiEncryptionType'
--
-- * 'eiKmsKeyVersion'
--
-- * 'eiEncryptionStatus'
encryptionInfo
:: EncryptionInfo
encryptionInfo =
EncryptionInfo'
{ _eiEncryptionType = Nothing
, _eiKmsKeyVersion = Nothing
, _eiEncryptionStatus = Nothing
}
-- | Output only. The type of encryption used to protect this resource.
eiEncryptionType :: Lens' EncryptionInfo (Maybe EncryptionInfoEncryptionType)
eiEncryptionType
= lens _eiEncryptionType
(\ s a -> s{_eiEncryptionType = a})
-- | Output only. The version of the Cloud KMS key specified in the parent
-- cluster that is in use for the data underlying this table.
eiKmsKeyVersion :: Lens' EncryptionInfo (Maybe Text)
eiKmsKeyVersion
= lens _eiKmsKeyVersion
(\ s a -> s{_eiKmsKeyVersion = a})
-- | Output only. The status of encrypt\/decrypt calls on underlying data for
-- this resource. Regardless of status, the existing data is always
-- encrypted at rest.
eiEncryptionStatus :: Lens' EncryptionInfo (Maybe Status)
eiEncryptionStatus
= lens _eiEncryptionStatus
(\ s a -> s{_eiEncryptionStatus = a})
instance FromJSON EncryptionInfo where
parseJSON
= withObject "EncryptionInfo"
(\ o ->
EncryptionInfo' <$>
(o .:? "encryptionType") <*> (o .:? "kmsKeyVersion")
<*> (o .:? "encryptionStatus"))
instance ToJSON EncryptionInfo where
toJSON EncryptionInfo'{..}
= object
(catMaybes
[("encryptionType" .=) <$> _eiEncryptionType,
("kmsKeyVersion" .=) <$> _eiKmsKeyVersion,
("encryptionStatus" .=) <$> _eiEncryptionStatus])
-- | Associates \`members\` with a \`role\`.
--
-- /See:/ 'binding' smart constructor.
data Binding =
Binding'
{ _bMembers :: !(Maybe [Text])
, _bRole :: !(Maybe Text)
, _bCondition :: !(Maybe Expr)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Binding' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'bMembers'
--
-- * 'bRole'
--
-- * 'bCondition'
binding
:: Binding
binding =
Binding' {_bMembers = Nothing, _bRole = Nothing, _bCondition = Nothing}
-- | Specifies the identities requesting access for a Cloud Platform
-- resource. \`members\` can have the following values: * \`allUsers\`: A
-- special identifier that represents anyone who is on the internet; with
-- or without a Google account. * \`allAuthenticatedUsers\`: A special
-- identifier that represents anyone who is authenticated with a Google
-- account or a service account. * \`user:{emailid}\`: An email address
-- that represents a specific Google account. For example,
-- \`alice\'example.com\` . * \`serviceAccount:{emailid}\`: An email
-- address that represents a service account. For example,
-- \`my-other-app\'appspot.gserviceaccount.com\`. * \`group:{emailid}\`: An
-- email address that represents a Google group. For example,
-- \`admins\'example.com\`. * \`deleted:user:{emailid}?uid={uniqueid}\`: An
-- email address (plus unique identifier) representing a user that has been
-- recently deleted. For example,
-- \`alice\'example.com?uid=123456789012345678901\`. If the user is
-- recovered, this value reverts to \`user:{emailid}\` and the recovered
-- user retains the role in the binding. *
-- \`deleted:serviceAccount:{emailid}?uid={uniqueid}\`: An email address
-- (plus unique identifier) representing a service account that has been
-- recently deleted. For example,
-- \`my-other-app\'appspot.gserviceaccount.com?uid=123456789012345678901\`.
-- If the service account is undeleted, this value reverts to
-- \`serviceAccount:{emailid}\` and the undeleted service account retains
-- the role in the binding. * \`deleted:group:{emailid}?uid={uniqueid}\`:
-- An email address (plus unique identifier) representing a Google group
-- that has been recently deleted. For example,
-- \`admins\'example.com?uid=123456789012345678901\`. If the group is
-- recovered, this value reverts to \`group:{emailid}\` and the recovered
-- group retains the role in the binding. * \`domain:{domain}\`: The G
-- Suite domain (primary) that represents all the users of that domain. For
-- example, \`google.com\` or \`example.com\`.
bMembers :: Lens' Binding [Text]
bMembers
= lens _bMembers (\ s a -> s{_bMembers = a}) .
_Default
. _Coerce
-- | Role that is assigned to \`members\`. For example, \`roles\/viewer\`,
-- \`roles\/editor\`, or \`roles\/owner\`.
bRole :: Lens' Binding (Maybe Text)
bRole = lens _bRole (\ s a -> s{_bRole = a})
-- | The condition that is associated with this binding. If the condition
-- evaluates to \`true\`, then this binding applies to the current request.
-- If the condition evaluates to \`false\`, then this binding does not
-- apply to the current request. However, a different role binding might
-- grant the same role to one or more of the members in this binding. To
-- learn which resources support conditions in their IAM policies, see the
-- [IAM
-- documentation](https:\/\/cloud.google.com\/iam\/help\/conditions\/resource-policies).
bCondition :: Lens' Binding (Maybe Expr)
bCondition
= lens _bCondition (\ s a -> s{_bCondition = a})
instance FromJSON Binding where
parseJSON
= withObject "Binding"
(\ o ->
Binding' <$>
(o .:? "members" .!= mempty) <*> (o .:? "role") <*>
(o .:? "condition"))
instance ToJSON Binding where
toJSON Binding'{..}
= object
(catMaybes
[("members" .=) <$> _bMembers,
("role" .=) <$> _bRole,
("condition" .=) <$> _bCondition])
-- | A collection of Bigtable Tables and the resources that serve them. All
-- tables in an instance are served from all Clusters in the instance.
--
-- /See:/ 'instance'' smart constructor.
data Instance =
Instance'
{ _iState :: !(Maybe InstanceState)
, _iName :: !(Maybe Text)
, _iDisplayName :: !(Maybe Text)
, _iLabels :: !(Maybe InstanceLabels)
, _iType :: !(Maybe InstanceType)
}
deriving (Eq, Show, Data, Typeable, Generic)
-- | Creates a value of 'Instance' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'iState'
--
-- * 'iName'
--
-- * 'iDisplayName'
--
-- * 'iLabels'
--
-- * 'iType'
instance'
:: Instance
instance' =
Instance'
{ _iState = Nothing
, _iName = Nothing
, _iDisplayName = Nothing
, _iLabels = Nothing
, _iType = Nothing
}
-- | Output only. The current state of the instance.
iState :: Lens' Instance (Maybe InstanceState)
iState = lens _iState (\ s a -> s{_iState = a})
-- | The unique name of the instance. Values are of the form
-- \`projects\/{project}\/instances\/a-z+[a-z0-9]\`.
iName :: Lens' Instance (Maybe Text)
iName = lens _iName (\ s a -> s{_iName = a})
-- | Required. The descriptive name for this instance as it appears in UIs.
-- Can be changed at any time, but should be kept globally unique to avoid
-- confusion.
iDisplayName :: Lens' Instance (Maybe Text)
iDisplayName
= lens _iDisplayName (\ s a -> s{_iDisplayName = a})
-- | Required. Labels are a flexible and lightweight mechanism for organizing
-- cloud resources into groups that reflect a customer\'s organizational
-- needs and deployment strategies. They can be used to filter resources
-- and aggregate metrics. * Label keys must be between 1 and 63 characters
-- long and must conform to the regular expression:
-- \`\\p{Ll}\\p{Lo}{0,62}\`. * Label values must be between 0 and 63
-- characters long and must conform to the regular expression:
-- \`[\\p{Ll}\\p{Lo}\\p{N}_-]{0,63}\`. * No more than 64 labels can be
-- associated with a given resource. * Keys and values must both be under
-- 128 bytes.
iLabels :: Lens' Instance (Maybe InstanceLabels)
iLabels = lens _iLabels (\ s a -> s{_iLabels = a})
-- | Required. The type of the instance. Defaults to \`PRODUCTION\`.
iType :: Lens' Instance (Maybe InstanceType)
iType = lens _iType (\ s a -> s{_iType = a})
instance FromJSON Instance where
parseJSON
= withObject "Instance"
(\ o ->
Instance' <$>
(o .:? "state") <*> (o .:? "name") <*>
(o .:? "displayName")
<*> (o .:? "labels")
<*> (o .:? "type"))
instance ToJSON Instance where
toJSON Instance'{..}
= object
(catMaybes
[("state" .=) <$> _iState, ("name" .=) <$> _iName,
("displayName" .=) <$> _iDisplayName,
("labels" .=) <$> _iLabels, ("type" .=) <$> _iType])
| brendanhay/gogol | gogol-bigtableadmin/gen/Network/Google/BigtableAdmin/Types/Product.hs | mpl-2.0 | 143,940 | 0 | 18 | 32,414 | 23,424 | 13,523 | 9,901 | 2,572 | 1 |
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
module Gonimo.Server.AuthHandlers where
import Control.Concurrent.STM (STM, TVar, readTVar)
import Control.Lens
import Control.Monad
import Control.Monad.Freer (Eff)
import Control.Monad (guard)
import Control.Monad.Freer.Reader (ask)
import Control.Monad.STM.Class (liftSTM)
import Control.Monad.Trans.Class (lift)
import Control.Monad.Trans.Maybe (MaybeT(..), runMaybeT)
import Utils.Control.Monad.Trans.Maybe (maybeT)
import qualified Data.Map.Strict as M
import Data.Proxy (Proxy (..))
import qualified Data.Set as S
import Data.Text (Text)
import Database.Persist (Entity (..))
import qualified Gonimo.Database.Effects as Db
import Gonimo.Database.Effects.Servant
import Gonimo.Server.Auth as Auth
import Gonimo.Server.AuthHandlers.Internal
import Gonimo.Server.DbEntities
import Gonimo.Server.Effects
import Gonimo.Server.EmailInvitation
import Gonimo.Server.Error
import Gonimo.Server.State
import Gonimo.Server.Types
import Gonimo.WebAPI (ReceiveChannelR,
ReceiveSocketR)
import Gonimo.WebAPI.Types (InvitationInfo (..),
InvitationReply (..))
import qualified Gonimo.WebAPI.Types as Client
import Servant.API ((:>))
import Servant.Server (ServantErr (..), err400,
err403)
import Servant.Subscriber (Event (ModifyEvent))
createInvitation :: AuthServerConstraint r => FamilyId -> Eff r (InvitationId, Invitation)
createInvitation fid = do
authorizeAuthData $ isFamilyMember fid
now <- getCurrentTime
isecret <- generateSecret
-- family <- getFamily fid -- defined but not used (yet).
senderId' <- authView $ clientEntity.to entityKey
let inv = Invitation {
invitationSecret = isecret
, invitationFamilyId = fid
, invitationCreated = now
, invitationDelivery = OtherDelivery
, invitationSenderId = senderId'
, invitationReceiverId = Nothing
}
iid <- runDb $ Db.insert inv
return (iid, inv)
putInvitationInfo :: AuthServerConstraint r => Secret -> Eff r InvitationInfo
putInvitationInfo invSecret = do
aid <- authView $ accountEntity . to entityKey
runDb $ do
Entity invId inv <- getBy404 $ SecretInvitation invSecret
guardWithM InvitationAlreadyClaimed
$ case invitationReceiverId inv of
Nothing -> do
Db.replace invId $ inv { invitationReceiverId = Just aid }
return True
Just receiverId' -> return $ receiverId' == aid
invFamily <- get404 $ invitationFamilyId inv
invClient <- get404 $ invitationSenderId inv
mInvUser <- Db.getBy $ AccountIdUser (clientAccountId invClient)
return InvitationInfo
{ invitationInfoFamily = familyName invFamily
, invitationInfoSendingClient = clientName invClient
, invitationInfoSendingUser = userLogin . entityVal <$> mInvUser
}
answerInvitation :: AuthServerConstraint r => Secret -> InvitationReply -> Eff r ()
answerInvitation invSecret reply = do
authData <- ask
let aid = authData ^. accountEntity . to entityKey
now <- getCurrentTime
inv <- runDb $ do
Entity iid inv <- getBy404 (SecretInvitation invSecret)
guardWith InvitationAlreadyClaimed
$ case invitationReceiverId inv of
Nothing -> True
Just receiverId' -> receiverId' == aid
Db.delete iid
return inv
runDb $ do -- Separate transaction - we want the invitation to be deleted now!
when (reply == InvitationAccept ) $ do
guardWith AlreadyFamilyMember
$ not $ isFamilyMember (invitationFamilyId inv) authData
Db.insert_ FamilyAccount {
familyAccountAccountId = aid
, familyAccountFamilyId = invitationFamilyId inv
, familyAccountJoined = now
, familyAccountInvitedBy = Just (invitationDelivery inv)
}
sendInvitation :: AuthServerConstraint r => Client.SendInvitation -> Eff r ()
sendInvitation (Client.SendInvitation iid d@(EmailInvitation email)) = do
authData <- ask -- Only allowed if user is member of the inviting family!
(inv, family) <- runDb $ do
inv <- get404 iid
authorize (isFamilyMember (invitationFamilyId inv)) authData
let newInv = inv {
invitationDelivery = d
}
Db.replace iid newInv
family <- get404 (invitationFamilyId inv)
return (newInv, family)
sendEmail $ makeInvitationEmail inv email (familyName family)
sendInvitation (Client.SendInvitation _ OtherDelivery) =
throwServant err400 {
errReasonPhrase = "OtherDelivery means - you took care of the delivery. How am I supposed to perform an 'OtherDelivery'?"
}
createFamily :: AuthServerConstraint r => FamilyName -> Eff r FamilyId
createFamily n = do
-- no authorization: - any valid user can create a family.
now <- getCurrentTime
uid <- askAccountId
runDb $ do
fid <- Db.insert Family {
familyName = n
, familyCreated = now
, familyLastAccessed = now
}
Db.insert_ FamilyAccount {
familyAccountAccountId = uid
, familyAccountFamilyId = fid
, familyAccountJoined = now
, familyAccountInvitedBy = Nothing
}
return fid
createChannel :: AuthServerConstraint r
=> FamilyId -> ClientId -> ClientId -> Eff r Secret
createChannel familyId toId fromId = do
-- is it a good idea to expose the db-id in the route - people know how to use
-- a packet sniffer
secret <- generateSecret
authorizedPut (putSecret secret fromId toId) familyId fromId toId
notify ModifyEvent endpoint (\f -> f familyId toId)
return secret
where
endpoint :: Proxy ("socket" :> ReceiveSocketR)
endpoint = Proxy
receiveSocket :: AuthServerConstraint r
=> FamilyId -> ClientId -> Eff r (ClientId, Secret)
-- | in this request @to@ is the one receiving the secret
receiveSocket familyId toId =
authorizedRecieve'(receiveSecret toId) familyId toId
putChannel :: AuthServerConstraint r
=> FamilyId -> ClientId -> ClientId -> Secret -> Text -> Eff r ()
putChannel familyId fromId toId token txt = do
authorizedPut (putData txt token fromId) familyId fromId toId
notify ModifyEvent endpoint (\f -> f familyId fromId toId token)
where
endpoint :: Proxy ("socket" :> ReceiveChannelR)
endpoint = Proxy
receiveChannel :: AuthServerConstraint r
=> FamilyId -> ClientId -> ClientId -> Secret -> Eff r Text
receiveChannel familyId fromId toId token =
authorizeJust (\(fromId',t) -> do guard (fromId == fromId'); return t)
=<< authorizedRecieve (receieveData token) familyId fromId toId
-- The following stuff should go somewhere else someday (e.g. to paradise):
-- | Get the family of the requesting device.
--
-- error 404 if not found.
-- TODO: Get this from in memory data structure when available.
getFamily :: ServerConstraint r => FamilyId -> Eff r Family
getFamily fid = runDb $ get404 fid
| charringer/gonimo-back | src/Gonimo/Server/AuthHandlers.hs | agpl-3.0 | 7,597 | 0 | 19 | 2,175 | 1,750 | 916 | 834 | -1 | -1 |
{-# LANGUAGE OverloadedStrings #-}
import Hakyll
import Control.Monad (forM_)
import Control.Arrow ((>>>), arr)
-- import Text.Pandoc
main :: IO ()
main = hakyll $ do
route "css/*" idRoute
compile "css/*" compressCssCompiler
forM_ ["images/*"] $ \f -> do
route f idRoute
compile f copyFileCompiler
-- Pages
forM_ pages $ \p -> do
route p $ setExtension "html"
compile p $ readPageCompiler
>>> arr (setField "projectUrl" projectUrl)
>>> pageRenderPandoc
>>> applyTemplateCompiler "templates/default.html"
>>> relativizeUrlsCompiler
-- Templates
compile "templates/*" templateCompiler
where
pages = [ "index.markdown"
]
projectUrl = "http://github.com/shaleny/haskell-holes"
| aartamonau/haskell-holes | gh-pages/hakyll.hs | lgpl-3.0 | 814 | 0 | 18 | 227 | 193 | 95 | 98 | 21 | 1 |
maximum' :: (Ord a) => [a] -> a
maximum' [] = error "Maximum of empty list"
maximum' [x] = x
maximum' (x:xs)
| x > maxTail = x
| otherwise = maxTail
where maxTail = maximum' xs
--alternatives:
--worst case exponential growth, e.g. list is sorted in ascending order
--maximum' (x:xs) = if x > maximum' xs then x else maximum' xs
--using if-else instead of guards. guards probably look nicer
--maximum' (x:xs) = if x > m then x else m
-- where m = maximum' xs
--using the _as pattern_
--maximum' (x:xs) = if x > m@(maximum' xs) then x else m
--using the max function
--maximum' (x:xs) = max x (maximum' xs)
--using a let expression
--maximum' (x:xs) = let m = maximum' xs in if x > m then x else m
replicate' :: (Num i, Ord i) => i -> a -> [a]
replicate' n x
| n <= 0 = []
| otherwise = x:(replicate' (n - 1) x)
take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _
| n <= 0 = []
take' _ [] = []
take' n (x:xs) = x : take' (n - 1) xs
reverse' :: [a] -> [a]
reverse' [] = []
-- not necessary; not always the case though
--reverse' [x] = [x]
reverse' (x:xs) = reverse' xs ++ [x]
repeat' :: a -> [a]
repeat' x = x:repeat' x
zip' :: [a] -> [b] -> [(a,b)]
zip' [] _ = []
zip' _ [] = []
zip' (x:xs) (y:ys) = [(x, y)] ++ zip' xs ys
elem' :: (Eq a) => a -> [a] -> Bool
elem' a [] = False
elem' a (x:xs)
| a == x = True
| otherwise = a `elem'` xs
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
--quicksort (x:xs) = quicksort (l_partition x xs) ++ [x] ++ quicksort (r_partition x xs)
-- where l_partition l ls = [a | a <- ls, a < l]
-- r_partition l ls = [a | a <- ls, a >= l]
quicksort (x:xs) = quicksort [x' | x' <- xs, x' < x] ++ [x] ++ quicksort [x' | x' <- xs, x' >= x]
| alexliew/learn_you_a_haskell | 4_recursion.hs | unlicense | 1,723 | 0 | 10 | 429 | 653 | 349 | 304 | 33 | 1 |
-- Taken from https://hackage.haskell.org/package/located-base-0.1.1.0/docs/src/GHC-Err-Located.html
{-# LANGUAGE CPP #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE ImplicitParams #-}
{-# LANGUAGE OverloadedStrings #-}
module Spark.Core.Internal.LocatedBase (error, undefined, HasCallStack, showCallStack) where
#if __GLASGOW_HASKELL__ < 800
import GHC.SrcLoc
import GHC.Stack (CallStack, getCallStack)
import Prelude hiding (error, undefined)
import qualified Prelude
import Text.Printf
import Data.Text(Text, unpack)
type HasCallStack = (?callStack :: CallStack)
error :: HasCallStack => Text -> a
error msg = Prelude.error (unpack msg ++ "\n" ++ showCallStack ?callStack)
undefined :: HasCallStack => a
undefined = error "Prelude.undefined"
showCallStack :: CallStack -> String
showCallStack stk = case getCallStack stk of
_:locs -> unlines $ "Callstack:" : map format locs
_ -> Prelude.error "showCallStack: empty call-stack"
where
format (fn, loc) = printf " %s, called at %s" fn (showSrcLoc loc)
#else
import GHC.Stack(HasCallStack, CallStack, prettyCallStack)
import qualified GHC.Stack()
import Data.Text(Text, unpack)
import qualified Prelude
import Prelude((.))
{-# DEPRECATED showCallStack "use GHC.Stack.prettyCallStack instead" #-}
showCallStack :: CallStack -> Prelude.String
showCallStack = prettyCallStack
error :: HasCallStack => Text -> a
error = Prelude.error . unpack
undefined :: HasCallStack => a
undefined = error "Prelude.undefined"
#endif
| krapsh/kraps-haskell | src/Spark/Core/Internal/LocatedBase.hs | apache-2.0 | 1,489 | 0 | 9 | 199 | 243 | 137 | 106 | -1 | -1 |
-- Only definition nodes should be considered typos
module OnlyDefinitionNodes where
import Notatypo
import Notatypo.Notatypo
<TYPO>imatypo</TYPO> :: Notatypo <TYPO>imatypotoo</TYPO>
<TYPO>imatypo</TYPO> = notatypo
data <TYPO>Imatypo</TYPO> <TYPO>imatypo</TYPO> = <TYPO>Imatypo</TYPO> Notatypo
newtype <TYPO>Imatypo</TYPO> <TYPO>imatypo</TYPO> = <TYPO>Imatypo</TYPO> notatypo
class <TYPO>Imatypo</TYPO> <TYPO>imatypo</TYPO> where
<TYPO>imatypo</TYPO> :: Notatypo <TYPO>imatypo</TYPO>
instance Notatypo (Notatypo <TYPO>imatypo</TYPO>) where
notatypo = Notatypo
| carymrobbins/intellij-haskforce | tests/gold/spellchecker/OnlyDefinitionNodes.hs | apache-2.0 | 571 | 22 | 45 | 61 | 245 | 127 | 118 | -1 | -1 |
{-|
Copyright : (C) 2012-2016, University of Twente
License : BSD2 (see the file LICENSE)
Maintainer : Christiaan Baaij <[email protected]>
Type and instance definitions for Primitive
-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
module CLaSH.Primitives.Types where
import Control.Applicative ((<|>))
import Data.Aeson (FromJSON (..), Value (..), (.:))
import Data.HashMap.Lazy (HashMap)
import qualified Data.HashMap.Strict as H
import qualified Data.Text as S
import Data.Text.Lazy (Text)
-- | Primitive Definitions
type PrimMap a = HashMap S.Text (Primitive a)
-- | Externally defined primitive
data Primitive a
-- | A primitive that has a template that can be filled out by the backend render
= BlackBox
{ name :: !S.Text -- ^ Name of the primitive
, template :: !(Either a a) -- ^ Either a /declaration/ or an /expression/ template.
}
-- | A primitive that carries additional information
| Primitive
{ name :: !S.Text -- ^ Name of the primitive
, primType :: !Text -- ^ Additional information
}
deriving Show
instance FromJSON (Primitive Text) where
parseJSON (Object v) = case H.toList v of
[(conKey,Object conVal)] -> case conKey of
"BlackBox" -> BlackBox <$> conVal .: "name" <*> ((Left <$> conVal .: "templateD") <|> (Right <$> conVal .: "templateE"))
"Primitive" -> Primitive <$> conVal .: "name" <*> conVal .: "primType"
_ -> error "Expected: BlackBox or Primitive object"
_ -> error "Expected: BlackBox or Primitive object"
parseJSON _ = error "Expected: BlackBox or Primitive object"
| ggreif/clash-compiler | clash-lib/src/CLaSH/Primitives/Types.hs | bsd-2-clause | 1,723 | 0 | 17 | 400 | 331 | 193 | 138 | 35 | 0 |
{-# LANGUAGE BangPatterns, CPP, RecordWildCards, ScopedTypeVariables #-}
#if __GLASGOW_HASKELL__ >= 702
{-# LANGUAGE Trustworthy #-}
#endif
-- |
-- Module : Data.Text.IO
-- Copyright : (c) 2009, 2010 Bryan O'Sullivan,
-- (c) 2009 Simon Marlow
-- License : BSD-style
-- Maintainer : [email protected]
-- Portability : GHC
--
-- Efficient locale-sensitive support for text I\/O.
--
-- Skip past the synopsis for some important notes on performance and
-- portability across different versions of GHC.
module Data.Text.IO
(
-- * Performance
-- $performance
-- * Locale support
-- $locale
-- * File-at-a-time operations
readFile
, writeFile
, appendFile
-- * Operations on handles
, hGetContents
, hGetChunk
, hGetLine
, hPutStr
, hPutStrLn
-- * Special cases for standard input and output
, interact
, getContents
, getLine
, putStr
, putStrLn
) where
import Data.Text (Text)
import Prelude hiding (appendFile, getContents, getLine, interact,
putStr, putStrLn, readFile, writeFile)
import System.IO (Handle, IOMode(..), hPutChar, openFile, stdin, stdout,
withFile)
import qualified Control.Exception as E
import Control.Monad (liftM2, when)
import Data.IORef (readIORef, writeIORef)
import qualified Data.Text as T
import Data.Text.Internal.Fusion (stream)
import Data.Text.Internal.Fusion.Types (Step(..), Stream(..))
import Data.Text.Internal.IO (hGetLineWith, readChunk)
import GHC.IO.Buffer (Buffer(..), BufferState(..), CharBufElem, CharBuffer,
RawCharBuffer, emptyBuffer, isEmptyBuffer, newCharBuffer,
writeCharBuf)
import GHC.IO.Exception (IOException(ioe_type), IOErrorType(InappropriateType))
import GHC.IO.Handle.Internals (augmentIOError, hClose_help, wantReadableHandle,
wantWritableHandle)
import GHC.IO.Handle.Text (commitBuffer')
import GHC.IO.Handle.Types (BufferList(..), BufferMode(..), Handle__(..),
HandleType(..), Newline(..))
import System.IO (hGetBuffering, hFileSize, hSetBuffering, hTell)
import System.IO.Error (isEOFError)
-- $performance
-- #performance#
--
-- The functions in this module obey the runtime system's locale,
-- character set encoding, and line ending conversion settings.
--
-- If you know in advance that you will be working with data that has
-- a specific encoding (e.g. UTF-8), and your application is highly
-- performance sensitive, you may find that it is faster to perform
-- I\/O with bytestrings and to encode and decode yourself than to use
-- the functions in this module.
--
-- Whether this will hold depends on the version of GHC you are using,
-- the platform you are working on, the data you are working with, and
-- the encodings you are using, so be sure to test for yourself.
-- | The 'readFile' function reads a file and returns the contents of
-- the file as a string. The entire file is read strictly, as with
-- 'getContents'.
readFile :: FilePath -> IO Text
readFile name = openFile name ReadMode >>= hGetContents
-- | Write a string to a file. The file is truncated to zero length
-- before writing begins.
writeFile :: FilePath -> Text -> IO ()
writeFile p = withFile p WriteMode . flip hPutStr
-- | Write a string the end of a file.
appendFile :: FilePath -> Text -> IO ()
appendFile p = withFile p AppendMode . flip hPutStr
catchError :: String -> Handle -> Handle__ -> IOError -> IO Text
catchError caller h Handle__{..} err
| isEOFError err = do
buf <- readIORef haCharBuffer
return $ if isEmptyBuffer buf
then T.empty
else T.singleton '\r'
| otherwise = E.throwIO (augmentIOError err caller h)
-- | /Experimental./ Read a single chunk of strict text from a
-- 'Handle'. The size of the chunk depends on the amount of input
-- currently buffered.
--
-- This function blocks only if there is no data available, and EOF
-- has not yet been reached. Once EOF is reached, this function
-- returns an empty string instead of throwing an exception.
hGetChunk :: Handle -> IO Text
hGetChunk h = wantReadableHandle "hGetChunk" h readSingleChunk
where
readSingleChunk hh@Handle__{..} = do
buf <- readIORef haCharBuffer
t <- readChunk hh buf `E.catch` catchError "hGetChunk" h hh
return (hh, t)
-- | Read the remaining contents of a 'Handle' as a string. The
-- 'Handle' is closed once the contents have been read, or if an
-- exception is thrown.
--
-- Internally, this function reads a chunk at a time from the
-- lower-level buffering abstraction, and concatenates the chunks into
-- a single string once the entire file has been read.
--
-- As a result, it requires approximately twice as much memory as its
-- result to construct its result. For files more than a half of
-- available RAM in size, this may result in memory exhaustion.
hGetContents :: Handle -> IO Text
hGetContents h = do
chooseGoodBuffering h
wantReadableHandle "hGetContents" h readAll
where
readAll hh@Handle__{..} = do
let readChunks = do
buf <- readIORef haCharBuffer
t <- readChunk hh buf `E.catch` catchError "hGetContents" h hh
if T.null t
then return [t]
else (t:) `fmap` readChunks
ts <- readChunks
(hh', _) <- hClose_help hh
return (hh'{haType=ClosedHandle}, T.concat ts)
-- | Use a more efficient buffer size if we're reading in
-- block-buffered mode with the default buffer size. When we can
-- determine the size of the handle we're reading, set the buffer size
-- to that, so that we can read the entire file in one chunk.
-- Otherwise, use a buffer size of at least 16KB.
chooseGoodBuffering :: Handle -> IO ()
chooseGoodBuffering h = do
bufMode <- hGetBuffering h
case bufMode of
BlockBuffering Nothing -> do
d <- E.catch (liftM2 (-) (hFileSize h) (hTell h)) $ \(e::IOException) ->
if ioe_type e == InappropriateType
then return 16384 -- faster than the 2KB default
else E.throwIO e
when (d > 0) . hSetBuffering h . BlockBuffering . Just . fromIntegral $ d
_ -> return ()
-- | Read a single line from a handle.
hGetLine :: Handle -> IO Text
hGetLine = hGetLineWith T.concat
-- | Write a string to a handle.
hPutStr :: Handle -> Text -> IO ()
-- This function is lifted almost verbatim from GHC.IO.Handle.Text.
hPutStr h t = do
(buffer_mode, nl) <-
wantWritableHandle "hPutStr" h $ \h_ -> do
bmode <- getSpareBuffer h_
return (bmode, haOutputNL h_)
let str = stream t
case buffer_mode of
(NoBuffering, _) -> hPutChars h str
(LineBuffering, buf) -> writeLines h nl buf str
(BlockBuffering _, buf)
| nl == CRLF -> writeBlocksCRLF h buf str
| otherwise -> writeBlocksRaw h buf str
hPutChars :: Handle -> Stream Char -> IO ()
hPutChars h (Stream next0 s0 _len) = loop s0
where
loop !s = case next0 s of
Done -> return ()
Skip s' -> loop s'
Yield x s' -> hPutChar h x >> loop s'
-- The following functions are largely lifted from GHC.IO.Handle.Text,
-- but adapted to a coinductive stream of data instead of an inductive
-- list.
--
-- We have several variations of more or less the same code for
-- performance reasons. Splitting the original buffered write
-- function into line- and block-oriented versions gave us a 2.1x
-- performance improvement. Lifting out the raw/cooked newline
-- handling gave a few more percent on top.
writeLines :: Handle -> Newline -> Buffer CharBufElem -> Stream Char -> IO ()
writeLines h nl buf0 (Stream next0 s0 _len) = outer s0 buf0
where
outer s1 Buffer{bufRaw=raw, bufSize=len} = inner s1 (0::Int)
where
inner !s !n =
case next0 s of
Done -> commit n False{-no flush-} True{-release-} >> return ()
Skip s' -> inner s' n
Yield x s'
| n + 1 >= len -> commit n True{-needs flush-} False >>= outer s
| x == '\n' -> do
n' <- if nl == CRLF
then do n1 <- writeCharBuf raw n '\r'
writeCharBuf raw n1 '\n'
else writeCharBuf raw n x
commit n' True{-needs flush-} False >>= outer s'
| otherwise -> writeCharBuf raw n x >>= inner s'
commit = commitBuffer h raw len
writeBlocksCRLF :: Handle -> Buffer CharBufElem -> Stream Char -> IO ()
writeBlocksCRLF h buf0 (Stream next0 s0 _len) = outer s0 buf0
where
outer s1 Buffer{bufRaw=raw, bufSize=len} = inner s1 (0::Int)
where
inner !s !n =
case next0 s of
Done -> commit n False{-no flush-} True{-release-} >> return ()
Skip s' -> inner s' n
Yield x s'
| n + 1 >= len -> commit n True{-needs flush-} False >>= outer s
| x == '\n' -> do n1 <- writeCharBuf raw n '\r'
writeCharBuf raw n1 '\n' >>= inner s'
| otherwise -> writeCharBuf raw n x >>= inner s'
commit = commitBuffer h raw len
writeBlocksRaw :: Handle -> Buffer CharBufElem -> Stream Char -> IO ()
writeBlocksRaw h buf0 (Stream next0 s0 _len) = outer s0 buf0
where
outer s1 Buffer{bufRaw=raw, bufSize=len} = inner s1 (0::Int)
where
inner !s !n =
case next0 s of
Done -> commit n False{-no flush-} True{-release-} >> return ()
Skip s' -> inner s' n
Yield x s'
| n + 1 >= len -> commit n True{-needs flush-} False >>= outer s
| otherwise -> writeCharBuf raw n x >>= inner s'
commit = commitBuffer h raw len
-- This function is completely lifted from GHC.IO.Handle.Text.
getSpareBuffer :: Handle__ -> IO (BufferMode, CharBuffer)
getSpareBuffer Handle__{haCharBuffer=ref,
haBuffers=spare_ref,
haBufferMode=mode}
= do
case mode of
NoBuffering -> return (mode, error "no buffer!")
_ -> do
bufs <- readIORef spare_ref
buf <- readIORef ref
case bufs of
BufferListCons b rest -> do
writeIORef spare_ref rest
return ( mode, emptyBuffer b (bufSize buf) WriteBuffer)
BufferListNil -> do
new_buf <- newCharBuffer (bufSize buf) WriteBuffer
return (mode, new_buf)
-- This function is completely lifted from GHC.IO.Handle.Text.
commitBuffer :: Handle -> RawCharBuffer -> Int -> Int -> Bool -> Bool
-> IO CharBuffer
commitBuffer hdl !raw !sz !count flush release =
wantWritableHandle "commitAndReleaseBuffer" hdl $
commitBuffer' raw sz count flush release
{-# INLINE commitBuffer #-}
-- | Write a string to a handle, followed by a newline.
hPutStrLn :: Handle -> Text -> IO ()
hPutStrLn h t = hPutStr h t >> hPutChar h '\n'
-- | The 'interact' function takes a function of type @Text -> Text@
-- as its argument. The entire input from the standard input device is
-- passed to this function as its argument, and the resulting string
-- is output on the standard output device.
interact :: (Text -> Text) -> IO ()
interact f = putStr . f =<< getContents
-- | Read all user input on 'stdin' as a single string.
getContents :: IO Text
getContents = hGetContents stdin
-- | Read a single line of user input from 'stdin'.
getLine :: IO Text
getLine = hGetLine stdin
-- | Write a string to 'stdout'.
putStr :: Text -> IO ()
putStr = hPutStr stdout
-- | Write a string to 'stdout', followed by a newline.
putStrLn :: Text -> IO ()
putStrLn = hPutStrLn stdout
-- $locale
--
-- /Note/: The behaviour of functions in this module depends on the
-- version of GHC you are using.
--
-- Beginning with GHC 6.12, text I\/O is performed using the system or
-- handle's current locale and line ending conventions.
--
-- Under GHC 6.10 and earlier, the system I\/O libraries do not
-- support locale-sensitive I\/O or line ending conversion. On these
-- versions of GHC, functions in this library all use UTF-8. What
-- does this mean in practice?
--
-- * All data that is read will be decoded as UTF-8.
--
-- * Before data is written, it is first encoded as UTF-8.
--
-- * On both reading and writing, the platform's native newline
-- conversion is performed.
--
-- If you must use a non-UTF-8 locale on an older version of GHC, you
-- will have to perform the transcoding yourself, e.g. as follows:
--
-- > import qualified Data.ByteString as B
-- > import Data.Text (Text)
-- > import Data.Text.Encoding (encodeUtf16)
-- >
-- > putStr_Utf16LE :: Text -> IO ()
-- > putStr_Utf16LE t = B.putStr (encodeUtf16LE t)
--
-- On transcoding errors, an 'IOError' exception is thrown. You can
-- use the API in "Data.Text.Encoding" if you need more control over
-- error handling or transcoding.
| text-utf8/text | Data/Text/IO.hs | bsd-2-clause | 12,894 | 0 | 21 | 3,221 | 2,713 | 1,435 | 1,278 | 181 | 4 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QPushButton.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:15
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QPushButton (
QqPushButton(..)
,autoDefault
,isDefault
,setAutoDefault
,setDefault
,qPushButton_delete
,qPushButton_deleteLater
)
where
import Foreign.C.Types
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Gui.QPaintDevice
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
instance QuserMethod (QPushButton ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QPushButton_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QPushButton_userMethod" qtc_QPushButton_userMethod :: Ptr (TQPushButton a) -> CInt -> IO ()
instance QuserMethod (QPushButtonSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QPushButton_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QPushButton ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QPushButton_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QPushButton_userMethodVariant" qtc_QPushButton_userMethodVariant :: Ptr (TQPushButton a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QPushButtonSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QPushButton_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
class QqPushButton x1 where
qPushButton :: x1 -> IO (QPushButton ())
instance QqPushButton (()) where
qPushButton ()
= withQPushButtonResult $
qtc_QPushButton
foreign import ccall "qtc_QPushButton" qtc_QPushButton :: IO (Ptr (TQPushButton ()))
instance QqPushButton ((QWidget t1)) where
qPushButton (x1)
= withQPushButtonResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton1 cobj_x1
foreign import ccall "qtc_QPushButton1" qtc_QPushButton1 :: Ptr (TQWidget t1) -> IO (Ptr (TQPushButton ()))
instance QqPushButton ((String)) where
qPushButton (x1)
= withQPushButtonResult $
withCWString x1 $ \cstr_x1 ->
qtc_QPushButton2 cstr_x1
foreign import ccall "qtc_QPushButton2" qtc_QPushButton2 :: CWString -> IO (Ptr (TQPushButton ()))
instance QqPushButton ((QIcon t1, String)) where
qPushButton (x1, x2)
= withQPushButtonResult $
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
qtc_QPushButton3 cobj_x1 cstr_x2
foreign import ccall "qtc_QPushButton3" qtc_QPushButton3 :: Ptr (TQIcon t1) -> CWString -> IO (Ptr (TQPushButton ()))
instance QqPushButton ((String, QWidget t2)) where
qPushButton (x1, x2)
= withQPushButtonResult $
withCWString x1 $ \cstr_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QPushButton4 cstr_x1 cobj_x2
foreign import ccall "qtc_QPushButton4" qtc_QPushButton4 :: CWString -> Ptr (TQWidget t2) -> IO (Ptr (TQPushButton ()))
instance QqPushButton ((QIcon t1, String, QWidget t3)) where
qPushButton (x1, x2, x3)
= withQPushButtonResult $
withObjectPtr x1 $ \cobj_x1 ->
withCWString x2 $ \cstr_x2 ->
withObjectPtr x3 $ \cobj_x3 ->
qtc_QPushButton5 cobj_x1 cstr_x2 cobj_x3
foreign import ccall "qtc_QPushButton5" qtc_QPushButton5 :: Ptr (TQIcon t1) -> CWString -> Ptr (TQWidget t3) -> IO (Ptr (TQPushButton ()))
autoDefault :: QPushButton a -> (()) -> IO (Bool)
autoDefault x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_autoDefault cobj_x0
foreign import ccall "qtc_QPushButton_autoDefault" qtc_QPushButton_autoDefault :: Ptr (TQPushButton a) -> IO CBool
instance Qevent (QPushButton ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_event_h" qtc_QPushButton_event_h :: Ptr (TQPushButton a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QPushButtonSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_event_h cobj_x0 cobj_x1
instance QfocusInEvent (QPushButton ()) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_focusInEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_focusInEvent_h" qtc_QPushButton_focusInEvent_h :: Ptr (TQPushButton a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusInEvent (QPushButtonSc a) ((QFocusEvent t1)) where
focusInEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_focusInEvent_h cobj_x0 cobj_x1
instance QfocusOutEvent (QPushButton ()) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_focusOutEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_focusOutEvent_h" qtc_QPushButton_focusOutEvent_h :: Ptr (TQPushButton a) -> Ptr (TQFocusEvent t1) -> IO ()
instance QfocusOutEvent (QPushButtonSc a) ((QFocusEvent t1)) where
focusOutEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_focusOutEvent_h cobj_x0 cobj_x1
instance QinitStyleOption (QPushButton ()) ((QStyleOptionButton t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_initStyleOption cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_initStyleOption" qtc_QPushButton_initStyleOption :: Ptr (TQPushButton a) -> Ptr (TQStyleOptionButton t1) -> IO ()
instance QinitStyleOption (QPushButtonSc a) ((QStyleOptionButton t1)) where
initStyleOption x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_initStyleOption cobj_x0 cobj_x1
isDefault :: QPushButton a -> (()) -> IO (Bool)
isDefault x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_isDefault cobj_x0
foreign import ccall "qtc_QPushButton_isDefault" qtc_QPushButton_isDefault :: Ptr (TQPushButton a) -> IO CBool
instance QisFlat (QPushButton a) (()) where
isFlat x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_isFlat cobj_x0
foreign import ccall "qtc_QPushButton_isFlat" qtc_QPushButton_isFlat :: Ptr (TQPushButton a) -> IO CBool
instance QkeyPressEvent (QPushButton ()) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_keyPressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_keyPressEvent_h" qtc_QPushButton_keyPressEvent_h :: Ptr (TQPushButton a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyPressEvent (QPushButtonSc a) ((QKeyEvent t1)) where
keyPressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_keyPressEvent_h cobj_x0 cobj_x1
instance Qmenu (QPushButton a) (()) where
menu x0 ()
= withQMenuResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_menu cobj_x0
foreign import ccall "qtc_QPushButton_menu" qtc_QPushButton_menu :: Ptr (TQPushButton a) -> IO (Ptr (TQMenu ()))
instance QqminimumSizeHint (QPushButton ()) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_minimumSizeHint_h cobj_x0
foreign import ccall "qtc_QPushButton_minimumSizeHint_h" qtc_QPushButton_minimumSizeHint_h :: Ptr (TQPushButton a) -> IO (Ptr (TQSize ()))
instance QqminimumSizeHint (QPushButtonSc a) (()) where
qminimumSizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_minimumSizeHint_h cobj_x0
instance QminimumSizeHint (QPushButton ()) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QPushButton_minimumSizeHint_qth_h" qtc_QPushButton_minimumSizeHint_qth_h :: Ptr (TQPushButton a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QminimumSizeHint (QPushButtonSc a) (()) where
minimumSizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_minimumSizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
instance QpaintEvent (QPushButton ()) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_paintEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_paintEvent_h" qtc_QPushButton_paintEvent_h :: Ptr (TQPushButton a) -> Ptr (TQPaintEvent t1) -> IO ()
instance QpaintEvent (QPushButtonSc a) ((QPaintEvent t1)) where
paintEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_paintEvent_h cobj_x0 cobj_x1
setAutoDefault :: QPushButton a -> ((Bool)) -> IO ()
setAutoDefault x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setAutoDefault cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_setAutoDefault" qtc_QPushButton_setAutoDefault :: Ptr (TQPushButton a) -> CBool -> IO ()
setDefault :: QPushButton a -> ((Bool)) -> IO ()
setDefault x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setDefault cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_setDefault" qtc_QPushButton_setDefault :: Ptr (TQPushButton a) -> CBool -> IO ()
instance QsetFlat (QPushButton a) ((Bool)) where
setFlat x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setFlat cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_setFlat" qtc_QPushButton_setFlat :: Ptr (TQPushButton a) -> CBool -> IO ()
instance QsetMenu (QPushButton a) ((QMenu t1)) where
setMenu x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_setMenu cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_setMenu" qtc_QPushButton_setMenu :: Ptr (TQPushButton a) -> Ptr (TQMenu t1) -> IO ()
instance QshowMenu (QPushButton a) (()) where
showMenu x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_showMenu cobj_x0
foreign import ccall "qtc_QPushButton_showMenu" qtc_QPushButton_showMenu :: Ptr (TQPushButton a) -> IO ()
instance QqsizeHint (QPushButton ()) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_sizeHint_h cobj_x0
foreign import ccall "qtc_QPushButton_sizeHint_h" qtc_QPushButton_sizeHint_h :: Ptr (TQPushButton a) -> IO (Ptr (TQSize ()))
instance QqsizeHint (QPushButtonSc a) (()) where
qsizeHint x0 ()
= withQSizeResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_sizeHint_h cobj_x0
instance QsizeHint (QPushButton ()) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
foreign import ccall "qtc_QPushButton_sizeHint_qth_h" qtc_QPushButton_sizeHint_qth_h :: Ptr (TQPushButton a) -> Ptr CInt -> Ptr CInt -> IO ()
instance QsizeHint (QPushButtonSc a) (()) where
sizeHint x0 ()
= withSizeResult $ \csize_ret_w csize_ret_h ->
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_sizeHint_qth_h cobj_x0 csize_ret_w csize_ret_h
qPushButton_delete :: QPushButton a -> IO ()
qPushButton_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_delete cobj_x0
foreign import ccall "qtc_QPushButton_delete" qtc_QPushButton_delete :: Ptr (TQPushButton a) -> IO ()
qPushButton_deleteLater :: QPushButton a -> IO ()
qPushButton_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_deleteLater cobj_x0
foreign import ccall "qtc_QPushButton_deleteLater" qtc_QPushButton_deleteLater :: Ptr (TQPushButton a) -> IO ()
instance QchangeEvent (QPushButton ()) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_changeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_changeEvent_h" qtc_QPushButton_changeEvent_h :: Ptr (TQPushButton a) -> Ptr (TQEvent t1) -> IO ()
instance QchangeEvent (QPushButtonSc a) ((QEvent t1)) where
changeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_changeEvent_h cobj_x0 cobj_x1
instance QcheckStateSet (QPushButton ()) (()) where
checkStateSet x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_checkStateSet cobj_x0
foreign import ccall "qtc_QPushButton_checkStateSet" qtc_QPushButton_checkStateSet :: Ptr (TQPushButton a) -> IO ()
instance QcheckStateSet (QPushButtonSc a) (()) where
checkStateSet x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_checkStateSet cobj_x0
instance QhitButton (QPushButton ()) ((Point)) where
hitButton x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QPushButton_hitButton_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QPushButton_hitButton_qth" qtc_QPushButton_hitButton_qth :: Ptr (TQPushButton a) -> CInt -> CInt -> IO CBool
instance QhitButton (QPushButtonSc a) ((Point)) where
hitButton x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QPushButton_hitButton_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance QqhitButton (QPushButton ()) ((QPoint t1)) where
qhitButton x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_hitButton cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_hitButton" qtc_QPushButton_hitButton :: Ptr (TQPushButton a) -> Ptr (TQPoint t1) -> IO CBool
instance QqhitButton (QPushButtonSc a) ((QPoint t1)) where
qhitButton x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_hitButton cobj_x0 cobj_x1
instance QkeyReleaseEvent (QPushButton ()) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_keyReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_keyReleaseEvent_h" qtc_QPushButton_keyReleaseEvent_h :: Ptr (TQPushButton a) -> Ptr (TQKeyEvent t1) -> IO ()
instance QkeyReleaseEvent (QPushButtonSc a) ((QKeyEvent t1)) where
keyReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_keyReleaseEvent_h cobj_x0 cobj_x1
instance QmouseMoveEvent (QPushButton ()) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mouseMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_mouseMoveEvent_h" qtc_QPushButton_mouseMoveEvent_h :: Ptr (TQPushButton a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseMoveEvent (QPushButtonSc a) ((QMouseEvent t1)) where
mouseMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mouseMoveEvent_h cobj_x0 cobj_x1
instance QmousePressEvent (QPushButton ()) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mousePressEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_mousePressEvent_h" qtc_QPushButton_mousePressEvent_h :: Ptr (TQPushButton a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmousePressEvent (QPushButtonSc a) ((QMouseEvent t1)) where
mousePressEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mousePressEvent_h cobj_x0 cobj_x1
instance QmouseReleaseEvent (QPushButton ()) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mouseReleaseEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_mouseReleaseEvent_h" qtc_QPushButton_mouseReleaseEvent_h :: Ptr (TQPushButton a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseReleaseEvent (QPushButtonSc a) ((QMouseEvent t1)) where
mouseReleaseEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mouseReleaseEvent_h cobj_x0 cobj_x1
instance QnextCheckState (QPushButton ()) (()) where
nextCheckState x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_nextCheckState cobj_x0
foreign import ccall "qtc_QPushButton_nextCheckState" qtc_QPushButton_nextCheckState :: Ptr (TQPushButton a) -> IO ()
instance QnextCheckState (QPushButtonSc a) (()) where
nextCheckState x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_nextCheckState cobj_x0
instance QtimerEvent (QPushButton ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_timerEvent" qtc_QPushButton_timerEvent :: Ptr (TQPushButton a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QPushButtonSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_timerEvent cobj_x0 cobj_x1
instance QactionEvent (QPushButton ()) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_actionEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_actionEvent_h" qtc_QPushButton_actionEvent_h :: Ptr (TQPushButton a) -> Ptr (TQActionEvent t1) -> IO ()
instance QactionEvent (QPushButtonSc a) ((QActionEvent t1)) where
actionEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_actionEvent_h cobj_x0 cobj_x1
instance QaddAction (QPushButton ()) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_addAction cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_addAction" qtc_QPushButton_addAction :: Ptr (TQPushButton a) -> Ptr (TQAction t1) -> IO ()
instance QaddAction (QPushButtonSc a) ((QAction t1)) (IO ()) where
addAction x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_addAction cobj_x0 cobj_x1
instance QcloseEvent (QPushButton ()) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_closeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_closeEvent_h" qtc_QPushButton_closeEvent_h :: Ptr (TQPushButton a) -> Ptr (TQCloseEvent t1) -> IO ()
instance QcloseEvent (QPushButtonSc a) ((QCloseEvent t1)) where
closeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_closeEvent_h cobj_x0 cobj_x1
instance QcontextMenuEvent (QPushButton ()) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_contextMenuEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_contextMenuEvent_h" qtc_QPushButton_contextMenuEvent_h :: Ptr (TQPushButton a) -> Ptr (TQContextMenuEvent t1) -> IO ()
instance QcontextMenuEvent (QPushButtonSc a) ((QContextMenuEvent t1)) where
contextMenuEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_contextMenuEvent_h cobj_x0 cobj_x1
instance Qcreate (QPushButton ()) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_create cobj_x0
foreign import ccall "qtc_QPushButton_create" qtc_QPushButton_create :: Ptr (TQPushButton a) -> IO ()
instance Qcreate (QPushButtonSc a) (()) (IO ()) where
create x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_create cobj_x0
instance Qcreate (QPushButton ()) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_create1 cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_create1" qtc_QPushButton_create1 :: Ptr (TQPushButton a) -> Ptr (TQVoid t1) -> IO ()
instance Qcreate (QPushButtonSc a) ((QVoid t1)) (IO ()) where
create x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_create1 cobj_x0 cobj_x1
instance Qcreate (QPushButton ()) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_create2 cobj_x0 cobj_x1 (toCBool x2)
foreign import ccall "qtc_QPushButton_create2" qtc_QPushButton_create2 :: Ptr (TQPushButton a) -> Ptr (TQVoid t1) -> CBool -> IO ()
instance Qcreate (QPushButtonSc a) ((QVoid t1, Bool)) (IO ()) where
create x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_create2 cobj_x0 cobj_x1 (toCBool x2)
instance Qcreate (QPushButton ()) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
foreign import ccall "qtc_QPushButton_create3" qtc_QPushButton_create3 :: Ptr (TQPushButton a) -> Ptr (TQVoid t1) -> CBool -> CBool -> IO ()
instance Qcreate (QPushButtonSc a) ((QVoid t1, Bool, Bool)) (IO ()) where
create x0 (x1, x2, x3)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_create3 cobj_x0 cobj_x1 (toCBool x2) (toCBool x3)
instance Qdestroy (QPushButton ()) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_destroy cobj_x0
foreign import ccall "qtc_QPushButton_destroy" qtc_QPushButton_destroy :: Ptr (TQPushButton a) -> IO ()
instance Qdestroy (QPushButtonSc a) (()) where
destroy x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_destroy cobj_x0
instance Qdestroy (QPushButton ()) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_destroy1 cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_destroy1" qtc_QPushButton_destroy1 :: Ptr (TQPushButton a) -> CBool -> IO ()
instance Qdestroy (QPushButtonSc a) ((Bool)) where
destroy x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_destroy1 cobj_x0 (toCBool x1)
instance Qdestroy (QPushButton ()) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
foreign import ccall "qtc_QPushButton_destroy2" qtc_QPushButton_destroy2 :: Ptr (TQPushButton a) -> CBool -> CBool -> IO ()
instance Qdestroy (QPushButtonSc a) ((Bool, Bool)) where
destroy x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_destroy2 cobj_x0 (toCBool x1) (toCBool x2)
instance QdevType (QPushButton ()) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_devType_h cobj_x0
foreign import ccall "qtc_QPushButton_devType_h" qtc_QPushButton_devType_h :: Ptr (TQPushButton a) -> IO CInt
instance QdevType (QPushButtonSc a) (()) where
devType x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_devType_h cobj_x0
instance QdragEnterEvent (QPushButton ()) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dragEnterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_dragEnterEvent_h" qtc_QPushButton_dragEnterEvent_h :: Ptr (TQPushButton a) -> Ptr (TQDragEnterEvent t1) -> IO ()
instance QdragEnterEvent (QPushButtonSc a) ((QDragEnterEvent t1)) where
dragEnterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dragEnterEvent_h cobj_x0 cobj_x1
instance QdragLeaveEvent (QPushButton ()) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dragLeaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_dragLeaveEvent_h" qtc_QPushButton_dragLeaveEvent_h :: Ptr (TQPushButton a) -> Ptr (TQDragLeaveEvent t1) -> IO ()
instance QdragLeaveEvent (QPushButtonSc a) ((QDragLeaveEvent t1)) where
dragLeaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dragLeaveEvent_h cobj_x0 cobj_x1
instance QdragMoveEvent (QPushButton ()) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dragMoveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_dragMoveEvent_h" qtc_QPushButton_dragMoveEvent_h :: Ptr (TQPushButton a) -> Ptr (TQDragMoveEvent t1) -> IO ()
instance QdragMoveEvent (QPushButtonSc a) ((QDragMoveEvent t1)) where
dragMoveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dragMoveEvent_h cobj_x0 cobj_x1
instance QdropEvent (QPushButton ()) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dropEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_dropEvent_h" qtc_QPushButton_dropEvent_h :: Ptr (TQPushButton a) -> Ptr (TQDropEvent t1) -> IO ()
instance QdropEvent (QPushButtonSc a) ((QDropEvent t1)) where
dropEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_dropEvent_h cobj_x0 cobj_x1
instance QenabledChange (QPushButton ()) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_enabledChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_enabledChange" qtc_QPushButton_enabledChange :: Ptr (TQPushButton a) -> CBool -> IO ()
instance QenabledChange (QPushButtonSc a) ((Bool)) where
enabledChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_enabledChange cobj_x0 (toCBool x1)
instance QenterEvent (QPushButton ()) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_enterEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_enterEvent_h" qtc_QPushButton_enterEvent_h :: Ptr (TQPushButton a) -> Ptr (TQEvent t1) -> IO ()
instance QenterEvent (QPushButtonSc a) ((QEvent t1)) where
enterEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_enterEvent_h cobj_x0 cobj_x1
instance QfocusNextChild (QPushButton ()) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_focusNextChild cobj_x0
foreign import ccall "qtc_QPushButton_focusNextChild" qtc_QPushButton_focusNextChild :: Ptr (TQPushButton a) -> IO CBool
instance QfocusNextChild (QPushButtonSc a) (()) where
focusNextChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_focusNextChild cobj_x0
instance QfocusNextPrevChild (QPushButton ()) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_focusNextPrevChild cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_focusNextPrevChild" qtc_QPushButton_focusNextPrevChild :: Ptr (TQPushButton a) -> CBool -> IO CBool
instance QfocusNextPrevChild (QPushButtonSc a) ((Bool)) where
focusNextPrevChild x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_focusNextPrevChild cobj_x0 (toCBool x1)
instance QfocusPreviousChild (QPushButton ()) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_focusPreviousChild cobj_x0
foreign import ccall "qtc_QPushButton_focusPreviousChild" qtc_QPushButton_focusPreviousChild :: Ptr (TQPushButton a) -> IO CBool
instance QfocusPreviousChild (QPushButtonSc a) (()) where
focusPreviousChild x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_focusPreviousChild cobj_x0
instance QfontChange (QPushButton ()) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_fontChange cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_fontChange" qtc_QPushButton_fontChange :: Ptr (TQPushButton a) -> Ptr (TQFont t1) -> IO ()
instance QfontChange (QPushButtonSc a) ((QFont t1)) where
fontChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_fontChange cobj_x0 cobj_x1
instance QheightForWidth (QPushButton ()) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_heightForWidth_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QPushButton_heightForWidth_h" qtc_QPushButton_heightForWidth_h :: Ptr (TQPushButton a) -> CInt -> IO CInt
instance QheightForWidth (QPushButtonSc a) ((Int)) where
heightForWidth x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_heightForWidth_h cobj_x0 (toCInt x1)
instance QhideEvent (QPushButton ()) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_hideEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_hideEvent_h" qtc_QPushButton_hideEvent_h :: Ptr (TQPushButton a) -> Ptr (TQHideEvent t1) -> IO ()
instance QhideEvent (QPushButtonSc a) ((QHideEvent t1)) where
hideEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_hideEvent_h cobj_x0 cobj_x1
instance QinputMethodEvent (QPushButton ()) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_inputMethodEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_inputMethodEvent" qtc_QPushButton_inputMethodEvent :: Ptr (TQPushButton a) -> Ptr (TQInputMethodEvent t1) -> IO ()
instance QinputMethodEvent (QPushButtonSc a) ((QInputMethodEvent t1)) where
inputMethodEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_inputMethodEvent cobj_x0 cobj_x1
instance QinputMethodQuery (QPushButton ()) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QPushButton_inputMethodQuery_h" qtc_QPushButton_inputMethodQuery_h :: Ptr (TQPushButton a) -> CLong -> IO (Ptr (TQVariant ()))
instance QinputMethodQuery (QPushButtonSc a) ((InputMethodQuery)) where
inputMethodQuery x0 (x1)
= withQVariantResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_inputMethodQuery_h cobj_x0 (toCLong $ qEnum_toInt x1)
instance QlanguageChange (QPushButton ()) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_languageChange cobj_x0
foreign import ccall "qtc_QPushButton_languageChange" qtc_QPushButton_languageChange :: Ptr (TQPushButton a) -> IO ()
instance QlanguageChange (QPushButtonSc a) (()) where
languageChange x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_languageChange cobj_x0
instance QleaveEvent (QPushButton ()) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_leaveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_leaveEvent_h" qtc_QPushButton_leaveEvent_h :: Ptr (TQPushButton a) -> Ptr (TQEvent t1) -> IO ()
instance QleaveEvent (QPushButtonSc a) ((QEvent t1)) where
leaveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_leaveEvent_h cobj_x0 cobj_x1
instance Qmetric (QPushButton ()) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_metric cobj_x0 (toCLong $ qEnum_toInt x1)
foreign import ccall "qtc_QPushButton_metric" qtc_QPushButton_metric :: Ptr (TQPushButton a) -> CLong -> IO CInt
instance Qmetric (QPushButtonSc a) ((PaintDeviceMetric)) where
metric x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_metric cobj_x0 (toCLong $ qEnum_toInt x1)
instance QmouseDoubleClickEvent (QPushButton ()) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mouseDoubleClickEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_mouseDoubleClickEvent_h" qtc_QPushButton_mouseDoubleClickEvent_h :: Ptr (TQPushButton a) -> Ptr (TQMouseEvent t1) -> IO ()
instance QmouseDoubleClickEvent (QPushButtonSc a) ((QMouseEvent t1)) where
mouseDoubleClickEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_mouseDoubleClickEvent_h cobj_x0 cobj_x1
instance Qmove (QPushButton ()) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_move1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QPushButton_move1" qtc_QPushButton_move1 :: Ptr (TQPushButton a) -> CInt -> CInt -> IO ()
instance Qmove (QPushButtonSc a) ((Int, Int)) where
move x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_move1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qmove (QPushButton ()) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QPushButton_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
foreign import ccall "qtc_QPushButton_move_qth" qtc_QPushButton_move_qth :: Ptr (TQPushButton a) -> CInt -> CInt -> IO ()
instance Qmove (QPushButtonSc a) ((Point)) where
move x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCPoint x1 $ \cpoint_x1_x cpoint_x1_y ->
qtc_QPushButton_move_qth cobj_x0 cpoint_x1_x cpoint_x1_y
instance Qqmove (QPushButton ()) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_move cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_move" qtc_QPushButton_move :: Ptr (TQPushButton a) -> Ptr (TQPoint t1) -> IO ()
instance Qqmove (QPushButtonSc a) ((QPoint t1)) where
qmove x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_move cobj_x0 cobj_x1
instance QmoveEvent (QPushButton ()) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_moveEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_moveEvent_h" qtc_QPushButton_moveEvent_h :: Ptr (TQPushButton a) -> Ptr (TQMoveEvent t1) -> IO ()
instance QmoveEvent (QPushButtonSc a) ((QMoveEvent t1)) where
moveEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_moveEvent_h cobj_x0 cobj_x1
instance QpaintEngine (QPushButton ()) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_paintEngine_h cobj_x0
foreign import ccall "qtc_QPushButton_paintEngine_h" qtc_QPushButton_paintEngine_h :: Ptr (TQPushButton a) -> IO (Ptr (TQPaintEngine ()))
instance QpaintEngine (QPushButtonSc a) (()) where
paintEngine x0 ()
= withObjectRefResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_paintEngine_h cobj_x0
instance QpaletteChange (QPushButton ()) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_paletteChange cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_paletteChange" qtc_QPushButton_paletteChange :: Ptr (TQPushButton a) -> Ptr (TQPalette t1) -> IO ()
instance QpaletteChange (QPushButtonSc a) ((QPalette t1)) where
paletteChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_paletteChange cobj_x0 cobj_x1
instance Qrepaint (QPushButton ()) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_repaint cobj_x0
foreign import ccall "qtc_QPushButton_repaint" qtc_QPushButton_repaint :: Ptr (TQPushButton a) -> IO ()
instance Qrepaint (QPushButtonSc a) (()) where
repaint x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_repaint cobj_x0
instance Qrepaint (QPushButton ()) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QPushButton_repaint2" qtc_QPushButton_repaint2 :: Ptr (TQPushButton a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance Qrepaint (QPushButtonSc a) ((Int, Int, Int, Int)) where
repaint x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_repaint2 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance Qrepaint (QPushButton ()) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_repaint1 cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_repaint1" qtc_QPushButton_repaint1 :: Ptr (TQPushButton a) -> Ptr (TQRegion t1) -> IO ()
instance Qrepaint (QPushButtonSc a) ((QRegion t1)) where
repaint x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_repaint1 cobj_x0 cobj_x1
instance QresetInputContext (QPushButton ()) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_resetInputContext cobj_x0
foreign import ccall "qtc_QPushButton_resetInputContext" qtc_QPushButton_resetInputContext :: Ptr (TQPushButton a) -> IO ()
instance QresetInputContext (QPushButtonSc a) (()) where
resetInputContext x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_resetInputContext cobj_x0
instance Qresize (QPushButton ()) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_resize1 cobj_x0 (toCInt x1) (toCInt x2)
foreign import ccall "qtc_QPushButton_resize1" qtc_QPushButton_resize1 :: Ptr (TQPushButton a) -> CInt -> CInt -> IO ()
instance Qresize (QPushButtonSc a) ((Int, Int)) (IO ()) where
resize x0 (x1, x2)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_resize1 cobj_x0 (toCInt x1) (toCInt x2)
instance Qqresize (QPushButton ()) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_resize cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_resize" qtc_QPushButton_resize :: Ptr (TQPushButton a) -> Ptr (TQSize t1) -> IO ()
instance Qqresize (QPushButtonSc a) ((QSize t1)) where
qresize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_resize cobj_x0 cobj_x1
instance Qresize (QPushButton ()) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QPushButton_resize_qth cobj_x0 csize_x1_w csize_x1_h
foreign import ccall "qtc_QPushButton_resize_qth" qtc_QPushButton_resize_qth :: Ptr (TQPushButton a) -> CInt -> CInt -> IO ()
instance Qresize (QPushButtonSc a) ((Size)) (IO ()) where
resize x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCSize x1 $ \csize_x1_w csize_x1_h ->
qtc_QPushButton_resize_qth cobj_x0 csize_x1_w csize_x1_h
instance QresizeEvent (QPushButton ()) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_resizeEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_resizeEvent_h" qtc_QPushButton_resizeEvent_h :: Ptr (TQPushButton a) -> Ptr (TQResizeEvent t1) -> IO ()
instance QresizeEvent (QPushButtonSc a) ((QResizeEvent t1)) where
resizeEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_resizeEvent_h cobj_x0 cobj_x1
instance QsetGeometry (QPushButton ()) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
foreign import ccall "qtc_QPushButton_setGeometry1" qtc_QPushButton_setGeometry1 :: Ptr (TQPushButton a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QPushButtonSc a) ((Int, Int, Int, Int)) where
setGeometry x0 (x1, x2, x3, x4)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setGeometry1 cobj_x0 (toCInt x1) (toCInt x2) (toCInt x3) (toCInt x4)
instance QqsetGeometry (QPushButton ()) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_setGeometry cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_setGeometry" qtc_QPushButton_setGeometry :: Ptr (TQPushButton a) -> Ptr (TQRect t1) -> IO ()
instance QqsetGeometry (QPushButtonSc a) ((QRect t1)) where
qsetGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_setGeometry cobj_x0 cobj_x1
instance QsetGeometry (QPushButton ()) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QPushButton_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
foreign import ccall "qtc_QPushButton_setGeometry_qth" qtc_QPushButton_setGeometry_qth :: Ptr (TQPushButton a) -> CInt -> CInt -> CInt -> CInt -> IO ()
instance QsetGeometry (QPushButtonSc a) ((Rect)) where
setGeometry x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCRect x1 $ \crect_x1_x crect_x1_y crect_x1_w crect_x1_h ->
qtc_QPushButton_setGeometry_qth cobj_x0 crect_x1_x crect_x1_y crect_x1_w crect_x1_h
instance QsetMouseTracking (QPushButton ()) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setMouseTracking cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_setMouseTracking" qtc_QPushButton_setMouseTracking :: Ptr (TQPushButton a) -> CBool -> IO ()
instance QsetMouseTracking (QPushButtonSc a) ((Bool)) where
setMouseTracking x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setMouseTracking cobj_x0 (toCBool x1)
instance QsetVisible (QPushButton ()) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setVisible_h cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_setVisible_h" qtc_QPushButton_setVisible_h :: Ptr (TQPushButton a) -> CBool -> IO ()
instance QsetVisible (QPushButtonSc a) ((Bool)) where
setVisible x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_setVisible_h cobj_x0 (toCBool x1)
instance QshowEvent (QPushButton ()) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_showEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_showEvent_h" qtc_QPushButton_showEvent_h :: Ptr (TQPushButton a) -> Ptr (TQShowEvent t1) -> IO ()
instance QshowEvent (QPushButtonSc a) ((QShowEvent t1)) where
showEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_showEvent_h cobj_x0 cobj_x1
instance QtabletEvent (QPushButton ()) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_tabletEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_tabletEvent_h" qtc_QPushButton_tabletEvent_h :: Ptr (TQPushButton a) -> Ptr (TQTabletEvent t1) -> IO ()
instance QtabletEvent (QPushButtonSc a) ((QTabletEvent t1)) where
tabletEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_tabletEvent_h cobj_x0 cobj_x1
instance QupdateMicroFocus (QPushButton ()) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_updateMicroFocus cobj_x0
foreign import ccall "qtc_QPushButton_updateMicroFocus" qtc_QPushButton_updateMicroFocus :: Ptr (TQPushButton a) -> IO ()
instance QupdateMicroFocus (QPushButtonSc a) (()) where
updateMicroFocus x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_updateMicroFocus cobj_x0
instance QwheelEvent (QPushButton ()) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_wheelEvent_h cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_wheelEvent_h" qtc_QPushButton_wheelEvent_h :: Ptr (TQPushButton a) -> Ptr (TQWheelEvent t1) -> IO ()
instance QwheelEvent (QPushButtonSc a) ((QWheelEvent t1)) where
wheelEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_wheelEvent_h cobj_x0 cobj_x1
instance QwindowActivationChange (QPushButton ()) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_windowActivationChange cobj_x0 (toCBool x1)
foreign import ccall "qtc_QPushButton_windowActivationChange" qtc_QPushButton_windowActivationChange :: Ptr (TQPushButton a) -> CBool -> IO ()
instance QwindowActivationChange (QPushButtonSc a) ((Bool)) where
windowActivationChange x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_windowActivationChange cobj_x0 (toCBool x1)
instance QchildEvent (QPushButton ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_childEvent" qtc_QPushButton_childEvent :: Ptr (TQPushButton a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QPushButtonSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QPushButton ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QPushButton_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QPushButton_connectNotify" qtc_QPushButton_connectNotify :: Ptr (TQPushButton a) -> CWString -> IO ()
instance QconnectNotify (QPushButtonSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QPushButton_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QPushButton ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QPushButton_customEvent" qtc_QPushButton_customEvent :: Ptr (TQPushButton a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QPushButtonSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QPushButton_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QPushButton ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QPushButton_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QPushButton_disconnectNotify" qtc_QPushButton_disconnectNotify :: Ptr (TQPushButton a) -> CWString -> IO ()
instance QdisconnectNotify (QPushButtonSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QPushButton_disconnectNotify cobj_x0 cstr_x1
instance QeventFilter (QPushButton ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QPushButton_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QPushButton_eventFilter_h" qtc_QPushButton_eventFilter_h :: Ptr (TQPushButton a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QPushButtonSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QPushButton_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QPushButton ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QPushButton_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QPushButton_receivers" qtc_QPushButton_receivers :: Ptr (TQPushButton a) -> CWString -> IO CInt
instance Qreceivers (QPushButtonSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QPushButton_receivers cobj_x0 cstr_x1
instance Qsender (QPushButton ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_sender cobj_x0
foreign import ccall "qtc_QPushButton_sender" qtc_QPushButton_sender :: Ptr (TQPushButton a) -> IO (Ptr (TQObject ()))
instance Qsender (QPushButtonSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QPushButton_sender cobj_x0
| keera-studios/hsQt | Qtc/Gui/QPushButton.hs | bsd-2-clause | 49,930 | 0 | 14 | 8,076 | 16,193 | 8,211 | 7,982 | -1 | -1 |
-- http://www.codewars.com/kata/530265044b7e23379d00076a
module PointInPolygon where
type Point = (Double, Double)
between :: Double -> Double -> Double -> Bool
between a b c = b<=a && a<=c || c<=a && a<=b
pointInPoly :: [Point] -> Point -> Bool
pointInPoly poly (px, py) = checkOx || checkOy where
poly' = map (\(ax, ay) -> (ax-px, ay-py)) poly
segments = zip poly' (tail poly' ++ [head poly'])
checkOx = checkSmth intersectOx
checkOy = checkSmth intersectOy
checkSmth f = (odd . length . filter id . map f) segments
intersectOy ((ax, ay), (bx, by)) = intersectOx ((ay, ax), (by, bx))
intersectOx ((ax, ay), (bx, by))
| ay == 0 = False
| by == 0 = bx >= 0
| ay == by = False
| ay * by > 0 = False
| ax <= 0 && bx <= 0 = False
| otherwise = x >= 0 && between x ax bx where
x = ax - ay * (ax - bx) / (ay - by) | Bodigrim/katas | src/haskell/3-Point-in-Polygon.hs | bsd-2-clause | 858 | 0 | 12 | 214 | 432 | 230 | 202 | 20 | 1 |
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QTextTableFormat.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:16
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Gui.QTextTableFormat (
QqTextTableFormat(..)
,QqTextTableFormat_nf(..)
,cellPadding
,cellSpacing
,clearColumnWidthConstraints
,headerRowCount
,setCellPadding
,setCellSpacing
,setColumns
,setHeaderRowCount
,qTextTableFormat_delete
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.Qt
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
import Qtc.Classes.Gui
import Qtc.ClassTypes.Gui
class QqTextTableFormat x1 where
qTextTableFormat :: x1 -> IO (QTextTableFormat ())
instance QqTextTableFormat (()) where
qTextTableFormat ()
= withQTextTableFormatResult $
qtc_QTextTableFormat
foreign import ccall "qtc_QTextTableFormat" qtc_QTextTableFormat :: IO (Ptr (TQTextTableFormat ()))
instance QqTextTableFormat ((QTextTableFormat t1)) where
qTextTableFormat (x1)
= withQTextTableFormatResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextTableFormat1 cobj_x1
foreign import ccall "qtc_QTextTableFormat1" qtc_QTextTableFormat1 :: Ptr (TQTextTableFormat t1) -> IO (Ptr (TQTextTableFormat ()))
class QqTextTableFormat_nf x1 where
qTextTableFormat_nf :: x1 -> IO (QTextTableFormat ())
instance QqTextTableFormat_nf (()) where
qTextTableFormat_nf ()
= withObjectRefResult $
qtc_QTextTableFormat
instance QqTextTableFormat_nf ((QTextTableFormat t1)) where
qTextTableFormat_nf (x1)
= withObjectRefResult $
withObjectPtr x1 $ \cobj_x1 ->
qtc_QTextTableFormat1 cobj_x1
instance Qalignment (QTextTableFormat a) (()) where
alignment x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_alignment cobj_x0
foreign import ccall "qtc_QTextTableFormat_alignment" qtc_QTextTableFormat_alignment :: Ptr (TQTextTableFormat a) -> IO CLong
cellPadding :: QTextTableFormat a -> (()) -> IO (Double)
cellPadding x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_cellPadding cobj_x0
foreign import ccall "qtc_QTextTableFormat_cellPadding" qtc_QTextTableFormat_cellPadding :: Ptr (TQTextTableFormat a) -> IO CDouble
cellSpacing :: QTextTableFormat a -> (()) -> IO (Double)
cellSpacing x0 ()
= withDoubleResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_cellSpacing cobj_x0
foreign import ccall "qtc_QTextTableFormat_cellSpacing" qtc_QTextTableFormat_cellSpacing :: Ptr (TQTextTableFormat a) -> IO CDouble
clearColumnWidthConstraints :: QTextTableFormat a -> (()) -> IO ()
clearColumnWidthConstraints x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_clearColumnWidthConstraints cobj_x0
foreign import ccall "qtc_QTextTableFormat_clearColumnWidthConstraints" qtc_QTextTableFormat_clearColumnWidthConstraints :: Ptr (TQTextTableFormat a) -> IO ()
instance Qcolumns (QTextTableFormat a) (()) where
columns x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_columns cobj_x0
foreign import ccall "qtc_QTextTableFormat_columns" qtc_QTextTableFormat_columns :: Ptr (TQTextTableFormat a) -> IO CInt
headerRowCount :: QTextTableFormat a -> (()) -> IO (Int)
headerRowCount x0 ()
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_headerRowCount cobj_x0
foreign import ccall "qtc_QTextTableFormat_headerRowCount" qtc_QTextTableFormat_headerRowCount :: Ptr (TQTextTableFormat a) -> IO CInt
instance QqisValid (QTextTableFormat ()) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_isValid cobj_x0
foreign import ccall "qtc_QTextTableFormat_isValid" qtc_QTextTableFormat_isValid :: Ptr (TQTextTableFormat a) -> IO CBool
instance QqisValid (QTextTableFormatSc a) (()) where
qisValid x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_isValid cobj_x0
instance QsetAlignment (QTextTableFormat a) ((Alignment)) (IO ()) where
setAlignment x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setAlignment cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QTextTableFormat_setAlignment" qtc_QTextTableFormat_setAlignment :: Ptr (TQTextTableFormat a) -> CLong -> IO ()
setCellPadding :: QTextTableFormat a -> ((Double)) -> IO ()
setCellPadding x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setCellPadding cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QTextTableFormat_setCellPadding" qtc_QTextTableFormat_setCellPadding :: Ptr (TQTextTableFormat a) -> CDouble -> IO ()
setCellSpacing :: QTextTableFormat a -> ((Double)) -> IO ()
setCellSpacing x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setCellSpacing cobj_x0 (toCDouble x1)
foreign import ccall "qtc_QTextTableFormat_setCellSpacing" qtc_QTextTableFormat_setCellSpacing :: Ptr (TQTextTableFormat a) -> CDouble -> IO ()
setColumns :: QTextTableFormat a -> ((Int)) -> IO ()
setColumns x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setColumns cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextTableFormat_setColumns" qtc_QTextTableFormat_setColumns :: Ptr (TQTextTableFormat a) -> CInt -> IO ()
setHeaderRowCount :: QTextTableFormat a -> ((Int)) -> IO ()
setHeaderRowCount x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_setHeaderRowCount cobj_x0 (toCInt x1)
foreign import ccall "qtc_QTextTableFormat_setHeaderRowCount" qtc_QTextTableFormat_setHeaderRowCount :: Ptr (TQTextTableFormat a) -> CInt -> IO ()
qTextTableFormat_delete :: QTextTableFormat a -> IO ()
qTextTableFormat_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QTextTableFormat_delete cobj_x0
foreign import ccall "qtc_QTextTableFormat_delete" qtc_QTextTableFormat_delete :: Ptr (TQTextTableFormat a) -> IO ()
| uduki/hsQt | Qtc/Gui/QTextTableFormat.hs | bsd-2-clause | 6,202 | 0 | 12 | 887 | 1,591 | 820 | 771 | -1 | -1 |
-------------------------------------------
module Color where
import Data.Maybe
-------------------------------------------
data Color = Black | White
deriving Eq
instance Show Color where
show Black = "\9787"
show White = "\9786"
instance Read Color where
readsPrec _ input
| head input == 'W' = [(White, tail input)]
| head input == 'B' = [(Black, tail input)]
| otherwise = []
changeColor :: Color -> Color
changeColor col
|col == White = Black
|otherwise = White
-- Compares colors when one is maybe a color (used in rate block)
compareColors :: Maybe Color -> Color -> Bool
compareColors c1 c2
|Data.Maybe.isJust c1 = unJust c1 == c2
|otherwise = False
unJust :: Maybe t -> t
unJust (Just x) = x
| irmikrys/Gomoku | src/Color.hs | bsd-3-clause | 746 | 0 | 10 | 160 | 247 | 124 | 123 | 22 | 1 |
{-# LANGUAGE GADTs, DataKinds, KindSignatures, StandaloneDeriving, TypeFamilies, FlexibleInstances #-}
module Data.BitVector.Sparse where
import Data.Bit
import qualified Data.List as L
-- BitVector is a compact representation of a Sparse bit vector.
-- It has not specific length, other than where the 1's are.
newtype BitVector = BitVector { unBitVector :: [Int] }
deriving (Eq, Ord)
instance Show BitVector where
show = concat . map show . toList
fromList :: [Bit] -> BitVector
fromList vs = BitVector [ i | (i,1) <- [1..] `zip` vs ]
toList :: BitVector -> [Bit]
toList (BitVector bv) = concat [ take (n-1) (repeat 0) ++ [1] | n <- L.zipWith (-) bv (0 : bv) ]
elems :: BitVector -> [Int]
elems = unBitVector
vector :: [Int] -> BitVector
vector = BitVector . L.sort
-- zipWith combines two bit vectors with a binary bit function
zipWith :: (Bit -> Bit -> Bit) -> BitVector -> BitVector -> BitVector
zipWith f _ _ | f 0 0 /= 0 = error "zipWith assumes f 0 0 == 0"
zipWith f (BitVector xs) (BitVector ys) = BitVector [ z | (z,1) <- loop xs ys ]
where
loop [] [] = []
loop (x:xs) [] = (x,f 1 0) : loop xs []
loop [] (y:ys) = (y,f 0 1) : loop ys []
loop (x:xs) (y:ys)
| x == y = (x,f 1 1) : loop xs ys
| x < y = (x,f 1 0) : loop xs (y:ys)
| x > y = (y,f 0 1) : loop (x:xs) ys
(!) :: BitVector -> Int -> Bit
(!) (BitVector xs) n = if n `elem` xs then 1 else 0
| ku-fpg/ecc-ldpc | src/Data/BitVector/Sparse.hs | bsd-3-clause | 1,486 | 0 | 11 | 405 | 635 | 341 | 294 | 28 | 4 |
{-# language CPP #-}
-- No documentation found for Chapter "DynamicState"
module Vulkan.Core10.Enums.DynamicState (DynamicState( DYNAMIC_STATE_VIEWPORT
, DYNAMIC_STATE_SCISSOR
, DYNAMIC_STATE_LINE_WIDTH
, DYNAMIC_STATE_DEPTH_BIAS
, DYNAMIC_STATE_BLEND_CONSTANTS
, DYNAMIC_STATE_DEPTH_BOUNDS
, DYNAMIC_STATE_STENCIL_COMPARE_MASK
, DYNAMIC_STATE_STENCIL_WRITE_MASK
, DYNAMIC_STATE_STENCIL_REFERENCE
, DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT
, DYNAMIC_STATE_LOGIC_OP_EXT
, DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT
, DYNAMIC_STATE_VERTEX_INPUT_EXT
, DYNAMIC_STATE_LINE_STIPPLE_EXT
, DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR
, DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV
, DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV
, DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV
, DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR
, DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT
, DYNAMIC_STATE_DISCARD_RECTANGLE_EXT
, DYNAMIC_STATE_VIEWPORT_W_SCALING_NV
, DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE
, DYNAMIC_STATE_DEPTH_BIAS_ENABLE
, DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE
, DYNAMIC_STATE_STENCIL_OP
, DYNAMIC_STATE_STENCIL_TEST_ENABLE
, DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE
, DYNAMIC_STATE_DEPTH_COMPARE_OP
, DYNAMIC_STATE_DEPTH_WRITE_ENABLE
, DYNAMIC_STATE_DEPTH_TEST_ENABLE
, DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE
, DYNAMIC_STATE_SCISSOR_WITH_COUNT
, DYNAMIC_STATE_VIEWPORT_WITH_COUNT
, DYNAMIC_STATE_PRIMITIVE_TOPOLOGY
, DYNAMIC_STATE_FRONT_FACE
, DYNAMIC_STATE_CULL_MODE
, ..
)) where
import Vulkan.Internal.Utils (enumReadPrec)
import Vulkan.Internal.Utils (enumShowsPrec)
import GHC.Show (showsPrec)
import Vulkan.Zero (Zero)
import Foreign.Storable (Storable)
import Data.Int (Int32)
import GHC.Read (Read(readPrec))
import GHC.Show (Show(showsPrec))
-- | VkDynamicState - Indicate which dynamic state is taken from dynamic
-- state commands
--
-- = See Also
--
-- <https://www.khronos.org/registry/vulkan/specs/1.2-extensions/html/vkspec.html#VK_VERSION_1_0 VK_VERSION_1_0>,
-- 'Vulkan.Core10.Pipeline.PipelineDynamicStateCreateInfo'
newtype DynamicState = DynamicState Int32
deriving newtype (Eq, Ord, Storable, Zero)
-- | 'DYNAMIC_STATE_VIEWPORT' specifies that the @pViewports@ state in
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo' will be ignored
-- and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetViewport' before any drawing
-- commands. The number of viewports used by a pipeline is still specified
-- by the @viewportCount@ member of
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo'.
pattern DYNAMIC_STATE_VIEWPORT = DynamicState 0
-- | 'DYNAMIC_STATE_SCISSOR' specifies that the @pScissors@ state in
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo' will be ignored
-- and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetScissor' before any drawing
-- commands. The number of scissor rectangles used by a pipeline is still
-- specified by the @scissorCount@ member of
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo'.
pattern DYNAMIC_STATE_SCISSOR = DynamicState 1
-- | 'DYNAMIC_STATE_LINE_WIDTH' specifies that the @lineWidth@ state in
-- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetLineWidth' before any drawing
-- commands that generate line primitives for the rasterizer.
pattern DYNAMIC_STATE_LINE_WIDTH = DynamicState 2
-- | 'DYNAMIC_STATE_DEPTH_BIAS' specifies that the @depthBiasConstantFactor@,
-- @depthBiasClamp@ and @depthBiasSlopeFactor@ states in
-- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetDepthBias' before any draws
-- are performed with @depthBiasEnable@ in
-- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo' set to
-- 'Vulkan.Core10.FundamentalTypes.TRUE'.
pattern DYNAMIC_STATE_DEPTH_BIAS = DynamicState 3
-- | 'DYNAMIC_STATE_BLEND_CONSTANTS' specifies that the @blendConstants@
-- state in 'Vulkan.Core10.Pipeline.PipelineColorBlendStateCreateInfo' will
-- be ignored and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetBlendConstants' before any
-- draws are performed with a pipeline state with
-- 'Vulkan.Core10.Pipeline.PipelineColorBlendAttachmentState' member
-- @blendEnable@ set to 'Vulkan.Core10.FundamentalTypes.TRUE' and any of
-- the blend functions using a constant blend color.
pattern DYNAMIC_STATE_BLEND_CONSTANTS = DynamicState 4
-- | 'DYNAMIC_STATE_DEPTH_BOUNDS' specifies that the @minDepthBounds@ and
-- @maxDepthBounds@ states of
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetDepthBounds' before any draws
-- are performed with a pipeline state with
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' member
-- @depthBoundsTestEnable@ set to 'Vulkan.Core10.FundamentalTypes.TRUE'.
pattern DYNAMIC_STATE_DEPTH_BOUNDS = DynamicState 5
-- | 'DYNAMIC_STATE_STENCIL_COMPARE_MASK' specifies that the @compareMask@
-- state in 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo'
-- for both @front@ and @back@ will be ignored and /must/ be set
-- dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetStencilCompareMask' before
-- any draws are performed with a pipeline state with
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' member
-- @stencilTestEnable@ set to 'Vulkan.Core10.FundamentalTypes.TRUE'
pattern DYNAMIC_STATE_STENCIL_COMPARE_MASK = DynamicState 6
-- | 'DYNAMIC_STATE_STENCIL_WRITE_MASK' specifies that the @writeMask@ state
-- in 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' for both
-- @front@ and @back@ will be ignored and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetStencilWriteMask' before any
-- draws are performed with a pipeline state with
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' member
-- @stencilTestEnable@ set to 'Vulkan.Core10.FundamentalTypes.TRUE'
pattern DYNAMIC_STATE_STENCIL_WRITE_MASK = DynamicState 7
-- | 'DYNAMIC_STATE_STENCIL_REFERENCE' specifies that the @reference@ state
-- in 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' for both
-- @front@ and @back@ will be ignored and /must/ be set dynamically with
-- 'Vulkan.Core10.CommandBufferBuilding.cmdSetStencilReference' before any
-- draws are performed with a pipeline state with
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' member
-- @stencilTestEnable@ set to 'Vulkan.Core10.FundamentalTypes.TRUE'
pattern DYNAMIC_STATE_STENCIL_REFERENCE = DynamicState 8
-- | 'DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT' specifies that the
-- @pColorWriteEnables@ state in
-- 'Vulkan.Extensions.VK_EXT_color_write_enable.PipelineColorWriteCreateInfoEXT'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_EXT_color_write_enable.cmdSetColorWriteEnableEXT'
-- before any draw call.
pattern DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT = DynamicState 1000381000
-- | 'DYNAMIC_STATE_LOGIC_OP_EXT' specifies that the @logicOp@ state in
-- 'Vulkan.Core10.Pipeline.PipelineColorBlendStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_EXT_extended_dynamic_state2.cmdSetLogicOpEXT'
-- before any drawing commands.
pattern DYNAMIC_STATE_LOGIC_OP_EXT = DynamicState 1000377003
-- | 'DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT' specifies that the
-- @patchControlPoints@ state in
-- 'Vulkan.Core10.Pipeline.PipelineTessellationStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_EXT_extended_dynamic_state2.cmdSetPatchControlPointsEXT'
-- before any drawing commands.
pattern DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT = DynamicState 1000377000
-- | 'DYNAMIC_STATE_VERTEX_INPUT_EXT' specifies that the @pVertexInputState@
-- state will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_EXT_vertex_input_dynamic_state.cmdSetVertexInputEXT'
-- before any drawing commands
pattern DYNAMIC_STATE_VERTEX_INPUT_EXT = DynamicState 1000352000
-- | 'DYNAMIC_STATE_LINE_STIPPLE_EXT' specifies that the @lineStippleFactor@
-- and @lineStipplePattern@ state in
-- 'Vulkan.Extensions.VK_EXT_line_rasterization.PipelineRasterizationLineStateCreateInfoEXT'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_EXT_line_rasterization.cmdSetLineStippleEXT'
-- before any draws are performed with a pipeline state with
-- 'Vulkan.Extensions.VK_EXT_line_rasterization.PipelineRasterizationLineStateCreateInfoEXT'
-- member @stippledLineEnable@ set to
-- 'Vulkan.Core10.FundamentalTypes.TRUE'.
pattern DYNAMIC_STATE_LINE_STIPPLE_EXT = DynamicState 1000259000
-- | 'DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR' specifies that state in
-- 'Vulkan.Extensions.VK_KHR_fragment_shading_rate.PipelineFragmentShadingRateStateCreateInfoKHR'
-- and
-- 'Vulkan.Extensions.VK_NV_fragment_shading_rate_enums.PipelineFragmentShadingRateEnumStateCreateInfoNV'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_KHR_fragment_shading_rate.cmdSetFragmentShadingRateKHR'
-- or
-- 'Vulkan.Extensions.VK_NV_fragment_shading_rate_enums.cmdSetFragmentShadingRateEnumNV'
-- before any drawing commands.
pattern DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR = DynamicState 1000226000
-- | 'DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV' specifies that the
-- @pExclusiveScissors@ state in
-- 'Vulkan.Extensions.VK_NV_scissor_exclusive.PipelineViewportExclusiveScissorStateCreateInfoNV'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_NV_scissor_exclusive.cmdSetExclusiveScissorNV'
-- before any drawing commands. The number of exclusive scissor rectangles
-- used by a pipeline is still specified by the @exclusiveScissorCount@
-- member of
-- 'Vulkan.Extensions.VK_NV_scissor_exclusive.PipelineViewportExclusiveScissorStateCreateInfoNV'.
pattern DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV = DynamicState 1000205001
-- | 'DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV' specifies that the
-- coarse sample order state in
-- 'Vulkan.Extensions.VK_NV_shading_rate_image.PipelineViewportCoarseSampleOrderStateCreateInfoNV'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_NV_shading_rate_image.cmdSetCoarseSampleOrderNV'
-- before any drawing commands.
pattern DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV = DynamicState 1000164006
-- | 'DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV' specifies that the
-- @pShadingRatePalettes@ state in
-- 'Vulkan.Extensions.VK_NV_shading_rate_image.PipelineViewportShadingRateImageStateCreateInfoNV'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_NV_shading_rate_image.cmdSetViewportShadingRatePaletteNV'
-- before any drawing commands.
pattern DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV = DynamicState 1000164004
-- | 'DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR' specifies that the
-- default stack size computation for the pipeline will be ignored and
-- /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_KHR_ray_tracing_pipeline.cmdSetRayTracingPipelineStackSizeKHR'
-- before any ray tracing calls are performed.
pattern DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR = DynamicState 1000347000
-- | 'DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT' specifies that the
-- @sampleLocationsInfo@ state in
-- 'Vulkan.Extensions.VK_EXT_sample_locations.PipelineSampleLocationsStateCreateInfoEXT'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_EXT_sample_locations.cmdSetSampleLocationsEXT'
-- before any draw or clear commands. Enabling custom sample locations is
-- still indicated by the @sampleLocationsEnable@ member of
-- 'Vulkan.Extensions.VK_EXT_sample_locations.PipelineSampleLocationsStateCreateInfoEXT'.
pattern DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT = DynamicState 1000143000
-- | 'DYNAMIC_STATE_DISCARD_RECTANGLE_EXT' specifies that the
-- @pDiscardRectangles@ state in
-- 'Vulkan.Extensions.VK_EXT_discard_rectangles.PipelineDiscardRectangleStateCreateInfoEXT'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_EXT_discard_rectangles.cmdSetDiscardRectangleEXT'
-- before any draw or clear commands. The
-- 'Vulkan.Extensions.VK_EXT_discard_rectangles.DiscardRectangleModeEXT'
-- and the number of active discard rectangles is still specified by the
-- @discardRectangleMode@ and @discardRectangleCount@ members of
-- 'Vulkan.Extensions.VK_EXT_discard_rectangles.PipelineDiscardRectangleStateCreateInfoEXT'.
pattern DYNAMIC_STATE_DISCARD_RECTANGLE_EXT = DynamicState 1000099000
-- | 'DYNAMIC_STATE_VIEWPORT_W_SCALING_NV' specifies that the
-- @pViewportScalings@ state in
-- 'Vulkan.Extensions.VK_NV_clip_space_w_scaling.PipelineViewportWScalingStateCreateInfoNV'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Extensions.VK_NV_clip_space_w_scaling.cmdSetViewportWScalingNV'
-- before any draws are performed with a pipeline state with
-- 'Vulkan.Extensions.VK_NV_clip_space_w_scaling.PipelineViewportWScalingStateCreateInfoNV'
-- member @viewportScalingEnable@ set to
-- 'Vulkan.Core10.FundamentalTypes.TRUE'
pattern DYNAMIC_STATE_VIEWPORT_W_SCALING_NV = DynamicState 1000087000
-- | 'DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE' specifies that the
-- @primitiveRestartEnable@ state in
-- 'Vulkan.Core10.Pipeline.PipelineInputAssemblyStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state2.cmdSetPrimitiveRestartEnable'
-- before any drawing commands.
pattern DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE = DynamicState 1000377004
-- | 'DYNAMIC_STATE_DEPTH_BIAS_ENABLE' specifies that the @depthBiasEnable@
-- state in 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state2.cmdSetDepthBiasEnable'
-- before any drawing commands.
pattern DYNAMIC_STATE_DEPTH_BIAS_ENABLE = DynamicState 1000377002
-- | 'DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE' specifies that the
-- @rasterizerDiscardEnable@ state in
-- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state2.cmdSetRasterizerDiscardEnable'
-- before any drawing commands.
pattern DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE = DynamicState 1000377001
-- | 'DYNAMIC_STATE_STENCIL_OP' specifies that the @failOp@, @passOp@,
-- @depthFailOp@, and @compareOp@ states in
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' for both
-- @front@ and @back@ will be ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetStencilOp'
-- before any draws are performed with a pipeline state with
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' member
-- @stencilTestEnable@ set to 'Vulkan.Core10.FundamentalTypes.TRUE'
pattern DYNAMIC_STATE_STENCIL_OP = DynamicState 1000267011
-- | 'DYNAMIC_STATE_STENCIL_TEST_ENABLE' specifies that the
-- @stencilTestEnable@ state in
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetStencilTestEnable'
-- before any draw call.
pattern DYNAMIC_STATE_STENCIL_TEST_ENABLE = DynamicState 1000267010
-- | 'DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE' specifies that the
-- @depthBoundsTestEnable@ state in
-- 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetDepthBoundsTestEnable'
-- before any draw call.
pattern DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE = DynamicState 1000267009
-- | 'DYNAMIC_STATE_DEPTH_COMPARE_OP' specifies that the @depthCompareOp@
-- state in 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetDepthCompareOp'
-- before any draw call.
pattern DYNAMIC_STATE_DEPTH_COMPARE_OP = DynamicState 1000267008
-- | 'DYNAMIC_STATE_DEPTH_WRITE_ENABLE' specifies that the @depthWriteEnable@
-- state in 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetDepthWriteEnable'
-- before any draw call.
pattern DYNAMIC_STATE_DEPTH_WRITE_ENABLE = DynamicState 1000267007
-- | 'DYNAMIC_STATE_DEPTH_TEST_ENABLE' specifies that the @depthTestEnable@
-- state in 'Vulkan.Core10.Pipeline.PipelineDepthStencilStateCreateInfo'
-- will be ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetDepthTestEnable'
-- before any draw call.
pattern DYNAMIC_STATE_DEPTH_TEST_ENABLE = DynamicState 1000267006
-- | 'DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE' specifies that the @stride@
-- state in 'Vulkan.Core10.Pipeline.VertexInputBindingDescription' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdBindVertexBuffers2'
-- before any draw call.
pattern DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE = DynamicState 1000267005
-- | 'DYNAMIC_STATE_SCISSOR_WITH_COUNT' specifies that the @scissorCount@ and
-- @pScissors@ state in
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo' will be ignored
-- and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetScissorWithCount'
-- before any draw call.
pattern DYNAMIC_STATE_SCISSOR_WITH_COUNT = DynamicState 1000267004
-- | 'DYNAMIC_STATE_VIEWPORT_WITH_COUNT' specifies that the @viewportCount@
-- and @pViewports@ state in
-- 'Vulkan.Core10.Pipeline.PipelineViewportStateCreateInfo' will be ignored
-- and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetViewportWithCount'
-- before any draw call.
pattern DYNAMIC_STATE_VIEWPORT_WITH_COUNT = DynamicState 1000267003
-- | 'DYNAMIC_STATE_PRIMITIVE_TOPOLOGY' specifies that the @topology@ state
-- in 'Vulkan.Core10.Pipeline.PipelineInputAssemblyStateCreateInfo' only
-- specifies the
-- <https://www.khronos.org/registry/vulkan/specs/1.3-extensions/html/vkspec.html#drawing-primitive-topology-class topology class>,
-- and the specific topology order and adjacency /must/ be set dynamically
-- with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetPrimitiveTopology'
-- before any drawing commands.
pattern DYNAMIC_STATE_PRIMITIVE_TOPOLOGY = DynamicState 1000267002
-- | 'DYNAMIC_STATE_FRONT_FACE' specifies that the @frontFace@ state in
-- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetFrontFace'
-- before any drawing commands.
pattern DYNAMIC_STATE_FRONT_FACE = DynamicState 1000267001
-- | 'DYNAMIC_STATE_CULL_MODE' specifies that the @cullMode@ state in
-- 'Vulkan.Core10.Pipeline.PipelineRasterizationStateCreateInfo' will be
-- ignored and /must/ be set dynamically with
-- 'Vulkan.Core13.Promoted_From_VK_EXT_extended_dynamic_state.cmdSetCullMode'
-- before any drawing commands.
pattern DYNAMIC_STATE_CULL_MODE = DynamicState 1000267000
{-# complete DYNAMIC_STATE_VIEWPORT,
DYNAMIC_STATE_SCISSOR,
DYNAMIC_STATE_LINE_WIDTH,
DYNAMIC_STATE_DEPTH_BIAS,
DYNAMIC_STATE_BLEND_CONSTANTS,
DYNAMIC_STATE_DEPTH_BOUNDS,
DYNAMIC_STATE_STENCIL_COMPARE_MASK,
DYNAMIC_STATE_STENCIL_WRITE_MASK,
DYNAMIC_STATE_STENCIL_REFERENCE,
DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT,
DYNAMIC_STATE_LOGIC_OP_EXT,
DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT,
DYNAMIC_STATE_VERTEX_INPUT_EXT,
DYNAMIC_STATE_LINE_STIPPLE_EXT,
DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR,
DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV,
DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV,
DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV,
DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR,
DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT,
DYNAMIC_STATE_DISCARD_RECTANGLE_EXT,
DYNAMIC_STATE_VIEWPORT_W_SCALING_NV,
DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE,
DYNAMIC_STATE_DEPTH_BIAS_ENABLE,
DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE,
DYNAMIC_STATE_STENCIL_OP,
DYNAMIC_STATE_STENCIL_TEST_ENABLE,
DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE,
DYNAMIC_STATE_DEPTH_COMPARE_OP,
DYNAMIC_STATE_DEPTH_WRITE_ENABLE,
DYNAMIC_STATE_DEPTH_TEST_ENABLE,
DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE,
DYNAMIC_STATE_SCISSOR_WITH_COUNT,
DYNAMIC_STATE_VIEWPORT_WITH_COUNT,
DYNAMIC_STATE_PRIMITIVE_TOPOLOGY,
DYNAMIC_STATE_FRONT_FACE,
DYNAMIC_STATE_CULL_MODE :: DynamicState #-}
conNameDynamicState :: String
conNameDynamicState = "DynamicState"
enumPrefixDynamicState :: String
enumPrefixDynamicState = "DYNAMIC_STATE_"
showTableDynamicState :: [(DynamicState, String)]
showTableDynamicState =
[ (DYNAMIC_STATE_VIEWPORT , "VIEWPORT")
, (DYNAMIC_STATE_SCISSOR , "SCISSOR")
, (DYNAMIC_STATE_LINE_WIDTH , "LINE_WIDTH")
, (DYNAMIC_STATE_DEPTH_BIAS , "DEPTH_BIAS")
, (DYNAMIC_STATE_BLEND_CONSTANTS , "BLEND_CONSTANTS")
, (DYNAMIC_STATE_DEPTH_BOUNDS , "DEPTH_BOUNDS")
, (DYNAMIC_STATE_STENCIL_COMPARE_MASK , "STENCIL_COMPARE_MASK")
, (DYNAMIC_STATE_STENCIL_WRITE_MASK , "STENCIL_WRITE_MASK")
, (DYNAMIC_STATE_STENCIL_REFERENCE , "STENCIL_REFERENCE")
, (DYNAMIC_STATE_COLOR_WRITE_ENABLE_EXT , "COLOR_WRITE_ENABLE_EXT")
, (DYNAMIC_STATE_LOGIC_OP_EXT , "LOGIC_OP_EXT")
, (DYNAMIC_STATE_PATCH_CONTROL_POINTS_EXT , "PATCH_CONTROL_POINTS_EXT")
, (DYNAMIC_STATE_VERTEX_INPUT_EXT , "VERTEX_INPUT_EXT")
, (DYNAMIC_STATE_LINE_STIPPLE_EXT , "LINE_STIPPLE_EXT")
, (DYNAMIC_STATE_FRAGMENT_SHADING_RATE_KHR , "FRAGMENT_SHADING_RATE_KHR")
, (DYNAMIC_STATE_EXCLUSIVE_SCISSOR_NV , "EXCLUSIVE_SCISSOR_NV")
, (DYNAMIC_STATE_VIEWPORT_COARSE_SAMPLE_ORDER_NV , "VIEWPORT_COARSE_SAMPLE_ORDER_NV")
, (DYNAMIC_STATE_VIEWPORT_SHADING_RATE_PALETTE_NV , "VIEWPORT_SHADING_RATE_PALETTE_NV")
, (DYNAMIC_STATE_RAY_TRACING_PIPELINE_STACK_SIZE_KHR, "RAY_TRACING_PIPELINE_STACK_SIZE_KHR")
, (DYNAMIC_STATE_SAMPLE_LOCATIONS_EXT , "SAMPLE_LOCATIONS_EXT")
, (DYNAMIC_STATE_DISCARD_RECTANGLE_EXT , "DISCARD_RECTANGLE_EXT")
, (DYNAMIC_STATE_VIEWPORT_W_SCALING_NV , "VIEWPORT_W_SCALING_NV")
, (DYNAMIC_STATE_PRIMITIVE_RESTART_ENABLE , "PRIMITIVE_RESTART_ENABLE")
, (DYNAMIC_STATE_DEPTH_BIAS_ENABLE , "DEPTH_BIAS_ENABLE")
, (DYNAMIC_STATE_RASTERIZER_DISCARD_ENABLE , "RASTERIZER_DISCARD_ENABLE")
, (DYNAMIC_STATE_STENCIL_OP , "STENCIL_OP")
, (DYNAMIC_STATE_STENCIL_TEST_ENABLE , "STENCIL_TEST_ENABLE")
, (DYNAMIC_STATE_DEPTH_BOUNDS_TEST_ENABLE , "DEPTH_BOUNDS_TEST_ENABLE")
, (DYNAMIC_STATE_DEPTH_COMPARE_OP , "DEPTH_COMPARE_OP")
, (DYNAMIC_STATE_DEPTH_WRITE_ENABLE , "DEPTH_WRITE_ENABLE")
, (DYNAMIC_STATE_DEPTH_TEST_ENABLE , "DEPTH_TEST_ENABLE")
, (DYNAMIC_STATE_VERTEX_INPUT_BINDING_STRIDE , "VERTEX_INPUT_BINDING_STRIDE")
, (DYNAMIC_STATE_SCISSOR_WITH_COUNT , "SCISSOR_WITH_COUNT")
, (DYNAMIC_STATE_VIEWPORT_WITH_COUNT , "VIEWPORT_WITH_COUNT")
, (DYNAMIC_STATE_PRIMITIVE_TOPOLOGY , "PRIMITIVE_TOPOLOGY")
, (DYNAMIC_STATE_FRONT_FACE , "FRONT_FACE")
, (DYNAMIC_STATE_CULL_MODE , "CULL_MODE")
]
instance Show DynamicState where
showsPrec = enumShowsPrec enumPrefixDynamicState
showTableDynamicState
conNameDynamicState
(\(DynamicState x) -> x)
(showsPrec 11)
instance Read DynamicState where
readPrec = enumReadPrec enumPrefixDynamicState showTableDynamicState conNameDynamicState DynamicState
| expipiplus1/vulkan | src/Vulkan/Core10/Enums/DynamicState.hs | bsd-3-clause | 27,560 | 1 | 10 | 5,844 | 1,310 | 877 | 433 | -1 | -1 |
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Control.Lens
import Control.Monad.State
import Data.Map.Strict (Map)
import qualified Data.Map.Strict as M
import FreeGame
-- import Linear
{-
Window size: 480 x 360
Game size: 50 x 50
Cell size: 6 x 6
-}
type Coord = V2 Int
data StaticEntity =
Wall
data Position = Transit {_start :: Coord, _dest :: Coord}
deriving (Eq, Ord)
makeLenses ''Position
data Zombie = Zombie {
_position :: Position
} deriving (Eq, Ord)
type GameMap = Map Coord (Either StaticEntity Zombie)
-- invariant that the coord of a zombie in the gamemap is equal to the
-- dest of the zombie's position
data GameState = GameState {
_gameMap :: GameMap,
_target :: Coord,
_ticker :: Int -- ticker `elem` [0,16)
}
makeLenses ''GameState
drawStaticEntity :: Picture2D p => Coord -> StaticEntity -> p ()
drawStaticEntity coord Wall =
color blue $ polygon $ map ((*) 12 . fmap fromIntegral)
[coord, coord & _x +~ 1, coord & traverse +~ 1, coord & _y +~ 1]
drawZombie :: Picture2D p => Bitmap -> Int -> Zombie -> p ()
drawZombie zombieSprite t Zombie {_position = p} =
let dvec = fmap fromIntegral $ p ^. dest - p ^. start
angle = view _y dvec `atan2` view _x dvec
pos = p ^.(start.to (fmap fromIntegral)) + (fromIntegral t / 16) *^ dvec
in rotateR angle $ translate (12*(pos+0.5)) $ bitmap zombieSprite
drawTarget :: Picture2D p => Coord -> p ()
drawTarget c = color green $ translate (12 * (fmap fromIntegral c + 0.5)) $
circleOutline 6
drawGame :: (Monad p, Picture2D p) => Bitmap -> GameState -> p ()
drawGame zombieSprite gameState = do
imapMOf_ (gameMap . ifolded <. _Left) drawStaticEntity gameState
let drawZombie1 = drawZombie zombieSprite $ gameState ^. ticker
mapMOf_ (gameMap . folded . _Right) drawZombie1 gameState
drawTarget $ gameState ^. target
loadMap :: FilePath -> IO GameMap
loadMap path = do
things <- path ^@!! act readFile . to lines . ifolded <.> ifolded
return $ M.fromList $ do
(c,t) <- things
let v = uncurry (flip V2) c
Just e <- [convert v t]
return (v, e)
where
convert _ '#' = Just $ Left Wall
convert c 'Z' =
Just $ Right Zombie {_position = Transit {_start = c, _dest = c}}
convert _ _ = Nothing
targetPos :: (Applicative f, Mouse f, Local f) => f Coord
targetPos = fmap floor . flip (/) 12 <$> mousePosition
gameFrame ::
(MonadState GameState f, Applicative f, Mouse f, Local f, Picture2D f) =>
Bitmap -> f ()
gameFrame zombieSprite = do
target <~ targetPos
s <- get
drawGame zombieSprite s
return ()
main :: IO ()
main = do
m <- loadMap "data/map1.map"
z <- readBitmap "data/zombie.png"
let initState = GameState {_gameMap = m, _target = V2 0 0, _ticker = 0}
gameFrame1 = execStateT (gameFrame z) initState
_ <- runGame Windowed (BoundingBox 0 0 600 600) $ foreverFrame gameFrame1
return () | Taneb/zombie-game | src/Main.hs | bsd-3-clause | 2,937 | 0 | 15 | 648 | 1,093 | 557 | 536 | -1 | -1 |
module Sharc.Instruments.ViolinsEnsemble (violinsEnsemble) where
import Sharc.Types
violinsEnsemble :: Instr
violinsEnsemble = Instr
"violinensemb"
"Violins (ensemble)"
(Legend "McGill" "1" "21")
(Range
(InstrRange
(HarmonicFreq 1 (Pitch 146.83 38 "d3"))
(Pitch 195.99 43 "g3")
(Amplitude 8592.67 (HarmonicFreq 31 (Pitch 277.183 49 "c#4")) 1.19))
(InstrRange
(HarmonicFreq 45 (Pitch 10488.69 46 "a#3"))
(Pitch 2349.32 86 "d7")
(Amplitude 2217.46 (HarmonicFreq 4 (Pitch 554.365 61 "c#5")) 30250.0)))
[note0
,note1
,note2
,note3
,note4
,note5
,note6
,note7
,note8
,note9
,note10
,note11
,note12
,note13
,note14
,note15
,note16
,note17
,note18
,note19
,note20
,note21
,note22
,note23
,note24
,note25
,note26
,note27
,note28
,note29
,note30
,note31
,note32
,note33
,note34
,note35
,note36
,note37
,note38
,note39
,note40
,note41
,note42
,note43]
note0 :: Note
note0 = Note
(Pitch 195.998 43 "g3")
1
(Range
(NoteRange
(NoteRangeAmplitude 9995.89 51 4.32)
(NoteRangeHarmonicFreq 1 195.99))
(NoteRange
(NoteRangeAmplitude 391.99 2 15043.0)
(NoteRangeHarmonicFreq 51 9995.89)))
[Harmonic 1 (-0.385) 1053.41
,Harmonic 2 (-1.663) 15043.0
,Harmonic 3 2.53 4708.62
,Harmonic 4 (-3.078) 4600.28
,Harmonic 5 2.867 2549.29
,Harmonic 6 1.182 612.21
,Harmonic 7 (-1.823) 2488.85
,Harmonic 8 0.746 4539.98
,Harmonic 9 (-0.915) 1994.89
,Harmonic 10 (-0.49) 9008.15
,Harmonic 11 (-2.913) 6054.15
,Harmonic 12 (-1.734) 1333.56
,Harmonic 13 0.842 733.47
,Harmonic 14 (-2.938) 789.17
,Harmonic 15 (-2.777) 404.53
,Harmonic 16 1.166 626.22
,Harmonic 17 (-1.014) 1089.54
,Harmonic 18 1.369 550.58
,Harmonic 19 1.489 686.78
,Harmonic 20 (-0.645) 667.55
,Harmonic 21 (-0.13) 116.79
,Harmonic 22 (-0.704) 1023.07
,Harmonic 23 (-0.311) 165.84
,Harmonic 24 0.711 284.08
,Harmonic 25 (-1.529) 413.28
,Harmonic 26 (-1.757) 112.44
,Harmonic 27 2.245 139.21
,Harmonic 28 1.658 144.19
,Harmonic 29 (-2.505) 141.83
,Harmonic 30 (-2.256) 177.0
,Harmonic 31 2.068 23.4
,Harmonic 32 0.391 203.0
,Harmonic 33 (-1.416) 57.3
,Harmonic 34 1.529 25.08
,Harmonic 35 1.473 34.31
,Harmonic 36 0.241 40.58
,Harmonic 37 (-1.857) 26.76
,Harmonic 38 (-2.682) 27.05
,Harmonic 39 (-1.493) 14.53
,Harmonic 40 (-0.548) 44.07
,Harmonic 41 1.297 7.41
,Harmonic 42 0.5 33.6
,Harmonic 43 (-0.968) 13.92
,Harmonic 44 (-1.009) 23.66
,Harmonic 45 1.249 20.72
,Harmonic 46 0.792 10.25
,Harmonic 47 (-2.204) 23.23
,Harmonic 48 (-0.617) 17.77
,Harmonic 49 (-2.043) 27.65
,Harmonic 50 (-1.93) 8.41
,Harmonic 51 (-2.597) 4.32]
note1 :: Note
note1 = Note
(Pitch 207.652 44 "g#3")
2
(Range
(NoteRange
(NoteRangeAmplitude 9344.34 45 3.23)
(NoteRangeHarmonicFreq 1 207.65))
(NoteRange
(NoteRangeAmplitude 415.3 2 14824.0)
(NoteRangeHarmonicFreq 48 9967.29)))
[Harmonic 1 (-3.115) 512.53
,Harmonic 2 (-1.569) 14824.0
,Harmonic 3 2.264 4317.48
,Harmonic 4 (-1.346) 1556.86
,Harmonic 5 0.19 961.61
,Harmonic 6 (-1.353) 774.04
,Harmonic 7 (-1.225) 1148.32
,Harmonic 8 1.52 583.72
,Harmonic 9 (-0.79) 1275.54
,Harmonic 10 1.514 894.23
,Harmonic 11 3.085 202.05
,Harmonic 12 0.142 292.6
,Harmonic 13 (-1.115) 294.48
,Harmonic 14 (-0.982) 211.9
,Harmonic 15 1.428 212.15
,Harmonic 16 2.818 637.66
,Harmonic 17 2.665 207.68
,Harmonic 18 (-2.233) 211.47
,Harmonic 19 (-1.152) 348.04
,Harmonic 20 2.842 126.9
,Harmonic 21 0.925 317.67
,Harmonic 22 (-2.249) 83.25
,Harmonic 23 (-7.7e-2) 130.6
,Harmonic 24 (-1.175) 198.02
,Harmonic 25 2.422 128.12
,Harmonic 26 2.186 86.87
,Harmonic 27 1.672 80.29
,Harmonic 28 (-1.749) 74.26
,Harmonic 29 2.415 53.79
,Harmonic 30 (-0.129) 80.31
,Harmonic 31 (-1.753) 16.43
,Harmonic 32 2.49 16.89
,Harmonic 33 (-9.0e-3) 15.98
,Harmonic 34 2.467 4.56
,Harmonic 35 1.893 14.43
,Harmonic 36 (-1.975) 16.86
,Harmonic 37 2.946 12.29
,Harmonic 38 2.902 15.27
,Harmonic 39 5.0e-3 13.62
,Harmonic 40 (-1.472) 18.53
,Harmonic 41 1.205 13.69
,Harmonic 42 1.333 9.56
,Harmonic 43 (-3.086) 6.4
,Harmonic 44 2.931 12.01
,Harmonic 45 0.362 3.23
,Harmonic 46 (-0.679) 8.75
,Harmonic 47 (-0.948) 9.11
,Harmonic 48 (-3.113) 4.56]
note2 :: Note
note2 = Note
(Pitch 220.0 45 "a3")
3
(Range
(NoteRange
(NoteRangeAmplitude 9460.0 43 1.4)
(NoteRangeHarmonicFreq 1 220.0))
(NoteRange
(NoteRangeAmplitude 660.0 3 12024.0)
(NoteRangeHarmonicFreq 45 9900.0)))
[Harmonic 1 1.401 3811.35
,Harmonic 2 0.953 6068.08
,Harmonic 3 1.72 12024.0
,Harmonic 4 1.684 1192.77
,Harmonic 5 (-2.146) 827.85
,Harmonic 6 (-3.005) 2074.12
,Harmonic 7 1.595 2428.64
,Harmonic 8 (-0.639) 611.5
,Harmonic 9 (-1.003) 1798.63
,Harmonic 10 (-1.09) 823.84
,Harmonic 11 (-2.256) 413.61
,Harmonic 12 (-1.098) 257.66
,Harmonic 13 2.519 92.14
,Harmonic 14 0.792 163.94
,Harmonic 15 (-1.223) 463.88
,Harmonic 16 0.296 392.38
,Harmonic 17 2.384 550.41
,Harmonic 18 1.255 583.65
,Harmonic 19 (-2.895) 1131.42
,Harmonic 20 (-0.738) 126.55
,Harmonic 21 2.9 87.06
,Harmonic 22 0.667 150.17
,Harmonic 23 3.053 76.15
,Harmonic 24 (-1.096) 126.13
,Harmonic 25 (-2.5) 42.15
,Harmonic 26 8.8e-2 211.29
,Harmonic 27 (-2.0e-3) 110.73
,Harmonic 28 (-5.8e-2) 21.91
,Harmonic 29 1.385 4.29
,Harmonic 30 3.12 11.28
,Harmonic 31 0.886 38.59
,Harmonic 32 1.215 21.18
,Harmonic 33 (-3.086) 28.64
,Harmonic 34 2.339 20.41
,Harmonic 35 2.419 10.22
,Harmonic 36 (-2.799) 48.15
,Harmonic 37 (-1.687) 27.91
,Harmonic 38 0.825 6.86
,Harmonic 39 (-2.033) 7.61
,Harmonic 40 (-1.638) 15.82
,Harmonic 41 (-0.979) 13.41
,Harmonic 42 1.741 14.95
,Harmonic 43 2.943 1.4
,Harmonic 44 1.046 11.23
,Harmonic 45 3.097 5.58]
note3 :: Note
note3 = Note
(Pitch 233.082 46 "a#3")
4
(Range
(NoteRange
(NoteRangeAmplitude 8857.11 38 2.5)
(NoteRangeHarmonicFreq 1 233.08))
(NoteRange
(NoteRangeAmplitude 466.16 2 11676.0)
(NoteRangeHarmonicFreq 45 10488.69)))
[Harmonic 1 1.547 4965.92
,Harmonic 2 (-0.731) 11676.0
,Harmonic 3 0.569 3310.08
,Harmonic 4 (-1.949) 998.55
,Harmonic 5 (-0.801) 506.99
,Harmonic 6 2.152 311.9
,Harmonic 7 (-2.057) 479.64
,Harmonic 8 (-2.686) 167.49
,Harmonic 9 (-0.807) 62.04
,Harmonic 10 (-2.963) 205.31
,Harmonic 11 (-2.108) 119.18
,Harmonic 12 (-0.81) 146.73
,Harmonic 13 (-1.91) 98.4
,Harmonic 14 1.254 134.14
,Harmonic 15 (-1.219) 63.28
,Harmonic 16 1.49 613.73
,Harmonic 17 (-1.006) 62.32
,Harmonic 18 (-0.467) 441.93
,Harmonic 19 (-3.126) 932.65
,Harmonic 20 1.24 71.86
,Harmonic 21 (-0.847) 374.36
,Harmonic 22 (-0.902) 115.68
,Harmonic 23 0.822 35.8
,Harmonic 24 1.8 65.81
,Harmonic 25 2.647 92.72
,Harmonic 26 (-1.757) 135.5
,Harmonic 27 2.896 85.03
,Harmonic 28 0.278 26.72
,Harmonic 29 (-1.824) 16.5
,Harmonic 30 1.983 9.42
,Harmonic 31 3.2e-2 23.79
,Harmonic 32 (-3.123) 13.27
,Harmonic 33 (-2.692) 12.43
,Harmonic 34 (-1.117) 25.96
,Harmonic 35 0.474 19.02
,Harmonic 36 1.45 8.48
,Harmonic 37 2.192 12.98
,Harmonic 38 1.842 2.5
,Harmonic 39 (-1.711) 8.65
,Harmonic 40 2.918 3.66
,Harmonic 41 2.998 9.24
,Harmonic 42 (-2.597) 12.54
,Harmonic 43 0.297 12.48
,Harmonic 44 0.105 7.1
,Harmonic 45 2.472 13.46]
note4 :: Note
note4 = Note
(Pitch 246.942 47 "b3")
5
(Range
(NoteRange
(NoteRangeAmplitude 9383.79 38 1.88)
(NoteRangeHarmonicFreq 1 246.94))
(NoteRange
(NoteRangeAmplitude 493.88 2 11805.0)
(NoteRangeHarmonicFreq 41 10124.62)))
[Harmonic 1 0.104 9718.0
,Harmonic 2 2.087 11805.0
,Harmonic 3 2.059 3568.54
,Harmonic 4 2.016 1030.16
,Harmonic 5 2.275 1343.64
,Harmonic 6 1.203 2083.79
,Harmonic 7 0.978 1380.11
,Harmonic 8 (-1.019) 2645.7
,Harmonic 9 1.295 1676.89
,Harmonic 10 1.603 145.3
,Harmonic 11 3.135 799.29
,Harmonic 12 (-2.168) 731.05
,Harmonic 13 1.822 813.39
,Harmonic 14 1.739 256.42
,Harmonic 15 (-2.535) 502.45
,Harmonic 16 (-2.699) 992.19
,Harmonic 17 0.478 678.25
,Harmonic 18 (-1.852) 94.17
,Harmonic 19 (-2.427) 194.63
,Harmonic 20 2.203 372.23
,Harmonic 21 2.226 127.5
,Harmonic 22 (-2.746) 147.86
,Harmonic 23 (-2.178) 106.08
,Harmonic 24 (-2.122) 55.32
,Harmonic 25 1.691 41.82
,Harmonic 26 (-2.488) 69.98
,Harmonic 27 0.346 27.48
,Harmonic 28 2.515 3.97
,Harmonic 29 (-2.616) 8.32
,Harmonic 30 1.677 28.24
,Harmonic 31 0.801 32.89
,Harmonic 32 0.153 69.11
,Harmonic 33 1.452 24.31
,Harmonic 34 1.2e-2 13.18
,Harmonic 35 1.672 22.51
,Harmonic 36 1.674 7.78
,Harmonic 37 (-2.713) 7.9
,Harmonic 38 2.59 1.88
,Harmonic 39 2.217 16.89
,Harmonic 40 (-1.356) 9.42
,Harmonic 41 2.69 4.47]
note5 :: Note
note5 = Note
(Pitch 261.626 48 "c4")
6
(Range
(NoteRange
(NoteRangeAmplitude 10203.41 39 2.42)
(NoteRangeHarmonicFreq 1 261.62))
(NoteRange
(NoteRangeAmplitude 261.62 1 27620.0)
(NoteRangeHarmonicFreq 39 10203.41)))
[Harmonic 1 (-0.81) 27620.0
,Harmonic 2 (-2.337) 25402.92
,Harmonic 3 (-3.038) 3472.67
,Harmonic 4 (-0.557) 1613.85
,Harmonic 5 (-2.127) 1506.6
,Harmonic 6 (-1.409) 1012.98
,Harmonic 7 (-2.636) 824.67
,Harmonic 8 0.635 847.85
,Harmonic 9 0.599 480.94
,Harmonic 10 2.645 248.75
,Harmonic 11 (-0.451) 391.77
,Harmonic 12 0.924 132.02
,Harmonic 13 (-0.649) 102.25
,Harmonic 14 (-0.834) 137.74
,Harmonic 15 (-0.373) 941.86
,Harmonic 16 (-1.7e-2) 118.58
,Harmonic 17 0.312 235.13
,Harmonic 18 (-1.125) 219.67
,Harmonic 19 (-2.338) 128.08
,Harmonic 20 (-0.884) 79.21
,Harmonic 21 (-2.32) 48.65
,Harmonic 22 1.507 76.41
,Harmonic 23 0.132 78.94
,Harmonic 24 1.311 29.09
,Harmonic 25 (-0.768) 26.12
,Harmonic 26 1.008 8.26
,Harmonic 27 (-2.707) 13.0
,Harmonic 28 (-1.223) 7.31
,Harmonic 29 (-1.215) 8.37
,Harmonic 30 (-2.907) 16.89
,Harmonic 31 (-2.539) 7.57
,Harmonic 32 (-2.421) 19.13
,Harmonic 33 (-1.776) 17.14
,Harmonic 34 (-2.63) 5.28
,Harmonic 35 (-2.294) 11.03
,Harmonic 36 (-1.981) 8.08
,Harmonic 37 (-2.786) 11.49
,Harmonic 38 (-3.053) 8.32
,Harmonic 39 2.678 2.42]
note6 :: Note
note6 = Note
(Pitch 277.183 49 "c#4")
7
(Range
(NoteRange
(NoteRangeAmplitude 8592.67 31 1.19)
(NoteRangeHarmonicFreq 1 277.18))
(NoteRange
(NoteRangeAmplitude 277.18 1 21312.0)
(NoteRangeHarmonicFreq 36 9978.58)))
[Harmonic 1 (-1.351) 21312.0
,Harmonic 2 (-2.537) 7387.07
,Harmonic 3 (-2.874) 1375.66
,Harmonic 4 0.684 671.59
,Harmonic 5 (-1.18) 1886.33
,Harmonic 6 (-8.1e-2) 1075.18
,Harmonic 7 (-1.55) 771.91
,Harmonic 8 2.406 947.31
,Harmonic 9 2.677 982.51
,Harmonic 10 (-2.577) 166.03
,Harmonic 11 6.9e-2 182.37
,Harmonic 12 (-2.63) 424.94
,Harmonic 13 (-2.496) 337.08
,Harmonic 14 (-2.318) 678.7
,Harmonic 15 (-1.984) 698.02
,Harmonic 16 (-1.265) 127.09
,Harmonic 17 (-1.289) 14.87
,Harmonic 18 0.345 36.39
,Harmonic 19 (-1.271) 53.43
,Harmonic 20 (-0.424) 81.11
,Harmonic 21 1.416 51.67
,Harmonic 22 2.121 24.92
,Harmonic 23 (-2.271) 9.24
,Harmonic 24 1.047 8.51
,Harmonic 25 (-1.541) 20.53
,Harmonic 26 (-2.769) 11.57
,Harmonic 27 1.773 15.63
,Harmonic 28 (-0.62) 2.48
,Harmonic 29 (-2.312) 5.59
,Harmonic 30 (-1.311) 9.78
,Harmonic 31 0.608 1.19
,Harmonic 32 1.758 8.35
,Harmonic 33 2.539 1.29
,Harmonic 34 0.389 3.91
,Harmonic 35 (-1.575) 6.77
,Harmonic 36 (-0.702) 3.21]
note7 :: Note
note7 = Note
(Pitch 146.832 38 "d3")
8
(Range
(NoteRange
(NoteRangeAmplitude 10131.4 69 2.43)
(NoteRangeHarmonicFreq 1 146.83))
(NoteRange
(NoteRangeAmplitude 293.66 2 13805.0)
(NoteRangeHarmonicFreq 69 10131.4)))
[Harmonic 1 0.397 28.03
,Harmonic 2 2.247 13805.0
,Harmonic 3 (-1.9) 64.46
,Harmonic 4 (-0.668) 9102.5
,Harmonic 5 1.916 36.81
,Harmonic 6 (-0.798) 2272.87
,Harmonic 7 2.638 9.46
,Harmonic 8 0.792 2131.23
,Harmonic 9 (-3.08) 54.51
,Harmonic 10 (-1.934) 5548.5
,Harmonic 11 1.48 35.34
,Harmonic 12 (-3.112) 2501.44
,Harmonic 13 0.544 36.65
,Harmonic 14 (-0.974) 1276.92
,Harmonic 15 1.394 159.23
,Harmonic 16 (-1.34) 1741.87
,Harmonic 17 (-0.807) 59.89
,Harmonic 18 (-3.019) 634.11
,Harmonic 19 2.033 17.99
,Harmonic 20 (-0.417) 759.96
,Harmonic 21 (-1.512) 29.22
,Harmonic 22 1.516 1119.82
,Harmonic 23 (-3.049) 51.38
,Harmonic 24 (-0.944) 299.62
,Harmonic 25 8.8e-2 24.61
,Harmonic 26 (-0.893) 132.21
,Harmonic 27 1.836 44.48
,Harmonic 28 (-0.502) 123.86
,Harmonic 29 2.338 10.59
,Harmonic 30 0.648 247.97
,Harmonic 31 (-0.373) 17.12
,Harmonic 32 (-1.065) 144.51
,Harmonic 33 1.126 34.64
,Harmonic 34 (-1.888) 105.22
,Harmonic 35 (-0.14) 8.62
,Harmonic 36 (-2.864) 63.68
,Harmonic 37 (-1.82) 17.87
,Harmonic 38 1.163 61.84
,Harmonic 39 8.8e-2 21.43
,Harmonic 40 (-0.621) 50.86
,Harmonic 41 2.606 25.88
,Harmonic 42 (-2.746) 52.49
,Harmonic 43 2.25 9.57
,Harmonic 44 (-2.146) 13.58
,Harmonic 45 0.759 8.7
,Harmonic 46 (-2.333) 30.07
,Harmonic 47 (-0.575) 7.33
,Harmonic 48 (-2.62) 33.63
,Harmonic 49 3.005 4.74
,Harmonic 50 (-0.432) 39.51
,Harmonic 51 (-1.858) 4.4
,Harmonic 52 (-2.009) 21.51
,Harmonic 53 (-0.127) 7.07
,Harmonic 54 (-1.667) 5.06
,Harmonic 55 1.31 7.29
,Harmonic 56 2.687 5.38
,Harmonic 57 0.942 7.84
,Harmonic 58 2.697 6.72
,Harmonic 59 (-0.539) 2.77
,Harmonic 60 (-2.907) 6.52
,Harmonic 61 (-0.505) 5.23
,Harmonic 62 2.635 13.91
,Harmonic 63 (-0.835) 6.03
,Harmonic 64 (-2.65) 6.44
,Harmonic 65 (-2.159) 7.77
,Harmonic 66 2.674 11.97
,Harmonic 67 (-1.871) 4.97
,Harmonic 68 2.083 8.45
,Harmonic 69 (-2.68) 2.43]
note8 :: Note
note8 = Note
(Pitch 311.127 51 "d#4")
9
(Range
(NoteRange
(NoteRangeAmplitude 9333.81 30 2.71)
(NoteRangeHarmonicFreq 1 311.12))
(NoteRange
(NoteRangeAmplitude 311.12 1 14766.0)
(NoteRangeHarmonicFreq 32 9956.06)))
[Harmonic 1 0.294 14766.0
,Harmonic 2 2.972 5993.44
,Harmonic 3 2.531 1253.13
,Harmonic 4 (-2.67) 983.67
,Harmonic 5 1.719 2416.75
,Harmonic 6 2.018 1887.15
,Harmonic 7 (-2.836) 3770.36
,Harmonic 8 (-1.443) 818.8
,Harmonic 9 0.912 428.5
,Harmonic 10 2.854 204.98
,Harmonic 11 (-2.892) 888.17
,Harmonic 12 1.333 928.03
,Harmonic 13 (-3.046) 1656.46
,Harmonic 14 (-0.125) 204.74
,Harmonic 15 1.529 201.43
,Harmonic 16 (-2.235) 252.4
,Harmonic 17 (-3.052) 135.21
,Harmonic 18 (-1.016) 99.83
,Harmonic 19 (-1.455) 194.15
,Harmonic 20 1.812 4.25
,Harmonic 21 0.688 17.33
,Harmonic 22 1.322 39.66
,Harmonic 23 0.158 29.56
,Harmonic 24 0.631 79.91
,Harmonic 25 2.311 7.59
,Harmonic 26 (-2.559) 14.23
,Harmonic 27 (-0.18) 12.59
,Harmonic 28 (-1.694) 6.4
,Harmonic 29 2.135 6.53
,Harmonic 30 (-2.536) 2.71
,Harmonic 31 (-1.677) 6.56
,Harmonic 32 (-0.185) 7.36]
note9 :: Note
note9 = Note
(Pitch 329.628 52 "e4")
10
(Range
(NoteRange
(NoteRangeAmplitude 7911.07 24 10.29)
(NoteRangeHarmonicFreq 1 329.62))
(NoteRange
(NoteRangeAmplitude 659.25 2 14690.0)
(NoteRangeHarmonicFreq 29 9559.21)))
[Harmonic 1 (-1.429) 1578.52
,Harmonic 2 2.715 14690.0
,Harmonic 3 0.16 8415.7
,Harmonic 4 (-2.47) 3646.75
,Harmonic 5 (-2.275) 2191.24
,Harmonic 6 2.805 1774.83
,Harmonic 7 3.003 370.33
,Harmonic 8 2.513 905.83
,Harmonic 9 (-0.556) 872.62
,Harmonic 10 0.666 416.06
,Harmonic 11 (-3.067) 357.93
,Harmonic 12 (-2.17) 199.26
,Harmonic 13 0.765 240.17
,Harmonic 14 1.172 115.32
,Harmonic 15 (-0.262) 84.43
,Harmonic 16 0.286 63.97
,Harmonic 17 (-1.462) 38.36
,Harmonic 18 2.814 54.23
,Harmonic 19 1.797 36.43
,Harmonic 20 (-2.19) 69.45
,Harmonic 21 (-1.117) 38.46
,Harmonic 22 (-3.087) 12.54
,Harmonic 23 0.427 20.89
,Harmonic 24 1.87 10.29
,Harmonic 25 2.035 26.26
,Harmonic 26 0.928 17.25
,Harmonic 27 (-2.802) 25.85
,Harmonic 28 (-2.235) 11.09
,Harmonic 29 3.007 15.46]
note10 :: Note
note10 = Note
(Pitch 349.228 53 "f4")
11
(Range
(NoteRange
(NoteRangeAmplitude 9429.15 27 25.48)
(NoteRangeHarmonicFreq 1 349.22))
(NoteRange
(NoteRangeAmplitude 349.22 1 19909.0)
(NoteRangeHarmonicFreq 28 9778.38)))
[Harmonic 1 (-1.36) 19909.0
,Harmonic 2 (-2.397) 19809.31
,Harmonic 3 0.99 3389.64
,Harmonic 4 (-6.6e-2) 3264.4
,Harmonic 5 (-0.75) 7957.52
,Harmonic 6 (-1.933) 4466.05
,Harmonic 7 2.114 3372.94
,Harmonic 8 (-3.113) 2268.26
,Harmonic 9 0.972 4045.05
,Harmonic 10 (-1.348) 3603.58
,Harmonic 11 (-1.296) 2884.92
,Harmonic 12 (-2.533) 4490.49
,Harmonic 13 0.627 395.04
,Harmonic 14 3.016 325.8
,Harmonic 15 (-4.9e-2) 437.77
,Harmonic 16 (-0.206) 495.17
,Harmonic 17 0.131 204.2
,Harmonic 18 1.219 218.92
,Harmonic 19 0.357 385.97
,Harmonic 20 2.887 146.12
,Harmonic 21 (-3.129) 220.74
,Harmonic 22 6.6e-2 134.35
,Harmonic 23 (-2.568) 58.52
,Harmonic 24 (-1.788) 56.63
,Harmonic 25 2.089 65.68
,Harmonic 26 (-1.762) 104.1
,Harmonic 27 (-0.41) 25.48
,Harmonic 28 1.94 64.98]
note11 :: Note
note11 = Note
(Pitch 369.994 54 "f#4")
12
(Range
(NoteRange
(NoteRangeAmplitude 9619.84 26 7.81)
(NoteRangeHarmonicFreq 1 369.99))
(NoteRange
(NoteRangeAmplitude 369.99 1 26432.0)
(NoteRangeHarmonicFreq 27 9989.83)))
[Harmonic 1 1.375 26432.0
,Harmonic 2 (-2.68) 7676.08
,Harmonic 3 (-1.605) 3130.68
,Harmonic 4 (-0.419) 9703.07
,Harmonic 5 2.782 6109.77
,Harmonic 6 1.731 6313.64
,Harmonic 7 0.549 669.39
,Harmonic 8 0.891 1888.88
,Harmonic 9 0.263 3369.03
,Harmonic 10 1.047 863.59
,Harmonic 11 8.7e-2 1915.64
,Harmonic 12 1.546 87.12
,Harmonic 13 (-1.784) 373.02
,Harmonic 14 0.476 149.59
,Harmonic 15 1.583 153.73
,Harmonic 16 (-0.657) 94.27
,Harmonic 17 (-2.439) 114.81
,Harmonic 18 (-2.666) 70.69
,Harmonic 19 (-2.583) 17.47
,Harmonic 20 2.322 89.73
,Harmonic 21 (-2.537) 137.84
,Harmonic 22 2.12 72.86
,Harmonic 23 3.098 32.2
,Harmonic 24 1.712 16.72
,Harmonic 25 2.476 19.5
,Harmonic 26 (-2.82) 7.81
,Harmonic 27 (-2.451) 13.71]
note12 :: Note
note12 = Note
(Pitch 391.995 55 "g4")
13
(Range
(NoteRange
(NoteRangeAmplitude 9407.88 24 1.43)
(NoteRangeHarmonicFreq 1 391.99))
(NoteRange
(NoteRangeAmplitude 391.99 1 21071.0)
(NoteRangeHarmonicFreq 25 9799.87)))
[Harmonic 1 1.74 21071.0
,Harmonic 2 (-0.201) 3080.7
,Harmonic 3 (-0.556) 507.31
,Harmonic 4 (-0.999) 7664.24
,Harmonic 5 1.52 6678.79
,Harmonic 6 1.547 2731.05
,Harmonic 7 2.449 1408.78
,Harmonic 8 2.555 749.86
,Harmonic 9 0.966 1087.55
,Harmonic 10 2.862 1417.83
,Harmonic 11 (-0.454) 501.67
,Harmonic 12 1.952 196.65
,Harmonic 13 2.383 207.17
,Harmonic 14 2.782 85.24
,Harmonic 15 0.305 79.06
,Harmonic 16 1.661 23.06
,Harmonic 17 (-1.415) 60.39
,Harmonic 18 (-0.77) 126.83
,Harmonic 19 2.798 54.52
,Harmonic 20 (-0.2) 118.83
,Harmonic 21 (-1.128) 94.48
,Harmonic 22 2.86 63.55
,Harmonic 23 (-2.03) 52.52
,Harmonic 24 2.692 1.43
,Harmonic 25 (-1.52) 26.5]
note13 :: Note
note13 = Note
(Pitch 415.305 56 "g#4")
14
(Range
(NoteRange
(NoteRangeAmplitude 8306.1 20 14.96)
(NoteRangeHarmonicFreq 1 415.3))
(NoteRange
(NoteRangeAmplitude 415.3 1 18389.0)
(NoteRangeHarmonicFreq 24 9967.32)))
[Harmonic 1 1.512 18389.0
,Harmonic 2 (-2.148) 1566.94
,Harmonic 3 1.96 1480.65
,Harmonic 4 0.282 4518.9
,Harmonic 5 3.017 3372.58
,Harmonic 6 (-1.512) 2295.0
,Harmonic 7 (-0.461) 294.99
,Harmonic 8 0.858 1454.49
,Harmonic 9 (-1.129) 1436.92
,Harmonic 10 2.612 1151.8
,Harmonic 11 1.799 40.02
,Harmonic 12 1.227 53.58
,Harmonic 13 0.56 175.38
,Harmonic 14 0.213 60.55
,Harmonic 15 (-2.622) 47.93
,Harmonic 16 2.355 25.44
,Harmonic 17 (-2.035) 48.9
,Harmonic 18 1.732 28.47
,Harmonic 19 1.804 42.68
,Harmonic 20 2.832 14.96
,Harmonic 21 (-2.04) 19.49
,Harmonic 22 0.357 15.01
,Harmonic 23 (-3.028) 42.14
,Harmonic 24 (-2.628) 18.8]
note14 :: Note
note14 = Note
(Pitch 440.0 57 "a4")
15
(Range
(NoteRange
(NoteRangeAmplitude 9240.0 21 5.12)
(NoteRangeHarmonicFreq 1 440.0))
(NoteRange
(NoteRangeAmplitude 440.0 1 17973.0)
(NoteRangeHarmonicFreq 23 10120.0)))
[Harmonic 1 1.946 17973.0
,Harmonic 2 (-0.278) 2205.82
,Harmonic 3 0.873 3877.62
,Harmonic 4 0.95 3093.75
,Harmonic 5 (-1.031) 3606.37
,Harmonic 6 0.896 480.55
,Harmonic 7 2.082 594.81
,Harmonic 8 0.658 1314.51
,Harmonic 9 1.226 1476.57
,Harmonic 10 0.545 262.08
,Harmonic 11 (-1.988) 67.09
,Harmonic 12 (-1.084) 356.17
,Harmonic 13 2.165 155.38
,Harmonic 14 (-1.91) 35.48
,Harmonic 15 3.02 21.8
,Harmonic 16 (-3.14) 48.07
,Harmonic 17 3.033 59.57
,Harmonic 18 (-1.91) 66.57
,Harmonic 19 (-1.962) 16.22
,Harmonic 20 1.903 23.99
,Harmonic 21 (-3.041) 5.12
,Harmonic 22 (-1.632) 7.81
,Harmonic 23 1.997 7.61]
note15 :: Note
note15 = Note
(Pitch 466.164 58 "a#4")
16
(Range
(NoteRange
(NoteRangeAmplitude 8857.11 19 19.46)
(NoteRangeHarmonicFreq 1 466.16))
(NoteRange
(NoteRangeAmplitude 466.16 1 16636.0)
(NoteRangeHarmonicFreq 21 9789.44)))
[Harmonic 1 1.526 16636.0
,Harmonic 2 (-1.236) 3703.0
,Harmonic 3 2.119 2860.84
,Harmonic 4 0.236 6411.23
,Harmonic 5 1.984 3482.92
,Harmonic 6 (-2.129) 200.55
,Harmonic 7 1.668 3074.95
,Harmonic 8 1.099 4108.69
,Harmonic 9 (-2.113) 3635.2
,Harmonic 10 (-1.836) 72.93
,Harmonic 11 (-1.186) 478.88
,Harmonic 12 1.644 154.11
,Harmonic 13 2.389 413.72
,Harmonic 14 (-0.95) 122.54
,Harmonic 15 3.045 456.41
,Harmonic 16 (-2.895) 102.01
,Harmonic 17 2.397 129.3
,Harmonic 18 (-1.272) 36.47
,Harmonic 19 2.015 19.46
,Harmonic 20 (-9.4e-2) 21.06
,Harmonic 21 (-0.282) 100.5]
note16 :: Note
note16 = Note
(Pitch 493.883 59 "b4")
17
(Range
(NoteRange
(NoteRangeAmplitude 6420.47 13 18.26)
(NoteRangeHarmonicFreq 1 493.88))
(NoteRange
(NoteRangeAmplitude 493.88 1 28968.0)
(NoteRangeHarmonicFreq 20 9877.66)))
[Harmonic 1 (-1.781) 28968.0
,Harmonic 2 1.39 4835.24
,Harmonic 3 1.262 5674.25
,Harmonic 4 0.295 3457.35
,Harmonic 5 0.684 303.97
,Harmonic 6 0.338 1379.44
,Harmonic 7 (-0.114) 1048.08
,Harmonic 8 (-0.489) 483.69
,Harmonic 9 (-2.869) 195.47
,Harmonic 10 1.992 133.35
,Harmonic 11 2.895 193.15
,Harmonic 12 (-2.293) 207.88
,Harmonic 13 (-1.915) 18.26
,Harmonic 14 1.461 169.98
,Harmonic 15 (-2.899) 20.94
,Harmonic 16 (-2.762) 42.46
,Harmonic 17 0.104 37.51
,Harmonic 18 2.614 60.9
,Harmonic 19 (-2.256) 33.09
,Harmonic 20 (-8.0e-3) 61.94]
note17 :: Note
note17 = Note
(Pitch 523.251 60 "c5")
18
(Range
(NoteRange
(NoteRangeAmplitude 9941.76 19 33.65)
(NoteRangeHarmonicFreq 1 523.25))
(NoteRange
(NoteRangeAmplitude 523.25 1 25823.0)
(NoteRangeHarmonicFreq 19 9941.76)))
[Harmonic 1 (-1.633) 25823.0
,Harmonic 2 1.728 1261.33
,Harmonic 3 (-2.49) 1507.27
,Harmonic 4 2.771 3191.32
,Harmonic 5 (-1.278) 1512.55
,Harmonic 6 (-1.593) 3502.56
,Harmonic 7 1.607 798.17
,Harmonic 8 1.142 1152.05
,Harmonic 9 (-1.475) 207.71
,Harmonic 10 (-1.409) 653.81
,Harmonic 11 1.539 166.53
,Harmonic 12 (-0.522) 52.78
,Harmonic 13 (-2.309) 461.12
,Harmonic 14 (-0.538) 73.37
,Harmonic 15 0.945 96.99
,Harmonic 16 2.165 95.13
,Harmonic 17 (-0.567) 103.74
,Harmonic 18 (-2.985) 59.4
,Harmonic 19 1.247 33.65]
note18 :: Note
note18 = Note
(Pitch 554.365 61 "c#5")
19
(Range
(NoteRange
(NoteRangeAmplitude 8315.47 15 45.94)
(NoteRangeHarmonicFreq 1 554.36))
(NoteRange
(NoteRangeAmplitude 2217.46 4 30250.0)
(NoteRangeHarmonicFreq 18 9978.57)))
[Harmonic 1 (-1.286) 23400.8
,Harmonic 2 (-0.948) 2157.54
,Harmonic 3 (-0.91) 6100.28
,Harmonic 4 (-2.278) 30250.0
,Harmonic 5 0.507 4789.39
,Harmonic 6 (-2.304) 6454.83
,Harmonic 7 (-2.413) 4232.58
,Harmonic 8 (-0.963) 2102.52
,Harmonic 9 1.921 767.38
,Harmonic 10 (-1.308) 210.06
,Harmonic 11 0.751 310.77
,Harmonic 12 (-2.136) 461.37
,Harmonic 13 2.031 426.2
,Harmonic 14 1.205 452.79
,Harmonic 15 (-3.057) 45.94
,Harmonic 16 1.403 136.59
,Harmonic 17 0.844 168.96
,Harmonic 18 1.12 98.76]
note19 :: Note
note19 = Note
(Pitch 587.33 62 "d5")
20
(Range
(NoteRange
(NoteRangeAmplitude 9397.28 16 20.55)
(NoteRangeHarmonicFreq 1 587.33))
(NoteRange
(NoteRangeAmplitude 587.33 1 15990.0)
(NoteRangeHarmonicFreq 17 9984.61)))
[Harmonic 1 (-1.892) 15990.0
,Harmonic 2 (-2.433) 1253.0
,Harmonic 3 (-0.477) 5756.47
,Harmonic 4 3.116 3471.39
,Harmonic 5 0.529 2662.79
,Harmonic 6 (-1.175) 1941.84
,Harmonic 7 2.84 1502.42
,Harmonic 8 (-0.865) 699.84
,Harmonic 9 (-0.189) 1499.66
,Harmonic 10 0.502 333.21
,Harmonic 11 0.871 318.28
,Harmonic 12 1.323 353.16
,Harmonic 13 (-2.453) 139.27
,Harmonic 14 (-0.763) 79.36
,Harmonic 15 1.615 48.81
,Harmonic 16 (-1.269) 20.55
,Harmonic 17 2.765 28.14]
note20 :: Note
note20 = Note
(Pitch 622.254 63 "d#5")
21
(Range
(NoteRange
(NoteRangeAmplitude 9956.06 16 101.84)
(NoteRangeHarmonicFreq 1 622.25))
(NoteRange
(NoteRangeAmplitude 622.25 1 20768.0)
(NoteRangeHarmonicFreq 16 9956.06)))
[Harmonic 1 (-0.931) 20768.0
,Harmonic 2 2.69 9136.38
,Harmonic 3 (-1.963) 7198.94
,Harmonic 4 (-2.697) 4619.92
,Harmonic 5 (-1.755) 1988.15
,Harmonic 6 (-0.195) 1531.5
,Harmonic 7 1.289 1545.57
,Harmonic 8 2.964 644.94
,Harmonic 9 (-1.265) 165.49
,Harmonic 10 (-2.121) 683.97
,Harmonic 11 0.935 393.72
,Harmonic 12 (-2.493) 294.3
,Harmonic 13 (-1.553) 203.04
,Harmonic 14 (-1.506) 129.79
,Harmonic 15 1.577 137.67
,Harmonic 16 1.924 101.84]
note21 :: Note
note21 = Note
(Pitch 659.255 64 "e5")
22
(Range
(NoteRange
(NoteRangeAmplitude 9888.82 15 68.34)
(NoteRangeHarmonicFreq 1 659.25))
(NoteRange
(NoteRangeAmplitude 659.25 1 25729.0)
(NoteRangeHarmonicFreq 15 9888.82)))
[Harmonic 1 1.127 25729.0
,Harmonic 2 1.558 6970.8
,Harmonic 3 2.867 5103.9
,Harmonic 4 2.803 3986.78
,Harmonic 5 (-0.943) 3261.87
,Harmonic 6 (-3.096) 716.3
,Harmonic 7 (-2.794) 1654.33
,Harmonic 8 0.348 482.42
,Harmonic 9 1.283 489.92
,Harmonic 10 1.602 272.78
,Harmonic 11 0.973 611.87
,Harmonic 12 3.022 223.34
,Harmonic 13 1.176 228.94
,Harmonic 14 (-3.111) 219.84
,Harmonic 15 2.44 68.34]
note22 :: Note
note22 = Note
(Pitch 698.456 65 "f5")
23
(Range
(NoteRange
(NoteRangeAmplitude 8381.47 12 33.93)
(NoteRangeHarmonicFreq 1 698.45))
(NoteRange
(NoteRangeAmplitude 698.45 1 11830.0)
(NoteRangeHarmonicFreq 14 9778.38)))
[Harmonic 1 1.46 11830.0
,Harmonic 2 0.886 10071.16
,Harmonic 3 2.711 7322.23
,Harmonic 4 (-2.191) 1588.96
,Harmonic 5 (-0.445) 1237.59
,Harmonic 6 (-0.135) 358.17
,Harmonic 7 2.541 594.1
,Harmonic 8 0.454 680.31
,Harmonic 9 (-0.263) 521.22
,Harmonic 10 (-9.9e-2) 147.88
,Harmonic 11 2.78 169.24
,Harmonic 12 (-0.646) 33.93
,Harmonic 13 2.379 238.5
,Harmonic 14 1.249 90.18]
note23 :: Note
note23 = Note
(Pitch 739.989 66 "f#5")
24
(Range
(NoteRange
(NoteRangeAmplitude 8139.87 11 310.93)
(NoteRangeHarmonicFreq 1 739.98))
(NoteRange
(NoteRangeAmplitude 1479.97 2 24124.0)
(NoteRangeHarmonicFreq 13 9619.85)))
[Harmonic 1 1.607 15725.63
,Harmonic 2 0.536 24124.0
,Harmonic 3 2.058 21906.18
,Harmonic 4 1.777 7006.14
,Harmonic 5 (-2.542) 3267.22
,Harmonic 6 1.369 3173.5
,Harmonic 7 (-0.952) 1259.11
,Harmonic 8 (-1.976) 605.16
,Harmonic 9 (-2.765) 637.08
,Harmonic 10 0.789 1553.97
,Harmonic 11 (-1.205) 310.93
,Harmonic 12 9.9e-2 328.09
,Harmonic 13 1.347 326.59]
note24 :: Note
note24 = Note
(Pitch 783.991 67 "g5")
25
(Range
(NoteRange
(NoteRangeAmplitude 9407.89 12 44.01)
(NoteRangeHarmonicFreq 1 783.99))
(NoteRange
(NoteRangeAmplitude 783.99 1 13605.0)
(NoteRangeHarmonicFreq 12 9407.89)))
[Harmonic 1 1.14 13605.0
,Harmonic 2 (-2.567) 5549.4
,Harmonic 3 (-2.287) 2707.21
,Harmonic 4 0.866 902.01
,Harmonic 5 0.834 1645.18
,Harmonic 6 (-1.813) 391.27
,Harmonic 7 (-0.955) 287.03
,Harmonic 8 (-2.841) 58.29
,Harmonic 9 2.04 177.33
,Harmonic 10 2.886 227.06
,Harmonic 11 2.69 83.78
,Harmonic 12 2.01 44.01]
note25 :: Note
note25 = Note
(Pitch 830.609 68 "g#5")
26
(Range
(NoteRange
(NoteRangeAmplitude 9967.3 12 84.12)
(NoteRangeHarmonicFreq 1 830.6))
(NoteRange
(NoteRangeAmplitude 830.6 1 5107.0)
(NoteRangeHarmonicFreq 12 9967.3)))
[Harmonic 1 (-2.624) 5107.0
,Harmonic 2 (-0.102) 1485.76
,Harmonic 3 (-0.16) 3470.12
,Harmonic 4 (-2.317) 4944.35
,Harmonic 5 (-1.547) 651.52
,Harmonic 6 2.643 823.69
,Harmonic 7 (-1.953) 444.72
,Harmonic 8 (-1.285) 162.6
,Harmonic 9 (-2.598) 162.32
,Harmonic 10 (-2.867) 153.86
,Harmonic 11 1.252 101.61
,Harmonic 12 (-0.5) 84.12]
note26 :: Note
note26 = Note
(Pitch 880.0 69 "a5")
27
(Range
(NoteRange
(NoteRangeAmplitude 7920.0 9 39.07)
(NoteRangeHarmonicFreq 1 880.0))
(NoteRange
(NoteRangeAmplitude 880.0 1 8811.0)
(NoteRangeHarmonicFreq 11 9680.0)))
[Harmonic 1 (-1.54) 8811.0
,Harmonic 2 2.995 2464.59
,Harmonic 3 (-0.328) 675.98
,Harmonic 4 (-0.76) 646.42
,Harmonic 5 0.974 1207.42
,Harmonic 6 0.513 678.04
,Harmonic 7 2.908 226.02
,Harmonic 8 2.515 104.67
,Harmonic 9 2.925 39.07
,Harmonic 10 (-1.389) 107.65
,Harmonic 11 1.931 50.26]
note27 :: Note
note27 = Note
(Pitch 932.328 70 "a#5")
28
(Range
(NoteRange
(NoteRangeAmplitude 8390.95 9 50.48)
(NoteRangeHarmonicFreq 1 932.32))
(NoteRange
(NoteRangeAmplitude 932.32 1 13960.0)
(NoteRangeHarmonicFreq 10 9323.27)))
[Harmonic 1 1.711 13960.0
,Harmonic 2 1.688 4217.79
,Harmonic 3 (-1.332) 1545.55
,Harmonic 4 (-0.549) 2674.39
,Harmonic 5 1.922 905.13
,Harmonic 6 0.441 276.8
,Harmonic 7 (-2.943) 80.49
,Harmonic 8 (-2.374) 263.24
,Harmonic 9 2.632 50.48
,Harmonic 10 (-9.1e-2) 98.51]
note28 :: Note
note28 = Note
(Pitch 987.767 71 "b5")
29
(Range
(NoteRange
(NoteRangeAmplitude 6914.36 7 2.9)
(NoteRangeHarmonicFreq 1 987.76))
(NoteRange
(NoteRangeAmplitude 987.76 1 4624.0)
(NoteRangeHarmonicFreq 10 9877.67)))
[Harmonic 1 1.401 4624.0
,Harmonic 2 (-1.91) 1397.53
,Harmonic 3 1.552 2343.5
,Harmonic 4 2.038 1642.77
,Harmonic 5 0.952 712.63
,Harmonic 6 0.874 165.4
,Harmonic 7 2.981 2.9
,Harmonic 8 1.756 65.29
,Harmonic 9 (-2.486) 63.37
,Harmonic 10 2.798 35.97]
note29 :: Note
note29 = Note
(Pitch 1046.5 72 "c6")
30
(Range
(NoteRange
(NoteRangeAmplitude 8372.0 8 68.49)
(NoteRangeHarmonicFreq 1 1046.5))
(NoteRange
(NoteRangeAmplitude 3139.5 3 10938.0)
(NoteRangeHarmonicFreq 9 9418.5)))
[Harmonic 1 1.24 5525.23
,Harmonic 2 2.621 7863.63
,Harmonic 3 0.759 10938.0
,Harmonic 4 (-2.136) 1014.35
,Harmonic 5 1.29 3683.24
,Harmonic 6 (-0.541) 897.3
,Harmonic 7 (-0.153) 257.83
,Harmonic 8 (-1.073) 68.49
,Harmonic 9 (-1.257) 86.66]
note30 :: Note
note30 = Note
(Pitch 1108.73 73 "c#6")
31
(Range
(NoteRange
(NoteRangeAmplitude 7761.11 7 40.95)
(NoteRangeHarmonicFreq 1 1108.73))
(NoteRange
(NoteRangeAmplitude 2217.46 2 16713.0)
(NoteRangeHarmonicFreq 9 9978.57)))
[Harmonic 1 (-7.7e-2) 3162.89
,Harmonic 2 (-1.728) 16713.0
,Harmonic 3 (-2.987) 2894.6
,Harmonic 4 2.733 3043.26
,Harmonic 5 (-0.757) 317.82
,Harmonic 6 2.211 354.02
,Harmonic 7 1.011 40.95
,Harmonic 8 (-0.675) 115.38
,Harmonic 9 (-2.944) 133.97]
note31 :: Note
note31 = Note
(Pitch 1174.66 74 "d6")
32
(Range
(NoteRange
(NoteRangeAmplitude 9397.28 8 49.44)
(NoteRangeHarmonicFreq 1 1174.66))
(NoteRange
(NoteRangeAmplitude 1174.66 1 4304.0)
(NoteRangeHarmonicFreq 8 9397.28)))
[Harmonic 1 (-2.308) 4304.0
,Harmonic 2 (-0.468) 2606.07
,Harmonic 3 (-2.369) 2822.4
,Harmonic 4 (-2.388) 450.38
,Harmonic 5 (-1.668) 457.0
,Harmonic 6 (-1.033) 164.74
,Harmonic 7 (-1.22) 77.04
,Harmonic 8 (-3.117) 49.44]
note32 :: Note
note32 = Note
(Pitch 1244.51 75 "d#6")
33
(Range
(NoteRange
(NoteRangeAmplitude 8711.57 7 27.73)
(NoteRangeHarmonicFreq 1 1244.51))
(NoteRange
(NoteRangeAmplitude 1244.51 1 11688.0)
(NoteRangeHarmonicFreq 8 9956.08)))
[Harmonic 1 1.842 11688.0
,Harmonic 2 0.606 6006.05
,Harmonic 3 (-0.453) 1107.77
,Harmonic 4 3.059 97.7
,Harmonic 5 0.639 96.99
,Harmonic 6 0.764 183.78
,Harmonic 7 1.891 27.73
,Harmonic 8 3.024 63.65]
note33 :: Note
note33 = Note
(Pitch 1318.51 76 "e6")
34
(Range
(NoteRange
(NoteRangeAmplitude 9229.57 7 25.52)
(NoteRangeHarmonicFreq 1 1318.51))
(NoteRange
(NoteRangeAmplitude 1318.51 1 3118.0)
(NoteRangeHarmonicFreq 7 9229.57)))
[Harmonic 1 (-1.29) 3118.0
,Harmonic 2 (-1.88) 1326.89
,Harmonic 3 0.714 564.21
,Harmonic 4 (-2.919) 1705.89
,Harmonic 5 (-3.074) 113.83
,Harmonic 6 (-0.106) 176.54
,Harmonic 7 (-2.5e-2) 25.52]
note34 :: Note
note34 = Note
(Pitch 1396.91 77 "f6")
35
(Range
(NoteRange
(NoteRangeAmplitude 6984.55 5 89.35)
(NoteRangeHarmonicFreq 1 1396.91))
(NoteRange
(NoteRangeAmplitude 4190.73 3 10508.0)
(NoteRangeHarmonicFreq 7 9778.37)))
[Harmonic 1 3.102 9112.26
,Harmonic 2 0.888 7305.77
,Harmonic 3 (-0.973) 10508.0
,Harmonic 4 2.151 180.93
,Harmonic 5 1.15 89.35
,Harmonic 6 1.818 137.14
,Harmonic 7 0.43 121.89]
note35 :: Note
note35 = Note
(Pitch 1479.98 78 "f#6")
36
(Range
(NoteRange
(NoteRangeAmplitude 8879.88 6 206.27)
(NoteRangeHarmonicFreq 1 1479.98))
(NoteRange
(NoteRangeAmplitude 2959.96 2 7077.0)
(NoteRangeHarmonicFreq 6 8879.88)))
[Harmonic 1 (-1.615) 7006.0
,Harmonic 2 (-2.447) 7077.0
,Harmonic 3 (-1.847) 2978.98
,Harmonic 4 (-2.381) 665.86
,Harmonic 5 (-0.912) 808.02
,Harmonic 6 (-0.431) 206.27]
note36 :: Note
note36 = Note
(Pitch 1567.98 79 "g6")
37
(Range
(NoteRange
(NoteRangeAmplitude 9407.88 6 110.07)
(NoteRangeHarmonicFreq 1 1567.98))
(NoteRange
(NoteRangeAmplitude 3135.96 2 6872.0)
(NoteRangeHarmonicFreq 6 9407.88)))
[Harmonic 1 (-2.528) 3547.28
,Harmonic 2 (-1.365) 6872.0
,Harmonic 3 (-2.235) 131.77
,Harmonic 4 2.142 317.95
,Harmonic 5 (-2.656) 301.41
,Harmonic 6 2.715 110.07]
note37 :: Note
note37 = Note
(Pitch 1661.22 80 "g#6")
38
(Range
(NoteRange
(NoteRangeAmplitude 8306.1 5 41.48)
(NoteRangeHarmonicFreq 1 1661.22))
(NoteRange
(NoteRangeAmplitude 3322.44 2 5203.0)
(NoteRangeHarmonicFreq 5 8306.1)))
[Harmonic 1 (-2.604) 1645.96
,Harmonic 2 (-1.682) 5203.0
,Harmonic 3 (-1.324) 210.21
,Harmonic 4 2.955 56.5
,Harmonic 5 2.164 41.48]
note38 :: Note
note38 = Note
(Pitch 1760.0 81 "a6")
39
(Range
(NoteRange
(NoteRangeAmplitude 7040.0 4 267.58)
(NoteRangeHarmonicFreq 1 1760.0))
(NoteRange
(NoteRangeAmplitude 1760.0 1 6896.0)
(NoteRangeHarmonicFreq 5 8800.0)))
[Harmonic 1 2.241 6896.0
,Harmonic 2 0.499 5561.79
,Harmonic 3 (-0.541) 938.81
,Harmonic 4 (-0.8) 267.58
,Harmonic 5 1.713 469.3]
note39 :: Note
note39 = Note
(Pitch 1864.66 82 "a#6")
40
(Range
(NoteRange
(NoteRangeAmplitude 9323.3 5 74.81)
(NoteRangeHarmonicFreq 1 1864.66))
(NoteRange
(NoteRangeAmplitude 3729.32 2 8236.0)
(NoteRangeHarmonicFreq 5 9323.3)))
[Harmonic 1 (-2.523) 3933.78
,Harmonic 2 0.927 8236.0
,Harmonic 3 (-1.32) 474.18
,Harmonic 4 7.6e-2 176.87
,Harmonic 5 0.759 74.81]
note40 :: Note
note40 = Note
(Pitch 1975.53 83 "b6")
41
(Range
(NoteRange
(NoteRangeAmplitude 9877.65 5 46.53)
(NoteRangeHarmonicFreq 1 1975.53))
(NoteRange
(NoteRangeAmplitude 1975.53 1 5959.0)
(NoteRangeHarmonicFreq 5 9877.65)))
[Harmonic 1 1.345 5959.0
,Harmonic 2 1.998 681.62
,Harmonic 3 1.607 368.42
,Harmonic 4 (-1.992) 120.5
,Harmonic 5 0.517 46.53]
note41 :: Note
note41 = Note
(Pitch 2093.0 84 "c7")
42
(Range
(NoteRange
(NoteRangeAmplitude 8372.0 4 89.75)
(NoteRangeHarmonicFreq 1 2093.0))
(NoteRange
(NoteRangeAmplitude 2093.0 1 4944.0)
(NoteRangeHarmonicFreq 4 8372.0)))
[Harmonic 1 (-1.941) 4944.0
,Harmonic 2 (-2.164) 4288.65
,Harmonic 3 0.506 517.88
,Harmonic 4 (-0.347) 89.75]
note42 :: Note
note42 = Note
(Pitch 2217.46 85 "c#7")
43
(Range
(NoteRange
(NoteRangeAmplitude 6652.38 3 119.9)
(NoteRangeHarmonicFreq 1 2217.46))
(NoteRange
(NoteRangeAmplitude 2217.46 1 6157.0)
(NoteRangeHarmonicFreq 4 8869.84)))
[Harmonic 1 (-2.084) 6157.0
,Harmonic 2 (-1.331) 3771.57
,Harmonic 3 0.242 119.9
,Harmonic 4 (-0.505) 192.73]
note43 :: Note
note43 = Note
(Pitch 2349.32 86 "d7")
44
(Range
(NoteRange
(NoteRangeAmplitude 9397.28 4 19.43)
(NoteRangeHarmonicFreq 1 2349.32))
(NoteRange
(NoteRangeAmplitude 2349.32 1 2461.0)
(NoteRangeHarmonicFreq 4 9397.28)))
[Harmonic 1 (-1.77) 2461.0
,Harmonic 2 1.24 464.93
,Harmonic 3 (-2.68) 38.83
,Harmonic 4 1.43 19.43] | anton-k/sharc-timbre | src/Sharc/Instruments/ViolinsEnsemble.hs | bsd-3-clause | 41,156 | 0 | 15 | 11,901 | 15,066 | 7,801 | 7,265 | 1,406 | 1 |
{-# LANGUAGE FlexibleInstances #-}
module Kalium.Haskell.Sugar where
import Kalium.Prelude
import Kalium.Util (closureM)
import Kalium.Haskell.Common
import Language.Haskell.Exts.Syntax
import Language.Haskell.Exts.SrcLoc (noLoc)
sugarcoat :: Module -> Module
sugarcoat = runIdentity . closureM sugar
class Sugar a where
sugar :: (Monad m) => a -> m a
instance (Sugar a, Traversable f) => Sugar (f a) where
sugar = traverse sugar
instance Sugar Module where
sugar (Module srcLoc name pragmas wtext exportSpec importDecls decls)
= Module srcLoc name pragmas wtext exportSpec importDecls <$> sugar decls
instance Sugar Decl where
sugar = \case
FunBind matches -> FunBind <$> sugar matches
PatBind srcLoc pat rhs binds
-> PatBind srcLoc pat <$> sugar rhs <*> sugar binds
TypeSig srcLoc names ty -> TypeSig srcLoc names <$> sugar ty
decl -> error ("unsupported decl: " ++ show decl)
instance Sugar Match where
sugar (Match srcLoc name pats ty rhs binds)
| UnGuardedRhs (Lambda _ pats' exp) <- rhs
= sugar $ Match srcLoc name (pats ++ pats') ty (UnGuardedRhs exp) binds
sugar (Match srcLoc name pats ty rhs binds)
= Match srcLoc name <$> sugar pats <*> sugar ty <*> sugar rhs <*> sugar binds
instance Sugar Binds where
sugar = \case
IPBinds {} -> error "not supported: IPBinds"
BDecls decls -> BDecls <$> sugar decls
sugarUniverseStrip a = expStripParen ParensUniverse <$> sugar a
instance Sugar Rhs where
sugar = \case
UnGuardedRhs (MultiIf rhss) -> sugar (GuardedRhss rhss)
UnGuardedRhs exp -> UnGuardedRhs <$> sugarUniverseStrip exp
GuardedRhss rhss -> GuardedRhss <$> sugar rhss
instance Sugar GuardedRhs where
sugar (GuardedRhs srcLoc stmts exp)
= GuardedRhs srcLoc <$> sugar stmts <*> sugarUniverseStrip exp
instance Sugar Stmt where
sugar = \case
Generator srcLoc pat exp
-> Generator srcLoc <$> sugar pat <*> sugarUniverseStrip exp
Qualifier exp -> Qualifier <$> sugarUniverseStrip exp
LetStmt binds -> LetStmt <$> sugar binds
RecStmt stmts -> RecStmt <$> sugar stmts
instance Sugar Pat where
sugar = \case
PatTypeSig srcLoc pat ty -> PatTypeSig srcLoc <$> sugar pat <*> sugar ty
PTuple boxed pats -> PTuple boxed <$> sugar pats
pat@PVar{} -> pure pat
pat@PWildCard{} -> pure pat
pat -> error ("unsupported pat: " ++ show pat)
instance Sugar Type where
sugar = \case
TyCon (Special (TupleCon boxed 2)) `TyApp` ty1 `TyApp` ty2
-> pure $ TyTuple boxed [ty1, ty2]
TyCon (Special FunCon) `TyApp` ty1 `TyApp` ty2 -> pure $ TyFun ty1 ty2
TyCon (Special ListCon) `TyApp` ty -> pure $ TyList ty
TyList (TyCon (HsIdent "Prelude" "Char"))
-> pure $ TyCon (HsIdent "Prelude" "String")
TyApp ty1 ty2 -> TyApp <$> sugar ty1 <*> sugar ty2
ty@TyCon{} -> pure ty
TyTuple boxed tys -> TyTuple boxed <$> sugar tys
TyFun ty1 ty2 -> TyFun <$> sugar ty1 <*> sugar ty2
TyList ty -> TyList <$> sugar ty
ty -> error ("unsupported type: " ++ show ty)
pattern App2 op x y = op `App` x `App` y
pattern App3 op x y z = op `App` x `App` y `App` z
instance Sugar Exp where
sugar = fmap expMatch . \case
exp@Var{} -> return exp
exp@Con{} -> return exp
exp@Lit{} -> return exp
List exps -> List <$> sugar exps
MultiIf rhss -> MultiIf <$> sugar rhss
If exp1 exp2 exp3 -> If <$> sugar exp1 <*> sugar exp2 <*> sugar exp3
EnumFromTo exp1 exp2 -> EnumFromTo <$> sugar exp1 <*> sugar exp2
Tuple boxed exps -> Tuple boxed <$> sugar exps
Paren exp -> Paren <$> sugar exp
App x y -> App <$> sugar x <*> sugar y
Lambda srcLoc pats exp -> Lambda srcLoc <$> sugar pats <*> sugar exp
InfixApp x op y -> InfixApp <$> sugar x <*> pure op <*> sugar y
RightSection op exp -> RightSection op <$> sugar exp
Do stmts -> Do <$> sugar stmts
Let binds exp -> Let <$> sugar binds <*> sugar exp
exp -> error ("unsupported exp: " ++ show exp)
expMatch
= expStripParen ParensAtom
. expMatchInfix
. expMatchIf
. expJoinLambda
. expJoinList
. expAppSection
. expDoMatch
. expLetMatch
isInfix op = lookup op fixtable /= Nothing
expMatchIf = \case
App3 (Var op) x y z | HsIdent "Data.Bool" "bool" <- op -> If z y x
If expCond expThen expElse
| MultiIf rhss <- expElse
-> MultiIf (GuardedRhs noLoc [Qualifier expCond] expThen : rhss)
| If expCond' expThen' expElse' <- expElse
-> MultiIf [ GuardedRhs noLoc [Qualifier expCond ] expThen
, GuardedRhs noLoc [Qualifier expCond'] expThen'
, GuardedRhs noLoc [Qualifier trueCond] expElse'
] where trueCond = Var (HsIdent "Prelude" "otherwise")
exp -> exp
expMatchInfix = \case
App2 (Con op) x y -> case op of
Special (TupleCon boxed _) -> Tuple boxed [x, y]
_ -> Paren (InfixApp (Paren x) (QConOp op) (Paren y))
App2 (Var op) x y | HsIdent "Prelude" "enumFromTo" <- op
-> EnumFromTo x y
App2 (Var op) x y | isInfix (QVarOp op)
-> Paren (InfixApp (Paren x) (QVarOp op) (Paren y))
exp -> exp
expStripParen outerLevel = \case
Paren exp | expLevel exp `lesserLevel` outerLevel -> exp
App (Paren x) y | expLevel x `lesserLevel` ParensApp -> App x y
App x (Paren y) | expLevel y `lesserLevel` ParensApp -> App x y
InfixApp (Paren (InfixApp l_lhs l_op l_rhs)) op rhs
| (Leftfix, l_n) <- whatfix l_op
, (Leftfix, n) <- whatfix op
, l_n == n
-> InfixApp (InfixApp l_lhs l_op l_rhs) op rhs
InfixApp lhs op (Paren (InfixApp r_lhs r_op r_rhs))
| (Rightfix, r_n) <- whatfix r_op
, (Rightfix, n) <- whatfix op
, r_n == n
-> InfixApp lhs op (InfixApp r_lhs r_op r_rhs)
InfixApp lhs op rhs | (fx, n) <- whatfix op
-> InfixApp
(expStripParen (ParensInfix fx n) lhs)
op
(expStripParen (ParensInfix fx n) rhs)
Do stmts ->
let strip = \case
Qualifier (Paren exp) -> Qualifier exp
stmt -> stmt
in Do (map strip stmts)
Let binds exp -> Let binds (expStripParen ParensUniverse exp)
Tuple boxed exps -> Tuple boxed (expStripParen ParensUniverse `map` exps)
List exps -> List (expStripParen ParensUniverse `map` exps)
EnumFromTo exp1 exp2 -> EnumFromTo
(expStripParen ParensUniverse exp1)
(expStripParen ParensUniverse exp2)
If exp1 exp2 exp3 -> If
(expStripParen ParensUniverse exp1)
(expStripParen ParensUniverse exp2)
(expStripParen ParensUniverse exp3)
exp -> exp
expJoinLambda = \case
Lambda srcLoc pats (Lambda _ pats' exp) -> Lambda srcLoc (pats ++ pats') exp
exp -> exp
expJoinList = \case
List xs | Just cs <- charList xs -> Lit (String cs)
InfixApp x (QConOp (Special Cons)) (List xs) -> List (x:xs)
InfixApp (Lit (Char c)) (QConOp (Special Cons)) (Lit (String cs))
-> Lit (String (c:cs))
exp -> exp
charList [] = Nothing
charList xs = traverse exChar xs
where
exChar = \case
Lit (Char c) -> Just c
_ -> Nothing
expAppSection = \case
App (RightSection (QVarOp op) y) x -> App2 (Var op) x y
App (RightSection (QConOp op) y) x -> App2 (Con op) x y
exp -> exp
expDoMatch = \case
App2 (Var (HsSymbol "Prelude" ">>=")) x (Lambda srcLoc [pat] a)
-> Do [Generator srcLoc pat x, Qualifier a]
App2 (Var (HsSymbol "Prelude" ">>")) x y
-> Do [Qualifier x, Qualifier y]
Do [Qualifier exp] -> exp
Do stmts -> Do (stmts >>= expandStmt) where
expandStmt = \case
Qualifier (Do stmts) -> stmts
stmt -> [stmt]
exp -> exp
expLetMatch = \case
App (Lambda srcLoc [pat] a) x ->
let decl = PatBind srcLoc pat (UnGuardedRhs x) (BDecls [])
in Let (BDecls [decl]) a
Let (BDecls decls) (Let (BDecls decls') a)
-> Let (BDecls (decls ++ decls')) a
exp -> exp
data Fixity = Nonfix | Leftfix | Rightfix
deriving (Eq)
data ParensLevel
= ParensAtom
| ParensApp
| ParensInfix Fixity Int
| ParensUniverse
deriving (Eq)
lesserLevel :: ParensLevel -> ParensLevel -> Bool
lesserLevel l ParensUniverse = l /= ParensUniverse
lesserLevel ParensAtom l = l /= ParensAtom
lesserLevel ParensApp ParensInfix{} = True
lesserLevel (ParensInfix _ n1) (ParensInfix _ n2) = n1 > n2
lesserLevel _ _ = False
expLevel :: Exp -> ParensLevel
expLevel = \case
Paren{} -> ParensAtom
Var{} -> ParensAtom
Con{} -> ParensAtom
Lit{} -> ParensAtom
List{} -> ParensAtom
EnumFromTo{} -> ParensAtom
App{} -> ParensApp
InfixApp _ op _ -> ParensInfix `uncurry` whatfix op
_ -> ParensUniverse
whatfix op = maybe (Leftfix, 9) id (lookup op fixtable)
fixtable = [ (QVarOp $ HsSymbol "Prelude" ".", (Rightfix, 9))
, (QVarOp $ HsSymbol "Prelude" "!!", (Leftfix, 9))
, (QVarOp $ HsSymbol "Prelude" "+", (Leftfix, 6))
, (QVarOp $ HsSymbol "Prelude" "-", (Leftfix, 6))
, (QVarOp $ HsSymbol "Prelude" "*", (Leftfix, 7))
, (QVarOp $ HsSymbol "Prelude" "/", (Leftfix, 7))
, (QVarOp $ HsIdent "Prelude" "div", (Leftfix, 7))
, (QVarOp $ HsIdent "Prelude" "mod", (Leftfix, 7))
, (QVarOp $ HsSymbol "Prelude" "++", (Rightfix, 5))
, (QVarOp $ HsSymbol "Control.Applicative" "<$" , (Leftfix, 4))
, (QVarOp $ HsSymbol "Control.Applicative" "<$>", (Leftfix, 4))
, (QVarOp $ HsSymbol "Prelude" "==", (Nonfix, 4))
, (QVarOp $ HsSymbol "Prelude" "/=", (Nonfix, 4))
, (QVarOp $ HsSymbol "Prelude" "<", (Nonfix, 4))
, (QVarOp $ HsSymbol "Prelude" ">", (Nonfix, 4))
, (QVarOp $ HsSymbol "Prelude" "<=", (Nonfix, 4))
, (QVarOp $ HsSymbol "Prelude" ">=", (Nonfix, 4))
, (QVarOp $ HsIdent "Prelude" "elem", (Nonfix, 4))
, (QVarOp $ HsSymbol "Prelude" "&&", (Rightfix, 3))
, (QVarOp $ HsSymbol "Prelude" "||", (Rightfix, 2))
, (QVarOp $ HsSymbol "Prelude" ">>=", (Leftfix, 1))
, (QVarOp $ HsSymbol "Prelude" ">>", (Leftfix, 1))
]
| rscprof/kalium | src/Kalium/Haskell/Sugar.hs | bsd-3-clause | 10,520 | 0 | 17 | 3,042 | 4,053 | 2,012 | 2,041 | -1 | -1 |
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Module : Language.SequentCore.Pretty
-- Description : Pretty printing of Sequent Core terms
-- Maintainer : [email protected]
-- Stability : experimental
--
-- Instances and functions for pretty-printing Sequent Core terms using GHC's
-- built-in pretty printer.
module Language.SequentCore.Pretty (
pprTopLevelBinds, pprParendTerm, pprCoreKont
) where
import Language.SequentCore.Syntax
import qualified GhcPlugins as GHC
import Outputable
import PprCore ()
import Data.List
ppr_bind :: OutputableBndr b => Bind b -> SDoc
ppr_bind (NonRec pair) = ppr_binding pair
ppr_bind (Rec binds) = hang (text "rec") 2 (vcat $ intersperse space $
ppr_block (char '{') (char ';') (char '}') (map ppr_binding binds))
ppr_binds_top :: OutputableBndr b => [Bind b] -> SDoc
ppr_binds_top binds = ppr_binds_with empty empty empty binds
-- | Print the given bindings as a sequence of top-level bindings.
pprTopLevelBinds :: OutputableBndr b => [Bind b] -> SDoc
pprTopLevelBinds = ppr_binds_top
ppr_block :: SDoc -> SDoc -> SDoc -> [SDoc] -> [SDoc]
ppr_block open _ close [] = [open <> close]
ppr_block open mid close (first : rest)
= open <+> first : map (mid <+>) rest ++ [close]
ppr_binds :: OutputableBndr b => [Bind b] -> SDoc
ppr_binds binds = ppr_binds_with (char '{') (char ';') (char '}') binds
ppr_binds_with :: OutputableBndr b => SDoc -> SDoc -> SDoc -> [Bind b] -> SDoc
ppr_binds_with open mid close binds = vcat $ intersperse space $ ppr_block open mid close (map ppr_bind binds)
ppr_binding :: OutputableBndr b => BindPair b -> SDoc
ppr_binding pair
= prefix <+> pprBndr LetBind val_bdr $$
hang (ppr val_bdr <+> equals) 2 (pprDeeper $ body pair)
where
val_bdr = binderOfPair pair
body (BindTerm _ term) = ppr term
body (BindJoin _ join) = ppr join
prefix | bindsJoin pair = text "join"
| otherwise = empty
ppr_comm :: OutputableBndr b => (SDoc -> SDoc) -> Command b -> SDoc
ppr_comm add_par comm
= maybe_add_par $ ppr_let <+> ppr_cut
where
(binds, cut) = flattenCommand comm
ppr_let
| null binds = empty
| otherwise = hang (text "let") 2 (ppr_binds binds) $$ text "in"
maybe_add_par = if null binds then noParens else add_par
ppr_cut
= case cut of
Left (term, fs, end)
-> sep [char '<' <> pprCoreTerm term,
cat $ ppr_block (char '|') (char ';') (char '>') $ (ppr_kont_frames fs ++ [ppr_end end])]
Right (args, j)
-> text "jump" <+> prefix <+> ppr j <+> parens (pprDeeper $ pprWithCommas pprCoreTerm args)
where prefix | GHC.isTyVar j = text "TYVAR"
| GHC.isCoVar j = text "COVAR"
| not (isJoinId j) = text "IDVAR"
| otherwise = empty
ppr_term :: OutputableBndr b => (SDoc -> SDoc) -> Term b -> SDoc
ppr_term _ (Var name) = prefix <+> ppr name
where prefix | GHC.isTyVar name = text "TYVAR"
| isJoinId name = text "PKVAR"
| otherwise = empty
-- Something is quite wrong if it's a type variable!
ppr_term add_par (Type ty) = add_par $ text "TYPE" <+> ppr ty
ppr_term add_par (Coercion co) = add_par $ text "CO" <+> ppr co
ppr_term add_par (Lit lit) = GHC.pprLiteral add_par lit
ppr_term add_par term@(Lam {})
| Compute ty comm <- body
= add_par $
hang (char '\\' <+> fsep (map (pprBndr LambdaBind) bndrs ++
[char '|', parens (ppr_kont_bndr ty)]) <+> arrow)
2 (pprDeeper $ pprCoreComm comm)
| otherwise
= add_par $
hang (char '\\' <+> fsep (map (pprBndr LambdaBind) bndrs) <+> arrow)
2 (pprDeeper $ pprCoreTerm body)
where
(bndrs, body) = lambdas term
ppr_term add_par (Compute ty comm)
= add_par $
hang (text "compute" <+> parens (ppr_kont_bndr ty))
2 (pprCoreComm comm)
ppr_kont_frames :: OutputableBndr b => [Frame b] -> [SDoc]
ppr_kont_frames = map ppr_frame
ppr_frame :: OutputableBndr b => Frame b -> SDoc
ppr_frame (App (Type ty))
= char '@' <+> ppr ty
ppr_frame (App v)
= char '$' <+> pprDeeper (ppr_term noParens v)
ppr_frame (Cast co)
= text "cast" <+> pprDeeper (ppr co)
ppr_frame (Tick _)
= text "tick" <+> text "..."
ppr_end :: OutputableBndr b => End b -> SDoc
ppr_end Return
= text "ret"
ppr_end (Case var alts)
= hang (text "case as" <+> pprBndr LetBind var <+> text "of") 2 $ pprDeeper $
vcat $ ppr_block (char '{') (char ';') (char '}') (map pprCoreAlt alts)
ppr_kont :: OutputableBndr b => (SDoc -> SDoc) -> Kont b -> SDoc
ppr_kont add_par (frames, end)
= add_par $ sep $ punctuate semi (ppr_kont_frames frames ++ [ppr_end end])
ppr_join :: OutputableBndr b => (SDoc -> SDoc) -> Join b -> SDoc
ppr_join add_par (Join bndrs body)
= add_par $
hang (char '\\' <+> argTuple <+> arrow)
2 (pprCoreComm body)
where
argTuple
= case bndrs of
[bndr] -> pprBndr LambdaBind bndr
_ -> parens (pprWithCommas (pprBndr LambdaBind) bndrs)
ppr_kont_bndr :: GHC.Type -> SDoc
ppr_kont_bndr ty =
text "ret" <+> dcolon <+> ppr ty
pprCoreAlt :: OutputableBndr b => Alt b -> SDoc
pprCoreAlt (Alt con args rhs)
= hang (ppr_case_pat con args <+> arrow) 2 (pprCoreComm rhs)
ppr_case_pat :: OutputableBndr a => GHC.AltCon -> [a] -> SDoc
ppr_case_pat con args
= ppr con <+> fsep (map ppr_bndr args)
where
ppr_bndr = pprBndr CaseBind
pprCoreComm :: OutputableBndr b => Command b -> SDoc
pprCoreComm comm = ppr_comm noParens comm
pprCoreTerm :: OutputableBndr b => Term b -> SDoc
pprCoreTerm val = ppr_term noParens val
pprCoreKont :: OutputableBndr b => Kont b -> SDoc
pprCoreKont kont = ppr_kont noParens kont
pprParendTerm :: OutputableBndr b => Term b -> SDoc
pprParendTerm term = ppr_term parens term
noParens :: SDoc -> SDoc
noParens pp = pp
instance OutputableBndr b => Outputable (Bind b) where
ppr = ppr_bind
instance OutputableBndr b => Outputable (BindPair b) where
ppr = ppr_binding
instance OutputableBndr b => Outputable (Term b) where
ppr = ppr_term noParens
instance OutputableBndr b => Outputable (Command b) where
ppr = ppr_comm noParens
instance OutputableBndr b => Outputable (Frame b) where
ppr = ppr_frame
instance OutputableBndr b => Outputable (End b) where
ppr = ppr_end
instance OutputableBndr b => Outputable (Join b) where
ppr = ppr_join noParens
instance OutputableBndr b => Outputable (Alt b) where
ppr = pprCoreAlt
| pdownen/sequent-core | src/Language/SequentCore/Pretty.hs | bsd-3-clause | 6,544 | 0 | 17 | 1,561 | 2,375 | 1,166 | 1,209 | 140 | 3 |
{-# LANGUAGE ScopedTypeVariables, RankNTypes, TypeFamilies, FlexibleContexts, ExistentialQuantification #-}
module Main where
import Language.KansasLava
import Data.Default
import qualified Matrix
import qualified Memory
import qualified Coerce
import qualified Others
import qualified Protocols
main :: IO ()
main = do
let opt = def { verboseOpt = 4 -- 4 == show cases that failed
, testNever = ["max","min","abs","signum"] -- for now
}
testDriver opt $ take 5 $ drop 0
[ Matrix.tests
, Memory.tests
, Coerce.tests
, Others.tests
, Protocols.tests
]
| andygill/kansas-lava | tests/Main.hs | bsd-3-clause | 702 | 0 | 12 | 230 | 134 | 80 | 54 | 19 | 1 |
module ParserAux where
import DataSpec
import Data.Char
import Expressions
import Auxiliary
import Processes
printExpressions [] = []
printExpressions updates = infixString [(printExpression var) ++ " := " ++ (printExpression val) | (var,val) <- updates] ", "
data Item = DataActions [(String, ActionType)]
| DataHiding [String]
| DataParam [String]
| DataGlobal (Variable, Type) Expression
| DataRenaming [(String, String)]
| DataUntilFormula String
| DataFormula Expression
| DataEncapsulation [String]
| DataNoCommunication [String]
| DataReach [String]
| DataReachCondition Expression
| DataStateReward Expression Expression
| DataCommunication [(String, String, String)]
| DataConstant String Expression
| DataEnumType String [String]
| DataNat String
| DataQueue String
| DataRangeType String Expression Expression
| DataFunction String [([String], String)]
| ParserProcess Process
| ParserInitialProcess InitialProcessDefinition
deriving (Show, Eq)
data ActionType = None | Bool | IntRange Expression Expression deriving (Show, Eq)
data InitialProcessDefinition = InitSingleProcess InitialProcess
| InitParallel InitialProcessDefinition InitialProcessDefinition
| InitHiding [Action] InitialProcessDefinition
| InitEncapsulation [Action] InitialProcessDefinition
| InitRenaming [(Action, Action)] InitialProcessDefinition
deriving (Show, Eq)
type LineNumber = Int
data ParseResult a = Ok a | Failed String
type ParserMonad a = String -> LineNumber -> ParseResult a
getLineNo :: ParserMonad LineNumber
getLineNo = \s l -> Ok l
thenParserMonad :: ParserMonad a -> (a -> ParserMonad b) -> ParserMonad b
m `thenParserMonad ` k = \s -> \l ->
case (m s l) of
Ok a -> k a s l
Failed e -> Failed e
returnParserMonad :: a -> ParserMonad a
returnParserMonad a = \s -> \l -> Ok a
failParserMonad :: String -> ParserMonad a
failParserMonad err = \s -> \l -> Failed (err ++ " on line " ++ show l)
-- For ParserUntil:
data UntilFormula = UntilFormula ActionExpression ActionExpression deriving (Show, Eq)
data ActionExpression = ActionName String [String]
| ActionOr ActionExpression ActionExpression
| ActionNot ActionExpression
| ActionTrue
deriving (Show, Eq)
| utwente-fmt/scoop | src/ParserAux.hs | bsd-3-clause | 2,666 | 0 | 10 | 805 | 671 | 378 | 293 | 57 | 2 |
module Data.Functor.Listable
( Listable(..)
, cons0
, cons1
, cons2
, cons3
, cons4
, cons5
, cons6
, (\/)
, Listable1(..)
, tiers1
, Listable2(..)
, tiers2
, liftCons1
, liftCons2
, liftCons3
) where
import Test.LeanCheck
class Listable1 l where
liftTiers :: [[a]] -> [[l a]]
tiers1 :: (Listable a, Listable1 l) => [[l a]]
tiers1 = liftTiers tiers
class Listable2 l where
liftTiers2 :: [[a]] -> [[b]] -> [[l a b]]
tiers2 :: (Listable a, Listable b, Listable2 l) => [[l a b]]
tiers2 = liftTiers2 tiers tiers
liftCons1 :: [[a]] -> (a -> b) -> [[b]]
liftCons1 tiers f = mapT f tiers `addWeight` 1
liftCons2 :: [[a]] -> [[b]] -> (a -> b -> c) -> [[c]]
liftCons2 tiers1 tiers2 f = mapT (uncurry f) (productWith (,) tiers1 tiers2) `addWeight` 1
liftCons3 :: [[a]] -> [[b]] -> [[c]] -> (a -> b -> c -> d) -> [[d]]
liftCons3 tiers1 tiers2 tiers3 f = mapT (uncurry3 f) (productWith (\ x (y, z) -> (x, y, z)) tiers1 (liftCons2 tiers2 tiers3 (,)) ) `addWeight` 1
where uncurry3 f (a, b, c) = f a b c
-- Instances
instance Listable1 Maybe where
liftTiers tiers = cons0 Nothing \/ liftCons1 tiers Just
instance Listable2 (,) where
liftTiers2 = productWith (,)
instance Listable a => Listable1 ((,) a) where
liftTiers = liftTiers2 tiers
| robrix/ui-effects | src/Data/Functor/Listable.hs | bsd-3-clause | 1,251 | 0 | 12 | 252 | 629 | 355 | 274 | 39 | 1 |
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings, ScopedTypeVariables #-}
------------------------------------------------------------------------------
-- | This module is where all the routes and handlers are defined for your
-- site. The 'app' function is the initializer that combines everything
-- together and is exported by this module.
module Site.Site
( app
) where
------------------------------------------------------------------------------
import Control.Applicative
import Control.Concurrent (withMVar)
import Control.Monad (mzero, unless, void)
import Control.Monad.State (gets)
import Control.Monad.Trans (liftIO, lift)
import Control.Monad.Trans.Either
import Control.Error.Safe (tryJust)
import Control.Lens ((^#))
import Data.Aeson
import Data.ByteString (ByteString)
import qualified Data.Configurator as DC
import Data.Int (Int64)
import Data.Maybe
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
import qualified Data.Text.Read as T
import Data.Time (UTCTime)
import Data.Time.Format (parseTime)
import Database.SQLite.Simple as S
import Snap.Core
import Snap.Snaplet
import Snap.Snaplet.Auth hiding (save)
import Snap.Snaplet.Auth.Backends.SqliteSimple
import Snap.Snaplet.Heist
import Snap.Snaplet.Session.Backends.CookieSession
import Snap.Snaplet.SqliteSimple
import Snap.Util.FileServe
import Snap.Extras.JSON
import System.Locale (defaultTimeLocale)
import Heist()
import qualified Heist.Interpreted as I
------------------------------------------------------------------------------
import qualified Model as M
import Site.Application
import Site.Util
type H = Handler App App
-- | Render login form
handleLogin :: Maybe T.Text -> Handler App (AuthManager App) ()
handleLogin authError =
heistLocal (I.bindSplices errs) $ render "login"
where
errs = [("loginError", I.textSplice c) | c <- maybeToList authError]
-- | Handle login submit. Either redirect to '/' on success or give
-- an error. We deliberately do NOT show the AuthFailure on the login
-- error, as we don't want to reveal to visitors whether or not the
-- login exists in the user database.
handleLoginSubmit :: H ()
handleLoginSubmit =
with auth $ loginUser "login" "password" Nothing
(\_ -> handleLogin . Just $ "Unknown login or incorrect password")
(redirect "/")
-- | Logs out and redirects the user to the site index.
handleLogout :: H ()
handleLogout = with auth logout >> redirect "/"
-- | Handle new user form submit
handleNewUser :: H ()
handleNewUser =
method GET (renderNewUserForm Nothing) <|> method POST handleFormSubmit
where
handleFormSubmit = do
authUser <- with auth $ registerUser "login" "password"
either (renderNewUserForm . Just) login authUser
renderNewUserForm (err :: Maybe AuthFailure) =
heistLocal (I.bindSplices errs) $ render "new_user"
where
errs = [("newUserError", I.textSplice . T.pack . show $ c) | c <- maybeToList err]
login user =
logRunEitherT $
lift (with auth (forceLogin user) >> redirect "/")
-- | Create dummy user for unit & E2E testing
createTestUser :: H (Maybe AuthUser)
createTestUser = do
testUserExists <- with auth $ usernameExists "test"
unless testUserExists (void $ with auth $ createUser "test" "test")
loginTestUser
where
loginTestUser = do
userOrErr <- with auth $ loginByUsername "test" (ClearText "test") True
either (\_ -> return Nothing) (return . Just) userOrErr
-- | Run actions with a logged in user or go back to the login screen
withLoggedInUser :: (M.User -> H ()) -> H ()
withLoggedInUser action = do
useTestUser <- gets _testUserOverride
go =<< if useTestUser then createTestUser else with auth currentUser
where
go :: Maybe AuthUser -> H ()
go Nothing =
with auth $ handleLogin (Just "Must be logged in to view the main page")
go (Just u) = logRunEitherT $ do
uid <- tryJust "withLoggedInUser: missing uid" (userId u)
uid' <- hoistEither (reader T.decimal (unUid uid))
return $ action (M.User uid' (userLogin u))
-- | Run an IO action with an SQLite connection
withDb :: (S.Connection -> IO a) -> H a
withDb action =
withTop db . withSqlite $ \conn -> action conn
handleTodos :: H ()
handleTodos =
method GET (withLoggedInUser get) <|>
method POST (withLoggedInUser save)
where
get user = do
date <- getParam "activatesDate"
includeDone <- getParam "includeDone"
-- TODO this is getting ugly
let queryFilter = fmap (M.TodoFilter (fromMaybe True (fmap readBool includeDone)) . decodeDate) date
withDb (\c -> M.listTodos c user queryFilter) >>= writeJSON
save user = logRunEitherT $ do
todo <- lift getJSON >>= hoistEither
return $ withDb (\conn -> M.saveTodo conn user todo) >>= writeJSON
decodeDate :: ByteString -> Maybe UTCTime
decodeDate s =
parseTime defaultTimeLocale "%Y-%m-%dT%T%QZ" (T.unpack . T.decodeUtf8 $ s)
readBool :: ByteString -> Bool
readBool "true" = True
readBool "false" = False
readBool _ = error "invalid bool get parameter in todo filter params"
handleNotes :: H ()
handleNotes =
method GET (withLoggedInUser get) <|>
method POST (withLoggedInUser save)
where
get user = do
id_ <- getParam "id"
case id_ of
Nothing ->
withDb (`M.listNotes` user) >>= writeJSON
Just noteId ->
logRunEitherT $ do
nid <- hoistEither (reader T.decimal (T.decodeUtf8 noteId))
return $ withDb (\conn -> M.queryNote conn user (M.NoteId nid)) >>= writeJSON
save user = logRunEitherT $ do
n <- lift getJSON >>= hoistEither
return $ withDb (\conn -> M.saveNote conn user n) >>= writeJSON
-- TODO lot of duplicate code here, find a way to reuse
handleTags :: H ()
handleTags =
method GET (withLoggedInUser getTags)
where
getTags user = do
tags <- withDb $ \conn -> M.listTags conn user
writeJSON tags
data AddTagParams =
AddTagParams
{ atpObjectId :: Int64
, atpTag :: T.Text
}
instance FromJSON AddTagParams where
parseJSON (Object v) =
AddTagParams <$> v .: "objectId"
<*> v .: "tag"
parseJSON _ = mzero
handleTodosAddTag :: H ()
handleTodosAddTag =
method POST (withLoggedInUser go)
where
go user =
getJSON >>= either (liftIO . print) addTag
where
addTag AddTagParams{..} = do
Just tag <- withDb $ \c -> do
M.addTodoTag c user (M.TodoId atpObjectId) atpTag
M.queryTodo c user (M.TodoId atpObjectId)
writeJSON tag
handleNotesAddTag :: H ()
handleNotesAddTag =
method POST (withLoggedInUser go)
where
go user =
getJSON >>= either (liftIO . print) addTag
where
addTag AddTagParams{..} = do
Just tag <- withDb $ \c -> do
M.addNoteTag c user (M.NoteId atpObjectId) atpTag
M.queryNote c user (M.NoteId atpObjectId)
writeJSON tag
-- | Render main page
mainPage :: H ()
mainPage = withLoggedInUser (const $ serveDirectory "static")
-- | The application's routes.
routes :: [(ByteString, Handler App App ())]
routes = [ ("/login", handleLoginSubmit)
, ("/logout", handleLogout)
, ("/new_user", handleNewUser)
, ("/api/todo/tag", handleTodosAddTag)
, ("/api/todo", handleTodos)
, ("/api/note/tag", handleNotesAddTag)
, ("/api/note", handleNotes)
, ("/api/tag", handleTags)
, ("/", mainPage)
, ("/static", serveDirectory "static")
]
-- | The application initializer.
app :: SnapletInit App App
app = makeSnaplet "app" "An snaplet example application." Nothing $ do
-- addRoutes must be called before heistInit - heist wants to
-- serve "" itself which means our mainPage handler never gets a
-- chance to get called.
addRoutes routes
h <- nestSnaplet "" heist $ heistInit "templates"
s <- nestSnaplet "sess" sess $
initCookieSessionManager "site_key.txt" "hstodo" (Just (14*24*3600))
-- Initialize auth that's backed by an sqlite database
d <- nestSnaplet "db" db sqliteInit
a <- nestSnaplet "auth" auth $ initSqliteAuth sess d
cc <- getSnapletUserConfig
useTestUser <- liftIO $ DC.lookupDefault False cc "test-user-override"
-- Grab the DB connection pool from the sqlite snaplet and call
-- into the Model to create all the DB tables if necessary.
let conn = sqliteConn $ d ^# snapletValue
liftIO $ withMVar conn M.createTables
addAuthSplices auth
return $ App h s d a useTestUser
| nurpax/hstodo | src/Site/Site.hs | bsd-3-clause | 8,968 | 0 | 23 | 2,235 | 2,332 | 1,206 | 1,126 | 181 | 3 |
module HJScript.DOM.Node (
Node(..), IsNode(..),
NodeType(..), nodeTypeVal,
nodeName, nodeType, nodeValue,
ownerDocument, prefix, cloneNode
) where
import HJScript.Lang
--import HJScript.DOM.Document
import HJScript.DOM.NodeTypes
----------------------------------------------------
-- the Node object type
----------------------------------------------------
-- data Node = Node deriving Show (is in NodeTypes)
instance IsClass Node
class IsClass n => IsNode n where
castToNode :: JObject n -> JObject Node
castToNode = castObject
castFromNode :: JObject Node -> JObject n
castFromNode = castObject
instance IsNode Node where
castToNode = id
castFromNode = id
----------------------------------------------------
-- Properties for Nodes
----------------------------------------------------
-- We move all properties dealing with children, siblings
-- and parents to ElementNode, since in our simple model
-- they only make sense on (subclasses of) Element nodes
-- anyway.
nodeName :: IsNode n => Exp n -> JString
nodeName = deref "nodeName"
nodeType :: IsNode n => Exp n -> JInt
nodeType = deref "nodeType"
nodeValue :: IsNode n => Exp n -> Var String
nodeValue = derefVar "nodeValue"
ownerDocument :: IsNode n => Exp n -> Exp Document
ownerDocument = deref "ownerDocument"
prefix :: IsNode n => Exp n -> Exp String
prefix = deref "prefix"
----------------------------------------------------
-- Methods for Nodes
----------------------------------------------------
cloneNode :: IsNode n => JBool -> Exp n -> Exp n
cloneNode = methodCall "cloneNode"
| seereason/HJScript | src/HJScript/DOM/Node.hs | bsd-3-clause | 1,645 | 0 | 8 | 297 | 336 | 181 | 155 | 28 | 1 |
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE ExplicitNamespaces #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
module Drive.Interpreter
( Combo (..)
, (:+:)
, identityI
, liftL
, liftR
, copyI
, (<--->)
, chainI
, (>--->)
, combineI
, (>---<)
) where
import Control.Monad.Free (Free)
import qualified Control.Monad.Free as Free
type (:+:) = Combo
data Combo f g a
= L (f a) | R (g a)
deriving (Functor)
infixl 9 <--->
(<--->) :: (Functor f, Functor g) => (t a -> Free f a) -> (t a -> Free g a) -> (t a -> Free (f :+: g) a)
(<--->) = copyI
infixl 9 >--->
(>--->) :: (Functor f, Monad g) => (forall y. (p y -> Free f y)) -> (forall x. (f x -> g x)) -> (Free p b -> g b)
(>--->) a b = chainI b a
infixl 9 >---<
(>---<) :: (f a -> m a) -> (g a -> m a) -> ( f :+: g ) a -> m a
(>---<) = combineI
identityI :: (Functor f) => (f a -> Free f a)
identityI = Free.liftF
liftL :: (Functor f, Functor g) => Free f a -> Free (f :+: g) a
liftL = Free.hoistFree L
liftR :: (Functor f, Functor g) => Free g a -> Free (f :+: g) a
liftR = Free.hoistFree R
copyI
:: (Functor f, Functor g)
=> (t a -> Free f a)
-> (t a -> Free g a)
-> (t a -> Free (f :+: g) a)
copyI a b c
= liftL (a c) >> liftR (b c)
chainI
:: (Functor g, Monad h)
=> (forall x. (g x -> h x))
-> (forall y. (f y -> Free g y))
-> (Free f a -> h a)
chainI a b
= Free.foldFree a . Free.foldFree b
combineI
:: (f a -> m a)
-> (g a -> m a)
-> ( f :+: g ) a
-> m a
-- combineI f _ (L t) = f t
-- combineI _ f (R t) = f t
combineI f g t
= case t of
(L x) -> f x
(R x) -> g x
| palf/free-driver | packages/drive-base/lib/Drive/Interpreter.hs | bsd-3-clause | 1,867 | 0 | 12 | 552 | 868 | 468 | 400 | 65 | 2 |
module Main ( main ) where
-- import AI.SVM.Simple
import Control.Applicative
import Control.Exception ( tryJust )
import Control.Lens ( Lens', lens, (.~), view, set )
import Control.Monad ( guard, liftM )
import qualified Data.ByteString.Lazy as LBS
import qualified Data.Csv as CSV
import qualified Data.Foldable as F
import Data.Maybe ( mapMaybe )
import Data.Monoid
import qualified Data.Text.Lazy as LText
import qualified Data.Text.Lazy.Builder as LText
import qualified Data.Text.Lazy.Builder.RealFloat as LText
import qualified Data.Text.Lazy.Encoding as LText
import qualified Data.Vector as V
import qualified Data.Vector.Unboxed as UV
import Options.Applicative
import System.Environment ( getEnv )
import System.FilePath
import System.IO.Error ( isDoesNotExistError )
import Codec.Archive
import LLVM.Analysis
import LLVM.Analysis.CallGraph
import LLVM.Analysis.CallGraphSCCTraversal
import LLVM.Analysis.UsesOf
import LLVM.Analysis.Util.Testing
import LLVM.Parse
import Foreign.Inference.Diagnostics
import Foreign.Inference.Interface
import Foreign.Inference.Report
import Foreign.Inference.Preprocessing
import Foreign.Inference.Analysis.Allocator
import Foreign.Inference.Analysis.Array
import Foreign.Inference.Analysis.ErrorHandling
import Foreign.Inference.Analysis.Escape
import Foreign.Inference.Analysis.Finalize
import Foreign.Inference.Analysis.Nullable
import Foreign.Inference.Analysis.Output
import Foreign.Inference.Analysis.RefCount
import Foreign.Inference.Analysis.Return
import Foreign.Inference.Analysis.SAP
import Foreign.Inference.Analysis.SAPPTRel
import Foreign.Inference.Analysis.ScalarEffects
import Foreign.Inference.Analysis.Transfer
import Foreign.Inference.Analysis.IndirectCallResolver
import Foreign.Inference.Analysis.Util.CompositeSummary
-- | The repository location is first chosen based on an environment
-- variable. The command line argument, if specified, will override
-- it. If the environment variable is not set, the command line
-- argument must be specified.
data Opts = Opts { inputDependencies :: [String]
, repositoryLocation :: FilePath
, diagnosticLevel :: Classification
, librarySource :: Maybe FilePath
, reportDir :: Maybe FilePath
, annotationFile :: Maybe FilePath
, noErrorLearning :: Bool
, noGeneralizeErrorCodes :: Bool
, dumpErrorFeatures :: Maybe FilePath
, noLearnRCZero :: Bool
, inputFile :: FilePath
}
deriving (Show)
cmdOpts :: FilePath -> Parser Opts
cmdOpts defaultRepo = Opts
<$> many (strOption
( long "dependency"
<> short 'd'
<> metavar "DEPENDENCY"
<> help "A dependency of the library being analyzed."))
<*> strOption
( long "repository"
<> short 'r'
<> metavar "DIRECTORY"
<> value defaultRepo
<> help "The directory containing dependency summaries. The summary of the input library will be stored here. (Default: consult environment)")
<*> option auto
( long "diagnostics"
<> metavar "DIAGNOSTIC"
<> value Warning
<> help "The level of diagnostics to show (Debug, Info, Warning, Error). Default: Warning" )
<*> optional (strOption
( long "source"
<> short 's'
<> metavar "FILE"
<> help "The source for the library being analyzed (tarball or zip archive). If provided, a report will be generated"))
<*> optional (strOption
( long "report-dir"
<> short 'p'
<> metavar "DIRECTORY"
<> help "The directory in which the summary report will be produced. Defaults to the REPOSITORY."))
<*> optional (strOption
( long "annotations"
<> short 'a'
<> metavar "FILE"
<> help "An optional file containing annotations for the library being analyzed."))
<*> switch
( long "disable-func-generalization"
<> help "Disable error reporting function learning entirely. This flag overrides a specified classifier." )
<*> switch
( long "disable-rc-generalization"
<> help "Do not use known error codes to flag other blocks returning the same value as reporting errors." )
<*> optional (strOption
( long "dump-error-features"
<> metavar "FILE"
<> help "Dump error function classification feature vectors for each function in the library into the given file."))
<*> switch
( long "disable-learn-rc-zero"
<> help "Never learn the value 0 as an error code.")
<*> argument str ( metavar "FILE" )
main :: IO ()
main = do
mRepLoc <- tryJust (guard . isDoesNotExistError) (getEnv "INFERENCE_REPOSITORY")
let repLoc = either (error "No dependency repository specified") id mRepLoc
args = info (helper <*> cmdOpts repLoc)
( fullDesc
<> progDesc "Infer interface annotations for FILE (which can be bitcode or llvm assembly)"
<> header "iiglue - A frontend for the FFI Inference engine")
execParser args >>= realMain
realMain :: Opts -> IO ()
realMain opts = do
let name = takeBaseName (inputFile opts)
parseOpts = case librarySource opts of
Nothing -> defaultParserOptions { metaPositionPrecision = PositionNone }
Just _ -> defaultParserOptions
mm <- buildModule [] requiredOptimizations (parseLLVMFile parseOpts) (inputFile opts)
dump opts name mm
elns :: Lens' AnalysisSummary (Maybe ErrorSummary)
elns = lens (Just . (view errorHandlingSummary)) (\s n -> maybe s (\n' -> set errorHandlingSummary n' s) n)
dump :: Opts -> String -> Module -> IO ()
dump opts name m = do
let pta = identifyIndirectCallTargets m
cg = callGraph m pta []
deps = inputDependencies opts
repo = repositoryLocation opts
baseDeps <- loadDependencies [repo] deps
ds <- case annotationFile opts of
Nothing -> return baseDeps
Just af -> do
annots <- loadAnnotations af
return $! addManualAnnotations baseDeps annots
let classifier = DefaultClassifier
-- Have to give a type signature here to fix all of the FuncLike
-- constraints to our metadata blob.
let funcLikes :: [FunctionMetadata]
funcLikes = map fromFunction (moduleDefinedFunctions m)
uses = computeUsesOf m
errCfg = defaultErrorAnalysisOptions { errorClassifier = classifier
, generalizeFromReturns = not (noGeneralizeErrorCodes opts)
, prohibitLearnZero = noLearnRCZero opts
}
errRes = identifyErrorHandling funcLikes ds uses pta errCfg
res0 = (errorHandlingSummary .~ errRes) mempty
phase1 :: [ComposableAnalysis AnalysisSummary FunctionMetadata]
phase1 = [ identifyReturns ds returnSummary
, identifyOutput m ds outputSummary
-- Nullable will depend on the error analysis result
, identifyNullable ds nullableSummary returnSummary elns
, identifyScalarEffects scalarEffectSummary
, identifyArrays ds arraySummary
-- Finalizers will depend on nullable so that error
-- paths don't interfere with finalizers
, identifyFinalizers ds pta finalizerSummary
, identifySAPPTRels ds sapPTRelSummary
, identifySAPs ds pta sapSummary sapPTRelSummary finalizerSummary
, identifyEscapes ds pta escapeSummary
, identifyRefCounting ds refCountSummary finalizerSummary scalarEffectSummary
, identifyAllocators ds pta allocatorSummary escapeSummary finalizerSummary outputSummary
]
phase1Func = callGraphComposeAnalysis phase1
phase1Res = parallelCallGraphSCCTraversal cg phase1Func res0
-- The transferRes includes (builds on) the phase1Res. The
-- transfer analysis depends on finalizers and symbolic access paths
transferRes = identifyTransfers funcLikes cg ds pta phase1Res finalizerSummary sapSummary transferSummary
-- Extract the diagnostics from each analysis and combine them
diags = mconcat $ extractSummary transferRes (view diagnosticLens)
-- Now just take the summaries
summaries = extractSummary transferRes ModuleSummary
let errDat = errorHandlingTrainingData funcLikes ds uses pta errCfg
F.for_ (dumpErrorFeatures opts) (dumpCSV errDat)
case formatDiagnostics (diagnosticLevel opts) diags of
Nothing -> return ()
Just diagString -> putStrLn diagString
-- Persist the module summary
saveModule repo name deps m summaries ds
case (reportDir opts, librarySource opts) of
(Nothing, _) -> return ()
(Just d, Nothing) -> writeSummary m summaries ds d
(Just d, Just archive) -> writeDetailedReport m summaries ds d archive
dumpCSV :: [(Value, UV.Vector Double)] -> FilePath -> IO ()
dumpCSV dat file = LBS.writeFile file (CSV.encode dat')
where
dat' = mapMaybe prettyName dat
dblToTxt = LText.encodeUtf8 . LText.toLazyText . LText.realFloat
prettyName (v, row) = do
ident <- valueName v
let bs = LText.encodeUtf8 $ LText.fromChunks [identifierContent ident]
return $ bs : map dblToTxt (UV.toList row)
writeSummary :: Module -> [ModuleSummary] -> DependencySummary -> FilePath -> IO ()
writeSummary m summaries ds rDir = do
let rep = compileSummaryReport m summaries ds
writeHTMLSummary rep rDir
-- | Called when a source tarball was provided. This generates and
-- writes the report for the Module in the location specified by the
-- user.
writeDetailedReport :: Module -> [ModuleSummary] -> DependencySummary -> FilePath -> FilePath -> IO ()
writeDetailedReport m summaries ds rDir fp = do
arc <- readArchive fp
let rep = compileDetailedReport m arc summaries ds
writeHTMLReport rep rDir
| travitch/iiglue | tools/IIGlue.hs | bsd-3-clause | 10,217 | 0 | 23 | 2,606 | 2,098 | 1,104 | 994 | 189 | 5 |
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes, ExistentialQuantification, NoImplicitPrelude #-}
module Unfold.Pure where
import Lib hiding (foldM)
import Data.Strict.Tuple
import Data.Strict.Maybe
import Data.Strict.Drive
import qualified Prelude as P
data Unfold a = forall acc. Unfold (acc -> Pair a (Drive acc)) (Drive acc)
toUnfold :: [a] -> Unfold a
toUnfold xs = Unfold (\(x:xs) -> Pair x (finish xs)) (finish xs) where
finish = haltWhen P.null
{-# INLINEABLE toUnfold #-}
iterate :: (a -> a) -> a -> Unfold a
iterate f x = Unfold (ap Pair More . f) (More x)
{-# INLINEABLE iterate #-}
repeat :: a -> Unfold a
repeat = iterate id
{-# INLINEABLE repeat #-}
enumFrom :: Enum a => a -> Unfold a
enumFrom = iterate succ
{-# INLINEABLE enumFrom #-}
{-enumFromTo :: Enum a => a -> a -> Unfold a
enumFromTo n m = Unfold (ap Pair More . f) (More n) where
finish = haltWhen
{-# INLINEABLE enumFrom #-}-}
{-enumFrom :: Enum a => a -> Unfold a
enumFrom = iterate succ
{-# INLINEABLE enumFrom #-}-}
| effectfully/prefolds | src/Unfold/Pure.hs | bsd-3-clause | 1,060 | 0 | 11 | 190 | 263 | 145 | 118 | 18 | 1 |
module HaskQuery (
module HaskQuery.AutoIndex,
Relation,
Cont,
Control.Monad.Trans.Cont.cont,
Control.Monad.Trans.Cont.runCont,
runQueryWithCollector,
empty,
emptyWithIndex,
size,
reindex,
runQuery,
select,
runQueryM,
executeM,
selectM,
filterM,
HaskQuery.filter,
selectWithIndex,
selectWithIndexM,
selectMaybe,
selectDynamic,
selectDynamicWithTypeM,
insert,
insertRows,
insertInto,
update,
delete
) where
import qualified Data.IntMap.Lazy
import qualified Data.List
import qualified Control.Monad.Trans.Cont
import qualified Data.Typeable
import qualified Data.Dynamic
import qualified Data.Proxy
import HaskQuery.AutoIndex
data Relation a b = Relation { _relation :: Data.IntMap.Lazy.IntMap a , _lastRowId :: Int, _indices :: UpdatableIndex a b} deriving (Show)
type Cont r a = Control.Monad.Trans.Cont.Cont r a
empty :: Relation a ()
empty = Relation { _relation = Data.IntMap.Lazy.empty, _lastRowId = 0, _indices = emptyIndex }
emptyWithIndex :: UpdatableIndex a c -> Relation a c
emptyWithIndex index = reindex empty index
size :: Relation a b -> Int
size relation = Data.IntMap.Lazy.size (_relation relation)
reindex :: Relation a b -> UpdatableIndex a c -> Relation a c
reindex indexedRelation newIndex =
let originalRelation = _relation indexedRelation
in indexedRelation { _relation = originalRelation, _indices = updateAutoWithInput newIndex $ Insert $ InsertSet {inserted = originalRelation} }
runQuery :: Control.Monad.Trans.Cont.Cont ([a] -> [a]) a -> [a]
runQuery query = (Control.Monad.Trans.Cont.runCont query (\value -> (\list -> value : list))) []
runQueryWithCollector :: (a , (b -> a -> a)) -> Control.Monad.Trans.Cont.Cont (a -> a) b -> a
runQueryWithCollector (collectorSeed, collectorFunction) query = Control.Monad.Trans.Cont.runCont query (\value -> (\collector -> collectorFunction value collector)) collectorSeed
select :: Relation a c -> Control.Monad.Trans.Cont.Cont (b -> b) a
select relation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> Data.IntMap.Lazy.foldl (\foldSeed value -> continuation value foldSeed) seed (_relation relation)))
filterM :: Monad m => Bool -> Control.Monad.Trans.Cont.Cont (a -> m a) ()
filterM predicate = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> if predicate then (continuation () seed ) else return seed))
filter :: Bool -> Control.Monad.Trans.Cont.Cont (a -> a) ()
filter predicate = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> if predicate then (continuation () seed ) else seed))
runQueryM :: Monad m => Control.Monad.Trans.Cont.Cont ([a] -> m [a]) a -> m [a]
runQueryM query = (Control.Monad.Trans.Cont.runCont query (\value -> (\list -> return (value : list)))) []
selectM :: Monad m => Relation a c -> Control.Monad.Trans.Cont.Cont (b -> m b) a
selectM relation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> Data.IntMap.Lazy.foldl (\foldSeed value -> foldSeed >>= continuation value) (return seed) (_relation relation)))
executeM :: Monad m => m a -> Control.Monad.Trans.Cont.Cont (b -> m b) a
executeM computation = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> do
value <- computation
result <- continuation value seed
return result))
selectWithIndex :: (c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> b) Int) -> Relation a c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> b) a
selectWithIndex indexAccessor relation indexValue = do
rowId <- indexAccessor (readAuto $ _indices relation) indexValue
return $ (_relation relation) Data.IntMap.Lazy.! rowId
selectWithIndexM :: (Monad m) => (c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> m b) Int) -> Relation a c -> indexValue -> Control.Monad.Trans.Cont.Cont (b -> m b) a
selectWithIndexM indexAccessor relation indexValue = do
rowId <- indexAccessor (readAuto $ _indices relation) indexValue
return $ (_relation relation) Data.IntMap.Lazy.! rowId
selectMaybe :: Maybe a -> Control.Monad.Trans.Cont.Cont (b->b) a
selectMaybe maybeValue = Control.Monad.Trans.Cont.cont (\continuation -> (case maybeValue of Just value -> continuation value ; Nothing -> id))
selectDynamic :: (Data.Typeable.Typeable a) => Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->b) a
selectDynamic value = Control.Monad.Trans.Cont.cont (\continuation -> (case Data.Dynamic.fromDynamic value of Just typed -> continuation typed ; Nothing -> id))
selectDynamicWithType :: (Data.Typeable.Typeable a) => Data.Proxy.Proxy a -> Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->b) a
selectDynamicWithType proxy value = selectDynamic value
selectDynamicWithTypeM :: (Data.Typeable.Typeable a, Monad m) => Data.Proxy.Proxy a -> Data.Dynamic.Dynamic -> Control.Monad.Trans.Cont.Cont (b->m b) a
selectDynamicWithTypeM proxy value = Control.Monad.Trans.Cont.cont (\continuation -> (\seed -> (case Data.Dynamic.fromDynamic value of Just typed -> continuation typed seed ; Nothing -> return seed)))
insert :: Relation a b -> a -> Relation a b
insert indexedRelation item =
let newRowId = (_lastRowId indexedRelation) + 1
updatedRelation = Data.IntMap.Lazy.insert newRowId item (_relation indexedRelation)
updatedIndex = updateAutoWithInput (_indices indexedRelation) (Insert $ InsertSet { inserted = Data.IntMap.Lazy.singleton newRowId item})
in
Relation { _relation = updatedRelation, _lastRowId = newRowId, _indices = updatedIndex}
insertRows :: Relation a b -> [a] -> Relation a b
insertRows indexedRelation rows = Data.List.foldl' (insert) indexedRelation rows
insertInto :: Relation a b -> Control.Monad.Trans.Cont.Cont (Relation a b -> Relation a b) a -> Relation a b
insertInto indexedRelation insertContinuation =
Control.Monad.Trans.Cont.runCont insertContinuation (\ row -> (\seedIndexedRelation -> insert seedIndexedRelation row)) indexedRelation
update :: Relation a b-> (a -> Bool) -> (a -> a) -> Relation a b
update indexedRelation predicate updateFunction =
let originalRelation = (_relation indexedRelation)
affectedRows = Data.IntMap.Lazy.filter predicate originalRelation
updateMap = Data.IntMap.Lazy.map (\row -> (row, updateFunction row)) affectedRows
updatedRows = Data.IntMap.Lazy.map (\ (row, updatedRow) -> updatedRow) updateMap
updatedIndex = updateAutoWithInput (_indices indexedRelation) $ Update $ UpdateSet { updated = updateMap }
in
indexedRelation { _relation = Data.IntMap.Lazy.union updatedRows originalRelation, _indices = updatedIndex }
delete :: Relation a b -> (a -> Bool) -> Relation a b
delete indexedRelation predicate =
let
originalRelation = (_relation indexedRelation)
affectedRows = Data.IntMap.Lazy.filter predicate originalRelation
updatedRelation = Data.IntMap.Lazy.difference originalRelation affectedRows
updatedIndex = updateAutoWithInput (_indices indexedRelation) $ Delete $ DeleteSet { deleted = affectedRows }
in
indexedRelation { _relation = updatedRelation, _indices = updatedIndex}
| stevechy/HaskQuery | HaskQuery.hs | bsd-3-clause | 7,064 | 0 | 15 | 1,088 | 2,388 | 1,318 | 1,070 | 109 | 2 |
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE OverloadedStrings #-}
module Config where
import Control.Exception (throwIO)
import Control.Monad.Except (ExceptT, MonadError)
import Control.Monad.Logger (runNoLoggingT,
runStdoutLoggingT)
import Control.Monad.Reader (MonadIO, MonadReader,
ReaderT)
import Control.Monad.Trans.Maybe (MaybeT (..), runMaybeT)
import qualified Data.ByteString.Char8 as BS
import Data.Monoid ((<>))
import Database.Persist.Postgresql (ConnectionPool,
ConnectionString,
createPostgresqlPool)
import Network.Wai (Middleware)
import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev)
import Servant (ServantErr)
import System.Environment (lookupEnv)
data Config = Config
{ getPool :: ConnectionPool
, getEnv :: Environment
}
data Environment =
Development
| Test
| Production
deriving (Eq, Show, Read)
defaultConfig :: Config
defaultConfig = Config
{ getPool = undefined
, getEnv = Development
}
setLogger :: Environment -> Middleware
setLogger Test = id
setLogger Development = logStdoutDev
setLogger Production = logStdout
makePool :: Environment -> IO ConnectionPool
makePool Test =
runNoLoggingT (createPostgresqlPool (connStr "test") (envPool Test))
makePool Development =
runStdoutLoggingT (createPostgresqlPool (connStr "dev") (envPool Development))
makePool Production = do
pool <- runMaybeT $ do
let keys = [ "host="
, "port="
, "user="
, "password="
, "dbname="
]
envs = [ "PGHOST"
, "PGPORT"
, "PGUSER"
, "PGPASS"
, "PGDATABASE"
]
envVars <- traverse (MaybeT . lookupEnv) envs
let prodStr = mconcat . zipWith (<>) keys $ BS.pack <$> envVars
runStdoutLoggingT $ createPostgresqlPool prodStr (envPool Production)
case pool of
Nothing -> throwIO (userError "Database Configuration not present in environment.")
Just a -> return a
envPool :: Environment -> Int
envPool Test = 1
envPool Development = 1
envPool Production = 8
connStr :: BS.ByteString -> ConnectionString
connStr sfx = "host=localhost dbname=potteryapp_" <> sfx <> " user=anna password='' port=5432"
| annakopp/potteryapp | src/Config.hs | bsd-3-clause | 2,869 | 0 | 17 | 1,103 | 565 | 317 | 248 | 64 | 2 |
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE OverloadedStrings #-}
module Duckling.Numeral.CA.Corpus (corpus) where
import Data.String
import Prelude
import Duckling.Locale
import Duckling.Numeral.Types
import Duckling.Resolve
import Duckling.Testing.Types
corpus :: Corpus
corpus =
(testContext { locale = makeLocale CA Nothing }, testOptions, allExamples)
allExamples :: [Example]
allExamples =
concat
[ examples (NumeralValue 1)
[ "1"
, "u"
, "un"
, "una"
]
, examples (NumeralValue 11)
[ "onze"
]
, examples (NumeralValue 12)
[ "dotze"
]
, examples (NumeralValue 13)
[ "tretze"
]
, examples (NumeralValue 14)
[ "catorze"
]
, examples (NumeralValue 15)
[ "quinze"
]
, examples (NumeralValue 16)
[ "setze"
]
, examples (NumeralValue 17)
[ "disset"
, "dèsset"
]
, examples (NumeralValue 18)
[ "divuit"
, "dihuit"
, "devuit"
]
, examples (NumeralValue 19)
[ "dinou"
, "dènou"
, "denou"
]
, examples (NumeralValue 20)
[ "vint"
]
, examples (NumeralValue 21)
[ "vint-i-un"
, "vint i un"
]
, examples (NumeralValue 22)
[ "vint-i-dos"
, "vint i dos"
]
, examples (NumeralValue 23)
[ "vint-i-tres"
, "vint i tres"
]
, examples (NumeralValue 37)
[ "trenta-set"
]
, examples (NumeralValue 40)
[ "quaranta"
]
, examples (NumeralValue 70)
[ "setanta"
]
, examples (NumeralValue 78)
[ "Setanta-vuit"
]
, examples (NumeralValue 80)
[ "vuitanta"
]
, examples (NumeralValue 33)
[ "33"
, "trenta-tres"
, "trenta-3"
]
, examples (NumeralValue 100000)
[ "100000"
, "100K"
, "100k"
]
, examples (NumeralValue 300)
[ "tres-cents"
]
, examples (NumeralValue 243)
[ "243"
]
, examples (NumeralValue 85)
[ "vuitanta-cinc"
]
, examples (NumeralValue 3000000)
[ "3M"
, "3000K"
, "3000000"
]
, examples (NumeralValue 1200000)
[ "1200000"
, "1200K"
]
, examples (NumeralValue (-1200000))
[ "-1200000"
, "-1200K"
]
, examples (NumeralValue 1.5)
[ "1 coma cinc"
, "una coma cinc"
, "u coma cinc"
]
, examples (NumeralValue 1)
[ "zero u"
, "zero un"
]
, examples (NumeralValue 2)
[ "zero dos"
]
, examples (NumeralValue 3)
[ "zero tres"
]
, examples (NumeralValue 4)
[ "zero quatre"
]
, examples (NumeralValue 5)
[ "zero cinc"
]
, examples (NumeralValue 6)
[ "zero sis"
]
, examples (NumeralValue 7)
[ "zero set"
]
, examples (NumeralValue 8)
[ "zero vuit"
]
, examples (NumeralValue 9)
[ "zero nou"
]
]
-- Ull, revisar la xifra amb decimals
| facebookincubator/duckling | Duckling/Numeral/CA/Corpus.hs | bsd-3-clause | 3,421 | 0 | 11 | 1,341 | 798 | 443 | 355 | 110 | 1 |
--------------------------------------------------------------------------------
{-# LANGUAGE OverloadedStrings #-}
module NumberSix.Handlers.Weather.Tests
( tests
) where
--------------------------------------------------------------------------------
import Data.Maybe (fromJust)
import Test.Framework (Test, testGroup)
import Test.HUnit (assert)
--------------------------------------------------------------------------------
import NumberSix.Handlers.Weather
import NumberSix.Tests.Util
--------------------------------------------------------------------------------
tests :: Test
tests = testGroup "NumberSix.Handlers.Weather.Tests"
[ cases "weather"
[ do
result <- getWeather "gent"
let (Weather (Temperature t) _) = fromJust result
assert $ -15 <= t && t <= 60
]
]
| jaspervdj/number-six | tests/NumberSix/Handlers/Weather/Tests.hs | bsd-3-clause | 943 | 0 | 17 | 232 | 147 | 82 | 65 | 15 | 1 |
{-# LANGUAGE ImplicitParams #-}
module Main where
import JKF.Parser.Kif
import Data.Encoding
import Data.Encoding.ISO2022JP
-- import Data.Encoding.CP932
import System.IO.Encoding (readFile)
import Prelude hiding (readFile)
import Control.Applicative ((<$>))
main :: IO ()
main = do
let ?enc = ISO2022JP
-- s <- System.IO.Encoding.readFile "../json-kifu-format/test/files/kif/9fu.kif"
s <- readTestKif "../json-kifu-format/test/files/kif/9fu.kif"
print $ parseKifu s
-- let bs = Data.Encoding.encodeLazyByteString ISO2022JP s
-- let sbs = Codec.Text.IConv.convert "ISO-2022-JP" "CP932" bs
-- let ss = Data.Encoding.decodeLazyByteString CP932 sbs
-- let ?enc = CP932
-- System.IO.Encoding.putStrLn ss
return ()
readTestKif filepath = do
let ?enc = ISO2022JP
System.IO.Encoding.readFile filepath
| suzuki-shin/jkf-hs | app/Main.hs | bsd-3-clause | 841 | 0 | 9 | 139 | 140 | 79 | 61 | 17 | 1 |
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1993-1998
-}
{-# LANGUAGE CPP #-}
{-# LANGUAGE LambdaCase #-}
module GHC.Iface.Syntax (
module GHC.Iface.Type,
IfaceDecl(..), IfaceFamTyConFlav(..), IfaceClassOp(..), IfaceAT(..),
IfaceConDecl(..), IfaceConDecls(..), IfaceEqSpec,
IfaceExpr(..), IfaceAlt, IfaceLetBndr(..), IfaceJoinInfo(..),
IfaceBinding(..), IfaceConAlt(..),
IfaceIdInfo(..), IfaceIdDetails(..), IfaceUnfolding(..),
IfaceInfoItem(..), IfaceRule(..), IfaceAnnotation(..), IfaceAnnTarget,
IfaceClsInst(..), IfaceFamInst(..), IfaceTickish(..),
IfaceClassBody(..),
IfaceBang(..),
IfaceSrcBang(..), SrcUnpackedness(..), SrcStrictness(..),
IfaceAxBranch(..),
IfaceTyConParent(..),
IfaceCompleteMatch(..),
-- * Binding names
IfaceTopBndr,
putIfaceTopBndr, getIfaceTopBndr,
-- Misc
ifaceDeclImplicitBndrs, visibleIfConDecls,
ifaceDeclFingerprints,
-- Free Names
freeNamesIfDecl, freeNamesIfRule, freeNamesIfFamInst,
-- Pretty printing
pprIfaceExpr,
pprIfaceDecl,
AltPpr(..), ShowSub(..), ShowHowMuch(..), showToIface, showToHeader
) where
#include "HsVersions.h"
import GhcPrelude
import GHC.Iface.Type
import BinFingerprint
import CoreSyn( IsOrphan, isOrphan )
import DynFlags( gopt, GeneralFlag (Opt_PrintAxiomIncomps) )
import Demand
import Class
import FieldLabel
import NameSet
import CoAxiom ( BranchIndex )
import Name
import CostCentre
import Literal
import ForeignCall
import Annotations( AnnPayload, AnnTarget )
import BasicTypes
import Outputable
import Module
import SrcLoc
import Fingerprint
import Binary
import BooleanFormula ( BooleanFormula, pprBooleanFormula, isTrue )
import Var( VarBndr(..), binderVar )
import TyCon ( Role (..), Injectivity(..), tyConBndrVisArgFlag )
import Util( dropList, filterByList, notNull, unzipWith, debugIsOn )
import DataCon (SrcStrictness(..), SrcUnpackedness(..))
import Lexeme (isLexSym)
import TysWiredIn ( constraintKindTyConName )
import Util (seqList)
import Control.Monad
import System.IO.Unsafe
import Control.DeepSeq
infixl 3 &&&
{-
************************************************************************
* *
Declarations
* *
************************************************************************
-}
-- | A binding top-level 'Name' in an interface file (e.g. the name of an
-- 'IfaceDecl').
type IfaceTopBndr = Name
-- It's convenient to have a Name in the Iface syntax, although in each
-- case the namespace is implied by the context. However, having a
-- Name makes things like ifaceDeclImplicitBndrs and ifaceDeclFingerprints
-- very convenient. Moreover, having the key of the binder means that
-- we can encode known-key things cleverly in the symbol table. See Note
-- [Symbol table representation of Names]
--
-- We don't serialise the namespace onto the disk though; rather we
-- drop it when serialising and add it back in when deserialising.
getIfaceTopBndr :: BinHandle -> IO IfaceTopBndr
getIfaceTopBndr bh = get bh
putIfaceTopBndr :: BinHandle -> IfaceTopBndr -> IO ()
putIfaceTopBndr bh name =
case getUserData bh of
UserData{ ud_put_binding_name = put_binding_name } ->
--pprTrace "putIfaceTopBndr" (ppr name) $
put_binding_name bh name
data IfaceDecl
= IfaceId { ifName :: IfaceTopBndr,
ifType :: IfaceType,
ifIdDetails :: IfaceIdDetails,
ifIdInfo :: IfaceIdInfo }
| IfaceData { ifName :: IfaceTopBndr, -- Type constructor
ifBinders :: [IfaceTyConBinder],
ifResKind :: IfaceType, -- Result kind of type constructor
ifCType :: Maybe CType, -- C type for CAPI FFI
ifRoles :: [Role], -- Roles
ifCtxt :: IfaceContext, -- The "stupid theta"
ifCons :: IfaceConDecls, -- Includes new/data/data family info
ifGadtSyntax :: Bool, -- True <=> declared using
-- GADT syntax
ifParent :: IfaceTyConParent -- The axiom, for a newtype,
-- or data/newtype family instance
}
| IfaceSynonym { ifName :: IfaceTopBndr, -- Type constructor
ifRoles :: [Role], -- Roles
ifBinders :: [IfaceTyConBinder],
ifResKind :: IfaceKind, -- Kind of the *result*
ifSynRhs :: IfaceType }
| IfaceFamily { ifName :: IfaceTopBndr, -- Type constructor
ifResVar :: Maybe IfLclName, -- Result variable name, used
-- only for pretty-printing
-- with --show-iface
ifBinders :: [IfaceTyConBinder],
ifResKind :: IfaceKind, -- Kind of the *tycon*
ifFamFlav :: IfaceFamTyConFlav,
ifFamInj :: Injectivity } -- injectivity information
| IfaceClass { ifName :: IfaceTopBndr, -- Name of the class TyCon
ifRoles :: [Role], -- Roles
ifBinders :: [IfaceTyConBinder],
ifFDs :: [FunDep IfLclName], -- Functional dependencies
ifBody :: IfaceClassBody -- Methods, superclasses, ATs
}
| IfaceAxiom { ifName :: IfaceTopBndr, -- Axiom name
ifTyCon :: IfaceTyCon, -- LHS TyCon
ifRole :: Role, -- Role of axiom
ifAxBranches :: [IfaceAxBranch] -- Branches
}
| IfacePatSyn { ifName :: IfaceTopBndr, -- Name of the pattern synonym
ifPatIsInfix :: Bool,
ifPatMatcher :: (IfExtName, Bool),
ifPatBuilder :: Maybe (IfExtName, Bool),
-- Everything below is redundant,
-- but needed to implement pprIfaceDecl
ifPatUnivBndrs :: [IfaceForAllBndr],
ifPatExBndrs :: [IfaceForAllBndr],
ifPatProvCtxt :: IfaceContext,
ifPatReqCtxt :: IfaceContext,
ifPatArgs :: [IfaceType],
ifPatTy :: IfaceType,
ifFieldLabels :: [FieldLabel] }
-- See also 'ClassBody'
data IfaceClassBody
-- Abstract classes don't specify their body; they only occur in @hs-boot@ and
-- @hsig@ files.
= IfAbstractClass
| IfConcreteClass {
ifClassCtxt :: IfaceContext, -- Super classes
ifATs :: [IfaceAT], -- Associated type families
ifSigs :: [IfaceClassOp], -- Method signatures
ifMinDef :: BooleanFormula IfLclName -- Minimal complete definition
}
data IfaceTyConParent
= IfNoParent
| IfDataInstance
IfExtName -- Axiom name
IfaceTyCon -- Family TyCon (pretty-printing only, not used in GHC.IfaceToCore)
-- see Note [Pretty printing via Iface syntax] in PprTyThing
IfaceAppArgs -- Arguments of the family TyCon
data IfaceFamTyConFlav
= IfaceDataFamilyTyCon -- Data family
| IfaceOpenSynFamilyTyCon
| IfaceClosedSynFamilyTyCon (Maybe (IfExtName, [IfaceAxBranch]))
-- ^ Name of associated axiom and branches for pretty printing purposes,
-- or 'Nothing' for an empty closed family without an axiom
-- See Note [Pretty printing via Iface syntax] in PprTyThing
| IfaceAbstractClosedSynFamilyTyCon
| IfaceBuiltInSynFamTyCon -- for pretty printing purposes only
data IfaceClassOp
= IfaceClassOp IfaceTopBndr
IfaceType -- Class op type
(Maybe (DefMethSpec IfaceType)) -- Default method
-- The types of both the class op itself,
-- and the default method, are *not* quantified
-- over the class variables
data IfaceAT = IfaceAT -- See Class.ClassATItem
IfaceDecl -- The associated type declaration
(Maybe IfaceType) -- Default associated type instance, if any
-- This is just like CoAxBranch
data IfaceAxBranch = IfaceAxBranch { ifaxbTyVars :: [IfaceTvBndr]
, ifaxbEtaTyVars :: [IfaceTvBndr]
, ifaxbCoVars :: [IfaceIdBndr]
, ifaxbLHS :: IfaceAppArgs
, ifaxbRoles :: [Role]
, ifaxbRHS :: IfaceType
, ifaxbIncomps :: [BranchIndex] }
-- See Note [Storing compatibility] in CoAxiom
data IfaceConDecls
= IfAbstractTyCon -- c.f TyCon.AbstractTyCon
| IfDataTyCon [IfaceConDecl] -- Data type decls
| IfNewTyCon IfaceConDecl -- Newtype decls
-- For IfDataTyCon and IfNewTyCon we store:
-- * the data constructor(s);
-- The field labels are stored individually in the IfaceConDecl
-- (there is some redundancy here, because a field label may occur
-- in multiple IfaceConDecls and represent the same field label)
data IfaceConDecl
= IfCon {
ifConName :: IfaceTopBndr, -- Constructor name
ifConWrapper :: Bool, -- True <=> has a wrapper
ifConInfix :: Bool, -- True <=> declared infix
-- The universal type variables are precisely those
-- of the type constructor of this data constructor
-- This is *easy* to guarantee when creating the IfCon
-- but it's not so easy for the original TyCon/DataCon
-- So this guarantee holds for IfaceConDecl, but *not* for DataCon
ifConExTCvs :: [IfaceBndr], -- Existential ty/covars
ifConUserTvBinders :: [IfaceForAllBndr],
-- The tyvars, in the order the user wrote them
-- INVARIANT: the set of tyvars in ifConUserTvBinders is exactly the
-- set of tyvars (*not* covars) of ifConExTCvs, unioned
-- with the set of ifBinders (from the parent IfaceDecl)
-- whose tyvars do not appear in ifConEqSpec
-- See Note [DataCon user type variable binders] in DataCon
ifConEqSpec :: IfaceEqSpec, -- Equality constraints
ifConCtxt :: IfaceContext, -- Non-stupid context
ifConArgTys :: [IfaceType], -- Arg types
ifConFields :: [FieldLabel], -- ...ditto... (field labels)
ifConStricts :: [IfaceBang],
-- Empty (meaning all lazy),
-- or 1-1 corresp with arg tys
-- See Note [Bangs on imported data constructors] in MkId
ifConSrcStricts :: [IfaceSrcBang] } -- empty meaning no src stricts
type IfaceEqSpec = [(IfLclName,IfaceType)]
-- | This corresponds to an HsImplBang; that is, the final
-- implementation decision about the data constructor arg
data IfaceBang
= IfNoBang | IfStrict | IfUnpack | IfUnpackCo IfaceCoercion
-- | This corresponds to HsSrcBang
data IfaceSrcBang
= IfSrcBang SrcUnpackedness SrcStrictness
data IfaceClsInst
= IfaceClsInst { ifInstCls :: IfExtName, -- See comments with
ifInstTys :: [Maybe IfaceTyCon], -- the defn of ClsInst
ifDFun :: IfExtName, -- The dfun
ifOFlag :: OverlapFlag, -- Overlap flag
ifInstOrph :: IsOrphan } -- See Note [Orphans] in InstEnv
-- There's always a separate IfaceDecl for the DFun, which gives
-- its IdInfo with its full type and version number.
-- The instance declarations taken together have a version number,
-- and we don't want that to wobble gratuitously
-- If this instance decl is *used*, we'll record a usage on the dfun;
-- and if the head does not change it won't be used if it wasn't before
-- The ifFamInstTys field of IfaceFamInst contains a list of the rough
-- match types
data IfaceFamInst
= IfaceFamInst { ifFamInstFam :: IfExtName -- Family name
, ifFamInstTys :: [Maybe IfaceTyCon] -- See above
, ifFamInstAxiom :: IfExtName -- The axiom
, ifFamInstOrph :: IsOrphan -- Just like IfaceClsInst
}
data IfaceRule
= IfaceRule {
ifRuleName :: RuleName,
ifActivation :: Activation,
ifRuleBndrs :: [IfaceBndr], -- Tyvars and term vars
ifRuleHead :: IfExtName, -- Head of lhs
ifRuleArgs :: [IfaceExpr], -- Args of LHS
ifRuleRhs :: IfaceExpr,
ifRuleAuto :: Bool,
ifRuleOrph :: IsOrphan -- Just like IfaceClsInst
}
data IfaceAnnotation
= IfaceAnnotation {
ifAnnotatedTarget :: IfaceAnnTarget,
ifAnnotatedValue :: AnnPayload
}
type IfaceAnnTarget = AnnTarget OccName
data IfaceCompleteMatch = IfaceCompleteMatch [IfExtName] IfExtName
instance Outputable IfaceCompleteMatch where
ppr (IfaceCompleteMatch cls ty) = text "COMPLETE" <> colon <+> ppr cls
<+> dcolon <+> ppr ty
-- Here's a tricky case:
-- * Compile with -O module A, and B which imports A.f
-- * Change function f in A, and recompile without -O
-- * When we read in old A.hi we read in its IdInfo (as a thunk)
-- (In earlier GHCs we used to drop IdInfo immediately on reading,
-- but we do not do that now. Instead it's discarded when the
-- ModIface is read into the various decl pools.)
-- * The version comparison sees that new (=NoInfo) differs from old (=HasInfo *)
-- and so gives a new version.
data IfaceIdInfo
= NoInfo -- When writing interface file without -O
| HasInfo [IfaceInfoItem] -- Has info, and here it is
data IfaceInfoItem
= HsArity Arity
| HsStrictness StrictSig
| HsInline InlinePragma
| HsUnfold Bool -- True <=> isStrongLoopBreaker is true
IfaceUnfolding -- See Note [Expose recursive functions]
| HsNoCafRefs
| HsLevity -- Present <=> never levity polymorphic
-- NB: Specialisations and rules come in separately and are
-- only later attached to the Id. Partial reason: some are orphans.
data IfaceUnfolding
= IfCoreUnfold Bool IfaceExpr -- True <=> INLINABLE, False <=> regular unfolding
-- Possibly could eliminate the Bool here, the information
-- is also in the InlinePragma.
| IfCompulsory IfaceExpr -- Only used for default methods, in fact
| IfInlineRule Arity -- INLINE pragmas
Bool -- OK to inline even if *un*-saturated
Bool -- OK to inline even if context is boring
IfaceExpr
| IfDFunUnfold [IfaceBndr] [IfaceExpr]
-- We only serialise the IdDetails of top-level Ids, and even then
-- we only need a very limited selection. Notably, none of the
-- implicit ones are needed here, because they are not put it
-- interface files
data IfaceIdDetails
= IfVanillaId
| IfRecSelId (Either IfaceTyCon IfaceDecl) Bool
| IfDFunId
{-
Note [Versioning of instances]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
See [https://gitlab.haskell.org/ghc/ghc/wikis/commentary/compiler/recompilation-avoidance#instances]
************************************************************************
* *
Functions over declarations
* *
************************************************************************
-}
visibleIfConDecls :: IfaceConDecls -> [IfaceConDecl]
visibleIfConDecls IfAbstractTyCon = []
visibleIfConDecls (IfDataTyCon cs) = cs
visibleIfConDecls (IfNewTyCon c) = [c]
ifaceDeclImplicitBndrs :: IfaceDecl -> [OccName]
-- *Excludes* the 'main' name, but *includes* the implicitly-bound names
-- Deeply revolting, because it has to predict what gets bound,
-- especially the question of whether there's a wrapper for a datacon
-- See Note [Implicit TyThings] in HscTypes
-- N.B. the set of names returned here *must* match the set of
-- TyThings returned by HscTypes.implicitTyThings, in the sense that
-- TyThing.getOccName should define a bijection between the two lists.
-- This invariant is used in GHC.Iface.Load.loadDecl (see note [Tricky iface loop])
-- The order of the list does not matter.
ifaceDeclImplicitBndrs (IfaceData {ifName = tc_name, ifCons = cons })
= case cons of
IfAbstractTyCon -> []
IfNewTyCon cd -> mkNewTyCoOcc (occName tc_name) : ifaceConDeclImplicitBndrs cd
IfDataTyCon cds -> concatMap ifaceConDeclImplicitBndrs cds
ifaceDeclImplicitBndrs (IfaceClass { ifBody = IfAbstractClass })
= []
ifaceDeclImplicitBndrs (IfaceClass { ifName = cls_tc_name
, ifBody = IfConcreteClass {
ifClassCtxt = sc_ctxt,
ifSigs = sigs,
ifATs = ats
}})
= -- (possibly) newtype coercion
co_occs ++
-- data constructor (DataCon namespace)
-- data worker (Id namespace)
-- no wrapper (class dictionaries never have a wrapper)
[dc_occ, dcww_occ] ++
-- associated types
[occName (ifName at) | IfaceAT at _ <- ats ] ++
-- superclass selectors
[mkSuperDictSelOcc n cls_tc_occ | n <- [1..n_ctxt]] ++
-- operation selectors
[occName op | IfaceClassOp op _ _ <- sigs]
where
cls_tc_occ = occName cls_tc_name
n_ctxt = length sc_ctxt
n_sigs = length sigs
co_occs | is_newtype = [mkNewTyCoOcc cls_tc_occ]
| otherwise = []
dcww_occ = mkDataConWorkerOcc dc_occ
dc_occ = mkClassDataConOcc cls_tc_occ
is_newtype = n_sigs + n_ctxt == 1 -- Sigh (keep this synced with buildClass)
ifaceDeclImplicitBndrs _ = []
ifaceConDeclImplicitBndrs :: IfaceConDecl -> [OccName]
ifaceConDeclImplicitBndrs (IfCon {
ifConWrapper = has_wrapper, ifConName = con_name })
= [occName con_name, work_occ] ++ wrap_occs
where
con_occ = occName con_name
work_occ = mkDataConWorkerOcc con_occ -- Id namespace
wrap_occs | has_wrapper = [mkDataConWrapperOcc con_occ] -- Id namespace
| otherwise = []
-- -----------------------------------------------------------------------------
-- The fingerprints of an IfaceDecl
-- We better give each name bound by the declaration a
-- different fingerprint! So we calculate the fingerprint of
-- each binder by combining the fingerprint of the whole
-- declaration with the name of the binder. (#5614, #7215)
ifaceDeclFingerprints :: Fingerprint -> IfaceDecl -> [(OccName,Fingerprint)]
ifaceDeclFingerprints hash decl
= (getOccName decl, hash) :
[ (occ, computeFingerprint' (hash,occ))
| occ <- ifaceDeclImplicitBndrs decl ]
where
computeFingerprint' =
unsafeDupablePerformIO
. computeFingerprint (panic "ifaceDeclFingerprints")
{-
************************************************************************
* *
Expressions
* *
************************************************************************
-}
data IfaceExpr
= IfaceLcl IfLclName
| IfaceExt IfExtName
| IfaceType IfaceType
| IfaceCo IfaceCoercion
| IfaceTuple TupleSort [IfaceExpr] -- Saturated; type arguments omitted
| IfaceLam IfaceLamBndr IfaceExpr
| IfaceApp IfaceExpr IfaceExpr
| IfaceCase IfaceExpr IfLclName [IfaceAlt]
| IfaceECase IfaceExpr IfaceType -- See Note [Empty case alternatives]
| IfaceLet IfaceBinding IfaceExpr
| IfaceCast IfaceExpr IfaceCoercion
| IfaceLit Literal
| IfaceFCall ForeignCall IfaceType
| IfaceTick IfaceTickish IfaceExpr -- from Tick tickish E
data IfaceTickish
= IfaceHpcTick Module Int -- from HpcTick x
| IfaceSCC CostCentre Bool Bool -- from ProfNote
| IfaceSource RealSrcSpan String -- from SourceNote
-- no breakpoints: we never export these into interface files
type IfaceAlt = (IfaceConAlt, [IfLclName], IfaceExpr)
-- Note: IfLclName, not IfaceBndr (and same with the case binder)
-- We reconstruct the kind/type of the thing from the context
-- thus saving bulk in interface files
data IfaceConAlt = IfaceDefault
| IfaceDataAlt IfExtName
| IfaceLitAlt Literal
data IfaceBinding
= IfaceNonRec IfaceLetBndr IfaceExpr
| IfaceRec [(IfaceLetBndr, IfaceExpr)]
-- IfaceLetBndr is like IfaceIdBndr, but has IdInfo too
-- It's used for *non-top-level* let/rec binders
-- See Note [IdInfo on nested let-bindings]
data IfaceLetBndr = IfLetBndr IfLclName IfaceType IfaceIdInfo IfaceJoinInfo
data IfaceJoinInfo = IfaceNotJoinPoint
| IfaceJoinPoint JoinArity
{-
Note [Empty case alternatives]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In Iface syntax an IfaceCase does not record the types of the alternatives,
unlike Core syntax Case. But we need this type if the alternatives are empty.
Hence IfaceECase. See Note [Empty case alternatives] in CoreSyn.
Note [Expose recursive functions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
For supercompilation we want to put *all* unfoldings in the interface
file, even for functions that are recursive (or big). So we need to
know when an unfolding belongs to a loop-breaker so that we can refrain
from inlining it (except during supercompilation).
Note [IdInfo on nested let-bindings]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Occasionally we want to preserve IdInfo on nested let bindings. The one
that came up was a NOINLINE pragma on a let-binding inside an INLINE
function. The user (Duncan Coutts) really wanted the NOINLINE control
to cross the separate compilation boundary.
In general we retain all info that is left by CoreTidy.tidyLetBndr, since
that is what is seen by importing module with --make
Note [Displaying axiom incompatibilities]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
With -fprint-axiom-incomps we display which closed type family equations
are incompatible with which. This information is sometimes necessary
because GHC doesn't try equations in order: any equation can be used when
all preceding equations that are incompatible with it do not apply.
For example, the last "a && a = a" equation in Data.Type.Bool.&& is
actually compatible with all previous equations, and can reduce at any
time.
This is displayed as:
Prelude> :i Data.Type.Equality.==
type family (==) (a :: k) (b :: k) :: Bool
where
{- #0 -} (==) (f a) (g b) = (f == g) && (a == b)
{- #1 -} (==) a a = 'True
-- incompatible with: #0
{- #2 -} (==) _1 _2 = 'False
-- incompatible with: #1, #0
The comment after an equation refers to all previous equations (0-indexed)
that are incompatible with it.
************************************************************************
* *
Printing IfaceDecl
* *
************************************************************************
-}
pprAxBranch :: SDoc -> BranchIndex -> IfaceAxBranch -> SDoc
-- The TyCon might be local (just an OccName), or this might
-- be a branch for an imported TyCon, so it would be an ExtName
-- So it's easier to take an SDoc here
--
-- This function is used
-- to print interface files,
-- in debug messages
-- in :info F for GHCi, which goes via toConToIfaceDecl on the family tycon
-- For user error messages we use Coercion.pprCoAxiom and friends
pprAxBranch pp_tc idx (IfaceAxBranch { ifaxbTyVars = tvs
, ifaxbCoVars = _cvs
, ifaxbLHS = pat_tys
, ifaxbRHS = rhs
, ifaxbIncomps = incomps })
= ASSERT2( null _cvs, pp_tc $$ ppr _cvs )
hang ppr_binders 2 (hang pp_lhs 2 (equals <+> ppr rhs))
$+$
nest 4 maybe_incomps
where
-- See Note [Printing foralls in type family instances] in GHC.Iface.Type
ppr_binders = maybe_index <+>
pprUserIfaceForAll (map (mkIfaceForAllTvBndr Specified) tvs)
pp_lhs = hang pp_tc 2 (pprParendIfaceAppArgs pat_tys)
-- See Note [Displaying axiom incompatibilities]
maybe_index
= sdocWithDynFlags $ \dflags ->
ppWhen (gopt Opt_PrintAxiomIncomps dflags) $
text "{-" <+> (text "#" <> ppr idx) <+> text "-}"
maybe_incomps
= sdocWithDynFlags $ \dflags ->
ppWhen (gopt Opt_PrintAxiomIncomps dflags && notNull incomps) $
text "--" <+> text "incompatible with:"
<+> pprWithCommas (\incomp -> text "#" <> ppr incomp) incomps
instance Outputable IfaceAnnotation where
ppr (IfaceAnnotation target value) = ppr target <+> colon <+> ppr value
instance NamedThing IfaceClassOp where
getName (IfaceClassOp n _ _) = n
instance HasOccName IfaceClassOp where
occName = getOccName
instance NamedThing IfaceConDecl where
getName = ifConName
instance HasOccName IfaceConDecl where
occName = getOccName
instance NamedThing IfaceDecl where
getName = ifName
instance HasOccName IfaceDecl where
occName = getOccName
instance Outputable IfaceDecl where
ppr = pprIfaceDecl showToIface
{-
Note [Minimal complete definition] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The minimal complete definition should only be included if a complete
class definition is shown. Since the minimal complete definition is
anonymous we can't reuse the same mechanism that is used for the
filtering of method signatures. Instead we just check if anything at all is
filtered and hide it in that case.
-}
data ShowSub
= ShowSub
{ ss_how_much :: ShowHowMuch
, ss_forall :: ShowForAllFlag }
-- See Note [Printing IfaceDecl binders]
-- The alternative pretty printer referred to in the note.
newtype AltPpr = AltPpr (Maybe (OccName -> SDoc))
data ShowHowMuch
= ShowHeader AltPpr -- ^Header information only, not rhs
| ShowSome [OccName] AltPpr
-- ^ Show only some sub-components. Specifically,
--
-- [@[]@] Print all sub-components.
-- [@(n:ns)@] Print sub-component @n@ with @ShowSub = ns@;
-- elide other sub-components to @...@
-- May 14: the list is max 1 element long at the moment
| ShowIface
-- ^Everything including GHC-internal information (used in --show-iface)
{-
Note [Printing IfaceDecl binders]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The binders in an IfaceDecl are just OccNames, so we don't know what module they
come from. But when we pretty-print a TyThing by converting to an IfaceDecl
(see PprTyThing), the TyThing may come from some other module so we really need
the module qualifier. We solve this by passing in a pretty-printer for the
binders.
When printing an interface file (--show-iface), we want to print
everything unqualified, so we can just print the OccName directly.
-}
instance Outputable ShowHowMuch where
ppr (ShowHeader _) = text "ShowHeader"
ppr ShowIface = text "ShowIface"
ppr (ShowSome occs _) = text "ShowSome" <+> ppr occs
showToHeader :: ShowSub
showToHeader = ShowSub { ss_how_much = ShowHeader $ AltPpr Nothing
, ss_forall = ShowForAllWhen }
showToIface :: ShowSub
showToIface = ShowSub { ss_how_much = ShowIface
, ss_forall = ShowForAllWhen }
ppShowIface :: ShowSub -> SDoc -> SDoc
ppShowIface (ShowSub { ss_how_much = ShowIface }) doc = doc
ppShowIface _ _ = Outputable.empty
-- show if all sub-components or the complete interface is shown
ppShowAllSubs :: ShowSub -> SDoc -> SDoc -- Note [Minimal complete definition]
ppShowAllSubs (ShowSub { ss_how_much = ShowSome [] _ }) doc = doc
ppShowAllSubs (ShowSub { ss_how_much = ShowIface }) doc = doc
ppShowAllSubs _ _ = Outputable.empty
ppShowRhs :: ShowSub -> SDoc -> SDoc
ppShowRhs (ShowSub { ss_how_much = ShowHeader _ }) _ = Outputable.empty
ppShowRhs _ doc = doc
showSub :: HasOccName n => ShowSub -> n -> Bool
showSub (ShowSub { ss_how_much = ShowHeader _ }) _ = False
showSub (ShowSub { ss_how_much = ShowSome (n:_) _ }) thing = n == occName thing
showSub (ShowSub { ss_how_much = _ }) _ = True
ppr_trim :: [Maybe SDoc] -> [SDoc]
-- Collapse a group of Nothings to a single "..."
ppr_trim xs
= snd (foldr go (False, []) xs)
where
go (Just doc) (_, so_far) = (False, doc : so_far)
go Nothing (True, so_far) = (True, so_far)
go Nothing (False, so_far) = (True, text "..." : so_far)
isIfaceDataInstance :: IfaceTyConParent -> Bool
isIfaceDataInstance IfNoParent = False
isIfaceDataInstance _ = True
pprClassRoles :: ShowSub -> IfaceTopBndr -> [IfaceTyConBinder] -> [Role] -> SDoc
pprClassRoles ss clas binders roles =
pprRoles (== Nominal)
(pprPrefixIfDeclBndr (ss_how_much ss) (occName clas))
binders
roles
pprClassStandaloneKindSig :: ShowSub -> IfaceTopBndr -> IfaceKind -> SDoc
pprClassStandaloneKindSig ss clas =
pprStandaloneKindSig (pprPrefixIfDeclBndr (ss_how_much ss) (occName clas))
constraintIfaceKind :: IfaceKind
constraintIfaceKind =
IfaceTyConApp (IfaceTyCon constraintKindTyConName (IfaceTyConInfo NotPromoted IfaceNormalTyCon)) IA_Nil
pprIfaceDecl :: ShowSub -> IfaceDecl -> SDoc
-- NB: pprIfaceDecl is also used for pretty-printing TyThings in GHCi
-- See Note [Pretty-printing TyThings] in PprTyThing
pprIfaceDecl ss (IfaceData { ifName = tycon, ifCType = ctype,
ifCtxt = context, ifResKind = kind,
ifRoles = roles, ifCons = condecls,
ifParent = parent,
ifGadtSyntax = gadt,
ifBinders = binders })
| gadt = vcat [ pp_roles
, pp_ki_sig
, pp_nd <+> pp_lhs <+> pp_kind <+> pp_where
, nest 2 (vcat pp_cons)
, nest 2 $ ppShowIface ss pp_extra ]
| otherwise = vcat [ pp_roles
, pp_ki_sig
, hang (pp_nd <+> pp_lhs) 2 (add_bars pp_cons)
, nest 2 $ ppShowIface ss pp_extra ]
where
is_data_instance = isIfaceDataInstance parent
-- See Note [Printing foralls in type family instances] in GHC.Iface.Type
pp_data_inst_forall :: SDoc
pp_data_inst_forall = pprUserIfaceForAll forall_bndrs
forall_bndrs :: [IfaceForAllBndr]
forall_bndrs = [Bndr (binderVar tc_bndr) Specified | tc_bndr <- binders]
cons = visibleIfConDecls condecls
pp_where = ppWhen (gadt && not (null cons)) $ text "where"
pp_cons = ppr_trim (map show_con cons) :: [SDoc]
pp_kind = ppUnless (if ki_sig_printable
then isIfaceTauType kind
-- Even in the presence of a standalone kind signature, a non-tau
-- result kind annotation cannot be discarded as it determines the arity.
-- See Note [Arity inference in kcDeclHeader_sig] in TcHsType
else isIfaceLiftedTypeKind kind)
(dcolon <+> ppr kind)
pp_lhs = case parent of
IfNoParent -> pprIfaceDeclHead suppress_bndr_sig context ss tycon binders
IfDataInstance{}
-> text "instance" <+> pp_data_inst_forall
<+> pprIfaceTyConParent parent
pp_roles
| is_data_instance = empty
| otherwise = pprRoles (== Representational) name_doc binders roles
-- Don't display roles for data family instances (yet)
-- See discussion on #8672.
ki_sig_printable =
-- If we print a standalone kind signature for a data instance, we leak
-- the internal constructor name:
--
-- type T15827.R:Dka :: forall k. k -> *
-- data instance forall k (a :: k). D a = MkD (Proxy a)
--
-- This T15827.R:Dka is a compiler-generated type constructor for the
-- data instance.
not is_data_instance
pp_ki_sig = ppWhen ki_sig_printable $
pprStandaloneKindSig name_doc (mkIfaceTyConKind binders kind)
-- See Note [Suppressing binder signatures] in GHC.Iface.Type
suppress_bndr_sig = SuppressBndrSig ki_sig_printable
name_doc = pprPrefixIfDeclBndr (ss_how_much ss) (occName tycon)
add_bars [] = Outputable.empty
add_bars (c:cs) = sep ((equals <+> c) : map (vbar <+>) cs)
ok_con dc = showSub ss dc || any (showSub ss . flSelector) (ifConFields dc)
show_con dc
| ok_con dc = Just $ pprIfaceConDecl ss gadt tycon binders parent dc
| otherwise = Nothing
pp_nd = case condecls of
IfAbstractTyCon{} -> text "data"
IfDataTyCon{} -> text "data"
IfNewTyCon{} -> text "newtype"
pp_extra = vcat [pprCType ctype]
pprIfaceDecl ss (IfaceClass { ifName = clas
, ifRoles = roles
, ifFDs = fds
, ifBinders = binders
, ifBody = IfAbstractClass })
= vcat [ pprClassRoles ss clas binders roles
, pprClassStandaloneKindSig ss clas (mkIfaceTyConKind binders constraintIfaceKind)
, text "class" <+> pprIfaceDeclHead suppress_bndr_sig [] ss clas binders <+> pprFundeps fds ]
where
-- See Note [Suppressing binder signatures] in GHC.Iface.Type
suppress_bndr_sig = SuppressBndrSig True
pprIfaceDecl ss (IfaceClass { ifName = clas
, ifRoles = roles
, ifFDs = fds
, ifBinders = binders
, ifBody = IfConcreteClass {
ifATs = ats,
ifSigs = sigs,
ifClassCtxt = context,
ifMinDef = minDef
}})
= vcat [ pprClassRoles ss clas binders roles
, pprClassStandaloneKindSig ss clas (mkIfaceTyConKind binders constraintIfaceKind)
, text "class" <+> pprIfaceDeclHead suppress_bndr_sig context ss clas binders <+> pprFundeps fds <+> pp_where
, nest 2 (vcat [ vcat asocs, vcat dsigs
, ppShowAllSubs ss (pprMinDef minDef)])]
where
pp_where = ppShowRhs ss $ ppUnless (null sigs && null ats) (text "where")
asocs = ppr_trim $ map maybeShowAssoc ats
dsigs = ppr_trim $ map maybeShowSig sigs
maybeShowAssoc :: IfaceAT -> Maybe SDoc
maybeShowAssoc asc@(IfaceAT d _)
| showSub ss d = Just $ pprIfaceAT ss asc
| otherwise = Nothing
maybeShowSig :: IfaceClassOp -> Maybe SDoc
maybeShowSig sg
| showSub ss sg = Just $ pprIfaceClassOp ss sg
| otherwise = Nothing
pprMinDef :: BooleanFormula IfLclName -> SDoc
pprMinDef minDef = ppUnless (isTrue minDef) $ -- hide empty definitions
text "{-# MINIMAL" <+>
pprBooleanFormula
(\_ def -> cparen (isLexSym def) (ppr def)) 0 minDef <+>
text "#-}"
-- See Note [Suppressing binder signatures] in GHC.Iface.Type
suppress_bndr_sig = SuppressBndrSig True
pprIfaceDecl ss (IfaceSynonym { ifName = tc
, ifBinders = binders
, ifSynRhs = mono_ty
, ifResKind = res_kind})
= vcat [ pprStandaloneKindSig name_doc (mkIfaceTyConKind binders res_kind)
, hang (text "type" <+> pprIfaceDeclHead suppress_bndr_sig [] ss tc binders <+> equals)
2 (sep [ pprIfaceForAll tvs, pprIfaceContextArr theta, ppr tau
, ppUnless (isIfaceLiftedTypeKind res_kind) (dcolon <+> ppr res_kind) ])
]
where
(tvs, theta, tau) = splitIfaceSigmaTy mono_ty
name_doc = pprPrefixIfDeclBndr (ss_how_much ss) (occName tc)
-- See Note [Suppressing binder signatures] in GHC.Iface.Type
suppress_bndr_sig = SuppressBndrSig True
pprIfaceDecl ss (IfaceFamily { ifName = tycon
, ifFamFlav = rhs, ifBinders = binders
, ifResKind = res_kind
, ifResVar = res_var, ifFamInj = inj })
| IfaceDataFamilyTyCon <- rhs
= vcat [ pprStandaloneKindSig name_doc (mkIfaceTyConKind binders res_kind)
, text "data family" <+> pprIfaceDeclHead suppress_bndr_sig [] ss tycon binders
]
| otherwise
= vcat [ pprStandaloneKindSig name_doc (mkIfaceTyConKind binders res_kind)
, hang (text "type family"
<+> pprIfaceDeclHead suppress_bndr_sig [] ss tycon binders
<+> ppShowRhs ss (pp_where rhs))
2 (pp_inj res_var inj <+> ppShowRhs ss (pp_rhs rhs))
$$
nest 2 (ppShowRhs ss (pp_branches rhs))
]
where
name_doc = pprPrefixIfDeclBndr (ss_how_much ss) (occName tycon)
pp_where (IfaceClosedSynFamilyTyCon {}) = text "where"
pp_where _ = empty
pp_inj Nothing _ = empty
pp_inj (Just res) inj
| Injective injectivity <- inj = hsep [ equals, ppr res
, pp_inj_cond res injectivity]
| otherwise = hsep [ equals, ppr res ]
pp_inj_cond res inj = case filterByList inj binders of
[] -> empty
tvs -> hsep [vbar, ppr res, text "->", interppSP (map ifTyConBinderName tvs)]
pp_rhs IfaceDataFamilyTyCon
= ppShowIface ss (text "data")
pp_rhs IfaceOpenSynFamilyTyCon
= ppShowIface ss (text "open")
pp_rhs IfaceAbstractClosedSynFamilyTyCon
= ppShowIface ss (text "closed, abstract")
pp_rhs (IfaceClosedSynFamilyTyCon {})
= empty -- see pp_branches
pp_rhs IfaceBuiltInSynFamTyCon
= ppShowIface ss (text "built-in")
pp_branches (IfaceClosedSynFamilyTyCon (Just (ax, brs)))
= vcat (unzipWith (pprAxBranch
(pprPrefixIfDeclBndr
(ss_how_much ss)
(occName tycon))
) $ zip [0..] brs)
$$ ppShowIface ss (text "axiom" <+> ppr ax)
pp_branches _ = Outputable.empty
-- See Note [Suppressing binder signatures] in GHC.Iface.Type
suppress_bndr_sig = SuppressBndrSig True
pprIfaceDecl _ (IfacePatSyn { ifName = name,
ifPatUnivBndrs = univ_bndrs, ifPatExBndrs = ex_bndrs,
ifPatProvCtxt = prov_ctxt, ifPatReqCtxt = req_ctxt,
ifPatArgs = arg_tys,
ifPatTy = pat_ty} )
= sdocWithDynFlags mk_msg
where
mk_msg dflags
= hang (text "pattern" <+> pprPrefixOcc name)
2 (dcolon <+> sep [univ_msg
, pprIfaceContextArr req_ctxt
, ppWhen insert_empty_ctxt $ parens empty <+> darrow
, ex_msg
, pprIfaceContextArr prov_ctxt
, pprIfaceType $ foldr (IfaceFunTy VisArg) pat_ty arg_tys ])
where
univ_msg = pprUserIfaceForAll univ_bndrs
ex_msg = pprUserIfaceForAll ex_bndrs
insert_empty_ctxt = null req_ctxt
&& not (null prov_ctxt && isEmpty dflags ex_msg)
pprIfaceDecl ss (IfaceId { ifName = var, ifType = ty,
ifIdDetails = details, ifIdInfo = info })
= vcat [ hang (pprPrefixIfDeclBndr (ss_how_much ss) (occName var) <+> dcolon)
2 (pprIfaceSigmaType (ss_forall ss) ty)
, ppShowIface ss (ppr details)
, ppShowIface ss (ppr info) ]
pprIfaceDecl _ (IfaceAxiom { ifName = name, ifTyCon = tycon
, ifAxBranches = branches })
= hang (text "axiom" <+> ppr name <+> dcolon)
2 (vcat $ unzipWith (pprAxBranch (ppr tycon)) $ zip [0..] branches)
pprCType :: Maybe CType -> SDoc
pprCType Nothing = Outputable.empty
pprCType (Just cType) = text "C type:" <+> ppr cType
-- if, for each role, suppress_if role is True, then suppress the role
-- output
pprRoles :: (Role -> Bool) -> SDoc -> [IfaceTyConBinder]
-> [Role] -> SDoc
pprRoles suppress_if tyCon bndrs roles
= sdocWithDynFlags $ \dflags ->
let froles = suppressIfaceInvisibles dflags bndrs roles
in ppUnless (all suppress_if froles || null froles) $
text "type role" <+> tyCon <+> hsep (map ppr froles)
pprStandaloneKindSig :: SDoc -> IfaceType -> SDoc
pprStandaloneKindSig tyCon ty = text "type" <+> tyCon <+> text "::" <+> ppr ty
pprInfixIfDeclBndr :: ShowHowMuch -> OccName -> SDoc
pprInfixIfDeclBndr (ShowSome _ (AltPpr (Just ppr_bndr))) name
= pprInfixVar (isSymOcc name) (ppr_bndr name)
pprInfixIfDeclBndr _ name
= pprInfixVar (isSymOcc name) (ppr name)
pprPrefixIfDeclBndr :: ShowHowMuch -> OccName -> SDoc
pprPrefixIfDeclBndr (ShowHeader (AltPpr (Just ppr_bndr))) name
= parenSymOcc name (ppr_bndr name)
pprPrefixIfDeclBndr (ShowSome _ (AltPpr (Just ppr_bndr))) name
= parenSymOcc name (ppr_bndr name)
pprPrefixIfDeclBndr _ name
= parenSymOcc name (ppr name)
instance Outputable IfaceClassOp where
ppr = pprIfaceClassOp showToIface
pprIfaceClassOp :: ShowSub -> IfaceClassOp -> SDoc
pprIfaceClassOp ss (IfaceClassOp n ty dm)
= pp_sig n ty $$ generic_dm
where
generic_dm | Just (GenericDM dm_ty) <- dm
= text "default" <+> pp_sig n dm_ty
| otherwise
= empty
pp_sig n ty
= pprPrefixIfDeclBndr (ss_how_much ss) (occName n)
<+> dcolon
<+> pprIfaceSigmaType ShowForAllWhen ty
instance Outputable IfaceAT where
ppr = pprIfaceAT showToIface
pprIfaceAT :: ShowSub -> IfaceAT -> SDoc
pprIfaceAT ss (IfaceAT d mb_def)
= vcat [ pprIfaceDecl ss d
, case mb_def of
Nothing -> Outputable.empty
Just rhs -> nest 2 $
text "Default:" <+> ppr rhs ]
instance Outputable IfaceTyConParent where
ppr p = pprIfaceTyConParent p
pprIfaceTyConParent :: IfaceTyConParent -> SDoc
pprIfaceTyConParent IfNoParent
= Outputable.empty
pprIfaceTyConParent (IfDataInstance _ tc tys)
= pprIfaceTypeApp topPrec tc tys
pprIfaceDeclHead :: SuppressBndrSig
-> IfaceContext -> ShowSub -> Name
-> [IfaceTyConBinder] -- of the tycon, for invisible-suppression
-> SDoc
pprIfaceDeclHead suppress_sig context ss tc_occ bndrs
= sdocWithDynFlags $ \ dflags ->
sep [ pprIfaceContextArr context
, pprPrefixIfDeclBndr (ss_how_much ss) (occName tc_occ)
<+> pprIfaceTyConBinders suppress_sig
(suppressIfaceInvisibles dflags bndrs bndrs) ]
pprIfaceConDecl :: ShowSub -> Bool
-> IfaceTopBndr
-> [IfaceTyConBinder]
-> IfaceTyConParent
-> IfaceConDecl -> SDoc
pprIfaceConDecl ss gadt_style tycon tc_binders parent
(IfCon { ifConName = name, ifConInfix = is_infix,
ifConUserTvBinders = user_tvbs,
ifConEqSpec = eq_spec, ifConCtxt = ctxt, ifConArgTys = arg_tys,
ifConStricts = stricts, ifConFields = fields })
| gadt_style = pp_prefix_con <+> dcolon <+> ppr_gadt_ty
| otherwise = ppr_ex_quant pp_h98_con
where
pp_h98_con
| not (null fields) = pp_prefix_con <+> pp_field_args
| is_infix
, [ty1, ty2] <- pp_args
= sep [ ty1
, pprInfixIfDeclBndr how_much (occName name)
, ty2]
| otherwise = pp_prefix_con <+> sep pp_args
how_much = ss_how_much ss
tys_w_strs :: [(IfaceBang, IfaceType)]
tys_w_strs = zip stricts arg_tys
pp_prefix_con = pprPrefixIfDeclBndr how_much (occName name)
-- If we're pretty-printing a H98-style declaration with existential
-- quantification, then user_tvbs will always consist of the universal
-- tyvar binders followed by the existential tyvar binders. So to recover
-- the visibilities of the existential tyvar binders, we can simply drop
-- the universal tyvar binders from user_tvbs.
ex_tvbs = dropList tc_binders user_tvbs
ppr_ex_quant = pprIfaceForAllPartMust ex_tvbs ctxt
pp_gadt_res_ty = mk_user_con_res_ty eq_spec
ppr_gadt_ty = pprIfaceForAllPart user_tvbs ctxt pp_tau
-- A bit gruesome this, but we can't form the full con_tau, and ppr it,
-- because we don't have a Name for the tycon, only an OccName
pp_tau | null fields
= case pp_args ++ [pp_gadt_res_ty] of
(t:ts) -> fsep (t : map (arrow <+>) ts)
[] -> panic "pp_con_taus"
| otherwise
= sep [pp_field_args, arrow <+> pp_gadt_res_ty]
ppr_bang IfNoBang = whenPprDebug $ char '_'
ppr_bang IfStrict = char '!'
ppr_bang IfUnpack = text "{-# UNPACK #-}"
ppr_bang (IfUnpackCo co) = text "! {-# UNPACK #-}" <>
pprParendIfaceCoercion co
pprFieldArgTy, pprArgTy :: (IfaceBang, IfaceType) -> SDoc
-- If using record syntax, the only reason one would need to parenthesize
-- a compound field type is if it's preceded by a bang pattern.
pprFieldArgTy (bang, ty) = ppr_arg_ty (bang_prec bang) bang ty
-- If not using record syntax, a compound field type might need to be
-- parenthesized if one of the following holds:
--
-- 1. We're using Haskell98 syntax.
-- 2. The field type is preceded with a bang pattern.
pprArgTy (bang, ty) = ppr_arg_ty (max gadt_prec (bang_prec bang)) bang ty
ppr_arg_ty :: PprPrec -> IfaceBang -> IfaceType -> SDoc
ppr_arg_ty prec bang ty = ppr_bang bang <> pprPrecIfaceType prec ty
-- If we're displaying the fields GADT-style, e.g.,
--
-- data Foo a where
-- MkFoo :: (Int -> Int) -> Maybe a -> Foo
--
-- Then we use `funPrec`, since that will ensure `Int -> Int` gets the
-- parentheses that it requires, but simple compound types like `Maybe a`
-- (which don't require parentheses in a function argument position) won't
-- get them, assuming that there are no bang patterns (see bang_prec).
--
-- If we're displaying the fields Haskell98-style, e.g.,
--
-- data Foo a = MkFoo (Int -> Int) (Maybe a)
--
-- Then not only must we parenthesize `Int -> Int`, we must also
-- parenthesize compound fields like (Maybe a). Therefore, we pick
-- `appPrec`, which has higher precedence than `funPrec`.
gadt_prec :: PprPrec
gadt_prec
| gadt_style = funPrec
| otherwise = appPrec
-- The presence of bang patterns or UNPACK annotations requires
-- surrounding the type with parentheses, if needed (#13699)
bang_prec :: IfaceBang -> PprPrec
bang_prec IfNoBang = topPrec
bang_prec IfStrict = appPrec
bang_prec IfUnpack = appPrec
bang_prec IfUnpackCo{} = appPrec
pp_args :: [SDoc] -- No records, e.g., ` Maybe a -> Int -> ...` or
-- `!(Maybe a) -> !Int -> ...`
pp_args = map pprArgTy tys_w_strs
pp_field_args :: SDoc -- Records, e.g., { x :: Maybe a, y :: Int } or
-- { x :: !(Maybe a), y :: !Int }
pp_field_args = braces $ sep $ punctuate comma $ ppr_trim $
zipWith maybe_show_label fields tys_w_strs
maybe_show_label :: FieldLabel -> (IfaceBang, IfaceType) -> Maybe SDoc
maybe_show_label lbl bty
| showSub ss sel = Just (pprPrefixIfDeclBndr how_much occ
<+> dcolon <+> pprFieldArgTy bty)
| otherwise = Nothing
where
sel = flSelector lbl
occ = mkVarOccFS (flLabel lbl)
mk_user_con_res_ty :: IfaceEqSpec -> SDoc
-- See Note [Result type of a data family GADT]
mk_user_con_res_ty eq_spec
| IfDataInstance _ tc tys <- parent
= pprIfaceType (IfaceTyConApp tc (substIfaceAppArgs gadt_subst tys))
| otherwise
= ppr_tc_app gadt_subst
where
gadt_subst = mkIfaceTySubst eq_spec
-- When pretty-printing a GADT return type, we:
--
-- 1. Take the data tycon binders, extract their variable names and
-- visibilities, and construct suitable arguments from them. (This is
-- the role of mk_tc_app_args.)
-- 2. Apply the GADT substitution constructed from the eq_spec.
-- (See Note [Result type of a data family GADT].)
-- 3. Pretty-print the data type constructor applied to its arguments.
-- This process will omit any invisible arguments, such as coercion
-- variables, if necessary. (See Note
-- [VarBndrs, TyCoVarBinders, TyConBinders, and visibility] in TyCoRep.)
ppr_tc_app gadt_subst =
pprPrefixIfDeclBndr how_much (occName tycon)
<+> pprParendIfaceAppArgs
(substIfaceAppArgs gadt_subst (mk_tc_app_args tc_binders))
mk_tc_app_args :: [IfaceTyConBinder] -> IfaceAppArgs
mk_tc_app_args [] = IA_Nil
mk_tc_app_args (Bndr bndr vis:tc_bndrs) =
IA_Arg (IfaceTyVar (ifaceBndrName bndr)) (tyConBndrVisArgFlag vis)
(mk_tc_app_args tc_bndrs)
instance Outputable IfaceRule where
ppr (IfaceRule { ifRuleName = name, ifActivation = act, ifRuleBndrs = bndrs,
ifRuleHead = fn, ifRuleArgs = args, ifRuleRhs = rhs,
ifRuleOrph = orph })
= sep [ hsep [ pprRuleName name
, if isOrphan orph then text "[orphan]" else Outputable.empty
, ppr act
, pp_foralls ]
, nest 2 (sep [ppr fn <+> sep (map pprParendIfaceExpr args),
text "=" <+> ppr rhs]) ]
where
pp_foralls = ppUnless (null bndrs) $ forAllLit <+> pprIfaceBndrs bndrs <> dot
instance Outputable IfaceClsInst where
ppr (IfaceClsInst { ifDFun = dfun_id, ifOFlag = flag
, ifInstCls = cls, ifInstTys = mb_tcs
, ifInstOrph = orph })
= hang (text "instance" <+> ppr flag
<+> (if isOrphan orph then text "[orphan]" else Outputable.empty)
<+> ppr cls <+> brackets (pprWithCommas ppr_rough mb_tcs))
2 (equals <+> ppr dfun_id)
instance Outputable IfaceFamInst where
ppr (IfaceFamInst { ifFamInstFam = fam, ifFamInstTys = mb_tcs
, ifFamInstAxiom = tycon_ax, ifFamInstOrph = orph })
= hang (text "family instance"
<+> (if isOrphan orph then text "[orphan]" else Outputable.empty)
<+> ppr fam <+> pprWithCommas (brackets . ppr_rough) mb_tcs)
2 (equals <+> ppr tycon_ax)
ppr_rough :: Maybe IfaceTyCon -> SDoc
ppr_rough Nothing = dot
ppr_rough (Just tc) = ppr tc
{-
Note [Result type of a data family GADT]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider
data family T a
data instance T (p,q) where
T1 :: T (Int, Maybe c)
T2 :: T (Bool, q)
The IfaceDecl actually looks like
data TPr p q where
T1 :: forall p q. forall c. (p~Int,q~Maybe c) => TPr p q
T2 :: forall p q. (p~Bool) => TPr p q
To reconstruct the result types for T1 and T2 that we
want to pretty print, we substitute the eq-spec
[p->Int, q->Maybe c] in the arg pattern (p,q) to give
T (Int, Maybe c)
Remember that in IfaceSyn, the TyCon and DataCon share the same
universal type variables.
----------------------------- Printing IfaceExpr ------------------------------------
-}
instance Outputable IfaceExpr where
ppr e = pprIfaceExpr noParens e
noParens :: SDoc -> SDoc
noParens pp = pp
pprParendIfaceExpr :: IfaceExpr -> SDoc
pprParendIfaceExpr = pprIfaceExpr parens
-- | Pretty Print an IfaceExpre
--
-- The first argument should be a function that adds parens in context that need
-- an atomic value (e.g. function args)
pprIfaceExpr :: (SDoc -> SDoc) -> IfaceExpr -> SDoc
pprIfaceExpr _ (IfaceLcl v) = ppr v
pprIfaceExpr _ (IfaceExt v) = ppr v
pprIfaceExpr _ (IfaceLit l) = ppr l
pprIfaceExpr _ (IfaceFCall cc ty) = braces (ppr cc <+> ppr ty)
pprIfaceExpr _ (IfaceType ty) = char '@' <> pprParendIfaceType ty
pprIfaceExpr _ (IfaceCo co) = text "@~" <> pprParendIfaceCoercion co
pprIfaceExpr add_par app@(IfaceApp _ _) = add_par (pprIfaceApp app [])
pprIfaceExpr _ (IfaceTuple c as) = tupleParens c (pprWithCommas ppr as)
pprIfaceExpr add_par i@(IfaceLam _ _)
= add_par (sep [char '\\' <+> sep (map pprIfaceLamBndr bndrs) <+> arrow,
pprIfaceExpr noParens body])
where
(bndrs,body) = collect [] i
collect bs (IfaceLam b e) = collect (b:bs) e
collect bs e = (reverse bs, e)
pprIfaceExpr add_par (IfaceECase scrut ty)
= add_par (sep [ text "case" <+> pprIfaceExpr noParens scrut
, text "ret_ty" <+> pprParendIfaceType ty
, text "of {}" ])
pprIfaceExpr add_par (IfaceCase scrut bndr [(con, bs, rhs)])
= add_par (sep [text "case"
<+> pprIfaceExpr noParens scrut <+> text "of"
<+> ppr bndr <+> char '{' <+> ppr_con_bs con bs <+> arrow,
pprIfaceExpr noParens rhs <+> char '}'])
pprIfaceExpr add_par (IfaceCase scrut bndr alts)
= add_par (sep [text "case"
<+> pprIfaceExpr noParens scrut <+> text "of"
<+> ppr bndr <+> char '{',
nest 2 (sep (map ppr_alt alts)) <+> char '}'])
pprIfaceExpr _ (IfaceCast expr co)
= sep [pprParendIfaceExpr expr,
nest 2 (text "`cast`"),
pprParendIfaceCoercion co]
pprIfaceExpr add_par (IfaceLet (IfaceNonRec b rhs) body)
= add_par (sep [text "let {",
nest 2 (ppr_bind (b, rhs)),
text "} in",
pprIfaceExpr noParens body])
pprIfaceExpr add_par (IfaceLet (IfaceRec pairs) body)
= add_par (sep [text "letrec {",
nest 2 (sep (map ppr_bind pairs)),
text "} in",
pprIfaceExpr noParens body])
pprIfaceExpr add_par (IfaceTick tickish e)
= add_par (pprIfaceTickish tickish <+> pprIfaceExpr noParens e)
ppr_alt :: (IfaceConAlt, [IfLclName], IfaceExpr) -> SDoc
ppr_alt (con, bs, rhs) = sep [ppr_con_bs con bs,
arrow <+> pprIfaceExpr noParens rhs]
ppr_con_bs :: IfaceConAlt -> [IfLclName] -> SDoc
ppr_con_bs con bs = ppr con <+> hsep (map ppr bs)
ppr_bind :: (IfaceLetBndr, IfaceExpr) -> SDoc
ppr_bind (IfLetBndr b ty info ji, rhs)
= sep [hang (ppr b <+> dcolon <+> ppr ty) 2 (ppr ji <+> ppr info),
equals <+> pprIfaceExpr noParens rhs]
------------------
pprIfaceTickish :: IfaceTickish -> SDoc
pprIfaceTickish (IfaceHpcTick m ix)
= braces (text "tick" <+> ppr m <+> ppr ix)
pprIfaceTickish (IfaceSCC cc tick scope)
= braces (pprCostCentreCore cc <+> ppr tick <+> ppr scope)
pprIfaceTickish (IfaceSource src _names)
= braces (pprUserRealSpan True src)
------------------
pprIfaceApp :: IfaceExpr -> [SDoc] -> SDoc
pprIfaceApp (IfaceApp fun arg) args = pprIfaceApp fun $
nest 2 (pprParendIfaceExpr arg) : args
pprIfaceApp fun args = sep (pprParendIfaceExpr fun : args)
------------------
instance Outputable IfaceConAlt where
ppr IfaceDefault = text "DEFAULT"
ppr (IfaceLitAlt l) = ppr l
ppr (IfaceDataAlt d) = ppr d
------------------
instance Outputable IfaceIdDetails where
ppr IfVanillaId = Outputable.empty
ppr (IfRecSelId tc b) = text "RecSel" <+> ppr tc
<+> if b
then text "<naughty>"
else Outputable.empty
ppr IfDFunId = text "DFunId"
instance Outputable IfaceIdInfo where
ppr NoInfo = Outputable.empty
ppr (HasInfo is) = text "{-" <+> pprWithCommas ppr is
<+> text "-}"
instance Outputable IfaceInfoItem where
ppr (HsUnfold lb unf) = text "Unfolding"
<> ppWhen lb (text "(loop-breaker)")
<> colon <+> ppr unf
ppr (HsInline prag) = text "Inline:" <+> ppr prag
ppr (HsArity arity) = text "Arity:" <+> int arity
ppr (HsStrictness str) = text "Strictness:" <+> pprIfaceStrictSig str
ppr HsNoCafRefs = text "HasNoCafRefs"
ppr HsLevity = text "Never levity-polymorphic"
instance Outputable IfaceJoinInfo where
ppr IfaceNotJoinPoint = empty
ppr (IfaceJoinPoint ar) = angleBrackets (text "join" <+> ppr ar)
instance Outputable IfaceUnfolding where
ppr (IfCompulsory e) = text "<compulsory>" <+> parens (ppr e)
ppr (IfCoreUnfold s e) = (if s
then text "<stable>"
else Outputable.empty)
<+> parens (ppr e)
ppr (IfInlineRule a uok bok e) = sep [text "InlineRule"
<+> ppr (a,uok,bok),
pprParendIfaceExpr e]
ppr (IfDFunUnfold bs es) = hang (text "DFun:" <+> sep (map ppr bs) <> dot)
2 (sep (map pprParendIfaceExpr es))
{-
************************************************************************
* *
Finding the Names in Iface syntax
* *
************************************************************************
This is used for dependency analysis in GHC.Iface.Utils, so that we
fingerprint a declaration before the things that depend on it. It
is specific to interface-file fingerprinting in the sense that we
don't collect *all* Names: for example, the DFun of an instance is
recorded textually rather than by its fingerprint when
fingerprinting the instance, so DFuns are not dependencies.
-}
freeNamesIfDecl :: IfaceDecl -> NameSet
freeNamesIfDecl (IfaceId { ifType = t, ifIdDetails = d, ifIdInfo = i})
= freeNamesIfType t &&&
freeNamesIfIdInfo i &&&
freeNamesIfIdDetails d
freeNamesIfDecl (IfaceData { ifBinders = bndrs, ifResKind = res_k
, ifParent = p, ifCtxt = ctxt, ifCons = cons })
= freeNamesIfVarBndrs bndrs &&&
freeNamesIfType res_k &&&
freeNamesIfaceTyConParent p &&&
freeNamesIfContext ctxt &&&
freeNamesIfConDecls cons
freeNamesIfDecl (IfaceSynonym { ifBinders = bndrs, ifResKind = res_k
, ifSynRhs = rhs })
= freeNamesIfVarBndrs bndrs &&&
freeNamesIfKind res_k &&&
freeNamesIfType rhs
freeNamesIfDecl (IfaceFamily { ifBinders = bndrs, ifResKind = res_k
, ifFamFlav = flav })
= freeNamesIfVarBndrs bndrs &&&
freeNamesIfKind res_k &&&
freeNamesIfFamFlav flav
freeNamesIfDecl (IfaceClass{ ifBinders = bndrs, ifBody = cls_body })
= freeNamesIfVarBndrs bndrs &&&
freeNamesIfClassBody cls_body
freeNamesIfDecl (IfaceAxiom { ifTyCon = tc, ifAxBranches = branches })
= freeNamesIfTc tc &&&
fnList freeNamesIfAxBranch branches
freeNamesIfDecl (IfacePatSyn { ifPatMatcher = (matcher, _)
, ifPatBuilder = mb_builder
, ifPatUnivBndrs = univ_bndrs
, ifPatExBndrs = ex_bndrs
, ifPatProvCtxt = prov_ctxt
, ifPatReqCtxt = req_ctxt
, ifPatArgs = args
, ifPatTy = pat_ty
, ifFieldLabels = lbls })
= unitNameSet matcher &&&
maybe emptyNameSet (unitNameSet . fst) mb_builder &&&
freeNamesIfVarBndrs univ_bndrs &&&
freeNamesIfVarBndrs ex_bndrs &&&
freeNamesIfContext prov_ctxt &&&
freeNamesIfContext req_ctxt &&&
fnList freeNamesIfType args &&&
freeNamesIfType pat_ty &&&
mkNameSet (map flSelector lbls)
freeNamesIfClassBody :: IfaceClassBody -> NameSet
freeNamesIfClassBody IfAbstractClass
= emptyNameSet
freeNamesIfClassBody (IfConcreteClass{ ifClassCtxt = ctxt, ifATs = ats, ifSigs = sigs })
= freeNamesIfContext ctxt &&&
fnList freeNamesIfAT ats &&&
fnList freeNamesIfClsSig sigs
freeNamesIfAxBranch :: IfaceAxBranch -> NameSet
freeNamesIfAxBranch (IfaceAxBranch { ifaxbTyVars = tyvars
, ifaxbCoVars = covars
, ifaxbLHS = lhs
, ifaxbRHS = rhs })
= fnList freeNamesIfTvBndr tyvars &&&
fnList freeNamesIfIdBndr covars &&&
freeNamesIfAppArgs lhs &&&
freeNamesIfType rhs
freeNamesIfIdDetails :: IfaceIdDetails -> NameSet
freeNamesIfIdDetails (IfRecSelId tc _) =
either freeNamesIfTc freeNamesIfDecl tc
freeNamesIfIdDetails _ = emptyNameSet
-- All other changes are handled via the version info on the tycon
freeNamesIfFamFlav :: IfaceFamTyConFlav -> NameSet
freeNamesIfFamFlav IfaceOpenSynFamilyTyCon = emptyNameSet
freeNamesIfFamFlav IfaceDataFamilyTyCon = emptyNameSet
freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon (Just (ax, br)))
= unitNameSet ax &&& fnList freeNamesIfAxBranch br
freeNamesIfFamFlav (IfaceClosedSynFamilyTyCon Nothing) = emptyNameSet
freeNamesIfFamFlav IfaceAbstractClosedSynFamilyTyCon = emptyNameSet
freeNamesIfFamFlav IfaceBuiltInSynFamTyCon = emptyNameSet
freeNamesIfContext :: IfaceContext -> NameSet
freeNamesIfContext = fnList freeNamesIfType
freeNamesIfAT :: IfaceAT -> NameSet
freeNamesIfAT (IfaceAT decl mb_def)
= freeNamesIfDecl decl &&&
case mb_def of
Nothing -> emptyNameSet
Just rhs -> freeNamesIfType rhs
freeNamesIfClsSig :: IfaceClassOp -> NameSet
freeNamesIfClsSig (IfaceClassOp _n ty dm) = freeNamesIfType ty &&& freeNamesDM dm
freeNamesDM :: Maybe (DefMethSpec IfaceType) -> NameSet
freeNamesDM (Just (GenericDM ty)) = freeNamesIfType ty
freeNamesDM _ = emptyNameSet
freeNamesIfConDecls :: IfaceConDecls -> NameSet
freeNamesIfConDecls (IfDataTyCon c) = fnList freeNamesIfConDecl c
freeNamesIfConDecls (IfNewTyCon c) = freeNamesIfConDecl c
freeNamesIfConDecls _ = emptyNameSet
freeNamesIfConDecl :: IfaceConDecl -> NameSet
freeNamesIfConDecl (IfCon { ifConExTCvs = ex_tvs, ifConCtxt = ctxt
, ifConArgTys = arg_tys
, ifConFields = flds
, ifConEqSpec = eq_spec
, ifConStricts = bangs })
= fnList freeNamesIfBndr ex_tvs &&&
freeNamesIfContext ctxt &&&
fnList freeNamesIfType arg_tys &&&
mkNameSet (map flSelector flds) &&&
fnList freeNamesIfType (map snd eq_spec) &&& -- equality constraints
fnList freeNamesIfBang bangs
freeNamesIfBang :: IfaceBang -> NameSet
freeNamesIfBang (IfUnpackCo co) = freeNamesIfCoercion co
freeNamesIfBang _ = emptyNameSet
freeNamesIfKind :: IfaceType -> NameSet
freeNamesIfKind = freeNamesIfType
freeNamesIfAppArgs :: IfaceAppArgs -> NameSet
freeNamesIfAppArgs (IA_Arg t _ ts) = freeNamesIfType t &&& freeNamesIfAppArgs ts
freeNamesIfAppArgs IA_Nil = emptyNameSet
freeNamesIfType :: IfaceType -> NameSet
freeNamesIfType (IfaceFreeTyVar _) = emptyNameSet
freeNamesIfType (IfaceTyVar _) = emptyNameSet
freeNamesIfType (IfaceAppTy s t) = freeNamesIfType s &&& freeNamesIfAppArgs t
freeNamesIfType (IfaceTyConApp tc ts) = freeNamesIfTc tc &&& freeNamesIfAppArgs ts
freeNamesIfType (IfaceTupleTy _ _ ts) = freeNamesIfAppArgs ts
freeNamesIfType (IfaceLitTy _) = emptyNameSet
freeNamesIfType (IfaceForAllTy tv t) = freeNamesIfVarBndr tv &&& freeNamesIfType t
freeNamesIfType (IfaceFunTy _ s t) = freeNamesIfType s &&& freeNamesIfType t
freeNamesIfType (IfaceCastTy t c) = freeNamesIfType t &&& freeNamesIfCoercion c
freeNamesIfType (IfaceCoercionTy c) = freeNamesIfCoercion c
freeNamesIfMCoercion :: IfaceMCoercion -> NameSet
freeNamesIfMCoercion IfaceMRefl = emptyNameSet
freeNamesIfMCoercion (IfaceMCo co) = freeNamesIfCoercion co
freeNamesIfCoercion :: IfaceCoercion -> NameSet
freeNamesIfCoercion (IfaceReflCo t) = freeNamesIfType t
freeNamesIfCoercion (IfaceGReflCo _ t mco)
= freeNamesIfType t &&& freeNamesIfMCoercion mco
freeNamesIfCoercion (IfaceFunCo _ c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceTyConAppCo _ tc cos)
= freeNamesIfTc tc &&& fnList freeNamesIfCoercion cos
freeNamesIfCoercion (IfaceAppCo c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceForAllCo _ kind_co co)
= freeNamesIfCoercion kind_co &&& freeNamesIfCoercion co
freeNamesIfCoercion (IfaceFreeCoVar _) = emptyNameSet
freeNamesIfCoercion (IfaceCoVarCo _) = emptyNameSet
freeNamesIfCoercion (IfaceHoleCo _) = emptyNameSet
freeNamesIfCoercion (IfaceAxiomInstCo ax _ cos)
= unitNameSet ax &&& fnList freeNamesIfCoercion cos
freeNamesIfCoercion (IfaceUnivCo p _ t1 t2)
= freeNamesIfProv p &&& freeNamesIfType t1 &&& freeNamesIfType t2
freeNamesIfCoercion (IfaceSymCo c)
= freeNamesIfCoercion c
freeNamesIfCoercion (IfaceTransCo c1 c2)
= freeNamesIfCoercion c1 &&& freeNamesIfCoercion c2
freeNamesIfCoercion (IfaceNthCo _ co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceLRCo _ co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceInstCo co co2)
= freeNamesIfCoercion co &&& freeNamesIfCoercion co2
freeNamesIfCoercion (IfaceKindCo c)
= freeNamesIfCoercion c
freeNamesIfCoercion (IfaceSubCo co)
= freeNamesIfCoercion co
freeNamesIfCoercion (IfaceAxiomRuleCo _ax cos)
-- the axiom is just a string, so we don't count it as a name.
= fnList freeNamesIfCoercion cos
freeNamesIfProv :: IfaceUnivCoProv -> NameSet
freeNamesIfProv IfaceUnsafeCoerceProv = emptyNameSet
freeNamesIfProv (IfacePhantomProv co) = freeNamesIfCoercion co
freeNamesIfProv (IfaceProofIrrelProv co) = freeNamesIfCoercion co
freeNamesIfProv (IfacePluginProv _) = emptyNameSet
freeNamesIfVarBndr :: VarBndr IfaceBndr vis -> NameSet
freeNamesIfVarBndr (Bndr bndr _) = freeNamesIfBndr bndr
freeNamesIfVarBndrs :: [VarBndr IfaceBndr vis] -> NameSet
freeNamesIfVarBndrs = fnList freeNamesIfVarBndr
freeNamesIfBndr :: IfaceBndr -> NameSet
freeNamesIfBndr (IfaceIdBndr b) = freeNamesIfIdBndr b
freeNamesIfBndr (IfaceTvBndr b) = freeNamesIfTvBndr b
freeNamesIfBndrs :: [IfaceBndr] -> NameSet
freeNamesIfBndrs = fnList freeNamesIfBndr
freeNamesIfLetBndr :: IfaceLetBndr -> NameSet
-- Remember IfaceLetBndr is used only for *nested* bindings
-- The IdInfo can contain an unfolding (in the case of
-- local INLINE pragmas), so look there too
freeNamesIfLetBndr (IfLetBndr _name ty info _ji) = freeNamesIfType ty
&&& freeNamesIfIdInfo info
freeNamesIfTvBndr :: IfaceTvBndr -> NameSet
freeNamesIfTvBndr (_fs,k) = freeNamesIfKind k
-- kinds can have Names inside, because of promotion
freeNamesIfIdBndr :: IfaceIdBndr -> NameSet
freeNamesIfIdBndr (_fs,k) = freeNamesIfKind k
freeNamesIfIdInfo :: IfaceIdInfo -> NameSet
freeNamesIfIdInfo NoInfo = emptyNameSet
freeNamesIfIdInfo (HasInfo i) = fnList freeNamesItem i
freeNamesItem :: IfaceInfoItem -> NameSet
freeNamesItem (HsUnfold _ u) = freeNamesIfUnfold u
freeNamesItem _ = emptyNameSet
freeNamesIfUnfold :: IfaceUnfolding -> NameSet
freeNamesIfUnfold (IfCoreUnfold _ e) = freeNamesIfExpr e
freeNamesIfUnfold (IfCompulsory e) = freeNamesIfExpr e
freeNamesIfUnfold (IfInlineRule _ _ _ e) = freeNamesIfExpr e
freeNamesIfUnfold (IfDFunUnfold bs es) = freeNamesIfBndrs bs &&& fnList freeNamesIfExpr es
freeNamesIfExpr :: IfaceExpr -> NameSet
freeNamesIfExpr (IfaceExt v) = unitNameSet v
freeNamesIfExpr (IfaceFCall _ ty) = freeNamesIfType ty
freeNamesIfExpr (IfaceType ty) = freeNamesIfType ty
freeNamesIfExpr (IfaceCo co) = freeNamesIfCoercion co
freeNamesIfExpr (IfaceTuple _ as) = fnList freeNamesIfExpr as
freeNamesIfExpr (IfaceLam (b,_) body) = freeNamesIfBndr b &&& freeNamesIfExpr body
freeNamesIfExpr (IfaceApp f a) = freeNamesIfExpr f &&& freeNamesIfExpr a
freeNamesIfExpr (IfaceCast e co) = freeNamesIfExpr e &&& freeNamesIfCoercion co
freeNamesIfExpr (IfaceTick _ e) = freeNamesIfExpr e
freeNamesIfExpr (IfaceECase e ty) = freeNamesIfExpr e &&& freeNamesIfType ty
freeNamesIfExpr (IfaceCase s _ alts)
= freeNamesIfExpr s &&& fnList fn_alt alts &&& fn_cons alts
where
fn_alt (_con,_bs,r) = freeNamesIfExpr r
-- Depend on the data constructors. Just one will do!
-- Note [Tracking data constructors]
fn_cons [] = emptyNameSet
fn_cons ((IfaceDefault ,_,_) : xs) = fn_cons xs
fn_cons ((IfaceDataAlt con,_,_) : _ ) = unitNameSet con
fn_cons (_ : _ ) = emptyNameSet
freeNamesIfExpr (IfaceLet (IfaceNonRec bndr rhs) body)
= freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs &&& freeNamesIfExpr body
freeNamesIfExpr (IfaceLet (IfaceRec as) x)
= fnList fn_pair as &&& freeNamesIfExpr x
where
fn_pair (bndr, rhs) = freeNamesIfLetBndr bndr &&& freeNamesIfExpr rhs
freeNamesIfExpr _ = emptyNameSet
freeNamesIfTc :: IfaceTyCon -> NameSet
freeNamesIfTc tc = unitNameSet (ifaceTyConName tc)
-- ToDo: shouldn't we include IfaceIntTc & co.?
freeNamesIfRule :: IfaceRule -> NameSet
freeNamesIfRule (IfaceRule { ifRuleBndrs = bs, ifRuleHead = f
, ifRuleArgs = es, ifRuleRhs = rhs })
= unitNameSet f &&&
fnList freeNamesIfBndr bs &&&
fnList freeNamesIfExpr es &&&
freeNamesIfExpr rhs
freeNamesIfFamInst :: IfaceFamInst -> NameSet
freeNamesIfFamInst (IfaceFamInst { ifFamInstFam = famName
, ifFamInstAxiom = axName })
= unitNameSet famName &&&
unitNameSet axName
freeNamesIfaceTyConParent :: IfaceTyConParent -> NameSet
freeNamesIfaceTyConParent IfNoParent = emptyNameSet
freeNamesIfaceTyConParent (IfDataInstance ax tc tys)
= unitNameSet ax &&& freeNamesIfTc tc &&& freeNamesIfAppArgs tys
-- helpers
(&&&) :: NameSet -> NameSet -> NameSet
(&&&) = unionNameSet
fnList :: (a -> NameSet) -> [a] -> NameSet
fnList f = foldr (&&&) emptyNameSet . map f
{-
Note [Tracking data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In a case expression
case e of { C a -> ...; ... }
You might think that we don't need to include the datacon C
in the free names, because its type will probably show up in
the free names of 'e'. But in rare circumstances this may
not happen. Here's the one that bit me:
module DynFlags where
import {-# SOURCE #-} Packages( PackageState )
data DynFlags = DF ... PackageState ...
module Packages where
import DynFlags
data PackageState = PS ...
lookupModule (df :: DynFlags)
= case df of
DF ...p... -> case p of
PS ... -> ...
Now, lookupModule depends on DynFlags, but the transitive dependency
on the *locally-defined* type PackageState is not visible. We need
to take account of the use of the data constructor PS in the pattern match.
************************************************************************
* *
Binary instances
* *
************************************************************************
Note that there is a bit of subtlety here when we encode names. While
IfaceTopBndrs is really just a synonym for Name, we need to take care to
encode them with {get,put}IfaceTopBndr. The difference becomes important when
we go to fingerprint an IfaceDecl. See Note [Fingerprinting IfaceDecls] for
details.
-}
instance Binary IfaceDecl where
put_ bh (IfaceId name ty details idinfo) = do
putByte bh 0
putIfaceTopBndr bh name
lazyPut bh (ty, details, idinfo)
-- See Note [Lazy deserialization of IfaceId]
put_ bh (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9) = do
putByte bh 2
putIfaceTopBndr bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh (IfaceSynonym a1 a2 a3 a4 a5) = do
putByte bh 3
putIfaceTopBndr bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh (IfaceFamily a1 a2 a3 a4 a5 a6) = do
putByte bh 4
putIfaceTopBndr bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
-- NB: Written in a funny way to avoid an interface change
put_ bh (IfaceClass {
ifName = a2,
ifRoles = a3,
ifBinders = a4,
ifFDs = a5,
ifBody = IfConcreteClass {
ifClassCtxt = a1,
ifATs = a6,
ifSigs = a7,
ifMinDef = a8
}}) = do
putByte bh 5
put_ bh a1
putIfaceTopBndr bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh (IfaceAxiom a1 a2 a3 a4) = do
putByte bh 6
putIfaceTopBndr bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh (IfacePatSyn a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11) = do
putByte bh 7
putIfaceTopBndr bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh a9
put_ bh a10
put_ bh a11
put_ bh (IfaceClass {
ifName = a1,
ifRoles = a2,
ifBinders = a3,
ifFDs = a4,
ifBody = IfAbstractClass }) = do
putByte bh 8
putIfaceTopBndr bh a1
put_ bh a2
put_ bh a3
put_ bh a4
get bh = do
h <- getByte bh
case h of
0 -> do name <- get bh
~(ty, details, idinfo) <- lazyGet bh
-- See Note [Lazy deserialization of IfaceId]
return (IfaceId name ty details idinfo)
1 -> error "Binary.get(TyClDecl): ForeignType"
2 -> do a1 <- getIfaceTopBndr bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
return (IfaceData a1 a2 a3 a4 a5 a6 a7 a8 a9)
3 -> do a1 <- getIfaceTopBndr bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
return (IfaceSynonym a1 a2 a3 a4 a5)
4 -> do a1 <- getIfaceTopBndr bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
return (IfaceFamily a1 a2 a3 a4 a5 a6)
5 -> do a1 <- get bh
a2 <- getIfaceTopBndr bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
return (IfaceClass {
ifName = a2,
ifRoles = a3,
ifBinders = a4,
ifFDs = a5,
ifBody = IfConcreteClass {
ifClassCtxt = a1,
ifATs = a6,
ifSigs = a7,
ifMinDef = a8
}})
6 -> do a1 <- getIfaceTopBndr bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
return (IfaceAxiom a1 a2 a3 a4)
7 -> do a1 <- getIfaceTopBndr bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
a9 <- get bh
a10 <- get bh
a11 <- get bh
return (IfacePatSyn a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11)
8 -> do a1 <- getIfaceTopBndr bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
return (IfaceClass {
ifName = a1,
ifRoles = a2,
ifBinders = a3,
ifFDs = a4,
ifBody = IfAbstractClass })
_ -> panic (unwords ["Unknown IfaceDecl tag:", show h])
{- Note [Lazy deserialization of IfaceId]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The use of lazyPut and lazyGet in the IfaceId Binary instance is
purely for performance reasons, to avoid deserializing details about
identifiers that will never be used. It's not involved in tying the
knot in the type checker. It saved ~1% of the total build time of GHC.
When we read an interface file, we extend the PTE, a mapping of Names
to TyThings, with the declarations we have read. The extension of the
PTE is strict in the Names, but not in the TyThings themselves.
GHC.Iface.Load.loadDecl calculates the list of (Name, TyThing) bindings to
add to the PTE. For an IfaceId, there's just one binding to add; and
the ty, details, and idinfo fields of an IfaceId are used only in the
TyThing. So by reading those fields lazily we may be able to save the
work of ever having to deserialize them (into IfaceType, etc.).
For IfaceData and IfaceClass, loadDecl creates extra implicit bindings
(the constructors and field selectors of the data declaration, or the
methods of the class), whose Names depend on more than just the Name
of the type constructor or class itself. So deserializing them lazily
would be more involved. Similar comments apply to the other
constructors of IfaceDecl with the additional point that they probably
represent a small proportion of all declarations.
-}
instance Binary IfaceFamTyConFlav where
put_ bh IfaceDataFamilyTyCon = putByte bh 0
put_ bh IfaceOpenSynFamilyTyCon = putByte bh 1
put_ bh (IfaceClosedSynFamilyTyCon mb) = putByte bh 2 >> put_ bh mb
put_ bh IfaceAbstractClosedSynFamilyTyCon = putByte bh 3
put_ _ IfaceBuiltInSynFamTyCon
= pprPanic "Cannot serialize IfaceBuiltInSynFamTyCon, used for pretty-printing only" Outputable.empty
get bh = do { h <- getByte bh
; case h of
0 -> return IfaceDataFamilyTyCon
1 -> return IfaceOpenSynFamilyTyCon
2 -> do { mb <- get bh
; return (IfaceClosedSynFamilyTyCon mb) }
3 -> return IfaceAbstractClosedSynFamilyTyCon
_ -> pprPanic "Binary.get(IfaceFamTyConFlav): Invalid tag"
(ppr (fromIntegral h :: Int)) }
instance Binary IfaceClassOp where
put_ bh (IfaceClassOp n ty def) = do
putIfaceTopBndr bh n
put_ bh ty
put_ bh def
get bh = do
n <- getIfaceTopBndr bh
ty <- get bh
def <- get bh
return (IfaceClassOp n ty def)
instance Binary IfaceAT where
put_ bh (IfaceAT dec defs) = do
put_ bh dec
put_ bh defs
get bh = do
dec <- get bh
defs <- get bh
return (IfaceAT dec defs)
instance Binary IfaceAxBranch where
put_ bh (IfaceAxBranch a1 a2 a3 a4 a5 a6 a7) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
return (IfaceAxBranch a1 a2 a3 a4 a5 a6 a7)
instance Binary IfaceConDecls where
put_ bh IfAbstractTyCon = putByte bh 0
put_ bh (IfDataTyCon cs) = putByte bh 1 >> put_ bh cs
put_ bh (IfNewTyCon c) = putByte bh 2 >> put_ bh c
get bh = do
h <- getByte bh
case h of
0 -> return IfAbstractTyCon
1 -> liftM IfDataTyCon (get bh)
2 -> liftM IfNewTyCon (get bh)
_ -> error "Binary(IfaceConDecls).get: Invalid IfaceConDecls"
instance Binary IfaceConDecl where
put_ bh (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11) = do
putIfaceTopBndr bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
put_ bh (length a9)
mapM_ (put_ bh) a9
put_ bh a10
put_ bh a11
get bh = do
a1 <- getIfaceTopBndr bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
n_fields <- get bh
a9 <- replicateM n_fields (get bh)
a10 <- get bh
a11 <- get bh
return (IfCon a1 a2 a3 a4 a5 a6 a7 a8 a9 a10 a11)
instance Binary IfaceBang where
put_ bh IfNoBang = putByte bh 0
put_ bh IfStrict = putByte bh 1
put_ bh IfUnpack = putByte bh 2
put_ bh (IfUnpackCo co) = putByte bh 3 >> put_ bh co
get bh = do
h <- getByte bh
case h of
0 -> do return IfNoBang
1 -> do return IfStrict
2 -> do return IfUnpack
_ -> do { a <- get bh; return (IfUnpackCo a) }
instance Binary IfaceSrcBang where
put_ bh (IfSrcBang a1 a2) =
do put_ bh a1
put_ bh a2
get bh =
do a1 <- get bh
a2 <- get bh
return (IfSrcBang a1 a2)
instance Binary IfaceClsInst where
put_ bh (IfaceClsInst cls tys dfun flag orph) = do
put_ bh cls
put_ bh tys
put_ bh dfun
put_ bh flag
put_ bh orph
get bh = do
cls <- get bh
tys <- get bh
dfun <- get bh
flag <- get bh
orph <- get bh
return (IfaceClsInst cls tys dfun flag orph)
instance Binary IfaceFamInst where
put_ bh (IfaceFamInst fam tys name orph) = do
put_ bh fam
put_ bh tys
put_ bh name
put_ bh orph
get bh = do
fam <- get bh
tys <- get bh
name <- get bh
orph <- get bh
return (IfaceFamInst fam tys name orph)
instance Binary IfaceRule where
put_ bh (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8) = do
put_ bh a1
put_ bh a2
put_ bh a3
put_ bh a4
put_ bh a5
put_ bh a6
put_ bh a7
put_ bh a8
get bh = do
a1 <- get bh
a2 <- get bh
a3 <- get bh
a4 <- get bh
a5 <- get bh
a6 <- get bh
a7 <- get bh
a8 <- get bh
return (IfaceRule a1 a2 a3 a4 a5 a6 a7 a8)
instance Binary IfaceAnnotation where
put_ bh (IfaceAnnotation a1 a2) = do
put_ bh a1
put_ bh a2
get bh = do
a1 <- get bh
a2 <- get bh
return (IfaceAnnotation a1 a2)
instance Binary IfaceIdDetails where
put_ bh IfVanillaId = putByte bh 0
put_ bh (IfRecSelId a b) = putByte bh 1 >> put_ bh a >> put_ bh b
put_ bh IfDFunId = putByte bh 2
get bh = do
h <- getByte bh
case h of
0 -> return IfVanillaId
1 -> do { a <- get bh; b <- get bh; return (IfRecSelId a b) }
_ -> return IfDFunId
instance Binary IfaceIdInfo where
put_ bh NoInfo = putByte bh 0
put_ bh (HasInfo i) = putByte bh 1 >> lazyPut bh i -- NB lazyPut
get bh = do
h <- getByte bh
case h of
0 -> return NoInfo
_ -> liftM HasInfo $ lazyGet bh -- NB lazyGet
instance Binary IfaceInfoItem where
put_ bh (HsArity aa) = putByte bh 0 >> put_ bh aa
put_ bh (HsStrictness ab) = putByte bh 1 >> put_ bh ab
put_ bh (HsUnfold lb ad) = putByte bh 2 >> put_ bh lb >> put_ bh ad
put_ bh (HsInline ad) = putByte bh 3 >> put_ bh ad
put_ bh HsNoCafRefs = putByte bh 4
put_ bh HsLevity = putByte bh 5
get bh = do
h <- getByte bh
case h of
0 -> liftM HsArity $ get bh
1 -> liftM HsStrictness $ get bh
2 -> do lb <- get bh
ad <- get bh
return (HsUnfold lb ad)
3 -> liftM HsInline $ get bh
4 -> return HsNoCafRefs
_ -> return HsLevity
instance Binary IfaceUnfolding where
put_ bh (IfCoreUnfold s e) = do
putByte bh 0
put_ bh s
put_ bh e
put_ bh (IfInlineRule a b c d) = do
putByte bh 1
put_ bh a
put_ bh b
put_ bh c
put_ bh d
put_ bh (IfDFunUnfold as bs) = do
putByte bh 2
put_ bh as
put_ bh bs
put_ bh (IfCompulsory e) = do
putByte bh 3
put_ bh e
get bh = do
h <- getByte bh
case h of
0 -> do s <- get bh
e <- get bh
return (IfCoreUnfold s e)
1 -> do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (IfInlineRule a b c d)
2 -> do as <- get bh
bs <- get bh
return (IfDFunUnfold as bs)
_ -> do e <- get bh
return (IfCompulsory e)
instance Binary IfaceExpr where
put_ bh (IfaceLcl aa) = do
putByte bh 0
put_ bh aa
put_ bh (IfaceType ab) = do
putByte bh 1
put_ bh ab
put_ bh (IfaceCo ab) = do
putByte bh 2
put_ bh ab
put_ bh (IfaceTuple ac ad) = do
putByte bh 3
put_ bh ac
put_ bh ad
put_ bh (IfaceLam (ae, os) af) = do
putByte bh 4
put_ bh ae
put_ bh os
put_ bh af
put_ bh (IfaceApp ag ah) = do
putByte bh 5
put_ bh ag
put_ bh ah
put_ bh (IfaceCase ai aj ak) = do
putByte bh 6
put_ bh ai
put_ bh aj
put_ bh ak
put_ bh (IfaceLet al am) = do
putByte bh 7
put_ bh al
put_ bh am
put_ bh (IfaceTick an ao) = do
putByte bh 8
put_ bh an
put_ bh ao
put_ bh (IfaceLit ap) = do
putByte bh 9
put_ bh ap
put_ bh (IfaceFCall as at) = do
putByte bh 10
put_ bh as
put_ bh at
put_ bh (IfaceExt aa) = do
putByte bh 11
put_ bh aa
put_ bh (IfaceCast ie ico) = do
putByte bh 12
put_ bh ie
put_ bh ico
put_ bh (IfaceECase a b) = do
putByte bh 13
put_ bh a
put_ bh b
get bh = do
h <- getByte bh
case h of
0 -> do aa <- get bh
return (IfaceLcl aa)
1 -> do ab <- get bh
return (IfaceType ab)
2 -> do ab <- get bh
return (IfaceCo ab)
3 -> do ac <- get bh
ad <- get bh
return (IfaceTuple ac ad)
4 -> do ae <- get bh
os <- get bh
af <- get bh
return (IfaceLam (ae, os) af)
5 -> do ag <- get bh
ah <- get bh
return (IfaceApp ag ah)
6 -> do ai <- get bh
aj <- get bh
ak <- get bh
return (IfaceCase ai aj ak)
7 -> do al <- get bh
am <- get bh
return (IfaceLet al am)
8 -> do an <- get bh
ao <- get bh
return (IfaceTick an ao)
9 -> do ap <- get bh
return (IfaceLit ap)
10 -> do as <- get bh
at <- get bh
return (IfaceFCall as at)
11 -> do aa <- get bh
return (IfaceExt aa)
12 -> do ie <- get bh
ico <- get bh
return (IfaceCast ie ico)
13 -> do a <- get bh
b <- get bh
return (IfaceECase a b)
_ -> panic ("get IfaceExpr " ++ show h)
instance Binary IfaceTickish where
put_ bh (IfaceHpcTick m ix) = do
putByte bh 0
put_ bh m
put_ bh ix
put_ bh (IfaceSCC cc tick push) = do
putByte bh 1
put_ bh cc
put_ bh tick
put_ bh push
put_ bh (IfaceSource src name) = do
putByte bh 2
put_ bh (srcSpanFile src)
put_ bh (srcSpanStartLine src)
put_ bh (srcSpanStartCol src)
put_ bh (srcSpanEndLine src)
put_ bh (srcSpanEndCol src)
put_ bh name
get bh = do
h <- getByte bh
case h of
0 -> do m <- get bh
ix <- get bh
return (IfaceHpcTick m ix)
1 -> do cc <- get bh
tick <- get bh
push <- get bh
return (IfaceSCC cc tick push)
2 -> do file <- get bh
sl <- get bh
sc <- get bh
el <- get bh
ec <- get bh
let start = mkRealSrcLoc file sl sc
end = mkRealSrcLoc file el ec
name <- get bh
return (IfaceSource (mkRealSrcSpan start end) name)
_ -> panic ("get IfaceTickish " ++ show h)
instance Binary IfaceConAlt where
put_ bh IfaceDefault = putByte bh 0
put_ bh (IfaceDataAlt aa) = putByte bh 1 >> put_ bh aa
put_ bh (IfaceLitAlt ac) = putByte bh 2 >> put_ bh ac
get bh = do
h <- getByte bh
case h of
0 -> return IfaceDefault
1 -> liftM IfaceDataAlt $ get bh
_ -> liftM IfaceLitAlt $ get bh
instance Binary IfaceBinding where
put_ bh (IfaceNonRec aa ab) = putByte bh 0 >> put_ bh aa >> put_ bh ab
put_ bh (IfaceRec ac) = putByte bh 1 >> put_ bh ac
get bh = do
h <- getByte bh
case h of
0 -> do { aa <- get bh; ab <- get bh; return (IfaceNonRec aa ab) }
_ -> do { ac <- get bh; return (IfaceRec ac) }
instance Binary IfaceLetBndr where
put_ bh (IfLetBndr a b c d) = do
put_ bh a
put_ bh b
put_ bh c
put_ bh d
get bh = do a <- get bh
b <- get bh
c <- get bh
d <- get bh
return (IfLetBndr a b c d)
instance Binary IfaceJoinInfo where
put_ bh IfaceNotJoinPoint = putByte bh 0
put_ bh (IfaceJoinPoint ar) = do
putByte bh 1
put_ bh ar
get bh = do
h <- getByte bh
case h of
0 -> return IfaceNotJoinPoint
_ -> liftM IfaceJoinPoint $ get bh
instance Binary IfaceTyConParent where
put_ bh IfNoParent = putByte bh 0
put_ bh (IfDataInstance ax pr ty) = do
putByte bh 1
put_ bh ax
put_ bh pr
put_ bh ty
get bh = do
h <- getByte bh
case h of
0 -> return IfNoParent
_ -> do
ax <- get bh
pr <- get bh
ty <- get bh
return $ IfDataInstance ax pr ty
instance Binary IfaceCompleteMatch where
put_ bh (IfaceCompleteMatch cs ts) = put_ bh cs >> put_ bh ts
get bh = IfaceCompleteMatch <$> get bh <*> get bh
{-
************************************************************************
* *
NFData instances
See Note [Avoiding space leaks in toIface*] in GHC.CoreToIface
* *
************************************************************************
-}
instance NFData IfaceDecl where
rnf = \case
IfaceId f1 f2 f3 f4 ->
rnf f1 `seq` rnf f2 `seq` rnf f3 `seq` rnf f4
IfaceData f1 f2 f3 f4 f5 f6 f7 f8 f9 ->
f1 `seq` seqList f2 `seq` f3 `seq` f4 `seq` f5 `seq`
rnf f6 `seq` rnf f7 `seq` rnf f8 `seq` rnf f9
IfaceSynonym f1 f2 f3 f4 f5 ->
rnf f1 `seq` f2 `seq` seqList f3 `seq` rnf f4 `seq` rnf f5
IfaceFamily f1 f2 f3 f4 f5 f6 ->
rnf f1 `seq` rnf f2 `seq` seqList f3 `seq` rnf f4 `seq` rnf f5 `seq` f6 `seq` ()
IfaceClass f1 f2 f3 f4 f5 ->
rnf f1 `seq` f2 `seq` seqList f3 `seq` rnf f4 `seq` rnf f5
IfaceAxiom nm tycon role ax ->
rnf nm `seq`
rnf tycon `seq`
role `seq`
rnf ax
IfacePatSyn f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11 ->
rnf f1 `seq` rnf f2 `seq` rnf f3 `seq` rnf f4 `seq` f5 `seq` f6 `seq`
rnf f7 `seq` rnf f8 `seq` rnf f9 `seq` rnf f10 `seq` f11 `seq` ()
instance NFData IfaceAxBranch where
rnf (IfaceAxBranch f1 f2 f3 f4 f5 f6 f7) =
rnf f1 `seq` rnf f2 `seq` rnf f3 `seq` rnf f4 `seq` f5 `seq` rnf f6 `seq` rnf f7
instance NFData IfaceClassBody where
rnf = \case
IfAbstractClass -> ()
IfConcreteClass f1 f2 f3 f4 -> rnf f1 `seq` rnf f2 `seq` rnf f3 `seq` f4 `seq` ()
instance NFData IfaceAT where
rnf (IfaceAT f1 f2) = rnf f1 `seq` rnf f2
instance NFData IfaceClassOp where
rnf (IfaceClassOp f1 f2 f3) = rnf f1 `seq` rnf f2 `seq` f3 `seq` ()
instance NFData IfaceTyConParent where
rnf = \case
IfNoParent -> ()
IfDataInstance f1 f2 f3 -> rnf f1 `seq` rnf f2 `seq` rnf f3
instance NFData IfaceConDecls where
rnf = \case
IfAbstractTyCon -> ()
IfDataTyCon f1 -> rnf f1
IfNewTyCon f1 -> rnf f1
instance NFData IfaceConDecl where
rnf (IfCon f1 f2 f3 f4 f5 f6 f7 f8 f9 f10 f11) =
rnf f1 `seq` rnf f2 `seq` rnf f3 `seq` rnf f4 `seq` f5 `seq` rnf f6 `seq`
rnf f7 `seq` rnf f8 `seq` f9 `seq` rnf f10 `seq` rnf f11
instance NFData IfaceSrcBang where
rnf (IfSrcBang f1 f2) = f1 `seq` f2 `seq` ()
instance NFData IfaceBang where
rnf x = x `seq` ()
instance NFData IfaceIdDetails where
rnf = \case
IfVanillaId -> ()
IfRecSelId (Left tycon) b -> rnf tycon `seq` rnf b
IfRecSelId (Right decl) b -> rnf decl `seq` rnf b
IfDFunId -> ()
instance NFData IfaceIdInfo where
rnf = \case
NoInfo -> ()
HasInfo f1 -> rnf f1
instance NFData IfaceInfoItem where
rnf = \case
HsArity a -> rnf a
HsStrictness str -> seqStrictSig str
HsInline p -> p `seq` () -- TODO: seq further?
HsUnfold b unf -> rnf b `seq` rnf unf
HsNoCafRefs -> ()
HsLevity -> ()
instance NFData IfaceUnfolding where
rnf = \case
IfCoreUnfold inlinable expr ->
rnf inlinable `seq` rnf expr
IfCompulsory expr ->
rnf expr
IfInlineRule arity b1 b2 e ->
rnf arity `seq` rnf b1 `seq` rnf b2 `seq` rnf e
IfDFunUnfold bndrs exprs ->
rnf bndrs `seq` rnf exprs
instance NFData IfaceExpr where
rnf = \case
IfaceLcl nm -> rnf nm
IfaceExt nm -> rnf nm
IfaceType ty -> rnf ty
IfaceCo co -> rnf co
IfaceTuple sort exprs -> sort `seq` rnf exprs
IfaceLam bndr expr -> rnf bndr `seq` rnf expr
IfaceApp e1 e2 -> rnf e1 `seq` rnf e2
IfaceCase e nm alts -> rnf e `seq` nm `seq` rnf alts
IfaceECase e ty -> rnf e `seq` rnf ty
IfaceLet bind e -> rnf bind `seq` rnf e
IfaceCast e co -> rnf e `seq` rnf co
IfaceLit l -> l `seq` () -- FIXME
IfaceFCall fc ty -> fc `seq` rnf ty
IfaceTick tick e -> rnf tick `seq` rnf e
instance NFData IfaceBinding where
rnf = \case
IfaceNonRec bndr e -> rnf bndr `seq` rnf e
IfaceRec binds -> rnf binds
instance NFData IfaceLetBndr where
rnf (IfLetBndr nm ty id_info join_info) =
rnf nm `seq` rnf ty `seq` rnf id_info `seq` rnf join_info
instance NFData IfaceFamTyConFlav where
rnf = \case
IfaceDataFamilyTyCon -> ()
IfaceOpenSynFamilyTyCon -> ()
IfaceClosedSynFamilyTyCon f1 -> rnf f1
IfaceAbstractClosedSynFamilyTyCon -> ()
IfaceBuiltInSynFamTyCon -> ()
instance NFData IfaceJoinInfo where
rnf x = x `seq` ()
instance NFData IfaceTickish where
rnf = \case
IfaceHpcTick m i -> rnf m `seq` rnf i
IfaceSCC cc b1 b2 -> cc `seq` rnf b1 `seq` rnf b2
IfaceSource src str -> src `seq` rnf str
instance NFData IfaceConAlt where
rnf = \case
IfaceDefault -> ()
IfaceDataAlt nm -> rnf nm
IfaceLitAlt lit -> lit `seq` ()
instance NFData IfaceCompleteMatch where
rnf (IfaceCompleteMatch f1 f2) = rnf f1 `seq` rnf f2
instance NFData IfaceRule where
rnf (IfaceRule f1 f2 f3 f4 f5 f6 f7 f8) =
rnf f1 `seq` f2 `seq` rnf f3 `seq` rnf f4 `seq` rnf f5 `seq` rnf f6 `seq` rnf f7 `seq` f8 `seq` ()
instance NFData IfaceFamInst where
rnf (IfaceFamInst f1 f2 f3 f4) =
rnf f1 `seq` rnf f2 `seq` rnf f3 `seq` f4 `seq` ()
instance NFData IfaceClsInst where
rnf (IfaceClsInst f1 f2 f3 f4 f5) =
f1 `seq` rnf f2 `seq` rnf f3 `seq` f4 `seq` f5 `seq` ()
instance NFData IfaceAnnotation where
rnf (IfaceAnnotation f1 f2) = f1 `seq` f2 `seq` ()
| sdiehl/ghc | compiler/GHC/Iface/Syntax.hs | bsd-3-clause | 98,706 | 109 | 79 | 31,831 | 22,782 | 11,505 | 11,277 | 1,803 | 14 |
{-# LANGUAGE OverloadedStrings #-}
import Test.Hspec
import LibText
import Prelude hiding (readFile, unlines)
import Data.Text
import Data.Text.IO
import Data.List as L
main :: IO ()
main = do
src <- readFile "test/testdata/TestMod.hs"
let expectedTokens = [
(((1,1),(1,29)),"ITblockComment"),
(((3,1),(3,7)),"ITmodule"),(((3,8),(3,15)),"ITconid"),
(((4,5),(4,6)),"IToparen"),(((4,7),(4,15)),"ITvarid"),
(((5,5),(5,6)),"ITcparen"),(((5,7),(5,12)),"ITwhere"),
(((7,1),(7,1)),"ITvocurly"),(((7,1),(7,7)),"ITimport"),(((7,8),(7,11)),"ITconid"),
(((9,1),(9,1)),"ITsemi"),(((9,1),(9,4)),"ITvarid"),(((9,5),(9,6)),"ITequal"),(((9,7),(0,0)),"ITquasiQuote"),
(((10,1),(0,0)),"ITquasiQuote"),
(((11,1),(0,0)),"ITquasiQuote"),
(((12,1),(0,0)),"ITquasiQuote"),
(((13,1),(0,0)),"ITquasiQuote"),
(((14,1),(0,0)),"ITquasiQuote"),
(((15,1),(15,17)),"ITquasiQuote"),
(((17,1),(17,1)),"ITsemi"),(((17,1),(17,9)),"ITvarid"),(((17,10),(17,12)),"ITdcolon"),(((17,13),(17,15)),"ITconid"),(((17,16),(17,17)),"IToparen"),(((17,17),(17,18)),"ITcparen"),
(((18,1),(18,1)),"ITsemi"),(((18,1),(18,9)),"ITvarid"),(((18,10),(18,11)),"ITequal"),(((18,12),(18,14)),"ITdo"),
(((19,3),(19,3)),"ITvocurly"),(((19,3),(19,6)),"ITlet"),(((19,7),(19,7)),"ITvocurly"),(((19,7),(19,11)),"ITvarid"),(((19,12),(19,13)),"ITequal"),(((19,14),(19,18)),"ITcase"),
(((19,19),(19,20)),"IToparen"),(((19,20),(19,21)),"ITinteger"),(((19,22),(19,24)),"ITvarsym"),(((19,25),(19,26)),"ITinteger"),(((19,27),(19,28)),"ITvarsym"),(((19,29),(19,30)),"ITinteger"),
(((19,30),(19,31)),"ITcparen"),(((19,32),(19,34)),"ITof"),
(((20,16),(20,16)),"ITvocurly"),(((20,16),(20,20)),"ITconid"),(((20,21),(20,23)),"ITrarrow"),(((20,24),(20,31)),"ITstring"),
(((21,16),(21,16)),"ITsemi"),(((21,16),(21,17)),"ITunderscore"),(((21,21),(21,23)),"ITrarrow"),(((21,24),(21,29)),"ITstring"),
(((23,3),(23,3)),"ITvccurly"),(((23,3),(23,3)),"ITvccurly"),(((23,3),(23,3)),"ITsemi"),(((23,3),(23,11)),"ITvarid"),(((23,12),(23,22)),"ITstring"),
(((25,1),(0,0)),"ITblockComment"),
(((26,1),(0,0)),"ITblockComment"),
(((27,1),(27,5)),"ITblockComment"),
(((28,1),(28,1)),"ITvccurly"),(((28,1),(28,1)),"ITsemi"),(((28,1),(28,6)),"ITvarid"),(((28,7),(28,9)),"ITdcolon"),(((28,10),(28,13)),"ITconid"),
(((29,1),(29,1)),"ITsemi"),(((29,1),(29,6)),"ITvarid"),(((29,7),(29,8)),"ITequal"),(((29,9),(29,18)),"ITvarid"),
(((31,1),(31,1)),"ITsemi"),(((31,1),(31,6)),"ITvarid"),(((31,7),(31,8)),"ITequal"),(((31,9),(0,0)),"ITstring"),
(((32,1),(0,0)),"ITstring"),
(((33,1),(33,9)),"ITstring"),(((33,12),(33,36)),"ITlineComment"),
(((35,1),(35,1)),"ITsemi")]
tokens <- ghcMainTestSpecNew
-- Prelude.putStrLn $ show tokens
hspec $
-- plan:
-- 1) lines src
-- 2) for each line: alternate WS ans tokens (for that line); last WS/token does NOT terminate with \x001F
describe "usind Data.Text, new strategy" $ do
-- TODO replace by inline multiline-splitting
it "1) splitMultilineTokens" $
splitMultilineTokens tokens `shouldBe` expectedTokens
it "2) splitLineTokens fst" $ do
let (result, _) = splitLineTokens 1 expectedTokens
result `shouldBe` [(((1,1),(1,29)),"ITblockComment")]
it "2a) splitLineTokens snd" $ do
let (_, result) = splitLineTokens 1 expectedTokens
result `shouldBe` L.drop 1 expectedTokens
it "2b) splitLineTokens snd empty" $ do
let (_, result) = splitLineTokens 35 expectedTokens
result `shouldBe` []
it "2c) splitLineTokens snd" $ do
let (result, _) = splitLineTokens 5 $ L.drop 5 expectedTokens
result `shouldBe` [(((5, 5), (5, 6)),"ITcparen"),(((5, 7), (5, 12)),"ITwhere")]
it "2d) splitLineTokens fst empty" $ do
let (result, _) = splitLineTokens 1 $ L.drop 1 expectedTokens
result `shouldBe` []
it "3) tokenizeLine" $ do
let result = tokenizeLine "module TestMod" [(((1, 1), (1, 7)),"ITmodule"),(((1, 8), (1, 15)),"ITconid")]
result `shouldBe` "ITmodule\x001Fmodule\x001FWS\x001F \x001FITconid\x001FTestMod"
it "3a) tokenizeLine only WS, no tokens" $ do
let result = tokenizeLine " " []
result `shouldBe` "WS\x001F "
it "3b) tokenizeLine empty line" $ do
let result = tokenizeLine "" []
result `shouldBe` ""
it "3c) tokenizeLine" $ do
let result = tokenizeLine " module TestMod " [(((1, 2), (1, 8)),"ITmodule"),(((1, 10), (1, 17)),"ITconid")]
result `shouldBe` "WS\x001F \x001FITmodule\x001Fmodule\x001FWS\x001F \x001FITconid\x001FTestMod\x001FWS\x001F "
it "3d) tokenizeLine multiline-first" $ do
let result = tokenizeLine "multi = \"line1\\" [(((31,1),(31,1)),"ITsemi"),(((31,1),(31,6)),"ITvarid"),(((31,7),(31,8)),"ITequal"),(((31,9),(0,0)),"ITstring")]
result `shouldBe` "ITsemi\x001F\x001FITvarid\x001Fmulti\x001FWS\x001F \x001FITequal\x001F=\x001FITstring\x001F \"line1\\"
it "3e) tokenizeLine multiline-middle" $ do
let result = tokenizeLine " \\ line2 \\ " [(((1, 1), (0, 0)),"ITstring")]
result `shouldBe` "ITstring\x001F \\ line2 \\ "
it "4) mapOverLines" $ do
let result = mapOverLines
["module TestMod", "line1 \\", " \\ line2 \\ ", "line3", " module TestMod "]
[(((1, 1), (1, 7)),"ITmodule"), (((1, 8), (1, 15)),"ITconid"),
(((2, 1), (4, 6)),"ITstring"),
(((5, 2), (5, 8)),"ITmodule"), (((5, 10), (5, 17)),"ITconid")
]
result `shouldBe` ["ITmodule\x001Fmodule\x001FWS\x001F \x001FITconid\x001FTestMod",
"ITstring\x001Fline1 \\",
"ITstring\x001F \\ line2 \\ ",
"ITstring\x001Fline3",
"WS\x001F \x001FITmodule\x001Fmodule\x001FWS\x001F \x001FITconid\x001FTestMod\x001FWS\x001F "
]
| clojj/haskell-view | test/SpecLibText.hs | bsd-3-clause | 6,213 | 0 | 20 | 1,300 | 3,151 | 1,992 | 1,159 | 89 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.