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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|
{- |
Description : Test file for Analysis_DFOL
-}
import DFOL.AS_DFOL
import DFOL.Analysis_DFOL
import DFOL.Sign
import Common.Id
import Data.Maybe
import Common.DocUtils
import qualified Common.Result as Result
import qualified Data.Map as Map
import qualified Data.Set as Set
mkTok :: String -> Token
mkTok s = Token s nullRange
natTok, matTok, plusTok, mTok, nTok, m1Tok :: NAME
natTok = mkTok "Nat"
matTok = mkTok "Mat"
plusTok = mkTok "plus"
mTok = mkTok "m"
m1Tok = mkTok "m0"
nTok = mkTok "n"
xTok = mkTok "x"
x1Tok = mkTok "x1"
x10Tok = mkTok "x10"
nat, mat, plus, m, n, m1 :: TERM
nat = Identifier natTok
mat = Identifier matTok
plus = Identifier plusTok
m = Identifier mTok
n = Identifier nTok
m1 = Identifier m1Tok
sig :: Sign
sig = Sign [([natTok], Sort),
([matTok], Func [Univ nat, Univ nat] Sort),
([plusTok], Pi [([mTok, m1Tok], Univ nat)] $ Func [Univ $ Appl mat [m, m1], Univ $ Appl mat [m, m1]] $ Univ $ Appl mat [m, m1])]
cont :: CONTEXT
cont = Context [([mTok, nTok], Univ nat)]
t0, t1, t2, t3, t4 :: TYPE
t0 = Pi [([mTok, nTok], Univ nat)] $ Func [Univ $ Appl mat [m, n], Univ $ Appl mat [m, n]] $ Univ $ Appl mat [m, n]
t1 = Pi [([mTok, m1Tok], Univ nat)] $ Func [Univ $ Appl mat [m, m1], Univ $ Appl mat [m, m1]] $ Univ $ Appl mat [m, m1]
t2 = Func [] $ typeRecForm t0
t3 = Func [Univ nat, Univ nat] Sort
t4 = Func [Univ nat] $ Func [Univ nat] $ Func [] Sort
t5 = Pi [([xTok], Sort)] $ Pi [([nTok], Sort)] $ Univ $ Appl mat [Identifier xTok, Identifier nTok]
t6 = Pi [([mTok], Sort)] $ Pi [([xTok], Sort)] $ Univ $ Appl mat [Identifier mTok, Identifier xTok]
t :: TYPE
t = let (Pi [([n1], t1)] s1) = t5
(Pi [([n2], t2)] s2) = t6
syms1 = Set.delete n1 $ getFreeVars s1
syms2 = Set.delete n2 $ getFreeVars s2
v = getNewName n1 $ Set.union syms1 syms2
type1 = translate (Map.singleton n1 (Identifier v)) syms1 s1
type2 = translate (Map.singleton n2 (Identifier v)) syms2 s2
in type2
u :: NAME
u = let (Pi [([n1], t1)] s1) = t5
(Pi [([n2], t2)] s2) = t6
syms1 = Set.delete n1 $ getFreeVars s1
syms2 = Set.delete n2 $ getFreeVars s2
v = getNewName n1 $ Set.union syms1 syms2
type1 = translate (Map.singleton n1 (Identifier v)) syms1 s1
type2 = translate (Map.singleton n2 (Identifier v)) syms2 s2
in v
|
mariefarrell/Hets
|
DFOL/Tests/Test_Analysis_DFOL.hs
|
gpl-2.0
| 2,367
| 0
| 15
| 569
| 1,156
| 632
| 524
| 60
| 1
|
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP #-}
module OptCoercion ( optCoercion, checkAxInstCo ) where
#include "HsVersions.h"
import Coercion
import Type hiding( substTyVarBndr, substTy, extendTvSubst )
import TcType ( exactTyVarsOfType )
import TyCon
import CoAxiom
import Var
import VarSet
import FamInstEnv ( flattenTys )
import VarEnv
import StaticFlags ( opt_NoOptCoercion )
import Outputable
import Pair
import FastString
import Util
import Unify
import ListSetOps
import InstEnv
import Control.Monad ( zipWithM )
{-
************************************************************************
* *
Optimising coercions
* *
************************************************************************
Note [Subtle shadowing in coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Supose we optimising a coercion
optCoercion (forall (co_X5:t1~t2). ...co_B1...)
The co_X5 is a wild-card; the bound variable of a coercion for-all
should never appear in the body of the forall. Indeed we often
write it like this
optCoercion ( (t1~t2) => ...co_B1... )
Just because it's a wild-card doesn't mean we are free to choose
whatever variable we like. For example it'd be wrong for optCoercion
to return
forall (co_B1:t1~t2). ...co_B1...
because now the co_B1 (which is really free) has been captured, and
subsequent substitutions will go wrong. That's why we can't use
mkCoPredTy in the ForAll case, where this note appears.
Note [Optimising coercion optimisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Looking up a coercion's role or kind is linear in the size of the
coercion. Thus, doing this repeatedly during the recursive descent
of coercion optimisation is disastrous. We must be careful to avoid
doing this if at all possible.
Because it is generally easy to know a coercion's components' roles
from the role of the outer coercion, we pass down the known role of
the input in the algorithm below. We also keep functions opt_co2
and opt_co3 separate from opt_co4, so that the former two do Phantom
checks that opt_co4 can avoid. This is a big win because Phantom coercions
rarely appear within non-phantom coercions -- only in some TyConAppCos
and some AxiomInstCos. We handle these cases specially by calling
opt_co2.
-}
optCoercion :: CvSubst -> Coercion -> NormalCo
-- ^ optCoercion applies a substitution to a coercion,
-- *and* optimises it to reduce its size
optCoercion env co
| opt_NoOptCoercion = substCo env co
| otherwise = opt_co1 env False co
type NormalCo = Coercion
-- Invariants:
-- * The substitution has been fully applied
-- * For trans coercions (co1 `trans` co2)
-- co1 is not a trans, and neither co1 nor co2 is identity
-- * If the coercion is the identity, it has no CoVars of CoTyCons in it (just types)
type NormalNonIdCo = NormalCo -- Extra invariant: not the identity
-- | Do we apply a @sym@ to the result?
type SymFlag = Bool
-- | Do we force the result to be representational?
type ReprFlag = Bool
-- | Optimize a coercion, making no assumptions.
opt_co1 :: CvSubst
-> SymFlag
-> Coercion -> NormalCo
opt_co1 env sym co = opt_co2 env sym (coercionRole co) co
{-
opt_co env sym co
= pprTrace "opt_co {" (ppr sym <+> ppr co $$ ppr env) $
co1 `seq`
pprTrace "opt_co done }" (ppr co1) $
(WARN( not same_co_kind, ppr co <+> dcolon <+> ppr (coercionType co)
$$ ppr co1 <+> dcolon <+> ppr (coercionType co1) )
WARN( not (coreEqCoercion co1 simple_result),
(text "env=" <+> ppr env) $$
(text "input=" <+> ppr co) $$
(text "simple=" <+> ppr simple_result) $$
(text "opt=" <+> ppr co1) )
co1)
where
co1 = opt_co' env sym co
same_co_kind = s1 `eqType` s2 && t1 `eqType` t2
Pair s t = coercionKind (substCo env co)
(s1,t1) | sym = (t,s)
| otherwise = (s,t)
Pair s2 t2 = coercionKind co1
simple_result | sym = mkSymCo (substCo env co)
| otherwise = substCo env co
-}
-- See Note [Optimising coercion optimisation]
-- | Optimize a coercion, knowing the coercion's role. No other assumptions.
opt_co2 :: CvSubst
-> SymFlag
-> Role -- ^ The role of the input coercion
-> Coercion -> NormalCo
opt_co2 env sym Phantom co = opt_phantom env sym co
opt_co2 env sym r co = opt_co3 env sym Nothing r co
-- See Note [Optimising coercion optimisation]
-- | Optimize a coercion, knowing the coercion's non-Phantom role.
opt_co3 :: CvSubst -> SymFlag -> Maybe Role -> Role -> Coercion -> NormalCo
opt_co3 env sym (Just Phantom) _ co = opt_phantom env sym co
opt_co3 env sym (Just Representational) r co = opt_co4 env sym True r co
-- if mrole is Just Nominal, that can't be a downgrade, so we can ignore
opt_co3 env sym _ r co = opt_co4 env sym False r co
-- See Note [Optimising coercion optimisation]
-- | Optimize a non-phantom coercion.
opt_co4 :: CvSubst -> SymFlag -> ReprFlag -> Role -> Coercion -> NormalCo
opt_co4 env _ rep r (Refl _r ty)
= ASSERT( r == _r )
Refl (chooseRole rep r) (substTy env ty)
opt_co4 env sym rep r (SymCo co) = opt_co4 env (not sym) rep r co
opt_co4 env sym rep r g@(TyConAppCo _r tc cos)
= ASSERT( r == _r )
case (rep, r) of
(True, Nominal) ->
mkTyConAppCo Representational tc
(zipWith3 (opt_co3 env sym)
(map Just (tyConRolesX Representational tc))
(repeat Nominal)
cos)
(False, Nominal) ->
mkTyConAppCo Nominal tc (map (opt_co4 env sym False Nominal) cos)
(_, Representational) ->
-- must use opt_co2 here, because some roles may be P
-- See Note [Optimising coercion optimisation]
mkTyConAppCo r tc (zipWith (opt_co2 env sym)
(tyConRolesX r tc) -- the current roles
cos)
(_, Phantom) -> pprPanic "opt_co4 sees a phantom!" (ppr g)
opt_co4 env sym rep r (AppCo co1 co2) = mkAppCo (opt_co4 env sym rep r co1)
(opt_co4 env sym False Nominal co2)
opt_co4 env sym rep r (ForAllCo tv co)
= case substTyVarBndr env tv of
(env', tv') -> mkForAllCo tv' (opt_co4 env' sym rep r co)
-- Use the "mk" functions to check for nested Refls
opt_co4 env sym rep r (CoVarCo cv)
| Just co <- lookupCoVar env cv
= opt_co4 (zapCvSubstEnv env) sym rep r co
| Just cv1 <- lookupInScope (getCvInScope env) cv
= ASSERT( isCoVar cv1 ) wrapRole rep r $ wrapSym sym (CoVarCo cv1)
-- cv1 might have a substituted kind!
| otherwise = WARN( True, ptext (sLit "opt_co: not in scope:") <+> ppr cv $$ ppr env)
ASSERT( isCoVar cv )
wrapRole rep r $ wrapSym sym (CoVarCo cv)
opt_co4 env sym rep r (AxiomInstCo con ind cos)
-- Do *not* push sym inside top-level axioms
-- e.g. if g is a top-level axiom
-- g a : f a ~ a
-- then (sym (g ty)) /= g (sym ty) !!
= ASSERT( r == coAxiomRole con )
wrapRole rep (coAxiomRole con) $
wrapSym sym $
-- some sub-cos might be P: use opt_co2
-- See Note [Optimising coercion optimisation]
AxiomInstCo con ind (zipWith (opt_co2 env False)
(coAxBranchRoles (coAxiomNthBranch con ind))
cos)
-- Note that the_co does *not* have sym pushed into it
opt_co4 env sym rep r (UnivCo s _r oty1 oty2)
= ASSERT( r == _r )
opt_univ env s (chooseRole rep r) a b
where
(a,b) = if sym then (oty2,oty1) else (oty1,oty2)
opt_co4 env sym rep r (TransCo co1 co2)
-- sym (g `o` h) = sym h `o` sym g
| sym = opt_trans in_scope co2' co1'
| otherwise = opt_trans in_scope co1' co2'
where
co1' = opt_co4 env sym rep r co1
co2' = opt_co4 env sym rep r co2
in_scope = getCvInScope env
opt_co4 env sym rep r co@(NthCo {}) = opt_nth_co env sym rep r co
opt_co4 env sym rep r (LRCo lr co)
| Just pr_co <- splitAppCo_maybe co
= ASSERT( r == Nominal )
opt_co4 env sym rep Nominal (pickLR lr pr_co)
| Just pr_co <- splitAppCo_maybe co'
= ASSERT( r == Nominal )
if rep
then opt_co4 (zapCvSubstEnv env) False True Nominal (pickLR lr pr_co)
else pickLR lr pr_co
| otherwise
= wrapRole rep Nominal $ LRCo lr co'
where
co' = opt_co4 env sym False Nominal co
opt_co4 env sym rep r (InstCo co ty)
-- See if the first arg is already a forall
-- ...then we can just extend the current substitution
| Just (tv, co_body) <- splitForAllCo_maybe co
= opt_co4 (extendTvSubst env tv ty') sym rep r co_body
-- See if it is a forall after optimization
-- If so, do an inefficient one-variable substitution
| Just (tv, co'_body) <- splitForAllCo_maybe co'
= substCoWithTy (getCvInScope env) tv ty' co'_body
| otherwise = InstCo co' ty'
where
co' = opt_co4 env sym rep r co
ty' = substTy env ty
opt_co4 env sym _ r (SubCo co)
= ASSERT( r == Representational )
opt_co4 env sym True Nominal co
-- XXX: We could add another field to CoAxiomRule that
-- would allow us to do custom simplifications.
opt_co4 env sym rep r (AxiomRuleCo co ts cs)
= ASSERT( r == coaxrRole co )
wrapRole rep r $
wrapSym sym $
AxiomRuleCo co (map (substTy env) ts)
(zipWith (opt_co2 env False) (coaxrAsmpRoles co) cs)
-------------
-- | Optimize a phantom coercion. The input coercion may not necessarily
-- be a phantom, but the output sure will be.
opt_phantom :: CvSubst -> SymFlag -> Coercion -> NormalCo
opt_phantom env sym co
= if sym
then opt_univ env (fsLit "opt_phantom") Phantom ty2 ty1
else opt_univ env (fsLit "opt_phantom") Phantom ty1 ty2
where
Pair ty1 ty2 = coercionKind co
opt_univ :: CvSubst -> FastString -> Role -> Type -> Type -> Coercion
opt_univ env prov role oty1 oty2
| Just (tc1, tys1) <- splitTyConApp_maybe oty1
, Just (tc2, tys2) <- splitTyConApp_maybe oty2
, tc1 == tc2
= mkTyConAppCo role tc1 (zipWith3 (opt_univ env prov) (tyConRolesX role tc1) tys1 tys2)
| Just (l1, r1) <- splitAppTy_maybe oty1
, Just (l2, r2) <- splitAppTy_maybe oty2
, typeKind l1 `eqType` typeKind l2 -- kind(r1) == kind(r2) by consequence
= let role' = if role == Phantom then Phantom else Nominal in
-- role' is to comform to mkAppCo's precondition
mkAppCo (opt_univ env prov role l1 l2) (opt_univ env prov role' r1 r2)
| Just (tv1, ty1) <- splitForAllTy_maybe oty1
, Just (tv2, ty2) <- splitForAllTy_maybe oty2
, tyVarKind tv1 `eqType` tyVarKind tv2 -- rule out a weird unsafeCo
= case substTyVarBndr2 env tv1 tv2 of { (env1, env2, tv') ->
let ty1' = substTy env1 ty1
ty2' = substTy env2 ty2 in
mkForAllCo tv' (opt_univ (zapCvSubstEnv2 env1 env2) prov role ty1' ty2') }
| otherwise
= mkUnivCo prov role (substTy env oty1) (substTy env oty2)
-------------
-- NthCo must be handled separately, because it's the one case where we can't
-- tell quickly what the component coercion's role is from the containing
-- coercion. To avoid repeated coercionRole calls as opt_co1 calls opt_co2,
-- we just look for nested NthCo's, which can happen in practice.
opt_nth_co :: CvSubst -> SymFlag -> ReprFlag -> Role -> Coercion -> NormalCo
opt_nth_co env sym rep r = go []
where
go ns (NthCo n co) = go (n:ns) co
-- previous versions checked if the tycon is decomposable. This
-- is redundant, because a non-decomposable tycon under an NthCo
-- is entirely bogus. See docs/core-spec/core-spec.pdf.
go ns co
= opt_nths ns co
-- input coercion is *not* yet sym'd or opt'd
opt_nths [] co = opt_co4 env sym rep r co
opt_nths (n:ns) (TyConAppCo _ _ cos) = opt_nths ns (cos `getNth` n)
-- here, the co isn't a TyConAppCo, so we opt it, hoping to get
-- a TyConAppCo as output. We don't know the role, so we use
-- opt_co1. This is slightly annoying, because opt_co1 will call
-- coercionRole, but as long as we don't have a long chain of
-- NthCo's interspersed with some other coercion former, we should
-- be OK.
opt_nths ns co = opt_nths' ns (opt_co1 env sym co)
-- input coercion *is* sym'd and opt'd
opt_nths' [] co
= if rep && (r == Nominal)
-- propagate the SubCo:
then opt_co4 (zapCvSubstEnv env) False True r co
else co
opt_nths' (n:ns) (TyConAppCo _ _ cos) = opt_nths' ns (cos `getNth` n)
opt_nths' ns co = wrapRole rep r (mk_nths ns co)
mk_nths [] co = co
mk_nths (n:ns) co = mk_nths ns (mkNthCo n co)
-------------
opt_transList :: InScopeSet -> [NormalCo] -> [NormalCo] -> [NormalCo]
opt_transList is = zipWith (opt_trans is)
opt_trans :: InScopeSet -> NormalCo -> NormalCo -> NormalCo
opt_trans is co1 co2
| isReflCo co1 = co2
| otherwise = opt_trans1 is co1 co2
opt_trans1 :: InScopeSet -> NormalNonIdCo -> NormalCo -> NormalCo
-- First arg is not the identity
opt_trans1 is co1 co2
| isReflCo co2 = co1
| otherwise = opt_trans2 is co1 co2
opt_trans2 :: InScopeSet -> NormalNonIdCo -> NormalNonIdCo -> NormalCo
-- Neither arg is the identity
opt_trans2 is (TransCo co1a co1b) co2
-- Don't know whether the sub-coercions are the identity
= opt_trans is co1a (opt_trans is co1b co2)
opt_trans2 is co1 co2
| Just co <- opt_trans_rule is co1 co2
= co
opt_trans2 is co1 (TransCo co2a co2b)
| Just co1_2a <- opt_trans_rule is co1 co2a
= if isReflCo co1_2a
then co2b
else opt_trans1 is co1_2a co2b
opt_trans2 _ co1 co2
= mkTransCo co1 co2
------
-- Optimize coercions with a top-level use of transitivity.
opt_trans_rule :: InScopeSet -> NormalNonIdCo -> NormalNonIdCo -> Maybe NormalCo
-- Push transitivity through matching destructors
opt_trans_rule is in_co1@(NthCo d1 co1) in_co2@(NthCo d2 co2)
| d1 == d2
, co1 `compatible_co` co2
= fireTransRule "PushNth" in_co1 in_co2 $
mkNthCo d1 (opt_trans is co1 co2)
opt_trans_rule is in_co1@(LRCo d1 co1) in_co2@(LRCo d2 co2)
| d1 == d2
, co1 `compatible_co` co2
= fireTransRule "PushLR" in_co1 in_co2 $
mkLRCo d1 (opt_trans is co1 co2)
-- Push transitivity inside instantiation
opt_trans_rule is in_co1@(InstCo co1 ty1) in_co2@(InstCo co2 ty2)
| ty1 `eqType` ty2
, co1 `compatible_co` co2
= fireTransRule "TrPushInst" in_co1 in_co2 $
mkInstCo (opt_trans is co1 co2) ty1
-- Push transitivity down through matching top-level constructors.
opt_trans_rule is in_co1@(TyConAppCo r1 tc1 cos1) in_co2@(TyConAppCo r2 tc2 cos2)
| tc1 == tc2
= ASSERT( r1 == r2 )
fireTransRule "PushTyConApp" in_co1 in_co2 $
TyConAppCo r1 tc1 (opt_transList is cos1 cos2)
opt_trans_rule is in_co1@(AppCo co1a co1b) in_co2@(AppCo co2a co2b)
= fireTransRule "TrPushApp" in_co1 in_co2 $
mkAppCo (opt_trans is co1a co2a) (opt_trans is co1b co2b)
-- Eta rules
opt_trans_rule is co1@(TyConAppCo r tc cos1) co2
| Just cos2 <- etaTyConAppCo_maybe tc co2
= ASSERT( length cos1 == length cos2 )
fireTransRule "EtaCompL" co1 co2 $
TyConAppCo r tc (opt_transList is cos1 cos2)
opt_trans_rule is co1 co2@(TyConAppCo r tc cos2)
| Just cos1 <- etaTyConAppCo_maybe tc co1
= ASSERT( length cos1 == length cos2 )
fireTransRule "EtaCompR" co1 co2 $
TyConAppCo r tc (opt_transList is cos1 cos2)
opt_trans_rule is co1@(AppCo co1a co1b) co2
| Just (co2a,co2b) <- etaAppCo_maybe co2
= fireTransRule "EtaAppL" co1 co2 $
mkAppCo (opt_trans is co1a co2a) (opt_trans is co1b co2b)
opt_trans_rule is co1 co2@(AppCo co2a co2b)
| Just (co1a,co1b) <- etaAppCo_maybe co1
= fireTransRule "EtaAppR" co1 co2 $
mkAppCo (opt_trans is co1a co2a) (opt_trans is co1b co2b)
-- Push transitivity inside forall
opt_trans_rule is co1 co2
| Just (tv1,r1) <- splitForAllCo_maybe co1
, Just (tv2,r2) <- etaForAllCo_maybe co2
, let r2' = substCoWithTy is' tv2 (mkTyVarTy tv1) r2
is' = is `extendInScopeSet` tv1
= fireTransRule "EtaAllL" co1 co2 $
mkForAllCo tv1 (opt_trans2 is' r1 r2')
| Just (tv2,r2) <- splitForAllCo_maybe co2
, Just (tv1,r1) <- etaForAllCo_maybe co1
, let r1' = substCoWithTy is' tv1 (mkTyVarTy tv2) r1
is' = is `extendInScopeSet` tv2
= fireTransRule "EtaAllR" co1 co2 $
mkForAllCo tv1 (opt_trans2 is' r1' r2)
-- Push transitivity inside axioms
opt_trans_rule is co1 co2
-- See Note [Why call checkAxInstCo during optimisation]
-- TrPushSymAxR
| Just (sym, con, ind, cos1) <- co1_is_axiom_maybe
, Just cos2 <- matchAxiom sym con ind co2
, True <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is (map mkSymCo cos2) cos1)
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushSymAxR" co1 co2 $ SymCo newAxInst
-- TrPushAxR
| Just (sym, con, ind, cos1) <- co1_is_axiom_maybe
, Just cos2 <- matchAxiom sym con ind co2
, False <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is cos1 cos2)
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushAxR" co1 co2 newAxInst
-- TrPushSymAxL
| Just (sym, con, ind, cos2) <- co2_is_axiom_maybe
, Just cos1 <- matchAxiom (not sym) con ind co1
, True <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is cos2 (map mkSymCo cos1))
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushSymAxL" co1 co2 $ SymCo newAxInst
-- TrPushAxL
| Just (sym, con, ind, cos2) <- co2_is_axiom_maybe
, Just cos1 <- matchAxiom (not sym) con ind co1
, False <- sym
, let newAxInst = AxiomInstCo con ind (opt_transList is cos1 cos2)
, Nothing <- checkAxInstCo newAxInst
= fireTransRule "TrPushAxL" co1 co2 newAxInst
-- TrPushAxSym/TrPushSymAx
| Just (sym1, con1, ind1, cos1) <- co1_is_axiom_maybe
, Just (sym2, con2, ind2, cos2) <- co2_is_axiom_maybe
, con1 == con2
, ind1 == ind2
, sym1 == not sym2
, let branch = coAxiomNthBranch con1 ind1
qtvs = coAxBranchTyVars branch
lhs = coAxNthLHS con1 ind1
rhs = coAxBranchRHS branch
pivot_tvs = exactTyVarsOfType (if sym2 then rhs else lhs)
, all (`elemVarSet` pivot_tvs) qtvs
= fireTransRule "TrPushAxSym" co1 co2 $
if sym2
then liftCoSubstWith role qtvs (opt_transList is cos1 (map mkSymCo cos2)) lhs -- TrPushAxSym
else liftCoSubstWith role qtvs (opt_transList is (map mkSymCo cos1) cos2) rhs -- TrPushSymAx
where
co1_is_axiom_maybe = isAxiom_maybe co1
co2_is_axiom_maybe = isAxiom_maybe co2
role = coercionRole co1 -- should be the same as coercionRole co2!
opt_trans_rule _ co1 co2 -- Identity rule
| (Pair ty1 _, r) <- coercionKindRole co1
, Pair _ ty2 <- coercionKind co2
, ty1 `eqType` ty2
= fireTransRule "RedTypeDirRefl" co1 co2 $
Refl r ty2
opt_trans_rule _ _ _ = Nothing
fireTransRule :: String -> Coercion -> Coercion -> Coercion -> Maybe Coercion
fireTransRule _rule _co1 _co2 res
= -- pprTrace ("Trans rule fired: " ++ _rule) (vcat [ppr _co1, ppr _co2, ppr res]) $
Just res
{-
Note [Conflict checking with AxiomInstCo]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Consider the following type family and axiom:
type family Equal (a :: k) (b :: k) :: Bool
type instance where
Equal a a = True
Equal a b = False
--
Equal :: forall k::BOX. k -> k -> Bool
axEqual :: { forall k::BOX. forall a::k. Equal k a a ~ True
; forall k::BOX. forall a::k. forall b::k. Equal k a b ~ False }
We wish to disallow (axEqual[1] <*> <Int> <Int). (Recall that the index is
0-based, so this is the second branch of the axiom.) The problem is that, on
the surface, it seems that (axEqual[1] <*> <Int> <Int>) :: (Equal * Int Int ~
False) and that all is OK. But, all is not OK: we want to use the first branch
of the axiom in this case, not the second. The problem is that the parameters
of the first branch can unify with the supplied coercions, thus meaning that
the first branch should be taken. See also Note [Branched instance checking]
in types/FamInstEnv.hs.
Note [Why call checkAxInstCo during optimisation]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
It is possible that otherwise-good-looking optimisations meet with disaster
in the presence of axioms with multiple equations. Consider
type family Equal (a :: *) (b :: *) :: Bool where
Equal a a = True
Equal a b = False
type family Id (a :: *) :: * where
Id a = a
axEq :: { [a::*]. Equal a a ~ True
; [a::*, b::*]. Equal a b ~ False }
axId :: [a::*]. Id a ~ a
co1 = Equal (axId[0] Int) (axId[0] Bool)
:: Equal (Id Int) (Id Bool) ~ Equal Int Bool
co2 = axEq[1] <Int> <Bool>
:: Equal Int Bool ~ False
We wish to optimise (co1 ; co2). We end up in rule TrPushAxL, noting that
co2 is an axiom and that matchAxiom succeeds when looking at co1. But, what
happens when we push the coercions inside? We get
co3 = axEq[1] (axId[0] Int) (axId[0] Bool)
:: Equal (Id Int) (Id Bool) ~ False
which is bogus! This is because the type system isn't smart enough to know
that (Id Int) and (Id Bool) are Surely Apart, as they're headed by type
families. At the time of writing, I (Richard Eisenberg) couldn't think of
a way of detecting this any more efficient than just building the optimised
coercion and checking.
-}
-- | Check to make sure that an AxInstCo is internally consistent.
-- Returns the conflicting branch, if it exists
-- See Note [Conflict checking with AxiomInstCo]
checkAxInstCo :: Coercion -> Maybe CoAxBranch
-- defined here to avoid dependencies in Coercion
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in CoreLint
checkAxInstCo (AxiomInstCo ax ind cos)
= let branch = coAxiomNthBranch ax ind
tvs = coAxBranchTyVars branch
incomps = coAxBranchIncomps branch
tys = map (pFst . coercionKind) cos
subst = zipOpenTvSubst tvs tys
target = Type.substTys subst (coAxBranchLHS branch)
in_scope = mkInScopeSet $
unionVarSets (map (tyVarsOfTypes . coAxBranchLHS) incomps)
flattened_target = flattenTys in_scope target in
check_no_conflict flattened_target incomps
where
check_no_conflict :: [Type] -> [CoAxBranch] -> Maybe CoAxBranch
check_no_conflict _ [] = Nothing
check_no_conflict flat (b@CoAxBranch { cab_lhs = lhs_incomp } : rest)
-- See Note [Apartness] in FamInstEnv
| SurelyApart <- tcUnifyTysFG instanceBindFun flat lhs_incomp
= check_no_conflict flat rest
| otherwise
= Just b
checkAxInstCo _ = Nothing
-----------
wrapSym :: SymFlag -> Coercion -> Coercion
wrapSym sym co | sym = SymCo co
| otherwise = co
-- | Conditionally set a role to be representational
wrapRole :: ReprFlag
-> Role -- ^ current role
-> Coercion -> Coercion
wrapRole False _ = id
wrapRole True current = downgradeRole Representational current
-- | If we require a representational role, return that. Otherwise,
-- return the "default" role provided.
chooseRole :: ReprFlag
-> Role -- ^ "default" role
-> Role
chooseRole True _ = Representational
chooseRole _ r = r
-----------
-- takes two tyvars and builds env'ts to map them to the same tyvar
substTyVarBndr2 :: CvSubst -> TyVar -> TyVar
-> (CvSubst, CvSubst, TyVar)
substTyVarBndr2 env tv1 tv2
= case substTyVarBndr env tv1 of
(env1, tv1') -> (env1, extendTvSubstAndInScope env tv2 (mkTyVarTy tv1'), tv1')
zapCvSubstEnv2 :: CvSubst -> CvSubst -> CvSubst
zapCvSubstEnv2 env1 env2 = mkCvSubst (is1 `unionInScope` is2) []
where is1 = getCvInScope env1
is2 = getCvInScope env2
-----------
isAxiom_maybe :: Coercion -> Maybe (Bool, CoAxiom Branched, Int, [Coercion])
isAxiom_maybe (SymCo co)
| Just (sym, con, ind, cos) <- isAxiom_maybe co
= Just (not sym, con, ind, cos)
isAxiom_maybe (AxiomInstCo con ind cos)
= Just (False, con, ind, cos)
isAxiom_maybe _ = Nothing
matchAxiom :: Bool -- True = match LHS, False = match RHS
-> CoAxiom br -> Int -> Coercion -> Maybe [Coercion]
-- If we succeed in matching, then *all the quantified type variables are bound*
-- E.g. if tvs = [a,b], lhs/rhs = [b], we'll fail
matchAxiom sym ax@(CoAxiom { co_ax_tc = tc }) ind co
= let (CoAxBranch { cab_tvs = qtvs
, cab_roles = roles
, cab_lhs = lhs
, cab_rhs = rhs }) = coAxiomNthBranch ax ind in
case liftCoMatch (mkVarSet qtvs) (if sym then (mkTyConApp tc lhs) else rhs) co of
Nothing -> Nothing
Just subst -> zipWithM (liftCoSubstTyVar subst) roles qtvs
-------------
compatible_co :: Coercion -> Coercion -> Bool
-- Check whether (co1 . co2) will be well-kinded
compatible_co co1 co2
= x1 `eqType` x2
where
Pair _ x1 = coercionKind co1
Pair x2 _ = coercionKind co2
-------------
etaForAllCo_maybe :: Coercion -> Maybe (TyVar, Coercion)
-- Try to make the coercion be of form (forall tv. co)
etaForAllCo_maybe co
| Just (tv, r) <- splitForAllCo_maybe co
= Just (tv, r)
| Pair ty1 ty2 <- coercionKind co
, Just (tv1, _) <- splitForAllTy_maybe ty1
, Just (tv2, _) <- splitForAllTy_maybe ty2
, tyVarKind tv1 `eqKind` tyVarKind tv2
= Just (tv1, mkInstCo co (mkTyVarTy tv1))
| otherwise
= Nothing
etaAppCo_maybe :: Coercion -> Maybe (Coercion,Coercion)
-- If possible, split a coercion
-- g :: t1a t1b ~ t2a t2b
-- into a pair of coercions (left g, right g)
etaAppCo_maybe co
| Just (co1,co2) <- splitAppCo_maybe co
= Just (co1,co2)
| (Pair ty1 ty2, Nominal) <- coercionKindRole co
, Just (_,t1) <- splitAppTy_maybe ty1
, Just (_,t2) <- splitAppTy_maybe ty2
, typeKind t1 `eqType` typeKind t2 -- Note [Eta for AppCo]
= Just (LRCo CLeft co, LRCo CRight co)
| otherwise
= Nothing
etaTyConAppCo_maybe :: TyCon -> Coercion -> Maybe [Coercion]
-- If possible, split a coercion
-- g :: T s1 .. sn ~ T t1 .. tn
-- into [ Nth 0 g :: s1~t1, ..., Nth (n-1) g :: sn~tn ]
etaTyConAppCo_maybe tc (TyConAppCo _ tc2 cos2)
= ASSERT( tc == tc2 ) Just cos2
etaTyConAppCo_maybe tc co
| isDecomposableTyCon tc
, Pair ty1 ty2 <- coercionKind co
, Just (tc1, tys1) <- splitTyConApp_maybe ty1
, Just (tc2, tys2) <- splitTyConApp_maybe ty2
, tc1 == tc2
, let n = length tys1
= ASSERT( tc == tc1 )
ASSERT( n == length tys2 )
Just (decomposeCo n co)
-- NB: n might be <> tyConArity tc
-- e.g. data family T a :: * -> *
-- g :: T a b ~ T c d
| otherwise
= Nothing
{-
Note [Eta for AppCo]
~~~~~~~~~~~~~~~~~~~~
Suppose we have
g :: s1 t1 ~ s2 t2
Then we can't necessarily make
left g :: s1 ~ s2
right g :: t1 ~ t2
because it's possible that
s1 :: * -> * t1 :: *
s2 :: (*->*) -> * t2 :: * -> *
and in that case (left g) does not have the same
kind on either side.
It's enough to check that
kind t1 = kind t2
because if g is well-kinded then
kind (s1 t2) = kind (s2 t2)
and these two imply
kind s1 = kind s2
-}
|
fmthoma/ghc
|
compiler/types/OptCoercion.hs
|
bsd-3-clause
| 27,220
| 0
| 15
| 6,654
| 6,342
| 3,216
| 3,126
| -1
| -1
|
{-# LANGUAGE ScopedTypeVariables #-}
-- |Client interface for the ROS Parameter Server API. Note that
-- dictionary values are not supported.
module Ros.Graph.ParameterServer (deleteParam, setParam, getParam, searchParam,
subscribeParam, unsubscribeParam, hasParam,
getParamNames) where
import Network.XmlRpc.Client
import Network.XmlRpc.Internals (XmlRpcType)
import Ros.Internal.RosTypes
-- |Delete a parameter on the server.
deleteParam :: URI -> CallerID -> ParamName -> IO (Int,String,Int)
deleteParam = flip remote "deleteParam"
-- |Set a parameter value on the server.
setParam :: XmlRpcType a => URI -> CallerID -> ParamName -> a -> IO (Int,String,Int)
setParam = flip remote "setParam"
-- Helper for extracting a value from a tuple returned by the
-- parameter server.
handleParam :: (Int,String,a) -> IO (Maybe a)
handleParam (1,_,x) = return $ Just x
handleParam (_,_,_) = return Nothing
-- |Retrieve parameter value from server.
getParam :: XmlRpcType a => URI -> CallerID -> ParamName -> IO (Maybe a)
getParam uri caller name = handleParam =<< remote uri "getParam" caller name
-- |Search for a parameter name on the Parameter Server. The search
-- starts in the caller's namespace and proceeds upwards through
-- parent namespaces until the Parameter Server finds a matching
-- key. The first non-trivial partial match is returned.
searchParam :: URI -> CallerID -> ParamName -> IO (Maybe String)
searchParam uri caller name = handle =<< remote uri "searchParam" caller name
where handle :: (Int, String, String) -> IO (Maybe String)
handle (1, _, n) = return $ Just n
handle (_, _, _) = return $ Nothing
-- |Retrieve parameter value from server and subscribe to updates to
-- that param. See paramUpdate() in the 'Ros.SlaveAPI' API.
subscribeParam :: XmlRpcType a => URI -> CallerID -> URI -> ParamName ->
IO (Maybe a)
subscribeParam uri caller myUri name =
handleParam =<< remote uri "subscribeParam" caller myUri name
-- |Unsubscribe from updates to a parameter. If there is an error, the
-- status message is returned on the 'Left'; otherwise whether or not
-- the caller was previously subscribed to the parameter is returned
-- on the 'Right'.
unsubscribeParam :: URI -> CallerID -> URI -> ParamName -> IO (Either String Bool)
unsubscribeParam uri caller myUri name =
handle =<< remote uri "unsubscribeParam" caller myUri name
where handle :: (Int, String, Int) -> IO (Either String Bool)
handle (1, _, 0) = return $ Right False
handle (1, _, _) = return $ Right True
handle (_, msg, _) = return $ Left msg
-- |Check if a parameter is stored on the server. If there is an
-- error, the status message is returned on the 'Left'; otherwise the
-- query response is returned on the 'Right'.
hasParam :: URI -> CallerID -> ParamName -> IO (Either String Bool)
hasParam uri caller name = handle =<< remote uri "hasParam" caller name
where handle :: (Int,String,Bool) -> IO (Either String Bool)
handle (1,_,b) = return $ Right b
handle (_,msg,_) = return $ Left msg
-- |Get a list of all parameter names stored on this server.
getParamNames :: URI -> CallerID -> IO (Either String [String])
getParamNames uri caller = handle =<< remote uri "getParamNames" caller
where handle :: (Int, String, [String]) -> IO (Either String [String])
handle (1,_,names) = return $ Right names
handle (_,msg,_) = return $ Left msg
|
bitemyapp/roshask
|
src/Ros/Graph/ParameterServer.hs
|
bsd-3-clause
| 3,541
| 0
| 12
| 754
| 916
| 497
| 419
| 42
| 3
|
{-# OPTIONS_GHC -XMagicHash -XBangPatterns -fno-warn-unused-imports #-}
{-# OPTIONS_HADDOCK hide #-}
-- XXX With a GHC 6.9 we get a spurious
-- Data/Array/Base.hs:26:0:
-- Warning: Module `Data.Ix' is imported, but nothing from it is used,
-- except perhaps instances visible in `Data.Ix'
-- To suppress this warning, use: import Data.Ix()
-- The -fno-warn-unused-imports works around that bug
-----------------------------------------------------------------------------
-- |
-- Module : Data.Array.Base
-- Copyright : (c) The University of Glasgow 2001
-- License : BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer : libraries@haskell.org
-- Stability : experimental
-- Portability : non-portable (MPTCs, uses Control.Monad.ST)
--
-- Basis for IArray and MArray. Not intended for external consumption;
-- use IArray or MArray instead.
--
-----------------------------------------------------------------------------
-- #hide
module Data.Array.Base where
import Control.Monad.ST.Lazy ( strictToLazyST )
import qualified Control.Monad.ST.Lazy as Lazy (ST)
import Data.Ix ( Ix, range, index, rangeSize )
import Foreign.C.Types
import Foreign.StablePtr
#ifdef __GLASGOW_HASKELL__
import Data.Char
import GHC.Arr ( STArray, unsafeIndex )
import qualified GHC.Arr as Arr
import qualified GHC.Arr as ArrST
import GHC.ST ( ST(..), runST )
import GHC.Base
import GHC.Word ( Word(..) )
import GHC.Ptr ( Ptr(..), FunPtr(..), nullPtr, nullFunPtr )
import GHC.Float ( Float(..), Double(..) )
import GHC.Stable ( StablePtr(..) )
import GHC.Int ( Int8(..), Int16(..), Int32(..), Int64(..) )
import GHC.Word ( Word8(..), Word16(..), Word32(..), Word64(..) )
#if __GLASGOW_HASKELL__ >= 611
import GHC.IO ( IO(..), stToIO )
import GHC.IOArray ( IOArray(..),
newIOArray, unsafeReadIOArray, unsafeWriteIOArray )
#else
import GHC.IOBase ( IO(..), IOArray(..), stToIO,
newIOArray, unsafeReadIOArray, unsafeWriteIOArray )
#endif
#else
import Data.Int
import Data.Word
import Foreign.Ptr
#endif
#ifdef __HUGS__
import Data.Bits
import Foreign.Storable
import qualified Hugs.Array as Arr
import qualified Hugs.ST as ArrST
import Hugs.Array ( unsafeIndex )
import Hugs.IOArray
import Hugs.ST ( STArray, ST(..), runST )
import Hugs.ByteArray
#endif
import Data.Typeable
#include "Typeable.h"
#ifdef __GLASGOW_HASKELL__
#include "MachDeps.h"
#endif
-----------------------------------------------------------------------------
-- Class of immutable arrays
{- | Class of immutable array types.
An array type has the form @(a i e)@ where @a@ is the array type
constructor (kind @* -> * -> *@), @i@ is the index type (a member of
the class 'Ix'), and @e@ is the element type. The @IArray@ class is
parameterised over both @a@ and @e@, so that instances specialised to
certain element types can be defined.
-}
class IArray a e where
-- | Extracts the bounds of an immutable array
bounds :: Ix i => a i e -> (i,i)
numElements :: Ix i => a i e -> Int
unsafeArray :: Ix i => (i,i) -> [(Int, e)] -> a i e
unsafeAt :: Ix i => a i e -> Int -> e
unsafeReplace :: Ix i => a i e -> [(Int, e)] -> a i e
unsafeAccum :: Ix i => (e -> e' -> e) -> a i e -> [(Int, e')] -> a i e
unsafeAccumArray :: Ix i => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> a i e
unsafeReplace arr ies = runST (unsafeReplaceST arr ies >>= unsafeFreeze)
unsafeAccum f arr ies = runST (unsafeAccumST f arr ies >>= unsafeFreeze)
unsafeAccumArray f e lu ies = runST (unsafeAccumArrayST f e lu ies >>= unsafeFreeze)
{-# INLINE safeRangeSize #-}
safeRangeSize :: Ix i => (i, i) -> Int
safeRangeSize (l,u) = let r = rangeSize (l, u)
in if r < 0 then error "Negative range size"
else r
{-# INLINE safeIndex #-}
safeIndex :: Ix i => (i, i) -> Int -> i -> Int
safeIndex (l,u) n i = let i' = index (l,u) i
in if (0 <= i') && (i' < n)
then i'
else error ("Error in array index; " ++ show i' ++
" not in range [0.." ++ show n ++ ")")
{-# INLINE unsafeReplaceST #-}
unsafeReplaceST :: (IArray a e, Ix i) => a i e -> [(Int, e)] -> ST s (STArray s i e)
unsafeReplaceST arr ies = do
marr <- thaw arr
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
return marr
{-# INLINE unsafeAccumST #-}
unsafeAccumST :: (IArray a e, Ix i) => (e -> e' -> e) -> a i e -> [(Int, e')] -> ST s (STArray s i e)
unsafeAccumST f arr ies = do
marr <- thaw arr
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
return marr
{-# INLINE unsafeAccumArrayST #-}
unsafeAccumArrayST :: Ix i => (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> ST s (STArray s i e)
unsafeAccumArrayST f e (l,u) ies = do
marr <- newArray (l,u) e
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
return marr
{-# INLINE array #-}
{-| Constructs an immutable array from a pair of bounds and a list of
initial associations.
The bounds are specified as a pair of the lowest and highest bounds in
the array respectively. For example, a one-origin vector of length 10
has bounds (1,10), and a one-origin 10 by 10 matrix has bounds
((1,1),(10,10)).
An association is a pair of the form @(i,x)@, which defines the value of
the array at index @i@ to be @x@. The array is undefined if any index
in the list is out of bounds. If any two associations in the list have
the same index, the value at that index is implementation-dependent.
(In GHC, the last value specified for that index is used.
Other implementations will also do this for unboxed arrays, but Haskell
98 requires that for 'Array' the value at such indices is bottom.)
Because the indices must be checked for these errors, 'array' is
strict in the bounds argument and in the indices of the association
list. Whether @array@ is strict or non-strict in the elements depends
on the array type: 'Data.Array.Array' is a non-strict array type, but
all of the 'Data.Array.Unboxed.UArray' arrays are strict. Thus in a
non-strict array, recurrences such as the following are possible:
> a = array (1,100) ((1,1) : [(i, i * a!(i-1)) | i \<- [2..100]])
Not every index within the bounds of the array need appear in the
association list, but the values associated with indices that do not
appear will be undefined.
If, in any dimension, the lower bound is greater than the upper bound,
then the array is legal, but empty. Indexing an empty array always
gives an array-bounds error, but 'bounds' still yields the bounds with
which the array was constructed.
-}
array :: (IArray a e, Ix i)
=> (i,i) -- ^ bounds of the array: (lowest,highest)
-> [(i, e)] -- ^ list of associations
-> a i e
array (l,u) ies
= let n = safeRangeSize (l,u)
in unsafeArray (l,u)
[(safeIndex (l,u) n i, e) | (i, e) <- ies]
-- Since unsafeFreeze is not guaranteed to be only a cast, we will
-- use unsafeArray and zip instead of a specialized loop to implement
-- listArray, unlike Array.listArray, even though it generates some
-- unnecessary heap allocation. Will use the loop only when we have
-- fast unsafeFreeze, namely for Array and UArray (well, they cover
-- almost all cases).
{-# INLINE [1] listArray #-}
-- | Constructs an immutable array from a list of initial elements.
-- The list gives the elements of the array in ascending order
-- beginning with the lowest index.
listArray :: (IArray a e, Ix i) => (i,i) -> [e] -> a i e
listArray (l,u) es =
let n = safeRangeSize (l,u)
in unsafeArray (l,u) (zip [0 .. n - 1] es)
{-# INLINE listArrayST #-}
listArrayST :: Ix i => (i,i) -> [e] -> ST s (STArray s i e)
listArrayST (l,u) es = do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
{-# RULES
"listArray/Array" listArray =
\lu es -> runST (listArrayST lu es >>= ArrST.unsafeFreezeSTArray)
#-}
{-# INLINE listUArrayST #-}
listUArrayST :: (MArray (STUArray s) e (ST s), Ix i)
=> (i,i) -> [e] -> ST s (STUArray s i e)
listUArrayST (l,u) es = do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
-- I don't know how to write a single rule for listUArrayST, because
-- the type looks like constrained over 's', which runST doesn't
-- like. In fact all MArray (STUArray s) instances are polymorphic
-- wrt. 's', but runST can't know that.
--
-- More precisely, we'd like to write this:
-- listUArray :: (forall s. MArray (STUArray s) e (ST s), Ix i)
-- => (i,i) -> [e] -> UArray i e
-- listUArray lu = runST (listUArrayST lu es >>= unsafeFreezeSTUArray)
-- {-# RULES listArray = listUArray
-- Then we could call listUArray at any type 'e' that had a suitable
-- MArray instance. But sadly we can't, because we don't have quantified
-- constraints. Hence the mass of rules below.
-- I would like also to write a rule for listUArrayST (or listArray or
-- whatever) applied to unpackCString#. Unfortunately unpackCString#
-- calls seem to be floated out, then floated back into the middle
-- of listUArrayST, so I was not able to do this.
#ifdef __GLASGOW_HASKELL__
type ListUArray e = forall i . Ix i => (i,i) -> [e] -> UArray i e
{-# RULES
"listArray/UArray/Bool" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Bool
"listArray/UArray/Char" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Char
"listArray/UArray/Int" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int
"listArray/UArray/Word" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word
"listArray/UArray/Ptr" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray (Ptr a)
"listArray/UArray/FunPtr" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray (FunPtr a)
"listArray/UArray/Float" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Float
"listArray/UArray/Double" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Double
"listArray/UArray/StablePtr" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray (StablePtr a)
"listArray/UArray/Int8" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int8
"listArray/UArray/Int16" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int16
"listArray/UArray/Int32" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int32
"listArray/UArray/Word8" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word8
"listArray/UArray/Word16" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word16
"listArray/UArray/Word32" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word32
#-}
{- Disable these rules for now since we disable unboxed Int64/Word64 arrays.
"listArray/UArray/Int64" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Int64
"listArray/UArray/Word64" listArray
= (\lu es -> runST (listUArrayST lu es >>= unsafeFreezeSTUArray)) :: ListUArray Word64
-}
#endif
{-# INLINE (!) #-}
-- | Returns the element of an immutable array at the specified index.
(!) :: (IArray a e, Ix i) => a i e -> i -> e
(!) arr i = case bounds arr of
(l,u) -> unsafeAt arr $ safeIndex (l,u) (numElements arr) i
{-# INLINE indices #-}
-- | Returns a list of all the valid indices in an array.
indices :: (IArray a e, Ix i) => a i e -> [i]
indices arr = case bounds arr of (l,u) -> range (l,u)
{-# INLINE elems #-}
-- | Returns a list of all the elements of an array, in the same order
-- as their indices.
elems :: (IArray a e, Ix i) => a i e -> [e]
elems arr = case bounds arr of
(_l, _u) -> [unsafeAt arr i | i <- [0 .. numElements arr - 1]]
{-# INLINE assocs #-}
-- | Returns the contents of an array as a list of associations.
assocs :: (IArray a e, Ix i) => a i e -> [(i, e)]
assocs arr = case bounds arr of
(l,u) -> [(i, arr ! i) | i <- range (l,u)]
{-# INLINE accumArray #-}
{-|
Constructs an immutable array from a list of associations. Unlike
'array', the same index is allowed to occur multiple times in the list
of associations; an /accumulating function/ is used to combine the
values of elements with the same index.
For example, given a list of values of some index type, hist produces
a histogram of the number of occurrences of each index within a
specified range:
> hist :: (Ix a, Num b) => (a,a) -> [a] -> Array a b
> hist bnds is = accumArray (+) 0 bnds [(i, 1) | i\<-is, inRange bnds i]
-}
accumArray :: (IArray a e, Ix i)
=> (e -> e' -> e) -- ^ An accumulating function
-> e -- ^ A default element
-> (i,i) -- ^ The bounds of the array
-> [(i, e')] -- ^ List of associations
-> a i e -- ^ Returns: the array
accumArray f initialValue (l,u) ies =
let n = safeRangeSize (l, u)
in unsafeAccumArray f initialValue (l,u)
[(safeIndex (l,u) n i, e) | (i, e) <- ies]
{-# INLINE (//) #-}
{-|
Takes an array and a list of pairs and returns an array identical to
the left argument except that it has been updated by the associations
in the right argument. For example, if m is a 1-origin, n by n matrix,
then @m\/\/[((i,i), 0) | i \<- [1..n]]@ is the same matrix, except with
the diagonal zeroed.
As with the 'array' function, if any two associations in the list have
the same index, the value at that index is implementation-dependent.
(In GHC, the last value specified for that index is used.
Other implementations will also do this for unboxed arrays, but Haskell
98 requires that for 'Array' the value at such indices is bottom.)
For most array types, this operation is O(/n/) where /n/ is the size
of the array. However, the diffarray package provides an array type
for which this operation has complexity linear in the number of updates.
-}
(//) :: (IArray a e, Ix i) => a i e -> [(i, e)] -> a i e
arr // ies = case bounds arr of
(l,u) -> unsafeReplace arr [ (safeIndex (l,u) (numElements arr) i, e)
| (i, e) <- ies]
{-# INLINE accum #-}
{-|
@accum f@ takes an array and an association list and accumulates pairs
from the list into the array with the accumulating function @f@. Thus
'accumArray' can be defined using 'accum':
> accumArray f z b = accum f (array b [(i, z) | i \<- range b])
-}
accum :: (IArray a e, Ix i) => (e -> e' -> e) -> a i e -> [(i, e')] -> a i e
accum f arr ies = case bounds arr of
(l,u) -> let n = numElements arr
in unsafeAccum f arr [(safeIndex (l,u) n i, e) | (i, e) <- ies]
{-# INLINE amap #-}
-- | Returns a new array derived from the original array by applying a
-- function to each of the elements.
amap :: (IArray a e', IArray a e, Ix i) => (e' -> e) -> a i e' -> a i e
amap f arr = case bounds arr of
(l,u) -> let n = numElements arr
in unsafeArray (l,u) [ (i, f (unsafeAt arr i))
| i <- [0 .. n - 1]]
{-# INLINE ixmap #-}
-- | Returns a new array derived from the original array by applying a
-- function to each of the indices.
ixmap :: (IArray a e, Ix i, Ix j) => (i,i) -> (i -> j) -> a j e -> a i e
ixmap (l,u) f arr =
array (l,u) [(i, arr ! f i) | i <- range (l,u)]
-----------------------------------------------------------------------------
-- Normal polymorphic arrays
instance IArray Arr.Array e where
{-# INLINE bounds #-}
bounds = Arr.bounds
{-# INLINE numElements #-}
numElements = Arr.numElements
{-# INLINE unsafeArray #-}
unsafeArray = Arr.unsafeArray
{-# INLINE unsafeAt #-}
unsafeAt = Arr.unsafeAt
{-# INLINE unsafeReplace #-}
unsafeReplace = Arr.unsafeReplace
{-# INLINE unsafeAccum #-}
unsafeAccum = Arr.unsafeAccum
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray = Arr.unsafeAccumArray
-----------------------------------------------------------------------------
-- Flat unboxed arrays
-- | Arrays with unboxed elements. Instances of 'IArray' are provided
-- for 'UArray' with certain element types ('Int', 'Float', 'Char',
-- etc.; see the 'UArray' class for a full list).
--
-- A 'UArray' will generally be more efficient (in terms of both time
-- and space) than the equivalent 'Data.Array.Array' with the same
-- element type. However, 'UArray' is strict in its elements - so
-- don\'t use 'UArray' if you require the non-strictness that
-- 'Data.Array.Array' provides.
--
-- Because the @IArray@ interface provides operations overloaded on
-- the type of the array, it should be possible to just change the
-- array type being used by a program from say @Array@ to @UArray@ to
-- get the benefits of unboxed arrays (don\'t forget to import
-- "Data.Array.Unboxed" instead of "Data.Array").
--
#ifdef __GLASGOW_HASKELL__
data UArray i e = UArray !i !i !Int ByteArray#
#endif
#ifdef __HUGS__
data UArray i e = UArray !i !i !Int !ByteArray
#endif
INSTANCE_TYPEABLE2(UArray,uArrayTc,"UArray")
{-# INLINE unsafeArrayUArray #-}
unsafeArrayUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (i,i) -> [(Int, e)] -> e -> ST s (UArray i e)
unsafeArrayUArray (l,u) ies default_elem = do
marr <- newArray (l,u) default_elem
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeFreezeSTUArray #-}
unsafeFreezeSTUArray :: STUArray s i e -> ST s (UArray i e)
#if __GLASGOW_HASKELL__
unsafeFreezeSTUArray (STUArray l u n marr#) = ST $ \s1# ->
case unsafeFreezeByteArray# marr# s1# of { (# s2#, arr# #) ->
(# s2#, UArray l u n arr# #) }
#elif __HUGS__
unsafeFreezeSTUArray (STUArray l u n marr) = do
arr <- unsafeFreezeMutableByteArray marr
return (UArray l u n arr)
#endif
{-# INLINE unsafeReplaceUArray #-}
unsafeReplaceUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> UArray i e -> [(Int, e)] -> ST s (UArray i e)
unsafeReplaceUArray arr ies = do
marr <- thawSTUArray arr
sequence_ [unsafeWrite marr i e | (i, e) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeAccumUArray #-}
unsafeAccumUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (e -> e' -> e) -> UArray i e -> [(Int, e')] -> ST s (UArray i e)
unsafeAccumUArray f arr ies = do
marr <- thawSTUArray arr
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE unsafeAccumArrayUArray #-}
unsafeAccumArrayUArray :: (MArray (STUArray s) e (ST s), Ix i)
=> (e -> e' -> e) -> e -> (i,i) -> [(Int, e')] -> ST s (UArray i e)
unsafeAccumArrayUArray f initialValue (l,u) ies = do
marr <- newArray (l,u) initialValue
sequence_ [do old <- unsafeRead marr i
unsafeWrite marr i (f old new)
| (i, new) <- ies]
unsafeFreezeSTUArray marr
{-# INLINE eqUArray #-}
eqUArray :: (IArray UArray e, Ix i, Eq e) => UArray i e -> UArray i e -> Bool
eqUArray arr1@(UArray l1 u1 n1 _) arr2@(UArray l2 u2 n2 _) =
if n1 == 0 then n2 == 0 else
l1 == l2 && u1 == u2 &&
and [unsafeAt arr1 i == unsafeAt arr2 i | i <- [0 .. n1 - 1]]
{-# INLINE [1] cmpUArray #-}
cmpUArray :: (IArray UArray e, Ix i, Ord e) => UArray i e -> UArray i e -> Ordering
cmpUArray arr1 arr2 = compare (assocs arr1) (assocs arr2)
{-# INLINE cmpIntUArray #-}
cmpIntUArray :: (IArray UArray e, Ord e) => UArray Int e -> UArray Int e -> Ordering
cmpIntUArray arr1@(UArray l1 u1 n1 _) arr2@(UArray l2 u2 n2 _) =
if n1 == 0 then if n2 == 0 then EQ else LT else
if n2 == 0 then GT else
case compare l1 l2 of
EQ -> foldr cmp (compare u1 u2) [0 .. (n1 `min` n2) - 1]
other -> other
where
cmp i rest = case compare (unsafeAt arr1 i) (unsafeAt arr2 i) of
EQ -> rest
other -> other
{-# RULES "cmpUArray/Int" cmpUArray = cmpIntUArray #-}
-----------------------------------------------------------------------------
-- Showing IArrays
{-# SPECIALISE
showsIArray :: (IArray UArray e, Ix i, Show i, Show e) =>
Int -> UArray i e -> ShowS
#-}
showsIArray :: (IArray a e, Ix i, Show i, Show e) => Int -> a i e -> ShowS
showsIArray p a =
showParen (p > 9) $
showString "array " .
shows (bounds a) .
showChar ' ' .
shows (assocs a)
-----------------------------------------------------------------------------
-- Flat unboxed arrays: instances
#ifdef __HUGS__
unsafeAtBArray :: Storable e => UArray i e -> Int -> e
unsafeAtBArray (UArray _ _ _ arr) = readByteArray arr
#endif
instance IArray UArray Bool where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies False)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) =
isTrue# ((indexWordArray# arr# (bOOL_INDEX i#) `and#` bOOL_BIT i#)
`neWord#` int2Word# 0#)
#endif
#ifdef __HUGS__
unsafeAt (UArray _ _ _ arr) i =
testBit (readByteArray arr (bOOL_INDEX i)::BitSet) (bOOL_SUBINDEX i)
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Char where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies '\0')
{-# INLINE unsafeAt #-}
#ifdef __GLASGOW_HASKELL__
unsafeAt (UArray _ _ _ arr#) (I# i#) = C# (indexWideCharArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I# (indexIntArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W# (indexWordArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray (Ptr a) where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullPtr)
{-# INLINE unsafeAt #-}
#ifdef __GLASGOW_HASKELL__
unsafeAt (UArray _ _ _ arr#) (I# i#) = Ptr (indexAddrArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray (FunPtr a) where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullFunPtr)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = FunPtr (indexAddrArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Float where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = F# (indexFloatArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Double where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = D# (indexDoubleArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray (StablePtr a) where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies nullStablePtr)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = StablePtr (indexStablePtrArray# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
-- bogus StablePtr value for initialising a UArray of StablePtr.
nullStablePtr :: StablePtr a
#ifdef __GLASGOW_HASKELL__
nullStablePtr = StablePtr (unsafeCoerce# 0#)
#endif
#ifdef __HUGS__
nullStablePtr = castPtrToStablePtr nullPtr
#endif
instance IArray UArray Int8 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I8# (indexInt8Array# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int16 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I16# (indexInt16Array# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int32 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = I32# (indexInt32Array# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Int64 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) =
I64# (unsafeCoerce# (indexInt64Array# arr# (unsafeCoerce# i#)))
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word8 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W8# (indexWord8Array# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word16 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W16# (indexWord16Array# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word32 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) = W32# (indexWord32Array# arr# i#)
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance IArray UArray Word64 where
{-# INLINE bounds #-}
bounds (UArray l u _ _) = (l,u)
{-# INLINE numElements #-}
numElements (UArray _ _ n _) = n
{-# INLINE unsafeArray #-}
unsafeArray lu ies = runST (unsafeArrayUArray lu ies 0)
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeAt #-}
unsafeAt (UArray _ _ _ arr#) (I# i#) =
W64# (unsafeCoerce# (indexWord64Array# arr# (unsafeCoerce# i#)))
#endif
#ifdef __HUGS__
unsafeAt = unsafeAtBArray
#endif
{-# INLINE unsafeReplace #-}
unsafeReplace arr ies = runST (unsafeReplaceUArray arr ies)
{-# INLINE unsafeAccum #-}
unsafeAccum f arr ies = runST (unsafeAccumUArray f arr ies)
{-# INLINE unsafeAccumArray #-}
unsafeAccumArray f initialValue lu ies = runST (unsafeAccumArrayUArray f initialValue lu ies)
instance (Ix ix, Eq e, IArray UArray e) => Eq (UArray ix e) where
(==) = eqUArray
instance (Ix ix, Ord e, IArray UArray e) => Ord (UArray ix e) where
compare = cmpUArray
instance (Ix ix, Show ix, Show e, IArray UArray e) => Show (UArray ix e) where
showsPrec = showsIArray
-----------------------------------------------------------------------------
-- Mutable arrays
{-# NOINLINE arrEleBottom #-}
arrEleBottom :: a
arrEleBottom = error "MArray: undefined array element"
{-| Class of mutable array types.
An array type has the form @(a i e)@ where @a@ is the array type
constructor (kind @* -> * -> *@), @i@ is the index type (a member of
the class 'Ix'), and @e@ is the element type.
The @MArray@ class is parameterised over both @a@ and @e@ (so that
instances specialised to certain element types can be defined, in the
same way as for 'IArray'), and also over the type of the monad, @m@,
in which the mutable array will be manipulated.
-}
class (Monad m) => MArray a e m where
-- | Returns the bounds of the array
getBounds :: Ix i => a i e -> m (i,i)
-- | Returns the number of elements in the array
getNumElements :: Ix i => a i e -> m Int
-- | Builds a new array, with every element initialised to the supplied
-- value.
newArray :: Ix i => (i,i) -> e -> m (a i e)
-- | Builds a new array, with every element initialised to an
-- undefined value. In a monadic context in which operations must
-- be deterministic (e.g. the ST monad), the array elements are
-- initialised to a fixed but undefined value, such as zero.
newArray_ :: Ix i => (i,i) -> m (a i e)
-- | Builds a new array, with every element initialised to an undefined
-- value.
unsafeNewArray_ :: Ix i => (i,i) -> m (a i e)
unsafeRead :: Ix i => a i e -> Int -> m e
unsafeWrite :: Ix i => a i e -> Int -> e -> m ()
{-# INLINE newArray #-}
-- The INLINE is crucial, because until we know at least which monad
-- we are in, the code below allocates like crazy. So inline it,
-- in the hope that the context will know the monad.
newArray (l,u) initialValue = do
let n = safeRangeSize (l,u)
marr <- unsafeNewArray_ (l,u)
sequence_ [unsafeWrite marr i initialValue | i <- [0 .. n - 1]]
return marr
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = newArray (l,u) arrEleBottom
{-# INLINE newArray_ #-}
newArray_ (l,u) = newArray (l,u) arrEleBottom
-- newArray takes an initialiser which all elements of
-- the newly created array are initialised to. unsafeNewArray_ takes
-- no initialiser, it is assumed that the array is initialised with
-- "undefined" values.
-- why not omit unsafeNewArray_? Because in the unboxed array
-- case we would like to omit the initialisation altogether if
-- possible. We can't do this for boxed arrays, because the
-- elements must all have valid values at all times in case of
-- garbage collection.
-- why not omit newArray? Because in the boxed case, we can omit the
-- default initialisation with undefined values if we *do* know the
-- initial value and it is constant for all elements.
instance MArray IOArray e IO where
#if defined(__HUGS__)
getBounds = return . boundsIOArray
getNumElements = return . getNumElementsIOArray
#elif defined(__GLASGOW_HASKELL__)
{-# INLINE getBounds #-}
getBounds (IOArray marr) = stToIO $ getBounds marr
{-# INLINE getNumElements #-}
getNumElements (IOArray marr) = stToIO $ getNumElements marr
#endif
newArray = newIOArray
unsafeRead = unsafeReadIOArray
unsafeWrite = unsafeWriteIOArray
{-# INLINE newListArray #-}
-- | Constructs a mutable array from a list of initial elements.
-- The list gives the elements of the array in ascending order
-- beginning with the lowest index.
newListArray :: (MArray a e m, Ix i) => (i,i) -> [e] -> m (a i e)
newListArray (l,u) es = do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
let fillFromList i xs | i == n = return ()
| otherwise = case xs of
[] -> return ()
y:ys -> unsafeWrite marr i y >> fillFromList (i+1) ys
fillFromList 0 es
return marr
{-# INLINE readArray #-}
-- | Read an element from a mutable array
readArray :: (MArray a e m, Ix i) => a i e -> i -> m e
readArray marr i = do
(l,u) <- getBounds marr
n <- getNumElements marr
unsafeRead marr (safeIndex (l,u) n i)
{-# INLINE writeArray #-}
-- | Write an element in a mutable array
writeArray :: (MArray a e m, Ix i) => a i e -> i -> e -> m ()
writeArray marr i e = do
(l,u) <- getBounds marr
n <- getNumElements marr
unsafeWrite marr (safeIndex (l,u) n i) e
{-# INLINE getElems #-}
-- | Return a list of all the elements of a mutable array
getElems :: (MArray a e m, Ix i) => a i e -> m [e]
getElems marr = do
(_l, _u) <- getBounds marr
n <- getNumElements marr
sequence [unsafeRead marr i | i <- [0 .. n - 1]]
{-# INLINE getAssocs #-}
-- | Return a list of all the associations of a mutable array, in
-- index order.
getAssocs :: (MArray a e m, Ix i) => a i e -> m [(i, e)]
getAssocs marr = do
(l,u) <- getBounds marr
n <- getNumElements marr
sequence [ do e <- unsafeRead marr (safeIndex (l,u) n i); return (i,e)
| i <- range (l,u)]
{-# INLINE mapArray #-}
-- | Constructs a new array derived from the original array by applying a
-- function to each of the elements.
mapArray :: (MArray a e' m, MArray a e m, Ix i) => (e' -> e) -> a i e' -> m (a i e)
mapArray f marr = do
(l,u) <- getBounds marr
n <- getNumElements marr
marr' <- newArray_ (l,u)
sequence_ [do e <- unsafeRead marr i
unsafeWrite marr' i (f e)
| i <- [0 .. n - 1]]
return marr'
{-# INLINE mapIndices #-}
-- | Constructs a new array derived from the original array by applying a
-- function to each of the indices.
mapIndices :: (MArray a e m, Ix i, Ix j) => (i,i) -> (i -> j) -> a j e -> m (a i e)
mapIndices (l',u') f marr = do
marr' <- newArray_ (l',u')
n' <- getNumElements marr'
sequence_ [do e <- readArray marr (f i')
unsafeWrite marr' (safeIndex (l',u') n' i') e
| i' <- range (l',u')]
return marr'
-----------------------------------------------------------------------------
-- Polymorphic non-strict mutable arrays (ST monad)
instance MArray (STArray s) e (ST s) where
{-# INLINE getBounds #-}
getBounds arr = return $! ArrST.boundsSTArray arr
{-# INLINE getNumElements #-}
getNumElements arr = return $! ArrST.numElementsSTArray arr
{-# INLINE newArray #-}
newArray = ArrST.newSTArray
{-# INLINE unsafeRead #-}
unsafeRead = ArrST.unsafeReadSTArray
{-# INLINE unsafeWrite #-}
unsafeWrite = ArrST.unsafeWriteSTArray
instance MArray (STArray s) e (Lazy.ST s) where
{-# INLINE getBounds #-}
getBounds arr = strictToLazyST (return $! ArrST.boundsSTArray arr)
{-# INLINE getNumElements #-}
getNumElements arr = strictToLazyST (return $! ArrST.numElementsSTArray arr)
{-# INLINE newArray #-}
newArray (l,u) e = strictToLazyST (ArrST.newSTArray (l,u) e)
{-# INLINE unsafeRead #-}
unsafeRead arr i = strictToLazyST (ArrST.unsafeReadSTArray arr i)
{-# INLINE unsafeWrite #-}
unsafeWrite arr i e = strictToLazyST (ArrST.unsafeWriteSTArray arr i e)
#ifdef __HUGS__
INSTANCE_TYPEABLE3(STArray,sTArrayTc,"STArray")
#endif
-----------------------------------------------------------------------------
-- Flat unboxed mutable arrays (ST monad)
-- | A mutable array with unboxed elements, that can be manipulated in
-- the 'ST' monad. The type arguments are as follows:
--
-- * @s@: the state variable argument for the 'ST' type
--
-- * @i@: the index type of the array (should be an instance of @Ix@)
--
-- * @e@: the element type of the array. Only certain element types
-- are supported.
--
-- An 'STUArray' will generally be more efficient (in terms of both time
-- and space) than the equivalent boxed version ('STArray') with the same
-- element type. However, 'STUArray' is strict in its elements - so
-- don\'t use 'STUArray' if you require the non-strictness that
-- 'STArray' provides.
#ifdef __GLASGOW_HASKELL__
data STUArray s i e = STUArray !i !i !Int (MutableByteArray# s)
#endif
#ifdef __HUGS__
data STUArray s i e = STUArray !i !i !Int !(MutableByteArray s)
#endif
INSTANCE_TYPEABLE3(STUArray,stUArrayTc,"STUArray")
#ifdef __GLASGOW_HASKELL__
instance Eq (STUArray s i e) where
STUArray _ _ _ arr1# == STUArray _ _ _ arr2# =
isTrue# (sameMutableByteArray# arr1# arr2#)
#endif
#ifdef __HUGS__
instance Eq (STUArray s i e) where
STUArray _ _ _ arr1 == STUArray _ _ _ arr2 = arr1 == arr2
#endif
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeNewArraySTUArray_ #-}
unsafeNewArraySTUArray_ :: Ix i
=> (i,i) -> (Int# -> Int#) -> ST s (STUArray s i e)
unsafeNewArraySTUArray_ (l,u) elemsToBytes
= case rangeSize (l,u) of
n@(I# n#) ->
ST $ \s1# ->
case newByteArray# (elemsToBytes n#) s1# of
(# s2#, marr# #) ->
(# s2#, STUArray l u n marr# #)
instance MArray (STUArray s) Bool (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE newArray #-}
newArray (l,u) initialValue = ST $ \s1# ->
case safeRangeSize (l,u) of { n@(I# n#) ->
case newByteArray# (bOOL_SCALE n#) s1# of { (# s2#, marr# #) ->
case bOOL_WORD_SCALE n# of { n'# ->
let loop i# s3# | isTrue# (i# ==# n'#) = s3#
| otherwise =
case writeWordArray# marr# i# e# s3# of { s4# ->
loop (i# +# 1#) s4# } in
case loop 0# s2# of { s3# ->
(# s3#, STUArray l u n marr# #) }}}}
where
!(W# e#) = if initialValue then maxBound else 0
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) bOOL_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds False
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWordArray# marr# (bOOL_INDEX i#) s1# of { (# s2#, e# #) ->
(# s2#, isTrue# ((e# `and#` bOOL_BIT i#) `neWord#` int2Word# 0#) #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) e = ST $ \s1# ->
case bOOL_INDEX i# of { j# ->
case readWordArray# marr# j# s1# of { (# s2#, old# #) ->
case if e then old# `or#` bOOL_BIT i#
else old# `and#` bOOL_NOT_BIT i# of { e# ->
case writeWordArray# marr# j# e# s2# of { s3# ->
(# s3#, () #) }}}}
instance MArray (STUArray s) Char (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 4#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds (chr 0)
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWideCharArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, C# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (C# e#) = ST $ \s1# ->
case writeWideCharArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readIntArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I# e#) = ST $ \s1# ->
case writeIntArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWordArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W# e#) = ST $ \s1# ->
case writeWordArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) (Ptr a) (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds nullPtr
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readAddrArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, Ptr e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (Ptr e#) = ST $ \s1# ->
case writeAddrArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) (FunPtr a) (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds nullFunPtr
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readAddrArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, FunPtr e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (FunPtr e#) = ST $ \s1# ->
case writeAddrArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Float (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) fLOAT_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readFloatArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, F# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (F# e#) = ST $ \s1# ->
case writeFloatArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Double (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) dOUBLE_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readDoubleArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, D# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (D# e#) = ST $ \s1# ->
case writeDoubleArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) (StablePtr a) (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) wORD_SCALE
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds (castPtrToStablePtr nullPtr)
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readStablePtrArray# marr# i# s1# of { (# s2#, e# #) ->
(# s2# , StablePtr e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (StablePtr e#) = ST $ \s1# ->
case writeStablePtrArray# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int8 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (\x -> x)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt8Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I8# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I8# e#) = ST $ \s1# ->
case writeInt8Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int16 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 2#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt16Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I16# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I16# e#) = ST $ \s1# ->
case writeInt16Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int32 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 4#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt32Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I32# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I32# e#) = ST $ \s1# ->
case writeInt32Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Int64 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 8#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readInt64Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, I64# (unsafeCoerce# e#) #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (I64# e#) = ST $ \s1# ->
case writeInt64Array# marr# i# (unsafeCoerce# e#) s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word8 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (\x -> x)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord8Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W8# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W8# e#) = ST $ \s1# ->
case writeWord8Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word16 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 2#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord16Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W16# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W16# e#) = ST $ \s1# ->
case writeWord16Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word32 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 4#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord32Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W32# e# #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W32# e#) = ST $ \s1# ->
case writeWord32Array# marr# i# e# s1# of { s2# ->
(# s2#, () #) }
instance MArray (STUArray s) Word64 (ST s) where
{-# INLINE getBounds #-}
getBounds (STUArray l u _ _) = return (l,u)
{-# INLINE getNumElements #-}
getNumElements (STUArray _ _ n _) = return n
{-# INLINE unsafeNewArray_ #-}
unsafeNewArray_ (l,u) = unsafeNewArraySTUArray_ (l,u) (*# 8#)
{-# INLINE newArray_ #-}
newArray_ arrBounds = newArray arrBounds 0
{-# INLINE unsafeRead #-}
unsafeRead (STUArray _ _ _ marr#) (I# i#) = ST $ \s1# ->
case readWord64Array# marr# i# s1# of { (# s2#, e# #) ->
(# s2#, W64# (unsafeCoerce# e#) #) }
{-# INLINE unsafeWrite #-}
unsafeWrite (STUArray _ _ _ marr#) (I# i#) (W64# e#) = ST $ \s1# ->
case writeWord64Array# marr# i# (unsafeCoerce# e#) s1# of { s2# ->
(# s2#, () #) }
-----------------------------------------------------------------------------
-- Translation between elements and bytes
bOOL_SCALE, bOOL_WORD_SCALE,
wORD_SCALE, dOUBLE_SCALE, fLOAT_SCALE :: Int# -> Int#
bOOL_SCALE n# = (n# +# last#) `uncheckedIShiftRA#` 3#
where !(I# last#) = SIZEOF_HSWORD * 8 - 1
bOOL_WORD_SCALE n# = bOOL_INDEX (n# +# last#)
where !(I# last#) = SIZEOF_HSWORD * 8 - 1
wORD_SCALE n# = scale# *# n# where !(I# scale#) = SIZEOF_HSWORD
dOUBLE_SCALE n# = scale# *# n# where !(I# scale#) = SIZEOF_HSDOUBLE
fLOAT_SCALE n# = scale# *# n# where !(I# scale#) = SIZEOF_HSFLOAT
bOOL_INDEX :: Int# -> Int#
#if SIZEOF_HSWORD == 4
bOOL_INDEX i# = i# `uncheckedIShiftRA#` 5#
#elif SIZEOF_HSWORD == 8
bOOL_INDEX i# = i# `uncheckedIShiftRA#` 6#
#endif
bOOL_BIT, bOOL_NOT_BIT :: Int# -> Word#
bOOL_BIT n# = int2Word# 1# `uncheckedShiftL#` (word2Int# (int2Word# n# `and#` mask#))
where !(W# mask#) = SIZEOF_HSWORD * 8 - 1
bOOL_NOT_BIT n# = bOOL_BIT n# `xor#` mb#
where !(W# mb#) = maxBound
#endif /* __GLASGOW_HASKELL__ */
#ifdef __HUGS__
newMBArray_ :: (Ix i, Storable e) => (i,i) -> ST s (STUArray s i e)
newMBArray_ = makeArray undefined
where
makeArray :: (Ix i, Storable e) => e -> (i,i) -> ST s (STUArray s i e)
makeArray dummy (l,u) = do
let n = safeRangeSize (l,u)
marr <- newMutableByteArray (n * sizeOf dummy)
return (STUArray l u n marr)
unsafeReadMBArray :: Storable e => STUArray s i e -> Int -> ST s e
unsafeReadMBArray (STUArray _ _ _ marr) = readMutableByteArray marr
unsafeWriteMBArray :: Storable e => STUArray s i e -> Int -> e -> ST s ()
unsafeWriteMBArray (STUArray _ _ _ marr) = writeMutableByteArray marr
getBoundsMBArray :: Storable e => STUArray s i e -> ST s (i, i)
getBoundsMBArray (STUArray l u _ _) = return (l,u)
getNumElementsMBArray :: Storable e => STUArray s i e -> ST s Int
getNumElementsMBArray (STUArray _ _ n _) = return n
instance MArray (STUArray s) Bool (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ (l,u) = do
let n = rangeSize (l,u)
marr <- newMutableByteArray (bOOL_SCALE n)
return (STUArray l u n marr)
newArray_ bounds = unsafeNewArray_ bounds
unsafeRead (STUArray _ _ _ marr) i = do
let ix = bOOL_INDEX i
bit = bOOL_SUBINDEX i
w <- readMutableByteArray marr ix
return (testBit (w::BitSet) bit)
unsafeWrite (STUArray _ _ _ marr) i e = do
let ix = bOOL_INDEX i
bit = bOOL_SUBINDEX i
w <- readMutableByteArray marr ix
writeMutableByteArray marr ix
(if e then setBit (w::BitSet) bit else clearBit w bit)
instance MArray (STUArray s) Char (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) (Ptr a) (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) (FunPtr a) (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Float (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Double (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) (StablePtr a) (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int8 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int16 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int32 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Int64 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word8 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word16 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word32 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
instance MArray (STUArray s) Word64 (ST s) where
getBounds = getBoundsMBArray
getNumElements = getNumElementsMBArray
unsafeNewArray_ = newMBArray_
newArray_ = unsafeNewArray_
unsafeRead = unsafeReadMBArray
unsafeWrite = unsafeWriteMBArray
type BitSet = Word8
bitSetSize = bitSize (0::BitSet)
bOOL_SCALE :: Int -> Int
bOOL_SCALE n = (n + bitSetSize - 1) `div` bitSetSize
bOOL_INDEX :: Int -> Int
bOOL_INDEX i = i `div` bitSetSize
bOOL_SUBINDEX :: Int -> Int
bOOL_SUBINDEX i = i `mod` bitSetSize
#endif /* __HUGS__ */
-----------------------------------------------------------------------------
-- Freezing
-- | Converts a mutable array (any instance of 'MArray') to an
-- immutable array (any instance of 'IArray') by taking a complete
-- copy of it.
freeze :: (Ix i, MArray a e m, IArray b e) => a i e -> m (b i e)
{-# NOINLINE [1] freeze #-}
freeze marr = do
(l,u) <- getBounds marr
n <- getNumElements marr
es <- mapM (unsafeRead marr) [0 .. n - 1]
-- The old array and index might not be well-behaved, so we need to
-- use the safe array creation function here.
return (listArray (l,u) es)
#ifdef __GLASGOW_HASKELL__
freezeSTUArray :: Ix i => STUArray s i e -> ST s (UArray i e)
freezeSTUArray (STUArray l u n marr#) = ST $ \s1# ->
case sizeofMutableByteArray# marr# of { n# ->
case newByteArray# n# s1# of { (# s2#, marr'# #) ->
case memcpy_freeze marr'# marr# (fromIntegral (I# n#)) of { IO m ->
case unsafeCoerce# m s2# of { (# s3#, _ #) ->
case unsafeFreezeByteArray# marr'# s3# of { (# s4#, arr# #) ->
(# s4#, UArray l u n arr# #) }}}}}
foreign import ccall unsafe "memcpy"
memcpy_freeze :: MutableByteArray# s -> MutableByteArray# s -> CSize
-> IO (Ptr a)
{-# RULES
"freeze/STArray" freeze = ArrST.freezeSTArray
"freeze/STUArray" freeze = freezeSTUArray
#-}
#endif /* __GLASGOW_HASKELL__ */
-- In-place conversion of mutable arrays to immutable ones places
-- a proof obligation on the user: no other parts of your code can
-- have a reference to the array at the point where you unsafely
-- freeze it (and, subsequently mutate it, I suspect).
{- |
Converts an mutable array into an immutable array. The
implementation may either simply cast the array from
one type to the other without copying the array, or it
may take a full copy of the array.
Note that because the array is possibly not copied, any subsequent
modifications made to the mutable version of the array may be
shared with the immutable version. It is safe to use, therefore, if
the mutable version is never modified after the freeze operation.
The non-copying implementation is supported between certain pairs
of array types only; one constraint is that the array types must
have identical representations. In GHC, The following pairs of
array types have a non-copying O(1) implementation of
'unsafeFreeze'. Because the optimised versions are enabled by
specialisations, you will need to compile with optimisation (-O) to
get them.
* 'Data.Array.IO.IOUArray' -> 'Data.Array.Unboxed.UArray'
* 'Data.Array.ST.STUArray' -> 'Data.Array.Unboxed.UArray'
* 'Data.Array.IO.IOArray' -> 'Data.Array.Array'
* 'Data.Array.ST.STArray' -> 'Data.Array.Array'
-}
{-# INLINE [1] unsafeFreeze #-}
unsafeFreeze :: (Ix i, MArray a e m, IArray b e) => a i e -> m (b i e)
unsafeFreeze = freeze
{-# RULES
"unsafeFreeze/STArray" unsafeFreeze = ArrST.unsafeFreezeSTArray
"unsafeFreeze/STUArray" unsafeFreeze = unsafeFreezeSTUArray
#-}
-----------------------------------------------------------------------------
-- Thawing
-- | Converts an immutable array (any instance of 'IArray') into a
-- mutable array (any instance of 'MArray') by taking a complete copy
-- of it.
thaw :: (Ix i, IArray a e, MArray b e m) => a i e -> m (b i e)
{-# NOINLINE [1] thaw #-}
thaw arr = case bounds arr of
(l,u) -> do
marr <- newArray_ (l,u)
let n = safeRangeSize (l,u)
sequence_ [ unsafeWrite marr i (unsafeAt arr i)
| i <- [0 .. n - 1]]
return marr
thawSTUArray :: Ix i => UArray i e -> ST s (STUArray s i e)
#if __GLASGOW_HASKELL__
thawSTUArray (UArray l u n arr#) = ST $ \s1# ->
case sizeofByteArray# arr# of { n# ->
case newByteArray# n# s1# of { (# s2#, marr# #) ->
case memcpy_thaw marr# arr# (fromIntegral (I# n#)) of { IO m ->
case unsafeCoerce# m s2# of { (# s3#, _ #) ->
(# s3#, STUArray l u n marr# #) }}}}
foreign import ccall unsafe "memcpy"
memcpy_thaw :: MutableByteArray# s -> ByteArray# -> CSize
-> IO (Ptr a)
{-# RULES
"thaw/STArray" thaw = ArrST.thawSTArray
"thaw/STUArray" thaw = thawSTUArray
#-}
#elif __HUGS__
thawSTUArray (UArray l u n arr) = do
marr <- thawByteArray arr
return (STUArray l u n marr)
#endif
-- In-place conversion of immutable arrays to mutable ones places
-- a proof obligation on the user: no other parts of your code can
-- have a reference to the array at the point where you unsafely
-- thaw it (and, subsequently mutate it, I suspect).
{- |
Converts an immutable array into a mutable array. The
implementation may either simply cast the array from
one type to the other without copying the array, or it
may take a full copy of the array.
Note that because the array is possibly not copied, any subsequent
modifications made to the mutable version of the array may be
shared with the immutable version. It is only safe to use,
therefore, if the immutable array is never referenced again in this
thread, and there is no possibility that it can be also referenced
in another thread. If you use an unsafeThaw/write/unsafeFreeze
sequence in a multi-threaded setting, then you must ensure that
this sequence is atomic with respect to other threads, or a garbage
collector crash may result (because the write may be writing to a
frozen array).
The non-copying implementation is supported between certain pairs
of array types only; one constraint is that the array types must
have identical representations. In GHC, The following pairs of
array types have a non-copying O(1) implementation of
'unsafeThaw'. Because the optimised versions are enabled by
specialisations, you will need to compile with optimisation (-O) to
get them.
* 'Data.Array.Unboxed.UArray' -> 'Data.Array.IO.IOUArray'
* 'Data.Array.Unboxed.UArray' -> 'Data.Array.ST.STUArray'
* 'Data.Array.Array' -> 'Data.Array.IO.IOArray'
* 'Data.Array.Array' -> 'Data.Array.ST.STArray'
-}
{-# INLINE [1] unsafeThaw #-}
unsafeThaw :: (Ix i, IArray a e, MArray b e m) => a i e -> m (b i e)
unsafeThaw = thaw
#ifdef __GLASGOW_HASKELL__
{-# INLINE unsafeThawSTUArray #-}
unsafeThawSTUArray :: Ix i => UArray i e -> ST s (STUArray s i e)
unsafeThawSTUArray (UArray l u n marr#) =
return (STUArray l u n (unsafeCoerce# marr#))
{-# RULES
"unsafeThaw/STArray" unsafeThaw = ArrST.unsafeThawSTArray
"unsafeThaw/STUArray" unsafeThaw = unsafeThawSTUArray
#-}
{-# INLINE unsafeThawIOArray #-}
unsafeThawIOArray :: Ix ix => Arr.Array ix e -> IO (IOArray ix e)
unsafeThawIOArray arr = stToIO $ do
marr <- ArrST.unsafeThawSTArray arr
return (IOArray marr)
{-# RULES
"unsafeThaw/IOArray" unsafeThaw = unsafeThawIOArray
#-}
thawIOArray :: Ix ix => Arr.Array ix e -> IO (IOArray ix e)
thawIOArray arr = stToIO $ do
marr <- ArrST.thawSTArray arr
return (IOArray marr)
{-# RULES
"thaw/IOArray" thaw = thawIOArray
#-}
freezeIOArray :: Ix ix => IOArray ix e -> IO (Arr.Array ix e)
freezeIOArray (IOArray marr) = stToIO (ArrST.freezeSTArray marr)
{-# RULES
"freeze/IOArray" freeze = freezeIOArray
#-}
{-# INLINE unsafeFreezeIOArray #-}
unsafeFreezeIOArray :: Ix ix => IOArray ix e -> IO (Arr.Array ix e)
unsafeFreezeIOArray (IOArray marr) = stToIO (ArrST.unsafeFreezeSTArray marr)
{-# RULES
"unsafeFreeze/IOArray" unsafeFreeze = unsafeFreezeIOArray
#-}
#endif /* __GLASGOW_HASKELL__ */
-- | Casts an 'STUArray' with one element type into one with a
-- different element type. All the elements of the resulting array
-- are undefined (unless you know what you\'re doing...).
castSTUArray :: STUArray s ix a -> ST s (STUArray s ix b)
#if __GLASGOW_HASKELL__
castSTUArray (STUArray l u n marr#) = return (STUArray l u n marr#)
#elif __HUGS__
castSTUArray (STUArray l u n marr) = return (STUArray l u n marr)
#endif
|
beni55/haste-compiler
|
libraries/ghc-7.8/array/Data/Array/Base.hs
|
bsd-3-clause
| 73,840
| 0
| 27
| 17,443
| 18,890
| 9,994
| 8,896
| -1
| -1
|
module Dwarf.Types
( -- * Dwarf information
DwarfInfo(..)
, pprDwarfInfo
, pprAbbrevDecls
-- * Dwarf frame
, DwarfFrame(..), DwarfFrameProc(..), DwarfFrameBlock(..)
, pprDwarfFrame
-- * Utilities
, pprByte
, pprData4'
, pprDwWord
, pprWord
, pprLEBWord
, pprLEBInt
, wordAlign
, sectionOffset
)
where
import Debug
import CLabel
import CmmExpr ( GlobalReg(..) )
import Encoding
import FastString
import Outputable
import Platform
import Reg
import Dwarf.Constants
import Data.Bits
import Data.List ( mapAccumL )
import qualified Data.Map as Map
import Data.Word
import Data.Char
import CodeGen.Platform
-- | Individual dwarf records. Each one will be encoded as an entry in
-- the .debug_info section.
data DwarfInfo
= DwarfCompileUnit { dwChildren :: [DwarfInfo]
, dwName :: String
, dwProducer :: String
, dwCompDir :: String
, dwLineLabel :: LitString }
| DwarfSubprogram { dwChildren :: [DwarfInfo]
, dwName :: String
, dwLabel :: CLabel }
| DwarfBlock { dwChildren :: [DwarfInfo]
, dwLabel :: CLabel
, dwMarker :: CLabel }
-- | Abbreviation codes used for encoding above records in the
-- .debug_info section.
data DwarfAbbrev
= DwAbbrNull -- ^ Pseudo, used for marking the end of lists
| DwAbbrCompileUnit
| DwAbbrSubprogram
| DwAbbrBlock
deriving (Eq, Enum)
-- | Generate assembly for the given abbreviation code
pprAbbrev :: DwarfAbbrev -> SDoc
pprAbbrev = pprLEBWord . fromIntegral . fromEnum
-- | Abbreviation declaration. This explains the binary encoding we
-- use for representing @DwarfInfo@.
pprAbbrevDecls :: Bool -> SDoc
pprAbbrevDecls haveDebugLine =
let mkAbbrev abbr tag chld flds =
let fld (tag, form) = pprLEBWord tag $$ pprLEBWord form
in pprAbbrev abbr $$ pprLEBWord tag $$ pprByte chld $$
vcat (map fld flds) $$ pprByte 0 $$ pprByte 0
in dwarfAbbrevSection $$
ptext dwarfAbbrevLabel <> colon $$
mkAbbrev DwAbbrCompileUnit dW_TAG_compile_unit dW_CHILDREN_yes
([ (dW_AT_name, dW_FORM_string)
, (dW_AT_producer, dW_FORM_string)
, (dW_AT_language, dW_FORM_data4)
, (dW_AT_comp_dir, dW_FORM_string)
, (dW_AT_use_UTF8, dW_FORM_flag)
] ++
(if haveDebugLine
then [ (dW_AT_stmt_list, dW_FORM_data4) ]
else [])) $$
mkAbbrev DwAbbrSubprogram dW_TAG_subprogram dW_CHILDREN_yes
[ (dW_AT_name, dW_FORM_string)
, (dW_AT_MIPS_linkage_name, dW_FORM_string)
, (dW_AT_external, dW_FORM_flag)
, (dW_AT_low_pc, dW_FORM_addr)
, (dW_AT_high_pc, dW_FORM_addr)
, (dW_AT_frame_base, dW_FORM_block1)
] $$
mkAbbrev DwAbbrBlock dW_TAG_lexical_block dW_CHILDREN_yes
[ (dW_AT_name, dW_FORM_string)
, (dW_AT_low_pc, dW_FORM_addr)
, (dW_AT_high_pc, dW_FORM_addr)
] $$
pprByte 0
-- | Generate assembly for DWARF data
pprDwarfInfo :: Bool -> DwarfInfo -> SDoc
pprDwarfInfo haveSrc d
= pprDwarfInfoOpen haveSrc d $$
vcat (map (pprDwarfInfo haveSrc) (dwChildren d)) $$
pprDwarfInfoClose
-- | Prints assembler data corresponding to DWARF info records. Note
-- that the binary format of this is paramterized in @abbrevDecls@ and
-- has to be kept in synch.
pprDwarfInfoOpen :: Bool -> DwarfInfo -> SDoc
pprDwarfInfoOpen haveSrc (DwarfCompileUnit _ name producer compDir lineLbl) =
pprAbbrev DwAbbrCompileUnit
$$ pprString name
$$ pprString producer
$$ pprData4 dW_LANG_Haskell
$$ pprString compDir
$$ pprFlag True -- use UTF8
$$ if haveSrc
then pprData4' (sectionOffset lineLbl dwarfLineLabel)
else empty
pprDwarfInfoOpen _ (DwarfSubprogram _ name label) = sdocWithDynFlags $ \df ->
pprAbbrev DwAbbrSubprogram
$$ pprString name
$$ pprString (renderWithStyle df (ppr label) (mkCodeStyle CStyle))
$$ pprFlag (externallyVisibleCLabel label)
$$ pprWord (ppr label)
$$ pprWord (ppr $ mkAsmTempEndLabel label)
$$ pprByte 1
$$ pprByte dW_OP_call_frame_cfa
pprDwarfInfoOpen _ (DwarfBlock _ label marker) = sdocWithDynFlags $ \df ->
pprAbbrev DwAbbrBlock
$$ pprString (renderWithStyle df (ppr label) (mkCodeStyle CStyle))
$$ pprWord (ppr marker)
$$ pprWord (ppr $ mkAsmTempEndLabel marker)
-- | Close a DWARF info record with children
pprDwarfInfoClose :: SDoc
pprDwarfInfoClose = pprAbbrev DwAbbrNull
-- | Information about unwind instructions for a procedure. This
-- corresponds to a "Common Information Entry" (CIE) in DWARF.
data DwarfFrame
= DwarfFrame
{ dwCieLabel :: CLabel
, dwCieInit :: UnwindTable
, dwCieProcs :: [DwarfFrameProc]
}
-- | Unwind instructions for an individual procedure. Corresponds to a
-- "Frame Description Entry" (FDE) in DWARF.
data DwarfFrameProc
= DwarfFrameProc
{ dwFdeProc :: CLabel
, dwFdeHasInfo :: Bool
, dwFdeBlocks :: [DwarfFrameBlock]
-- ^ List of blocks. Order must match asm!
}
-- | Unwind instructions for a block. Will become part of the
-- containing FDE.
data DwarfFrameBlock
= DwarfFrameBlock
{ dwFdeBlock :: CLabel
, dwFdeBlkHasInfo :: Bool
, dwFdeUnwind :: UnwindTable
}
-- | Header for the .debug_frame section. Here we emit the "Common
-- Information Entry" record that etablishes general call frame
-- parameters and the default stack layout.
pprDwarfFrame :: DwarfFrame -> SDoc
pprDwarfFrame DwarfFrame{dwCieLabel=cieLabel,dwCieInit=cieInit,dwCieProcs=procs}
= sdocWithPlatform $ \plat ->
let cieStartLabel= mkAsmTempDerivedLabel cieLabel (fsLit "_start")
cieEndLabel = mkAsmTempEndLabel cieLabel
length = ppr cieEndLabel <> char '-' <> ppr cieStartLabel
spReg = dwarfGlobalRegNo plat Sp
retReg = dwarfReturnRegNo plat
wordSize = platformWordSize plat
pprInit (g, uw) = pprSetUnwind plat g (Nothing, uw)
in vcat [ ppr cieLabel <> colon
, pprData4' length -- Length of CIE
, ppr cieStartLabel <> colon
, pprData4' (ptext (sLit "-1"))
-- Common Information Entry marker (-1 = 0xf..f)
, pprByte 3 -- CIE version (we require DWARF 3)
, pprByte 0 -- Augmentation (none)
, pprByte 1 -- Code offset multiplicator
, pprByte (128-fromIntegral wordSize)
-- Data offset multiplicator
-- (stacks grow down => "-w" in signed LEB128)
, pprByte retReg -- virtual register holding return address
] $$
-- Initial unwind table
vcat (map pprInit $ Map.toList cieInit) $$
vcat [ -- RET = *CFA
pprByte (dW_CFA_offset+retReg)
, pprByte 0
-- Sp' = CFA
-- (we need to set this manually as our Sp register is
-- often not the architecture's default stack register)
, pprByte dW_CFA_val_offset
, pprLEBWord (fromIntegral spReg)
, pprLEBWord 0
] $$
wordAlign $$
ppr cieEndLabel <> colon $$
-- Procedure unwind tables
vcat (map (pprFrameProc cieLabel cieInit) procs)
-- | Writes a "Frame Description Entry" for a procedure. This consists
-- mainly of referencing the CIE and writing state machine
-- instructions to describe how the frame base (CFA) changes.
pprFrameProc :: CLabel -> UnwindTable -> DwarfFrameProc -> SDoc
pprFrameProc frameLbl initUw (DwarfFrameProc procLbl hasInfo blocks)
= let fdeLabel = mkAsmTempDerivedLabel procLbl (fsLit "_fde")
fdeEndLabel = mkAsmTempDerivedLabel procLbl (fsLit "_fde_end")
procEnd = mkAsmTempEndLabel procLbl
ifInfo str = if hasInfo then text str else empty
-- see [Note: Info Offset]
in vcat [ pprData4' (ppr fdeEndLabel <> char '-' <> ppr fdeLabel)
, ppr fdeLabel <> colon
, pprData4' (ppr frameLbl <> char '-' <>
ptext dwarfFrameLabel) -- Reference to CIE
, pprWord (ppr procLbl <> ifInfo "-1") -- Code pointer
, pprWord (ppr procEnd <> char '-' <>
ppr procLbl <> ifInfo "+1") -- Block byte length
] $$
vcat (snd $ mapAccumL pprFrameBlock initUw blocks) $$
wordAlign $$
ppr fdeEndLabel <> colon
-- | Generates unwind information for a block. We only generate
-- instructions where unwind information actually changes. This small
-- optimisations saves a lot of space, as subsequent blocks often have
-- the same unwind information.
pprFrameBlock :: UnwindTable -> DwarfFrameBlock -> (UnwindTable, SDoc)
pprFrameBlock oldUws (DwarfFrameBlock blockLbl hasInfo uws)
| uws == oldUws
= (oldUws, empty)
| otherwise
= (,) uws $ sdocWithPlatform $ \plat ->
let lbl = ppr blockLbl <> if hasInfo then text "-1" else empty
-- see [Note: Info Offset]
isChanged g v | old == Just v = Nothing
| otherwise = Just (old, v)
where old = Map.lookup g oldUws
changed = Map.toList $ Map.mapMaybeWithKey isChanged uws
died = Map.toList $ Map.difference oldUws uws
in pprByte dW_CFA_set_loc $$ pprWord lbl $$
vcat (map (uncurry $ pprSetUnwind plat) changed) $$
vcat (map (pprUndefUnwind plat . fst) died)
-- [Note: Info Offset]
--
-- GDB was pretty much written with C-like programs in mind, and as a
-- result they assume that once you have a return address, it is a
-- good idea to look at (PC-1) to unwind further - as that's where the
-- "call" instruction is supposed to be.
--
-- Now on one hand, code generated by GHC looks nothing like what GDB
-- expects, and in fact going up from a return pointer is guaranteed
-- to land us inside an info table! On the other hand, that actually
-- gives us some wiggle room, as we expect IP to never *actually* end
-- up inside the info table, so we can "cheat" by putting whatever GDB
-- expects to see there. This is probably pretty safe, as GDB cannot
-- assume (PC-1) to be a valid code pointer in the first place - and I
-- have seen no code trying to correct this.
--
-- Note that this will not prevent GDB from failing to look-up the
-- correct function name for the frame, as that uses the symbol table,
-- which we can not manipulate as easily.
-- | Get DWARF register ID for a given GlobalReg
dwarfGlobalRegNo :: Platform -> GlobalReg -> Word8
dwarfGlobalRegNo p = maybe 0 (dwarfRegNo p . RegReal) . globalRegMaybe p
-- | Generate code for setting the unwind information for a register,
-- optimized using its known old value in the table. Note that "Sp" is
-- special: We see it as synonym for the CFA.
pprSetUnwind :: Platform -> GlobalReg -> (Maybe UnwindExpr, UnwindExpr) -> SDoc
pprSetUnwind _ Sp (Just (UwReg s _), UwReg s' o') | s == s'
= if o' >= 0
then pprByte dW_CFA_def_cfa_offset $$ pprLEBWord (fromIntegral o')
else pprByte dW_CFA_def_cfa_offset_sf $$ pprLEBInt o'
pprSetUnwind plat Sp (_, UwReg s' o')
= if o' >= 0
then pprByte dW_CFA_def_cfa $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat s') $$
pprLEBWord (fromIntegral o')
else pprByte dW_CFA_def_cfa_sf $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat s') $$
pprLEBInt o'
pprSetUnwind _ Sp (_, uw)
= pprByte dW_CFA_def_cfa_expression $$ pprUnwindExpr False uw
pprSetUnwind plat g (_, UwDeref (UwReg Sp o))
| o < 0 && ((-o) `mod` platformWordSize plat) == 0 -- expected case
= pprByte (dW_CFA_offset + dwarfGlobalRegNo plat g) $$
pprLEBWord (fromIntegral ((-o) `div` platformWordSize plat))
| otherwise
= pprByte dW_CFA_offset_extended_sf $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprLEBInt o
pprSetUnwind plat g (_, UwDeref uw)
= pprByte dW_CFA_expression $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprUnwindExpr True uw
pprSetUnwind plat g (_, uw)
= pprByte dW_CFA_val_expression $$
pprLEBWord (fromIntegral (dwarfGlobalRegNo plat g)) $$
pprUnwindExpr True uw
-- | Generates a DWARF expression for the given unwind expression. If
-- @spIsCFA@ is true, we see @Sp@ as the frame base CFA where it gets
-- mentioned.
pprUnwindExpr :: Bool -> UnwindExpr -> SDoc
pprUnwindExpr spIsCFA expr
= sdocWithPlatform $ \plat ->
let ppr (UwConst i)
| i >= 0 && i < 32 = pprByte (dW_OP_lit0 + fromIntegral i)
| otherwise = pprByte dW_OP_consts $$ pprLEBInt i -- lazy...
ppr (UwReg Sp i) | spIsCFA
= if i == 0
then pprByte dW_OP_call_frame_cfa
else ppr (UwPlus (UwReg Sp 0) (UwConst i))
ppr (UwReg g i) = pprByte (dW_OP_breg0+dwarfGlobalRegNo plat g) $$
pprLEBInt i
ppr (UwDeref u) = ppr u $$ pprByte dW_OP_deref
ppr (UwPlus u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_plus
ppr (UwMinus u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_minus
ppr (UwTimes u1 u2) = ppr u1 $$ ppr u2 $$ pprByte dW_OP_mul
in ptext (sLit "\t.byte 1f-.-1") $$
ppr expr $$
ptext (sLit "1:")
-- | Generate code for re-setting the unwind information for a
-- register to "undefined"
pprUndefUnwind :: Platform -> GlobalReg -> SDoc
pprUndefUnwind _ Sp = panic "pprUndefUnwind Sp" -- should never happen
pprUndefUnwind plat g = pprByte dW_CFA_undefined $$
pprLEBWord (fromIntegral $ dwarfGlobalRegNo plat g)
-- | Align assembly at (machine) word boundary
wordAlign :: SDoc
wordAlign = sdocWithPlatform $ \plat ->
ptext (sLit "\t.align ") <> case platformOS plat of
OSDarwin -> case platformWordSize plat of
8 -> text "3"
4 -> text "2"
_other -> error "wordAlign: Unsupported word size!"
_other -> ppr (platformWordSize plat)
-- | Assembly for a single byte of constant DWARF data
pprByte :: Word8 -> SDoc
pprByte x = ptext (sLit "\t.byte ") <> ppr (fromIntegral x :: Word)
-- | Assembly for a constant DWARF flag
pprFlag :: Bool -> SDoc
pprFlag f = pprByte (if f then 0xff else 0x00)
-- | Assembly for 4 bytes of dynamic DWARF data
pprData4' :: SDoc -> SDoc
pprData4' x = ptext (sLit "\t.long ") <> x
-- | Assembly for 4 bytes of constant DWARF data
pprData4 :: Word -> SDoc
pprData4 = pprData4' . ppr
-- | Assembly for a DWARF word of dynamic data. This means 32 bit, as
-- we are generating 32 bit DWARF.
pprDwWord :: SDoc -> SDoc
pprDwWord = pprData4'
-- | Assembly for a machine word of dynamic data. Depends on the
-- architecture we are currently generating code for.
pprWord :: SDoc -> SDoc
pprWord s = (<> s) . sdocWithPlatform $ \plat ->
case platformWordSize plat of
4 -> ptext (sLit "\t.long ")
8 -> ptext (sLit "\t.quad ")
n -> panic $ "pprWord: Unsupported target platform word length " ++
show n ++ "!"
-- | Prints a number in "little endian base 128" format. The idea is
-- to optimize for small numbers by stopping once all further bytes
-- would be 0. The highest bit in every byte signals whether there
-- are further bytes to read.
pprLEBWord :: Word -> SDoc
pprLEBWord x | x < 128 = pprByte (fromIntegral x)
| otherwise = pprByte (fromIntegral $ 128 .|. (x .&. 127)) $$
pprLEBWord (x `shiftR` 7)
-- | Same as @pprLEBWord@, but for a signed number
pprLEBInt :: Int -> SDoc
pprLEBInt x | x >= -64 && x < 64
= pprByte (fromIntegral (x .&. 127))
| otherwise = pprByte (fromIntegral $ 128 .|. (x .&. 127)) $$
pprLEBInt (x `shiftR` 7)
-- | Generates a dynamic null-terminated string. If required the
-- caller needs to make sure that the string is escaped properly.
pprString' :: SDoc -> SDoc
pprString' str = ptext (sLit "\t.asciz \"") <> str <> char '"'
-- | Generate a string constant. We take care to escape the string.
pprString :: String -> SDoc
pprString str
= pprString' $ hcat $ map escapeChar $
if utf8EncodedLength str == length str
then str
else map (chr . fromIntegral) $ bytesFS $ mkFastString str
-- | Escape a single non-unicode character
escapeChar :: Char -> SDoc
escapeChar '\\' = ptext (sLit "\\\\")
escapeChar '\"' = ptext (sLit "\\\"")
escapeChar '\n' = ptext (sLit "\\n")
escapeChar c
| isAscii c && isPrint c && c /= '?' -- prevents trigraph warnings
= char c
| otherwise
= char '\\' <> char (intToDigit (ch `div` 64)) <>
char (intToDigit ((ch `div` 8) `mod` 8)) <>
char (intToDigit (ch `mod` 8))
where ch = ord c
-- | Generate an offset into another section. This is tricky because
-- this is handled differently depending on platform: Mac Os expects
-- us to calculate the offset using assembler arithmetic. Meanwhile,
-- GNU tools expect us to just reference the target directly, and will
-- figure out on their own that we actually need an offset.
sectionOffset :: LitString -> LitString -> SDoc
sectionOffset target section = sdocWithPlatform $ \plat ->
case platformOS plat of
OSDarwin -> ptext target <> char '-' <> ptext section
_other -> ptext target
|
green-haskell/ghc
|
compiler/nativeGen/Dwarf/Types.hs
|
bsd-3-clause
| 17,330
| 0
| 21
| 4,473
| 3,882
| 2,032
| 1,850
| 307
| 8
|
module JSON where
foo :: a -> a
foo = id
|
ezyang/ghc
|
testsuite/tests/driver/json2.hs
|
bsd-3-clause
| 42
| 0
| 5
| 12
| 18
| 11
| 7
| 3
| 1
|
{-# LANGUAGE EmptyDataDecls #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE QuasiQuotes #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TemplateHaskell #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ViewPatterns #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Main (main, resourcesApp, Widget, WorldId) where
import Blaze.ByteString.Builder
import Control.Applicative (liftA2)
import Control.Concurrent (runInUnboundThread)
import Control.Monad (replicateM)
import Control.Monad.Logger (runNoLoggingT)
import Control.Monad.Primitive (PrimState)
import Control.Monad.Reader (ReaderT)
import Control.Monad.Trans.Resource (InternalState)
import Data.Aeson (encode)
import qualified Data.ByteString.Lazy as L
import Data.Pool (Pool, createPool)
import Data.Int (Int64)
import Data.IORef (newIORef)
import Data.Function (on)
import Data.List (sortBy)
import Data.Pool (withResource)
import Data.Text (Text)
import Database.MongoDB (Field ((:=)), (=:))
import qualified Database.MongoDB as Mongo
import Database.Persist (Key, PersistEntity,
PersistEntityBackend,
PersistStore, get, update,
(=.))
import qualified Database.Persist.MySQL as My
import Database.Persist.TH (mkPersist, mpsGeneric,
persistLowerCase, sqlSettings)
import Network (PortID (PortNumber))
import Network.HTTP.Types
import Network.Wai
import qualified Network.Wai.Handler.Warp as Warp
import System.Environment (getArgs)
import System.IO.Unsafe (unsafePerformIO)
import qualified System.Random.MWC as R
import Text.Blaze.Html.Renderer.Utf8 (renderHtmlBuilder)
import Yesod.Core
mkPersist sqlSettings { mpsGeneric = True } [persistLowerCase|
World sql=World
randomNumber Int sql=randomNumber
|]
mkPersist sqlSettings { mpsGeneric = True } [persistLowerCase|
Fortune sql=Fortune
message Text sql=message
|]
data App = App
{ appGen :: !(R.Gen (PrimState IO))
, mySqlPool :: !(Pool My.SqlBackend)
, mongoDBPool :: !(Pool Mongo.Pipe)
}
-- | Not actually using the non-raw mongoDB.
-- persistent-mongoDB expects a field of '_id', not 'id'
mkYesod "App" [parseRoutes|
/json JsonR GET
/db DbR GET
/dbs/#Int DbsR GET
!/dbs/#Text DbsDefaultR GET
/mongo/raw/db MongoRawDbR GET
/mongo/raw/dbs/#Int MongoRawDbsR GET
!/mongo/raw/dbs/#Text MongoRawDbsDefaultR GET
/updates/#Int UpdatesR GET
!/updates/#Text UpdatesDefaultR GET
/fortunes FortunesR GET
/plaintext PlaintextR GET
|]
fakeInternalState :: InternalState
fakeInternalState = unsafePerformIO $ newIORef $ error "fakeInternalState forced"
{-# NOINLINE fakeInternalState #-}
instance Yesod App where
makeSessionBackend _ = return Nothing
{-# INLINE makeSessionBackend #-}
shouldLog _ _ _ = False
{-# INLINE shouldLog #-}
yesodMiddleware = id
{-# INLINE yesodMiddleware #-}
cleanPath _ = Right
{-# INLINE cleanPath #-}
yesodWithInternalState _ _ = ($ fakeInternalState)
{-# INLINE yesodWithInternalState #-}
maximumContentLength _ _ = Nothing
{-# INLINE maximumContentLength #-}
getJsonR :: Handler ()
getJsonR = sendWaiResponse
$ responseBuilder
status200
[("Content-Type", simpleContentType typeJson)]
$ copyByteString
$ L.toStrict
$ encode
$ object ["message" .= ("Hello, World!" :: Text)]
getDbR :: Handler Value
getDbR = getDb (intQuery runMySQL My.toSqlKey)
getMongoRawDbR :: Handler Value
getMongoRawDbR = getDb rawMongoIntQuery
getDbsR :: Int -> Handler Value
getDbsR cnt = do
App {..} <- getYesod
multiRandomHandler randomNumber (intQuery runMySQL My.toSqlKey) cnt'
where
cnt' | cnt < 1 = 1
| cnt > 500 = 500
| otherwise = cnt
getDbsDefaultR :: Text -> Handler Value
getDbsDefaultR _ = getDbsR 1
getMongoRawDbsR :: Int -> Handler Value
getMongoRawDbsR cnt = multiRandomHandler randomNumber rawMongoIntQuery cnt'
where
cnt' | cnt < 1 = 1
| cnt > 500 = 500
| otherwise = cnt
getMongoRawDbsDefaultR :: Text -> Handler Value
getMongoRawDbsDefaultR _ = getMongoRawDbsR 1
getUpdatesR :: Int -> Handler Value
getUpdatesR cnt = multiRandomHandler randomPair go cnt'
where
cnt' | cnt < 1 = 1
| cnt > 500 = 500
| otherwise = cnt
go = uncurry (intUpdate runMySQL My.toSqlKey)
getUpdatesDefaultR :: Text -> Handler Value
getUpdatesDefaultR _ = getUpdatesR 1
randomNumber :: R.Gen (PrimState IO) -> IO Int64
randomNumber appGen = R.uniformR (1, 10000) appGen
randomPair :: R.Gen (PrimState IO) -> IO (Int64, Int64)
randomPair appGen = liftA2 (,) (randomNumber appGen) (randomNumber appGen)
getDb :: (Int64 -> Handler Value) -> Handler Value
getDb query = do
app <- getYesod
i <- liftIO (randomNumber (appGen app))
value <- query i
sendWaiResponse
$ responseBuilder
status200
[("Content-Type", simpleContentType typeJson)]
$ copyByteString
$ L.toStrict
$ encode value
runMongoDB :: Mongo.Action Handler b -> Handler b
runMongoDB f = do
App {..} <- getYesod
withResource mongoDBPool $ \pipe ->
Mongo.access pipe Mongo.ReadStaleOk "hello_world" f
runMySQL :: My.SqlPersistT Handler b -> Handler b
runMySQL f = do
App {..} <- getYesod
My.runSqlPool f mySqlPool
intQuery :: (MonadIO m, PersistEntity val, PersistStore backend
, backend ~ PersistEntityBackend val
) =>
(ReaderT backend m (Maybe val) -> m (Maybe (WorldGeneric backend)))
-> (Int64 -> Key val)
-> Int64 -> m Value
intQuery db toKey i = do
Just x <- db $ get $ toKey i
return $ jsonResult (worldRandomNumber x)
where
jsonResult :: Int -> Value
jsonResult n = object ["id" .= i, "randomNumber" .= n]
rawMongoIntQuery :: Mongo.Val v => v -> Handler Value
rawMongoIntQuery i = do
Just x <- runMongoDB $ Mongo.findOne (Mongo.select ["id" =: i] "world")
return $ documentToJson x
intUpdate :: (Functor m, Monad m, MonadIO m
, PersistStore backend) =>
(ReaderT backend m (Maybe (WorldGeneric backend))
-> m (Maybe (WorldGeneric backend)))
-> (Int64 -> Key (WorldGeneric backend))
-> Int64 -> Int64 -> m Value
intUpdate db toKey i v = do
Just x <- db $ get k
_ <- db $ fmap (const Nothing) $
update k [WorldRandomNumber =. fromIntegral v]
return $ object ["id" .= i, "randomNumber" .= v]
where
k = toKey i
multiRandomHandler :: ToJSON a
=> (R.Gen (PrimState IO) -> IO b)
-> (b -> Handler a)
-> Int
-> Handler Value
multiRandomHandler rand operation cnt = do
App {..} <- getYesod
nums <- liftIO $ replicateM cnt (rand appGen)
return . array =<< mapM operation nums
documentToJson :: [Field] -> Value
documentToJson = object . map toAssoc
where
toAssoc :: Field -> (Text, Value)
toAssoc ("_id" := v) = ("id", toJSON v)
toAssoc (l := v) = (l, toJSON v)
instance ToJSON Mongo.Value where
toJSON (Mongo.Int32 i) = toJSON i
toJSON (Mongo.Int64 i) = toJSON i
toJSON (Mongo.Float f) = toJSON f
toJSON (Mongo.Doc d) = documentToJson d
toJSON s = error $ "no convert for: " ++ show s
getFortunesR :: Handler ()
getFortunesR = do
es <- runMySQL $ My.selectList [] []
sendWaiResponse
$ responseBuilder status200 [("Content-type", typeHtml)]
$ fortuneTemplate (messages es)
where
messages es = sortBy (compare `on` snd)
((0, "Additional fortune added at request time.") : map stripEntity es)
stripEntity e =
(My.fromSqlKey (My.entityKey e), fortuneMessage . My.entityVal $ e)
getPlaintextR :: Handler ()
getPlaintextR = sendWaiResponse
$ responseBuilder
status200
[("Content-Type", simpleContentType typePlain)]
$ copyByteString "Hello, World!"
fortuneTemplate :: [(Int64, Text)] -> Builder
fortuneTemplate messages = renderHtmlBuilder $ [shamlet|
$doctype 5
<html>
<head>
<title>Fortunes
<body>
<table>
<tr>
<th>id
<th>message
$forall message <- messages
<tr>
<td>#{fst message}
<td>#{snd message}
|]
main :: IO ()
main = R.withSystemRandom $ \gen -> do
[cores, host] <- getArgs
myPool <- runNoLoggingT $ My.createMySQLPool My.defaultConnectInfo
{ My.connectUser = "benchmarkdbuser"
, My.connectPassword = "benchmarkdbpass"
, My.connectDatabase = "hello_world"
, My.connectHost = host
} 1000
mongoPool <- createPool
(Mongo.connect $ Mongo.Host host $ PortNumber 27017)
Mongo.close
(read cores) -- what is the optimal stripe count? 1 is said to be a good default
3 -- 3 second timeout
1000
app <- toWaiAppPlain App
{ appGen = gen
, mySqlPool = myPool
, mongoDBPool = mongoPool
}
runInUnboundThread $ Warp.runSettings
( Warp.setPort 8000
$ Warp.setHost "*"
$ Warp.setOnException (\_ _ -> return ())
Warp.defaultSettings
) app
|
actframework/FrameworkBenchmarks
|
frameworks/Haskell/yesod/yesod-mysql-mongo/src/yesod.hs
|
bsd-3-clause
| 10,405
| 0
| 17
| 3,292
| 2,580
| 1,355
| 1,225
| 230
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{- |
Module : Network.MPD.Applicative.StoredPlaylists
Copyright : (c) Joachim Fasting 2012
License : MIT
Maintainer : joachifm@fastmail.fm
Stability : stable
Portability : unportable
Stored playlists.
-}
module Network.MPD.Applicative.StoredPlaylists
( listPlaylist
, listPlaylistInfo
, listPlaylists
, load
, playlistAdd
, playlistClear
, playlistDelete
, playlistMove
, rename
, rm
, save
) where
import Network.MPD.Applicative.Internal
import Network.MPD.Applicative.Util
import Network.MPD.Commands.Arg hiding (Command)
import Network.MPD.Commands.Types
import Network.MPD.Util
import Control.Applicative
-- | List song items in the playlist.
listPlaylist :: PlaylistName -> Command [Path]
listPlaylist plName = Command p ["listplaylist" <@> plName]
where
p = map Path . takeValues <$> getResponse
-- | List song items in the playlist with metadata.
listPlaylistInfo :: PlaylistName -> Command [Song]
listPlaylistInfo plName =
Command (liftParser takeSongs) ["listplaylistinfo" <@> plName]
-- | Get a list of stored playlists.
listPlaylists :: Command [PlaylistName]
listPlaylists = Command p ["listplaylists"]
where
p = map PlaylistName . go [] . toAssocList <$> getResponse
-- XXX: need to fail gracefully here
-- After each playlist name we get a timestamp
go acc [] = acc
go acc ((_, b):_:xs) = go (b : acc) xs
go _ _ = error "listPlaylists: bug"
-- | Load playlist into the current queue.
load :: PlaylistName -> Command ()
load plName = Command emptyResponse ["load" <@> plName]
-- | Add a database path to the named playlist.
playlistAdd :: PlaylistName -> Path -> Command ()
playlistAdd plName path =
Command emptyResponse ["playlistadd" <@> plName <++> path]
-- | Clear the playlist.
playlistClear :: PlaylistName -> Command ()
playlistClear plName = Command emptyResponse ["playlistclear" <@> plName]
-- | Delete the item at the given position from the playlist.
playlistDelete :: PlaylistName -> Position -> Command ()
playlistDelete name pos =
Command emptyResponse ["playlistdelete" <@> name <++> pos]
-- | Move a song to a new position within the playlist.
playlistMove :: PlaylistName -> Id -> Position -> Command ()
playlistMove name from to =
Command emptyResponse ["playlistmove" <@> name <++> from <++> to]
-- | Rename the playlist.
rename :: PlaylistName -> PlaylistName -> Command ()
rename plName new = Command emptyResponse ["rename" <@> plName <++> new]
-- | Remove the playlist.
rm :: PlaylistName -> Command ()
rm plName = Command emptyResponse ["rm" <@> plName]
-- | Save current queue to the named playlist.
save :: PlaylistName -> Command ()
save plName = Command emptyResponse ["save" <@> plName]
|
matthewleon/libmpd-haskell
|
src/Network/MPD/Applicative/StoredPlaylists.hs
|
mit
| 2,886
| 0
| 11
| 616
| 634
| 343
| 291
| 50
| 3
|
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import Data.Aeson
import GHCore
import Data.Maybe (fromJust)
import qualified Data.ByteString.Lazy as B
import qualified Data.ByteString.Lazy.Char8 as B8
import Network.Curl
getResp :: String -> IO String
getResp url = do
token <- readFile "token.txt"
let headers = [CurlHttpHeaders ["Authorization: token "++token]]
r :: (CurlResponse_ [(String, String)] String) <- curlGetResponse_ url headers
let rBody = respBody r
-- see headers
let respHs = respHeaders r
mapM_ (putStrLn .show) respHs
return rBody
comments = do
rBody <- getResp "https://api.github.com/repos/MackeyRMS/mackey/issues/208/comments"
-- putStrLn rBody
let json = B8.pack rBody
let r = decode json :: Maybe [Comment]
let xs = fromJust r
mapM_ (putStrLn.show) xs
followers = do
rsp <- getResp "https://api.github.com/users/danchoi/followers"
let users = fromJust ( (decode $ B8.pack rsp) :: Maybe [User] )
mapM_ (putStrLn . show . userLogin) users
main = comments
|
danchoi/ghb
|
Ghb/Test.hs
|
mit
| 1,059
| 1
| 15
| 210
| 330
| 167
| 163
| 28
| 1
|
main :: IO ()
main = do
c <- getChar
if c /= ' '
then do
putChar c
main
else return ()
|
timtian090/Playground
|
Haskell/LearnYouAHaskellForGreatGood/buffering.hs
|
mit
| 111
| 0
| 10
| 47
| 52
| 24
| 28
| 8
| 2
|
import System.Environment
import System.IO
-- import System.IO.Error
import Prelude hiding (catch)
import Control.Exception (catch)
main = doBlock `catch` handler
where
doBlock :: IO ()
doBlock = do
(fileName:_) <- getArgs
contents <- readFile fileName
putStrLn $ "The file has " ++ show (length (lines contents)) ++ " lines."
handler :: IOError -> IO ()
handler e = putStrLn "Some IO error!"
|
feliposz/learning-stuff
|
haskell/countLines3.hs
|
mit
| 478
| 0
| 15
| 146
| 138
| 72
| 66
| 12
| 1
|
{-# LANGUAGE MultiParamTypeClasses
, ImplicitParams
#-}
module U.Exec (
SystemExec(..)
, SystemExecCache(..)
, calculateInteractions
--TODO move it
, GravitationalConstant(..) -- Force :* Distance:^I2 :/ Mass:^I2
) where
import Control.Monad (mzero)
import Utils
import U.Defs
import U.Objects
--import U.Exec.Mutable
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
class SystemExec sys d where
execInteractions :: sys d -> d {- Time -} -> sys d
class SystemExecCache sys d where
systemStellarStates :: sys d -> [StellarBodyEntry d]
systemStellarState :: sys d -> StellarBodyContainer d -> BodyState d
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
data GravitationalConstant d = GravitationalConstant { getG :: d } -- Force :* Distance:^I2 :/ Mass:^I2
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
instance (SystemExecCache sys d, Num d) => HasPosition sys StellarBodyContainer d where
position sys = snd . systemStellarState sys
distance sys x y = c x - c y
where c = position sys
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
interact :: (Num d) => d -> [Effect a d] -> Effect a d
interact zero effects x y = foldr (+) (zeroVec, zeroVec) interractions
where zeroVec = (zero, zero)
interractions = map (($ x) . ($ y)) effects
zeroFor :: StellarBodyContainer d -> d
zeroFor (StellarBodyContainer d) = zero
-- !!!! --
effects :: (Body a d, HasPosition sys a d, Floating d, HasZero d) =>
(?g :: GravitationalConstant d) =>
sys d -> [Effect (a d) d]
effects sys = map ($ sys) [gravityEffect]
-- !!!! --
calculateInteractions :: (SystemExecCache System d, HasPosition System StellarBodyContainer d, Floating d, HasZero d) =>
(?g :: GravitationalConstant d) =>
System d -> d {- Time -} -> [StellarBodyEntry d]
calculateInteractions sys time = do (a, (_, ap)) <- stellarBodies sys --TODO
(b, _) <- stellarBodies sys
let (force, imp) = U.Exec.interact (zeroFor a) (effects sys) a b
if a /= b then return $ calculateMovement time (a, (force, imp, ap))
else mzero
--calculateMovements time = map (calculateMovement time)
calculateMovement :: (Body body d, Fractional d) =>
d {- Time -}
-> (body d, (Vector d {- Force -}, Vector d {- Impulse -}, Position d))
-> (body d, (Vector d {- Impulse -}, Position d))
calculateMovement time (obj, (force, imp, pos)) = (obj, (impulse, position)) -- TODO collisions
where impulse = imp + vecF (time *) force
position = pos + vecF (\x -> x / mass obj * time) impulse
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
gravityEffect :: (Body a d, HasPosition sys a d, Floating d, HasZero d) =>
(?g :: GravitationalConstant d) =>
sys d -> Effect (a d) d
gravityEffect sys x y = (force, (zero, zero))
where dist = distance sys x y
forceAbs = getG ?g * mass x * mass y / vecAbs dist ** 2
norm = vecNorm dist
force = vecF (forceAbs *) norm
-- TODO
impactEffect :: (HasZero d) => Effect a d
impactEffect x y = ((zero, zero), impulse)
where impulse = undefined
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
--instance SystemMExec (MSystem StellarBodyContainer ArtificialContainer) StellarBodyContainer ArtificialContainer d where
-- guardStellarInteraction = upd
-- TODO other factors, like mass loss
-- return ()
-- execInteractions sys time =
|
fehu/hgt
|
space-independent/src/U/Exec.hs
|
mit
| 4,430
| 0
| 13
| 1,525
| 1,046
| 571
| 475
| -1
| -1
|
module GHCJS.DOM.SVGPathSegLinetoHorizontalRel (
) where
|
manyoo/ghcjs-dom
|
ghcjs-dom-webkit/src/GHCJS/DOM/SVGPathSegLinetoHorizontalRel.hs
|
mit
| 59
| 0
| 3
| 7
| 10
| 7
| 3
| 1
| 0
|
module ContrMo where
import Control.Monad as C
import threepenny-gui
-- forM :: Monad m => [a] -> (a -> m b) -> m [b]
-- forM_ :: Monad m => [a] -> (a -> m b) -> m ()
{-
*ContrMo> forM [1,2,3] print
1
2
3
[(),(),()]
*ContrMo> forM_ [1,2,3] print
1
2
3
-}
-- replicateM :: Monad m => Int -> m a -> m [a]
{-
*ContrMo> replicateM 3 (putStrLn "hello")
hello
hello
hello
[(),(),()]
-}
-- A do if true or a don't do if false
-- when :: Monad m => Bool -> m () -> m ()
{-
*ContrMo> :i C.<=<
(<=<) :: Monad m => (b -> m c) -> (a -> m b) -> a -> m c
-- Defined in ‘Control.Monad’
infixr 1 <=<
*ContrMo> :i C.=<<
(=<<) :: Monad m => (a -> m b) -> m a -> m b
-- Defined in ‘Control.Monad’
infixr 1 =<<
*ContrMo> :i C.>=>
(>=>) :: Monad m => (a -> m b) -> (b -> m c) -> a -> m c
-- Defined in ‘Control.Monad’
infixr 1 >=>
*ContrMo> :i C.>>
class Monad (m :: * -> *) where
...
(>>) :: m a -> m b -> m b
...
-- Defined in ‘GHC.Base’
-}
{- liftM :: Monad m => (a1 -> r) -> m a1 -> m r
*ContrMo> C.liftM (1+) (Just 3)
Just 4
-}
-- filterM :: Monad m => (a -> m Bool) -> [a] -> m [a]
{-
-}
askToKeep x = do
putStrLn ("keeps" ++ (show x) ++ "?")
(c : _) <- getLine
return (c == 'y')
askWhichToKeep xs = filterM askToKeep xs
sayAddition x y = do
let z = x + y
putStrLn ( (show x) ++ " + " ++
(show y) ++ " = " ++
(show z))
return z
talkingSum xs = foldM sayAddition 0 xs
{-
*ContrMo> talkingSum [1,2,3]
0 + 1 = 1
1 + 2 = 3
3 + 3 = 6
6
-}
|
HaskellForCats/HaskellForCats
|
controlMonad.hs
|
mit
| 1,496
| 7
| 14
| 402
| 196
| 102
| 94
| -1
| -1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE FlexibleContexts #-}
module Main where
import Control.Monad.IO.Class (MonadIO, liftIO)
import Control.Monad.Reader (MonadReader, ReaderT, asks, runReaderT)
import Control.Monad.Trans.Class (MonadTrans, lift)
import Data.Aeson (Value (Null), (.=), object)
import Data.Text.Lazy (Text)
import qualified Database.Persist as DB
import qualified Database.Persist.Postgresql as DB
import Network.HTTP.Types.Status (created201, internalServerError500,
notFound404)
import Network.Wai (Middleware)
import Network.Wai.Middleware.RequestLogger (logStdout, logStdoutDev)
import Web.Scotty.Trans (ActionT, Options, ScottyT, defaultHandler, delete,
get, json, jsonData, middleware, notFound, param, post, put, scottyOptsT,
setHeader, settings, showError, status)
import Config
import Model (Application, ApplicationId, Event, EventId, migrateAll)
type Error = Text
main :: IO ()
main = getConfig >>= runApplication
runApplication :: Config -> IO ()
runApplication c = do
o <- getOptions (environment c)
let r m = runReaderT (runConfigM m) c
scottyOptsT o r r application
application :: ScottyT Error ConfigM ()
application = do
runDB (DB.runMigration migrateAll)
e <- lift (asks environment)
middleware (loggingM e)
defaultHandler (defaultH e)
get "/events" getEventsA
post "/events" postEventsA
get "/event/:id" getEventA
put "/event/:id" putEventA
delete "/event/:id" deleteEventA
notFound notFoundA
runDB :: (MonadTrans t, MonadIO (t ConfigM)) =>
DB.SqlPersistT IO a -> t ConfigM a
runDB q = do
p <- lift (asks pool)
liftIO (DB.runSqlPool q p)
loggingM :: Environment -> Middleware
loggingM Development = logStdoutDev
loggingM Production = logStdout
loggingM Test = id
type Action = ActionT Error ConfigM ()
defaultH :: Environment -> Error -> Action
defaultH e x = do
status internalServerError500
let o = case e of
Development -> object ["error" .= showError x]
Production -> Null
Test -> object ["error" .= showError x]
json o
getEventsA :: Action
getEventsA = do
setHeader "Access-Control-Allow-Origin" "*"
ts <- runDB (DB.selectList [] [])
json (ts :: [DB.Entity Event])
postEventsA :: Action
postEventsA = do
setHeader "Access-Control-Allow-Origin" "*"
t <- jsonData
runDB (DB.insert_ t)
status created201
json (t :: Event)
getEventA :: Action
getEventA = do
setHeader "Access-Control-Allow-Origin" "*"
i <- param "id"
m <- runDB (DB.get (toKey i))
case m of
Nothing -> notFoundA
Just t -> json (t :: Event)
putEventA :: Action
putEventA = do
setHeader "Access-Control-Allow-Origin" "*"
i <- param "id"
t <- jsonData
runDB (DB.repsert (toKey i) t)
json (t :: Event)
deleteEventA :: Action
deleteEventA = do
setHeader "Access-Control-Allow-Origin" "*"
i <- param "id"
runDB (DB.delete (toKey i :: EventId))
json Null
toKey :: DB.ToBackendKey DB.SqlBackend a => Integer -> DB.Key a
toKey i = DB.toSqlKey (fromIntegral (i :: Integer))
notFoundA :: Action
notFoundA = do
status notFound404
json Null
|
toddmohney/EventCalendar
|
src/Main.hs
|
mit
| 3,084
| 0
| 16
| 548
| 1,075
| 550
| 525
| 96
| 3
|
-- I think this file is obsolete since it uses Overload -- jcp.
----------------------------------------------------------------
-- Region tracker
----------------------------------------------------------------
module Region
( SSDTracker, make, update
, tracker
) where
import Video
( Video
, acquireRegion
)
import XVision
( EdgeTracker, mkEdgeTracker, find_EdgeTracker
, colorToBW
)
import SP
( Tracker, statefulSP
)
import Error
( Error
)
import Geometry
import Pipe
import IOExts
import XVision hiding (Offset)
import Prelude hiding(sum,or)
import XVUtilities
import Overload(size)
----------------------------------------------------------------
-- Exports
--
-- One of the interesting things in this interface is that
-- the SSD tracker always scales its input image to match
-- the original image. So, if you're tracking a 100x200
-- reference image and the Region shrinks to 50x100 then
-- the image is doubled in size while being grabbed.
----------------------------------------------------------------
make :: Image_Int -> IO SSDTracker
update :: Video -> SSDTracker -> Region -> IO (Region,Error)
tracker :: Video -> Image_Int -> Tracker Region
----------------------------------------------------------------
-- Implementations
----------------------------------------------------------------
type SSDTracker = (Sz,Image_Int -> (DeltaRegion,Error))
make im = return (size im, ssd im)
update v (sz@(w,h),ssd) r = do
{ pic <- acquireRegion v sz r
; let (rawdelta,residual) = ssd (colorToBW pic)
; let delta = rotate' sx sy a rawdelta
; return (r `addRegionDelta` delta, residual)
}
where
(sz_x,sz_y) = size_Region r
sx = fromInt w / sz_x
sy = fromInt h / sz_y
a = angle_Region r
addRegionDelta = undefined
bigger :: Double -> Sz -> Sz
bigger n (x,y) = (round (n * fromInt x), round (n * fromInt y))
-- ToDo: I doubt I'm doing the right things with sx and sy
rotate' sx sy theta (dx,dy,dtheta) = (sx * dx',sy * dy',dtheta)
where
Cartesian dx' dy' = rotate (-theta) (Cartesian dx dy)
tracker v im = statefulSP (make im) (update v)
----------------------------------------------------------------
-- SSD
--
-- This is the core of the original XVision SSD tracker
--
-- It could do with a cleanup to match the new interface.
----------------------------------------------------------------
type DeltaRegion = (Double,Double,Double)
ssd :: Image_Int -> (Image_Int -> (DeltaRegion,Error))
ssd r0 = \ r ->
let
error = compressxy (r0 - r)
delta = m0 `multColVector` imageToColVector error
residuals = imageToMatrix error - m * delta
residual = norm residuals
in
( mkDelta (head (fromMatrix delta)), residual )
where
m = mkSSD r0
m0 = inverse_M (m_t * m) * m_t
m_t = transpose_M m
mkDelta :: [Double] -> DeltaRegion
mkDelta [x,y,theta] = (x,y,theta)
-- ToDo: rename this sucker
mkSSD :: Image_Int -> Matrix
mkSSD ref0 = m
where
(x,y) = size ref0 - (1,1)
dx = smoothDx ref0
dy = smoothDy ref0
dt = dx `productImage` cY (x,y) - dy `productImage` cX (x,y)
m = colsToMatrix (x*y) [dx,dy,dt]
-- ToDo: add enough colVector/rowVector support to let me write:
-- cX (c,r) = column [-hc..hc] * row (replicate r 1)
-- cY (c,r) = column (replicate c 1) * column [-hr..hr]
cY :: Sz -> Matrix
cY (c,r) = matrix (c,r) (replicate r [-hc..])
where
hc = fromInt ((c-1) `div` 2)
cX :: Sz -> Matrix
cX (c,r) = transpose_M (cY (r,c))
----------------------------------------------------------------
-- Matrix support
----------------------------------------------------------------
matrix :: (Int,Int) -> [[Double]] -> Matrix
matrix (r,c) xs = unsafePerformIO $
do{ m <- emptyMatrix (c,r)
; mapM_ (setMatrix m) (zip ixs (concat (map (take r) xs)))
; return m
}
where
ixs = [0..c-1] `cross` [0..r-1]
fromMatrix :: Matrix -> [[Double]]
fromMatrix m = [ [ getMatrix m (x,y) | y <- [0..r-1] ] | x <- [0..c-1] ]
where
(c,r) = size m
mtMatrix :: Sz -> Matrix
mtMatrix sz = unsafePerformIO (emptyMatrix sz)
colsToMatrix :: Int -> [Image_Int] -> Matrix
colsToMatrix sz is = foldl addColumn2 (mtMatrix (0,sz)) is
cross :: [a] -> [b] -> [(a,b)]
cross as bs = [(a,b) | a <- as, b <- bs]
----------------------------------------------------------------
-- Static Image ops
----------------------------------------------------------------
compressxy :: Image_Int -> Image_Int
compressxy = compressx . compressy
----------------------------------------------------------------
-- End
----------------------------------------------------------------
|
jatinshah/autonomous_systems
|
project/fvision.hugs/garbage/region.hs
|
mit
| 4,645
| 20
| 20
| 872
| 1,415
| 793
| 622
| 83
| 1
|
import Control.Monad (void)
import qualified Graphics.UI.Threepenny as UI
import Graphics.UI.Threepenny.Core
import Graphics.UI.Threepenny.Events
import TimerControl
import Data.Time.Clock.POSIX
import Data.Time.Format
{-----------------------------------------------------------------------------
Main
------------------------------------------------------------------------------}
main :: IO ()
main = startGUI defaultConfig setup
data Action = Clicked | MouseLeave
deriving Eq
setup :: Window -> UI ()
setup window = void $ do
return window # set title "Kitchen Timer"
timerVal <- UI.h1
min <- UI.button
sec <- UI.button
start <- UI.button
let buttons = [min, sec, start]
getBody window #+ [
column [
grid [[element timerVal]
,[element min, element sec, element start]]
]]
let
clickAsPos :: Element -> Event Action
clickAsPos = fmap (\_ -> Clicked) . UI.click
leaveAsTag = fmap (\_ -> MouseLeave) . UI.leave
buttonAsB x = stepper False $ (pure (==[Clicked])) <@> (unions [clickAsPos x, leaveAsTag x])
-- need this to be true on button down and false on button up?
minIn <- buttonAsB min
secIn <- buttonAsB sec
startIn <- buttonAsB start
let
cell :: a -> Behavior a -> UI (Behavior a)
cell v c = stepper v (c <@ (unions [click min, click sec, click start]))
secToTimestamp = formatTime defaultTimeLocale "%X" . posixSecondsToUTCTime . fromIntegral
p_eq = (==)
f_zero = 0
f_countdown = (+)
f_countup = (-)
f_display = secToTimestamp
f_incMinutes = (+60)
f_incSeconds = (+1)
i_dsp = "00:00"
i_time = 0
s_dt = pure 0 --TODO
s_btnMin = (minIn :: Behavior Bool)
s_btnSec = secIn
s_btnStartStop = startIn
(display, _) <- timer_without_beep
cell
p_eq
f_zero
f_countdown
f_countup
f_display
f_incMinutes
f_incSeconds
i_dsp
i_time
s_dt
s_btnMin
s_btnSec
s_btnStartStop
element timerVal # sink value display
|
santolucito/Euterpea_Projects
|
threepennytest/Main.hs
|
mit
| 2,420
| 0
| 17
| 877
| 614
| 324
| 290
| 64
| 1
|
{-# htermination guard :: Bool -> [] () #-}
import Monad
|
ComputationWithBoundedResources/ara-inference
|
doc/tpdb_trs/Haskell/full_haskell/Monad_guard_2.hs
|
mit
| 57
| 0
| 3
| 11
| 5
| 3
| 2
| 1
| 0
|
{- |
Module : DataAssociation.SimpleRulesGenerator
Description : Associasion Rules Generator.
License : MIT
Stability : development
Generates rules by analysing confidence of the subsets of __large__ itemsets.
see __1.1__ in <http://rakesh.agrawal-family.com/papers/vldb94apriori.pdf>.
Defines the __SimpleRulesGenerator__ instance of AssociationRulesGenerator.
-}
module DataAssociation.SimpleRulesGenerator where
import DataAssociation.Definitions
import DataAssociation.Abstract
import DataAssociation.Utils
import Data.Map (Map, member, (!))
import qualified Data.Map as Map
import qualified Data.Set as Set
import Control.Arrow( (&&&), second )
import GHC.Float
-----------------------------------------------------------------------------
-- | The __SimpleRulesGenerator__ instance. Defined in "DataAssociation.SimpleRulesGenerator".
-- Based on 'subsetsFiltered'.
instance (Ord (set it), Ord it, Itemset set it) =>
AssociationRulesGenerator set it where
generateAssociationRules minconf transactions largeItemsets = rules
where rules = generateAssociationRules' minconf transactions largeItemsets
-- | SimpleRulesGenerator debug.
generateAssociationRules' :: (Itemset set it, Ord (set it), Ord it) =>
MinConfidence -- ^ minimal confidence for accepting a rule
-> [set it] -- ^ original full list of 'Itemset's
-> Map (set it) Float -- ^ __large__ 'Itemset's with the corresponding support
-> [AssocRule set it] -- ^ @[(association rule, confidence, support)]@
generateAssociationRules' minconf transactions largeItemsets =
do let (parentAndSubsets, cache) = subsetsFiltered transactions largeItemsets minconf
(parent, subsets) <- parentAndSubsets
subset <- subsets
let spdiff = newItemset $ itemsetDiff parent subset
let sup = cache ! parent
let conf = sup / (cache ! subset)
let rule = AssocRule subset spdiff conf sup
return rule
-----------------------------------------------------------------------------
-- | Generates subsets of __large__ itemsets with sufficient confidence
subsetsFiltered :: (Ord (set it), Itemset set it) =>
[set it] -- ^ /transactions/
-> Map (set it) Float -- ^ __large__ itemsets {L_{1}, ..., L_{N}} with corresponding support
-> MinConfidence -- ^ minimal confidence for rules
-> ([(set it, [set it])], Map (set it) Float) -- ^ ([(/parent/ from L_{?}, its subsets with sufficient confidence)],
-- support cache)
subsetsFiltered transactions parents mS@(MinConfidence minconf) =
inner (Map.keys parents) [] parents
where trSize = length transactions
inner [] acc supportCache = (map (second Set.toList) acc, supportCache)
inner (p:parents') acc supportCache =
inner parents' ((p, Set.map fst subs):acc) (Map.union supportCache cacheUpd)
where subs = Set.filter filterSufficientConfidence (Set.fromList subs')
filterSufficientConfidence (set, sup) = (supportCache ! p) / sup >= minconf
(subs', cacheUpd) = second Map.unions (unzip subsEtc)
subsEtc = supportEtc $ nonemptySubsets (Set.singleton p) Set.empty
nonemptySubsets ps acc =
if setSize (Set.findMin ps) == 1
then acc
else nonemptySubsets subs (Set.union acc subs)
where subs = Set.fromList $ concatMap allSubsetsOneShorter (Set.toList ps)
supportEtc sets = do
set <- Set.toList sets
let (support, cacheUpdate) =
if set `member` supportCache
then (supportCache ! set, Map.empty)
else let sup = Map.map (calculateSupport trSize)
(countSupported transactions [set])
in (sup ! set, sup)
return ((set, support), cacheUpdate)
|
fehu/min-dat--a-priori
|
core/src/DataAssociation/SimpleRulesGenerator.hs
|
mit
| 4,351
| 1
| 13
| 1,367
| 874
| 469
| 405
| -1
| -1
|
module Test.Arbitrary where
import Test.QuickCheck
import Control.Monad (forM)
import Data.Core.Graph.NodeManager (NodeMap)
import Data.Core.Graph.PureCore (Graph, empty, fromAdj)
import qualified Data.IntMap.Strict as IM
newtype TestNodeMap v = TestNodeMap(NodeMap v) deriving Show
instance Arbitrary v => Arbitrary (TestNodeMap v) where
arbitrary = fmap (TestNodeMap . IM.fromList . map (\(NonNegative i, x) -> (i, x))) arbitrary
instance Arbitrary Graph where
arbitrary = frequency [(1, return empty), (20, denseGraph)]
where denseGraph =
do n <- choose (0, 30::Int)
let nodeList = [1..n]
adj <- forM nodeList $ \i ->
do bits <- vectorOf n arbitrary
return (i, [ x | (x,b) <- zip nodeList bits, b ])
return $ fromAdj adj
|
factisresearch/graph-core
|
src/Test/Arbitrary.hs
|
mit
| 877
| 0
| 20
| 259
| 304
| 168
| 136
| 18
| 0
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE StrictData #-}
{-# LANGUAGE TupleSections #-}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-portfolioproductassociation.html
module Stratosphere.Resources.ServiceCatalogPortfolioProductAssociation where
import Stratosphere.ResourceImports
-- | Full data type definition for ServiceCatalogPortfolioProductAssociation.
-- See 'serviceCatalogPortfolioProductAssociation' for a more convenient
-- constructor.
data ServiceCatalogPortfolioProductAssociation =
ServiceCatalogPortfolioProductAssociation
{ _serviceCatalogPortfolioProductAssociationAcceptLanguage :: Maybe (Val Text)
, _serviceCatalogPortfolioProductAssociationPortfolioId :: Val Text
, _serviceCatalogPortfolioProductAssociationProductId :: Val Text
, _serviceCatalogPortfolioProductAssociationSourcePortfolioId :: Maybe (Val Text)
} deriving (Show, Eq)
instance ToResourceProperties ServiceCatalogPortfolioProductAssociation where
toResourceProperties ServiceCatalogPortfolioProductAssociation{..} =
ResourceProperties
{ resourcePropertiesType = "AWS::ServiceCatalog::PortfolioProductAssociation"
, resourcePropertiesProperties =
hashMapFromList $ catMaybes
[ fmap (("AcceptLanguage",) . toJSON) _serviceCatalogPortfolioProductAssociationAcceptLanguage
, (Just . ("PortfolioId",) . toJSON) _serviceCatalogPortfolioProductAssociationPortfolioId
, (Just . ("ProductId",) . toJSON) _serviceCatalogPortfolioProductAssociationProductId
, fmap (("SourcePortfolioId",) . toJSON) _serviceCatalogPortfolioProductAssociationSourcePortfolioId
]
}
-- | Constructor for 'ServiceCatalogPortfolioProductAssociation' containing
-- required fields as arguments.
serviceCatalogPortfolioProductAssociation
:: Val Text -- ^ 'scpproaPortfolioId'
-> Val Text -- ^ 'scpproaProductId'
-> ServiceCatalogPortfolioProductAssociation
serviceCatalogPortfolioProductAssociation portfolioIdarg productIdarg =
ServiceCatalogPortfolioProductAssociation
{ _serviceCatalogPortfolioProductAssociationAcceptLanguage = Nothing
, _serviceCatalogPortfolioProductAssociationPortfolioId = portfolioIdarg
, _serviceCatalogPortfolioProductAssociationProductId = productIdarg
, _serviceCatalogPortfolioProductAssociationSourcePortfolioId = Nothing
}
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-portfolioproductassociation.html#cfn-servicecatalog-portfolioproductassociation-acceptlanguage
scpproaAcceptLanguage :: Lens' ServiceCatalogPortfolioProductAssociation (Maybe (Val Text))
scpproaAcceptLanguage = lens _serviceCatalogPortfolioProductAssociationAcceptLanguage (\s a -> s { _serviceCatalogPortfolioProductAssociationAcceptLanguage = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-portfolioproductassociation.html#cfn-servicecatalog-portfolioproductassociation-portfolioid
scpproaPortfolioId :: Lens' ServiceCatalogPortfolioProductAssociation (Val Text)
scpproaPortfolioId = lens _serviceCatalogPortfolioProductAssociationPortfolioId (\s a -> s { _serviceCatalogPortfolioProductAssociationPortfolioId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-portfolioproductassociation.html#cfn-servicecatalog-portfolioproductassociation-productid
scpproaProductId :: Lens' ServiceCatalogPortfolioProductAssociation (Val Text)
scpproaProductId = lens _serviceCatalogPortfolioProductAssociationProductId (\s a -> s { _serviceCatalogPortfolioProductAssociationProductId = a })
-- | http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-portfolioproductassociation.html#cfn-servicecatalog-portfolioproductassociation-sourceportfolioid
scpproaSourcePortfolioId :: Lens' ServiceCatalogPortfolioProductAssociation (Maybe (Val Text))
scpproaSourcePortfolioId = lens _serviceCatalogPortfolioProductAssociationSourcePortfolioId (\s a -> s { _serviceCatalogPortfolioProductAssociationSourcePortfolioId = a })
|
frontrowed/stratosphere
|
library-gen/Stratosphere/Resources/ServiceCatalogPortfolioProductAssociation.hs
|
mit
| 4,142
| 0
| 15
| 362
| 462
| 263
| 199
| 41
| 1
|
module Flowskell.Interpreter (initSchemeEnv, initPrimitives, evalFrame) where
import Data.Maybe (isJust)
import Graphics.Rendering.OpenGL hiding (Bool, Float) -- get, $=
import Control.Monad
import Control.Monad.Error
import Language.Scheme.Core (r5rsEnv, evalString, evalLisp', primitiveBindings)
import Language.Scheme.Types
import Language.Scheme.Util (escapeBackslashes)
import Language.Scheme.Parser
import Language.Scheme.Variables (extendEnv)
import Flowskell.Lib.GL (glIOPrimitives)
import Flowskell.Lib.Random (randomIOPrimitives)
import Flowskell.Lib.Time (timeIOPrimitives)
import Flowskell.Lib.Color (colorIOPrimitives)
import Flowskell.Lib.Math (mathIOPrimitives)
import Flowskell.State
#ifdef USE_JACK
import Flowskell.Lib.Jack (initJack)
#endif
#ifdef USE_TEXTURES
import Flowskell.Lib.Textures (initTextures)
#endif
#ifdef RENDER_TO_TEXTURE
import Flowskell.Lib.Shaders (initShaders)
#endif
import Paths_Flowskell
defaultPrimitives = timeIOPrimitives ++ glIOPrimitives ++ randomIOPrimitives ++ colorIOPrimitives ++ mathIOPrimitives
mkPrimitiveList b = map (\(n, f) -> (('v', n), CustFunc $ makeThrowErrorFunc f)) b
where makeThrowErrorFunc f obj = liftIO $ f obj
-- |Try to evaluate LispVal, call catch function if it fails
tryEval :: Env -> LispVal -> (LispError -> IO a) -> IO ()
tryEval env lisp catch =
evalLisp' env lisp >>= \x -> case x of
Left error -> catch error >> return ()
_ -> return ()
reportError :: String -> LispError -> IO ()
reportError file err = putStrLn $ "Failure in " ++ file ++ ":\n" ++ (show err)
initSchemeEnv extraPrimitives filename = do
let fskPrimitives = mkPrimitiveList $ defaultPrimitives ++ extraPrimitives
fskLib <- getDataFileName "lib/flowskell.scm"
env <- r5rsEnv >>= flip extendEnv fskPrimitives
mapM_ (\f -> tryEval env (List [Atom "load", String f]) $ reportError f)
[fskLib, filename]
return env
evalFrame state env =
tryEval env (List [Atom "every-frame-entry-point"]) $ \ error -> do
reportError "<source>" error
maybeLastEnv <- get $ lastEnvironment state
when (isJust maybeLastEnv) $ environment state $= maybeLastEnv
initPrimitives state = do
#ifdef RENDER_TO_TEXTURE
shaderIOPrimitives <- initShaders state
#else
shaderIOPrimitives <- return []
#endif
#ifdef USE_TEXTURES
texturesIOPrimitives <- initTextures state
#else
texturesIOPrimitives <- return []
#endif
#ifdef USE_JACK
jackIOPrimitives <- initJack
#else
jackIOPrimitives <- return []
#endif
return $ shaderIOPrimitives ++ texturesIOPrimitives ++ jackIOPrimitives
|
lordi/flowskell
|
src/Flowskell/Interpreter.hs
|
gpl-2.0
| 2,586
| 0
| 15
| 399
| 692
| 374
| 318
| 44
| 2
|
module Main where
import qualified Pipeline as P
main = do
putStrLn "this is main"
P.main
|
averagehat/Pathogen.hs
|
app/Main.hs
|
gpl-2.0
| 95
| 0
| 7
| 21
| 26
| 15
| 11
| 5
| 1
|
import Control.Monad.Instances
import Data.List
import Data.Char
import Data.Maybe
import Text.Printf
import System.Environment
import Text.Regex.Posix
-- First, three helpers
io f = interact (unlines . f . lines)
showln = (++ "\n") . show
regexBool r l = l =~ r :: Bool -- simple boolean regex matching
-- remove duplicate lines from a file (like uniq)
uniq = nub -- Warning: Unix uniq discards *consecutive* dupes,
-- but 'nub' discards all dupes.
-- repeat the input file infinitely
rpt = cycle
-- Return the head -10 line of a file
take' = take 10
-- Remove the first 10 lines of a file
drop' = drop 10
-- Return the head -1 line of a file
head' = head
-- Return the tail -1 line of a file
tail' = last
-- return the last ten lines of a file
tail10 = drop =<< subtract 10 . length
-- Reverse lines in a file (tac)
tac = reverse
-- Reverse characters on each line (rev)
rev = map reverse
-- Reverse words on each line
rev_w = map (unwords . reverse . words)
-- Count number of characters in a file (like wc -c)
wc_c = showln . length
-- Count number of lines in a file, like wc -l
wc_l = showln . length . lines
-- Count number of words in a file (like wc -w)
wc_w = showln . length . words
-- double space a file
space = intersperse ""
-- undo double space
unspace = filter (not.null)
-- remove the first occurrence of the line "str"
remove = delete
-- make a string all upper case
upper = map toUpper
-- remove leading space from each line
clean = map (dropWhile isSpace)
-- remove trailing whitespace
clean' = map (reverse . dropWhile isSpace . reverse)
-- delete leading and trailing whitespace
clean'' = map (f . f)
where f = reverse . dropWhile isSpace
-- insert blank space at beginning of each line
blank = map (s ++)
where s = replicate 8 ' '
-- join lines of a file
join = return . concat
-- Translate the letter 'e' to '*', like tr 'e' '*' (or y// in sed)
tr a b = interact (map f)
where f c = if c == a then b else c
-- Delete characters from a string.
tr_d a = tr a ' '
-- lines matching the regular expression "[bf]oo" from a file
grep = filter (regexBool "[bf]oo")
-- lines not matching the regular expression "[bf]oo" from a file
grep_v = filter (not . regexBool "[bf]oo")
-- number each line of a file
num = zipWith (printf "%3d %s") [(1::Int)..]
-- Compute a simple cksum of a file
cksum = foldl' k 5381
where k h c = h * 33 + ord c
-- And our main wrapper
main = do
who <- getProgName
maybe (return ()) id $ lookup who $
[("blank", io blank )
,("cksum", interact (showln . cksum) )
,("clean", io clean'' )
,("echo" , interact id )
,("drop", interact drop' )
,("grep", io grep )
,("grep -v", io grep_v )
,("head", io (return . head') )
,("join", io join )
,("num", io num )
,("remove", io (remove "str") )
,("revw", io rev_w )
,("reverse", io rev )
,("reverseword", io rev_w )
,("rpt", io rpt )
,("sort", interact sort )
,("space", io space )
,("tac", interact tac )
,("take", io take' )
,("tail", io (return . tail') )
-- ,( "tr" , interact tr)
-- ,( "tr -d", interact (tr_d . unwords))
,("unspace", io unspace )
,("upper", interact upper )
,("uniq", interact uniq )
,("wc_c", interact wc_c )
,("wc_l", interact wc_l )
,("wc_w", interact wc_w )
]
|
violetkz/haskell_learning
|
unixcmd.hs
|
gpl-2.0
| 4,072
| 0
| 12
| 1,519
| 898
| 507
| 391
| 71
| 2
|
cubicSplineInterp x [xjp2, xjp1, xj, xjm1, xjm2]
| x > xjp2 = 0
| x >= xjp1 = (1/(6*h^3)) * (xjp2 -x)^3
| x >= xj = 1/6 + (1/(2*h)) *(xjp1-x) + (1/(2*h^2)) *(xjp1-x)^2 - (1/(2*h^3)) *(xjp1-x)^3
| x >= xjm1 = 2/3 - 1/(h^2) *(x-xj)^2 - 1/(2*h^3) *(x-xj)^3
| x >= xjm2 = 1/(6*h^3) * (x-xjm2)^3
| otherwise = 0
where
h = xjp1 - xj
|
Marcus-Rosti/numerical-methods
|
src/ch_04/Ch_04.hs
|
gpl-2.0
| 365
| 0
| 17
| 105
| 346
| 181
| 165
| 8
| 1
|
module Projection (
project
, match ) where
import ErrM
import AbsAST
import ParAST
import PrintAST
import Data.List (find)
import Data.Maybe
import Data.Map (Map,(!))
import qualified Data.Map as Map
---- Projection patterns
patterns :: [(String, Map Integer Expression -> Relation)]
patterns = [ ("(PhrUtt * $1 *)", \m -> project (m ! 1))
, ("(UseCl * PPos $1)", \m -> project (m ! 1))
-- Negation
, ("(UseCl * PNeg $1)", \m -> negation (project (m ! 1)))
-- Intersective modification
, ("(AdjCN * $1)", \m -> intersect (project (m ! 1)))
-- Quantifiers
]
++ quantifier_patterns "every"
++ quantifier_patterns "some"
++ quantifier_patterns "no"
++
[ ("(PredetNP not_Predet (DetCN every_Det $1) $2)", \m -> reljoin (negation (restr "every" (project (m ! 1))))
(negation (scope "every" (project (m ! 2)))))
, ("(PredetNP not_Predet (PredetNP all_Predet (DetCN (DetQuant IndefArt NumPl) $1)) $2)",
\m -> reljoin (restr "every" (project (m ! 1)))
(restr "every" (project (m ! 2))))
, ("(ComplSlash $2 (PredetNP all_Predet (DetCN (DetQuant IndefArt NumPl) $1)))",
\m -> reljoin (restr "every" (project (m ! 1)))
(restr "every" (project (m ! 2))))
-- TODO some verbs are not upward-monotone
-- , ("(ComplSlash * $1)", \m -> ...)
-- non-operator contexts (everything else)
, ("(* $1)", \m -> project (m ! 1))
, ("(* $1 $2)", \m -> reljoin (project (m ! 1)) (project (m ! 2)))
]
quantifier_patterns s = [
-- subject position
("(PredVP "++s++"body_NP $2)", \m -> scope s (project (m ! 2)))
, ("(PredVP "++s++"thing_NP $2)", \m -> scope s (project (m ! 2)))
, ("(PredVP (DetCN "++s++"_Det $1) $2)", \m -> reljoin (restr s (project (m ! 1))) (scope s (project (m ! 2))))
-- object position
, ("(ComplSlash $2 "++s++"body_NP)", \m -> scope s (project (m ! 2)))
, ("(ComplSlash $2 "++s++"thing_NP)", \m -> scope s (project (m ! 2)))
, ("(ComplSlash $2 (DetCN "++s++"_Det $1))", \m -> reljoin (restr s (project (m ! 1))) (scope s (project (m ! 2))))
]
---- Projection behavior of operators
reljoin :: Relation -> Relation -> Relation
reljoin Equivalent r = r
reljoin r Equivalent = r
reljoin Entails Entails = Entails
reljoin Entails Excludes = DisjointWith
reljoin Entails DisjointWith = DisjointWith
reljoin IsEntailedBy IsEntailedBy = IsEntailedBy
reljoin IsEntailedBy Excludes = Overlaps
reljoin IsEntailedBy Overlaps = Overlaps
reljoin Excludes Entails = Overlaps
reljoin Excludes IsEntailedBy = DisjointWith
reljoin Excludes Excludes = Equivalent
reljoin Excludes DisjointWith = IsEntailedBy
reljoin Excludes Overlaps = Entails
reljoin Excludes IndependentOf = IndependentOf
reljoin DisjointWith IsEntailedBy = DisjointWith
reljoin DisjointWith Excludes = Entails
reljoin DisjointWith Overlaps = Entails
reljoin Overlaps Entails = Overlaps
reljoin Overlaps Excludes = IsEntailedBy
reljoin Overlaps DisjointWith = IsEntailedBy
reljoin IndependentOf Excludes = IndependentOf
-- the rest
reljoin r None = r
reljoin None r = r
reljoin _ _ = None
-- Negation
negation :: Relation -> Relation
negation Entails = IsEntailedBy
negation IsEntailedBy = Entails
negation DisjointWith = Overlaps
negation Overlaps = DisjointWith
negation relation = relation
-- Intersective modification
intersect :: Relation -> Relation
intersect Excludes = DisjointWith
intersect Overlaps = IndependentOf
intersect relation = relation
-- Quantifiers
restr :: String -> Relation -> Relation
restr "every" Entails = IsEntailedBy
restr "every" IsEntailedBy = Entails
restr "every" Excludes = DisjointWith
restr "every" DisjointWith = IndependentOf
restr "every" Overlaps = DisjointWith
restr "every" relation = relation
restr "some" Excludes = Overlaps
restr "some" DisjointWith = IndependentOf
restr "some" relation = relation
restr "no" relation = negation (restr "some" relation)
scope :: String -> Relation -> Relation
scope "every" Excludes = DisjointWith
scope "every" Overlaps = IndependentOf
scope "every" relation = relation
scope "some" Excludes = Overlaps
scope "some" DisjointWith = IndependentOf
scope "some" relation = relation
scope "no" relation = negation (scope "some" relation)
-- Intersective modification
---- Machinery
project :: Expression -> Relation
project (Change r) = r
project e = case find isJust $ map (try e) patterns of
Just (Just r) -> r
Nothing -> None
try :: Expression -> (String, Map Integer Expression -> Relation) -> Maybe Relation
try expr (str,func) = case pExpression $ myLexer $ str of
Ok e -> case match e expr of
Just m -> Just (func m)
Nothing -> Nothing
_ -> Nothing
match :: Expression -> Expression -> Maybe (Map Integer Expression)
match (Constant (Ident s1)) (Constant (Ident s2))
| s1 == s2 = Just $ Map.empty
| otherwise = Nothing
match (Change r1) (Change r2)
| r1 == r2 = Just $ Map.empty
| otherwise = Nothing
match Wildcard _ = Just $ Map.empty
match (Slot i) e = Just $ Map.singleton i e
match (List []) (List []) = Just $ Map.empty
match (List (e1:es1)) (List (e2:es2)) =
case (match e1 e2, match (List es1) (List es2)) of
(Just m, Just m') -> Just $ Map.union m m'
_ -> Nothing
match _ _ = Nothing
|
cunger/mule
|
src/Projection.hs
|
gpl-3.0
| 6,289
| 0
| 17
| 2,065
| 1,861
| 979
| 882
| 117
| 3
|
-- Problem 1
-- (*) Find the last element of a list.
myLast :: [a] -> a
myLast list = last list
-- Problem 2
-- (*) Find the last but one element of a list.
myButLast :: [a] -> a
myButLast x = x !! ( (length x) - 2 )
-- Problem 3
-- (*) Find the K'th element of a list. The first element in the list is number 1.
elementAt :: [a] -> Int -> a
elementAt x i = x !! (i-1)
-- Problem 6
-- Find out whether a list is a palindrome. A palindrome can be read forward
-- or backward; e.g. (x a m a x).
isPalindrome :: (Eq a) => [a] -> Bool
isPalindrome x = x == (reverse x)
-- Problem 8
-- (**) Eliminate consecutive duplicates of list elements.
|
susu/haskell-problems
|
99_hs_problems/p1-10.hs
|
gpl-3.0
| 647
| 0
| 9
| 149
| 148
| 84
| 64
| 8
| 1
|
{-# LANGUAGE DeriveDataTypeable, TemplateHaskell, GeneralizedNewtypeDeriving, StandaloneDeriving #-}
{-|
This module defines the Sitemap type,
which is used for routing, as well as its
mapping to and from path segments.
-}
module Blog.Sitemap where
import Blog.Instances()
import Blog.Posts.Core (PostId(..))
import Control.Applicative
import Data.Data (Data)
import Data.Text (Text)
import qualified Data.Text as Text
import Data.Time
( Day
, FormatTime, ParseTime
, readsTime
, showGregorian
)
import Data.Typeable (Typeable)
import System.Locale (defaultTimeLocale, iso8601DateFormat)
import Web.Routes
import Web.Routes.TH (derivePathInfo)
data Sitemap
= Home
| Post PostSite
| User UserSite
deriving (Eq, Ord, Read, Show, Data, Typeable)
data PostSite
= View PathDay Text
| Edit PostId
| Delete PostId
| New
deriving (Eq, Ord, Read, Show, Data, Typeable)
data UserSite
= UserLogin
| UserLogout
| UserNew
deriving (Eq, Ord, Read, Show, Data, Typeable)
-- for avoiding orphan instances
newtype PathDay = PathDay Day
deriving (Eq, Ord, Read, Show, Data, Typeable, ParseTime, FormatTime)
parseReadS :: msg -> ReadS a -> URLParser a
parseReadS msg r =
pToken msg $ \str ->
case r (Text.unpack str) of
[(x,"")] -> Just x
_ -> Nothing
instance PathInfo PathDay where
toPathSegments (PathDay day) =
[Text.pack $ showGregorian day]
fromPathSegments =
PathDay <$>
parseReadS "valid date"
(readsTime defaultTimeLocale (iso8601DateFormat Nothing))
derivePathInfo ''UserSite
derivePathInfo ''PostSite
derivePathInfo ''Sitemap
|
aslatter/blog
|
Blog/Sitemap.hs
|
gpl-3.0
| 1,669
| 0
| 11
| 357
| 470
| 258
| 212
| 51
| 2
|
module TestUtilities
( sequencer
, tmpA
, tmpB
) where
sequencer :: Int -> Int -> [Float]
sequencer n k = [(fromIntegral x) / (fromIntegral k) | x <- [0..n]]
tmpA :: (Num a, Floating a) => [a]
tmpA = [0.05, 0.05, 0.1, 0.2, 0.15, 0.25, 0.1, 0.025, 0.025, 0.05] -- proportion of 'words'
tmpB :: (Num a, Floating a) => [a]
tmpB = [a * b | (a, b) <- zip tmpA (replicate 10 10000)] -- actual counts
|
R-Morgan/hasStat
|
TestUtilities.hs
|
gpl-3.0
| 411
| 0
| 10
| 96
| 195
| 113
| 82
| 10
| 1
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Main.IOS
(
main',
) where
import MyPrelude
import File
import Game
import Game
import Game.Run
import Game.Run.Helpers.Make
import Game.Run.Iteration
import OpenGL
import OpenGL.Helpers
import OpenAL
import OpenAL.Helpers
import Test
main' :: IO ()
main' = do
-- define MEnv
let init = Init
{
initScreenOrientations = [ OrientationLandscapeLeft,
OrientationLandscapeRight ],
initScreenMultisample = 4,
initScreenRate = 0,
initSoundSampleRate = 22050,
initKeysAcclGyroRate = 0.1
}
-- run MEnv!
let a = ()
c <- runMEnvIOS init loadGameData unloadGameData
begin iterate end a
return ()
where
begin _ = do
-- setup OpenGL and OpenAL
io $ do
-- OpenGL --
-- (see invariants.txt for GL state)
glClearColor 0 0 0 0
glDisable gl_STENCIL_TEST
glClearStencil 0
-- lets use premultiplied colors to represent colors, as default
glEnable gl_BLEND
glBlendEquationSeparate gl_FUNC_ADD gl_FUNC_ADD
glBlendFuncSeparate -- premultiplied alpha blending:
gl_ONE gl_ONE_MINUS_SRC_ALPHA
gl_CONSTANT_ALPHA gl_ZERO
-- cool effect blending
--gl_SRC_ALPHA gl_DST_ALPHA
--gl_SRC_ALPHA gl_DST_ALPHA
glDepthMask gl_TRUE
glDepthFunc gl_LEQUAL
glEnable gl_DEPTH_TEST
glDisable gl_DITHER -- ??
-- OpenAL --
alDistanceModel al_INVERSE_DISTANCE
-- doppler, speed of sound, ...
-- we want to play this game with a local player (if possible)
playersAuthenticateLocalPlayer
-- if first run, create folders and files for dynamic data
createDynamicData
-- load the RunWorld not assocciated with any local player ("empty")
path <- fileRunWorldEmpty
run <- loadRunWorld path
-- test
return (run, (), [iterationTestTweak])
--return (run, (), [iterationTestGL])
iterate (a, b, stack) = do
iterateABStack a b stack
end (run, b, stack) = do
saveRunWorld run
|
karamellpelle/grid
|
test/source/Main/IOS.hs
|
gpl-3.0
| 3,325
| 0
| 12
| 1,231
| 390
| 214
| 176
| 52
| 1
|
module Routes
(routes) where
import Control.Monad.IO.Class (liftIO)
import Happstack.Server hiding (host)
import Response
import Database.CourseQueries (retrieveCourse, allCourses, queryGraphs, courseInfo, deptList, getGraphJSON)
import Database.CourseInsertion (saveGraphJSON)
import Data.Text.Lazy (Text)
routes :: String -> Text -> Text -> [ (String, ServerPart Response)]
routes staticDir aboutContents privacyContents = [
("grid", gridResponse),
("graph", graphResponse),
("image", graphImageResponse),
("timetable-image", lookText' "session" >>= \session -> readCookieValue "selected-lectures" >>= exportTimetableImageResponse session),
("timetable-pdf", lookCookieValue "selected-lectures" >>= exportTimetablePDFResponse),
("post", postResponse),
("draw", drawResponse),
("about", aboutResponse aboutContents),
("privacy", privacyResponse privacyContents),
("static", serveDirectory DisableBrowsing [] staticDir),
("course", lookText' "name" >>= retrieveCourse),
("all-courses", liftIO allCourses),
("graphs", liftIO queryGraphs),
("course-info", lookText' "dept" >>= courseInfo),
("depts", liftIO deptList),
("timesearch", searchResponse),
("calendar", lookCookieValue "selected-lectures" >>= calendarResponse),
("get-json-data", lookText' "graphName" >>= \graphName -> liftIO $ getGraphJSON graphName),
("loading", lookText' "size" >>= loadingResponse),
("save-json", lookBS "jsonData" >>= \jsonStr -> lookText' "nameData" >>= \nameStr -> liftIO $ saveGraphJSON jsonStr nameStr)
]
|
hermish/courseography
|
app/Routes.hs
|
gpl-3.0
| 1,580
| 0
| 12
| 230
| 435
| 253
| 182
| 30
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# OPTIONS_GHC -fno-warn-duplicate-exports #-}
{-# OPTIONS_GHC -fno-warn-unused-binds #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- |
-- Module : Network.Google.Resource.MapsEngine.Rasters.Permissions.List
-- Copyright : (c) 2015-2016 Brendan Hay
-- License : Mozilla Public License, v. 2.0.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : auto-generated
-- Portability : non-portable (GHC extensions)
--
-- Return all of the permissions for the specified asset.
--
-- /See:/ <https://developers.google.com/maps-engine/ Google Maps Engine API Reference> for @mapsengine.rasters.permissions.list@.
module Network.Google.Resource.MapsEngine.Rasters.Permissions.List
(
-- * REST Resource
RastersPermissionsListResource
-- * Creating a Request
, rastersPermissionsList
, RastersPermissionsList
-- * Request Lenses
, rplId
) where
import Network.Google.MapsEngine.Types
import Network.Google.Prelude
-- | A resource alias for @mapsengine.rasters.permissions.list@ method which the
-- 'RastersPermissionsList' request conforms to.
type RastersPermissionsListResource =
"mapsengine" :>
"v1" :>
"rasters" :>
Capture "id" Text :>
"permissions" :>
QueryParam "alt" AltJSON :>
Get '[JSON] PermissionsListResponse
-- | Return all of the permissions for the specified asset.
--
-- /See:/ 'rastersPermissionsList' smart constructor.
newtype RastersPermissionsList = RastersPermissionsList'
{ _rplId :: Text
} deriving (Eq,Show,Data,Typeable,Generic)
-- | Creates a value of 'RastersPermissionsList' with the minimum fields required to make a request.
--
-- Use one of the following lenses to modify other fields as desired:
--
-- * 'rplId'
rastersPermissionsList
:: Text -- ^ 'rplId'
-> RastersPermissionsList
rastersPermissionsList pRplId_ =
RastersPermissionsList'
{ _rplId = pRplId_
}
-- | The ID of the asset whose permissions will be listed.
rplId :: Lens' RastersPermissionsList Text
rplId = lens _rplId (\ s a -> s{_rplId = a})
instance GoogleRequest RastersPermissionsList where
type Rs RastersPermissionsList =
PermissionsListResponse
type Scopes RastersPermissionsList =
'["https://www.googleapis.com/auth/mapsengine",
"https://www.googleapis.com/auth/mapsengine.readonly"]
requestClient RastersPermissionsList'{..}
= go _rplId (Just AltJSON) mapsEngineService
where go
= buildClient
(Proxy :: Proxy RastersPermissionsListResource)
mempty
|
rueshyna/gogol
|
gogol-maps-engine/gen/Network/Google/Resource/MapsEngine/Rasters/Permissions/List.hs
|
mpl-2.0
| 3,029
| 0
| 13
| 685
| 307
| 189
| 118
| 51
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Kinesis.MergeShards
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Merges two adjacent shards in a stream and combines them into a single shard
-- to reduce the stream's capacity to ingest and transport data. Two shards are
-- considered adjacent if the union of the hash key ranges for the two shards
-- form a contiguous set with no gaps. For example, if you have two shards, one
-- with a hash key range of 276...381 and the other with a hash key range of
-- 382...454, then you could merge these two shards into a single shard that
-- would have a hash key range of 276...454. After the merge, the single child
-- shard receives data for all hash key values covered by the two parent shards.
--
-- 'MergeShards' is called when there is a need to reduce the overall capacity of
-- a stream because of excess capacity that is not being used. You must specify
-- the shard to be merged and the adjacent shard for a stream. For more
-- information about merging shards, see <http://docs.aws.amazon.com/kinesis/latest/dev/kinesis-using-api-java.html#kinesis-using-api-java-resharding-merge Merge Two Shards> in the /Amazon KinesisDeveloper Guide/.
--
-- If the stream is in the 'ACTIVE' state, you can call 'MergeShards'. If a stream
-- is in the 'CREATING', 'UPDATING', or 'DELETING' state, 'MergeShards' returns a 'ResourceInUseException'. If the specified stream does not exist, 'MergeShards' returns a 'ResourceNotFoundException'.
--
-- You can use 'DescribeStream' to check the state of the stream, which is
-- returned in 'StreamStatus'.
--
-- 'MergeShards' is an asynchronous operation. Upon receiving a 'MergeShards'
-- request, Amazon Kinesis immediately returns a response and sets the 'StreamStatus' to 'UPDATING'. After the operation is completed, Amazon Kinesis sets the 'StreamStatus' to 'ACTIVE'. Read and write operations continue to work while the stream is in
-- the 'UPDATING' state.
--
-- You use 'DescribeStream' to determine the shard IDs that are specified in the 'MergeShards' request.
--
-- If you try to operate on too many streams in parallel using 'CreateStream', 'DeleteStream', 'MergeShards' or 'SplitShard', you will receive a 'LimitExceededException'.
--
-- 'MergeShards' has limit of 5 transactions per second per account.
--
-- <http://docs.aws.amazon.com/kinesis/latest/APIReference/API_MergeShards.html>
module Network.AWS.Kinesis.MergeShards
(
-- * Request
MergeShards
-- ** Request constructor
, mergeShards
-- ** Request lenses
, msAdjacentShardToMerge
, msShardToMerge
, msStreamName
-- * Response
, MergeShardsResponse
-- ** Response constructor
, mergeShardsResponse
) where
import Network.AWS.Data (Object)
import Network.AWS.Prelude
import Network.AWS.Request.JSON
import Network.AWS.Kinesis.Types
import qualified GHC.Exts
data MergeShards = MergeShards
{ _msAdjacentShardToMerge :: Text
, _msShardToMerge :: Text
, _msStreamName :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'MergeShards' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'msAdjacentShardToMerge' @::@ 'Text'
--
-- * 'msShardToMerge' @::@ 'Text'
--
-- * 'msStreamName' @::@ 'Text'
--
mergeShards :: Text -- ^ 'msStreamName'
-> Text -- ^ 'msShardToMerge'
-> Text -- ^ 'msAdjacentShardToMerge'
-> MergeShards
mergeShards p1 p2 p3 = MergeShards
{ _msStreamName = p1
, _msShardToMerge = p2
, _msAdjacentShardToMerge = p3
}
-- | The shard ID of the adjacent shard for the merge.
msAdjacentShardToMerge :: Lens' MergeShards Text
msAdjacentShardToMerge =
lens _msAdjacentShardToMerge (\s a -> s { _msAdjacentShardToMerge = a })
-- | The shard ID of the shard to combine with the adjacent shard for the merge.
msShardToMerge :: Lens' MergeShards Text
msShardToMerge = lens _msShardToMerge (\s a -> s { _msShardToMerge = a })
-- | The name of the stream for the merge.
msStreamName :: Lens' MergeShards Text
msStreamName = lens _msStreamName (\s a -> s { _msStreamName = a })
data MergeShardsResponse = MergeShardsResponse
deriving (Eq, Ord, Read, Show, Generic)
-- | 'MergeShardsResponse' constructor.
mergeShardsResponse :: MergeShardsResponse
mergeShardsResponse = MergeShardsResponse
instance ToPath MergeShards where
toPath = const "/"
instance ToQuery MergeShards where
toQuery = const mempty
instance ToHeaders MergeShards
instance ToJSON MergeShards where
toJSON MergeShards{..} = object
[ "StreamName" .= _msStreamName
, "ShardToMerge" .= _msShardToMerge
, "AdjacentShardToMerge" .= _msAdjacentShardToMerge
]
instance AWSRequest MergeShards where
type Sv MergeShards = Kinesis
type Rs MergeShards = MergeShardsResponse
request = post "MergeShards"
response = nullResponse MergeShardsResponse
|
kim/amazonka
|
amazonka-kinesis/gen/Network/AWS/Kinesis/MergeShards.hs
|
mpl-2.0
| 5,871
| 0
| 9
| 1,216
| 518
| 325
| 193
| 63
| 1
|
-- brittany { lconfig_columnAlignMode: { tag: ColumnAlignModeDisabled }, lconfig_indentPolicy: IndentPolicyLeft }
import Test hiding ()
import Test as T hiding ()
|
lspitzner/brittany
|
data/Test474.hs
|
agpl-3.0
| 163
| 0
| 4
| 21
| 18
| 13
| 5
| 2
| 0
|
module Palindroms where
import Data.Char
firstLast :: [a] -> [a]
firstLast [] = []
firstLast [x] = []
firstLast xs = tail (init xs)
isPalindrom :: String -> Bool
isPalindrom [] = True
isPalindrom [x] = True
isPalindrom str = (toUpper (str !! 0)) == (toUpper $ last str) && isPalindrom (firstLast str)
|
ice1000/OI-codes
|
codewars/101-200/is-it-a-palindrome.hs
|
agpl-3.0
| 308
| 0
| 10
| 60
| 144
| 76
| 68
| 10
| 1
|
module TypeInterface2 where
f x y = x + y + 3
|
dmp1ce/Haskell-Programming-Exercises
|
Chapter 5/typeInterface2.hs
|
unlicense
| 47
| 0
| 6
| 13
| 22
| 12
| 10
| 2
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : Haddock.Interface.Create
-- Copyright : (c) Simon Marlow 2003-2006,
-- David Waern 2006-2009
-- License : BSD-like
--
-- Maintainer : haddock@projects.haskell.org
-- Stability : experimental
-- Portability : portable
-----------------------------------------------------------------------------
module Haddock.Interface.Create (createInterface) where
import Haddock.Types
import Haddock.Options
import Haddock.GhcUtils
import Haddock.Utils
import Haddock.Convert
import Haddock.Interface.LexParseRn
import Haddock.Interface.ExtractFnArgDocs
import qualified Data.Map as Map
import Data.Map (Map)
import Data.List
import Data.Maybe
import Data.Ord
import Control.Monad
import qualified Data.Traversable as Traversable
import GHC hiding (flags)
import HscTypes
import Name
import Bag
import RdrName (GlobalRdrEnv)
-- | Process the data in a GhcModule to produce an interface.
-- To do this, we need access to already processed modules in the topological
-- sort. That's what's in the interface map.
createInterface :: TypecheckedModule -> [Flag] -> IfaceMap -> InstIfaceMap
-> ErrMsgGhc Interface
createInterface tm flags modMap instIfaceMap = do
let ms = pm_mod_summary . tm_parsed_module $ tm
mi = moduleInfo tm
mdl = ms_mod ms
dflags = ms_hspp_opts ms
instances = modInfoInstances mi
exportedNames = modInfoExports mi
-- XXX: confirm always a Just.
Just (group_, _, optExports, optDocHeader) = renamedSource tm
-- The pattern-match should not fail, because createInterface is only
-- done on loaded modules.
Just gre <- liftGhcToErrMsgGhc $ lookupLoadedHomeModuleGRE (moduleName mdl)
opts0 <- liftErrMsg $ mkDocOpts (haddockOptions dflags) flags mdl
let opts
| Flag_IgnoreAllExports `elem` flags = OptIgnoreExports : opts0
| otherwise = opts0
(info, mbDoc) <- liftErrMsg $ lexParseRnHaddockModHeader dflags gre optDocHeader
decls0 <- liftErrMsg $ declInfos dflags gre (topDecls group_)
let localInsts = filter (nameIsLocalOrFrom mdl . getName) instances
declDocs = [ (decl, doc) | (L _ decl, (Just doc, _), _) <- decls0 ]
instanceDocMap = mkInstanceDocMap localInsts declDocs
decls = filterOutInstances decls0
declMap = mkDeclMap decls
exports = fmap (reverse . map unLoc) optExports
ignoreExps = Flag_IgnoreAllExports `elem` flags
liftErrMsg $ warnAboutFilteredDecls mdl decls0
exportItems <- mkExportItems modMap mdl gre exportedNames decls declMap
opts exports ignoreExps instances instIfaceMap dflags
let visibleNames = mkVisibleNames exportItems opts
-- prune the export list to just those declarations that have
-- documentation, if the 'prune' option is on.
let
prunedExportItems
| OptPrune `elem` opts = pruneExportItems exportItems
| otherwise = exportItems
return Interface {
ifaceMod = mdl,
ifaceOrigFilename = msHsFilePath ms,
ifaceInfo = info,
ifaceDoc = mbDoc,
ifaceRnDoc = Nothing,
ifaceOptions = opts,
ifaceRnDocMap = Map.empty,
ifaceExportItems = prunedExportItems,
ifaceRnExportItems = [],
ifaceExports = exportedNames,
ifaceVisibleExports = visibleNames,
ifaceDeclMap = declMap,
ifaceSubMap = mkSubMap declMap exportedNames,
ifaceInstances = instances,
ifaceInstanceDocMap = instanceDocMap
}
-------------------------------------------------------------------------------
-- Doc options
--
-- Haddock options that are embedded in the source file
-------------------------------------------------------------------------------
mkDocOpts :: Maybe String -> [Flag] -> Module -> ErrMsgM [DocOption]
mkDocOpts mbOpts flags mdl = do
opts <- case mbOpts of
Just opts -> case words $ replace ',' ' ' opts of
[] -> tell ["No option supplied to DOC_OPTION/doc_option"] >> return []
xs -> liftM catMaybes (mapM parseOption xs)
Nothing -> return []
if Flag_HideModule (moduleString mdl) `elem` flags
then return $ OptHide : opts
else return opts
parseOption :: String -> ErrMsgM (Maybe DocOption)
parseOption "hide" = return (Just OptHide)
parseOption "prune" = return (Just OptPrune)
parseOption "ignore-exports" = return (Just OptIgnoreExports)
parseOption "not-home" = return (Just OptNotHome)
parseOption other = tell ["Unrecognised option: " ++ other] >> return Nothing
--------------------------------------------------------------------------------
-- Declarations
--------------------------------------------------------------------------------
mkInstanceDocMap :: [Instance] -> [(HsDecl name, doc)] -> Map Name doc
mkInstanceDocMap instances decls =
-- We relate Instances to InstDecls using the SrcSpans buried inside them.
-- That should work for normal user-written instances (from looking at GHC
-- sources). We can assume that commented instances are user-written.
-- This lets us relate Names (from Instances) to comments (associated
-- with InstDecls).
let docMap = Map.fromList [ (loc, doc)
| (InstD (InstDecl (L loc _) _ _ _), doc) <- decls ]
in Map.fromList [ (name, doc) | inst <- instances
, let name = getName inst
, Just doc <- [ Map.lookup (getSrcSpan name) docMap ] ]
-- | Make a sub map from a declaration map. Make sure we only include exported
-- names.
mkSubMap :: Map Name DeclInfo -> [Name] -> Map Name [Name]
mkSubMap declMap exports =
Map.filterWithKey (\k _ -> k `elem` exports) (Map.map filterSubs declMap)
where
filterSubs (_, _, subs) = [ sub | (sub, _) <- subs, sub `elem` exports ]
-- Make a map from names to 'DeclInfo's. Exclude declarations that don't have
-- names (e.g. instances and stand-alone documentation comments). Include
-- subordinate names, but map them to their parent declarations.
mkDeclMap :: [DeclInfo] -> Map Name DeclInfo
mkDeclMap decls = Map.fromList . concat $
[ (declName d, (parent, doc, subs)) : subDecls
| (parent@(L _ d), doc, subs) <- decls
, let subDecls = [ (n, (parent, doc', [])) | (n, doc') <- subs ]
, not (isDocD d), not (isInstD d) ]
declInfos :: DynFlags -> GlobalRdrEnv -> [(Decl, MaybeDocStrings)] -> ErrMsgM [DeclInfo]
declInfos dflags gre decls =
forM decls $ \(parent@(L _ d), mbDocString) -> do
mbDoc <- lexParseRnHaddockCommentList dflags NormalHaddockComment
gre mbDocString
fnArgsDoc <- fmap (Map.mapMaybe id) $
Traversable.forM (getDeclFnArgDocs d) $
\doc -> lexParseRnHaddockComment dflags NormalHaddockComment gre doc
let subs_ = subordinates d
subs <- forM subs_ $ \(subName, mbSubDocStr, subFnArgsDocStr) -> do
mbSubDoc <- lexParseRnHaddockCommentList dflags NormalHaddockComment
gre mbSubDocStr
subFnArgsDoc <- fmap (Map.mapMaybe id) $
Traversable.forM subFnArgsDocStr $
\doc -> lexParseRnHaddockComment dflags NormalHaddockComment gre doc
return (subName, (mbSubDoc, subFnArgsDoc))
return (parent, (mbDoc, fnArgsDoc), subs)
-- | If you know the HsDecl can't contain any docs
-- (e.g., it was loaded from a .hi file and you don't have a .haddock file
-- to help you find out about the subs or docs)
-- then you can use this to get its subs.
subordinatesWithNoDocs :: HsDecl Name -> [(Name, DocForDecl Name)]
subordinatesWithNoDocs decl = map noDocs (subordinates decl)
where
-- check the condition... or shouldn't we be checking?
noDocs (n, doc1, doc2) | null doc1, Map.null doc2
= (n, noDocForDecl)
noDocs _ = error ("no-docs thing has docs! " ++ pretty decl)
subordinates :: HsDecl Name -> [(Name, MaybeDocStrings, Map Int HsDocString)]
subordinates (TyClD d) = classDataSubs d
subordinates _ = []
classDataSubs :: TyClDecl Name -> [(Name, MaybeDocStrings, Map Int HsDocString)]
classDataSubs decl
| isClassDecl decl = classSubs
| isDataDecl decl = dataSubs
| otherwise = []
where
classSubs = [ (declName d, doc, fnArgsDoc)
| (L _ d, doc) <- classDecls decl
, let fnArgsDoc = getDeclFnArgDocs d ]
dataSubs = constrs ++ fields
where
cons = map unL $ tcdCons decl
-- should we use the type-signature of the constructor
-- and the docs of the fields to produce fnArgsDoc for the constr,
-- just in case someone exports it without exporting the type
-- and perhaps makes it look like a function? I doubt it.
constrs = [ (unL $ con_name c, maybeToList $ fmap unL $ con_doc c, Map.empty)
| c <- cons ]
fields = [ (unL n, maybeToList $ fmap unL doc, Map.empty)
| RecCon flds <- map con_details cons
, ConDeclField n _ doc <- flds ]
-- All the sub declarations of a class (that we handle), ordered by
-- source location, with documentation attached if it exists.
classDecls :: TyClDecl Name -> [(Decl, MaybeDocStrings)]
classDecls = filterDecls . collectDocs . sortByLoc . declsFromClass
declsFromClass :: TyClDecl a -> [Located (HsDecl a)]
declsFromClass class_ = docs ++ defs ++ sigs ++ ats
where
docs = mkDecls tcdDocs DocD class_
defs = mkDecls (bagToList . tcdMeths) ValD class_
sigs = mkDecls tcdSigs SigD class_
ats = mkDecls tcdATs TyClD class_
declName :: HsDecl a -> a
declName (TyClD d) = tcdName d
declName (ForD (ForeignImport n _ _)) = unLoc n
-- we have normal sigs only (since they are taken from ValBindsOut)
declName (SigD sig) = fromJust $ sigNameNoLoc sig
declName _ = error "unexpected argument to declName"
-- | The top-level declarations of a module that we care about,
-- ordered by source location, with documentation attached if it exists.
topDecls :: HsGroup Name -> [(Decl, MaybeDocStrings)]
topDecls = filterClasses . filterDecls . collectDocs . sortByLoc . declsFromGroup
filterOutInstances :: [(Located (HsDecl a), b, c)] -> [(Located (HsDecl a), b, c)]
filterOutInstances = filter (\(L _ d, _, _) -> not (isInstD d))
-- | Take all declarations except pragmas, infix decls, rules and value
-- bindings from an 'HsGroup'.
declsFromGroup :: HsGroup Name -> [Decl]
declsFromGroup group_ =
mkDecls (concat . hs_tyclds) TyClD group_ ++
mkDecls hs_derivds DerivD group_ ++
mkDecls hs_defds DefD group_ ++
mkDecls hs_fords ForD group_ ++
mkDecls hs_docs DocD group_ ++
mkDecls hs_instds InstD group_ ++
mkDecls (typesigs . hs_valds) SigD group_
where
typesigs (ValBindsOut _ sigs) = filter isVanillaLSig sigs
typesigs _ = error "expected ValBindsOut"
-- | Take a field of declarations from a data structure and create HsDecls
-- using the given constructor
mkDecls :: (a -> [Located b]) -> (b -> c) -> a -> [Located c]
mkDecls field con struct = [ L loc (con decl) | L loc decl <- field struct ]
-- | Sort by source location
sortByLoc :: [Located a] -> [Located a]
sortByLoc = sortBy (comparing getLoc)
warnAboutFilteredDecls :: Module -> [(LHsDecl Name, b, c)] -> ErrMsgM ()
warnAboutFilteredDecls mdl decls = do
let modStr = moduleString mdl
let typeInstances =
nub [ tcdName d | (L _ (TyClD d), _, _) <- decls, isFamInstDecl d ]
unless (null typeInstances) $
tell [
"Warning: " ++ modStr ++ ": Instances of type and data "
++ "families are not yet supported. Instances of the following families "
++ "will be filtered out:\n " ++ concat (intersperse ", "
$ map (occNameString . nameOccName) typeInstances) ]
let instances = nub [ pretty i | (L _ (InstD (InstDecl i _ _ ats)), _, _) <- decls
, not (null ats) ]
unless (null instances) $
tell [
"Warning: " ++ modStr ++ ": We do not support associated types in instances yet. "
++ "These instances are affected:\n" ++ concat (intersperse ", " instances) ]
--------------------------------------------------------------------------------
-- Filtering of declarations
--
-- We filter out declarations that we don't intend to handle later.
--------------------------------------------------------------------------------
-- | Filter out declarations that we don't handle in Haddock
filterDecls :: [(Decl, doc)] -> [(Decl, doc)]
filterDecls decls = filter (isHandled . unL . fst) decls
where
isHandled (ForD (ForeignImport {})) = True
isHandled (TyClD {}) = True
isHandled (InstD {}) = True
isHandled (SigD d) = isVanillaLSig (reL d)
-- we keep doc declarations to be able to get at named docs
isHandled (DocD _) = True
isHandled _ = False
-- | Go through all class declarations and filter their sub-declarations
filterClasses :: [(Decl, doc)] -> [(Decl, doc)]
filterClasses decls = [ if isClassD d then (L loc (filterClass d), doc) else x
| x@(L loc d, doc) <- decls ]
where
filterClass (TyClD c) =
TyClD $ c { tcdSigs = filter isVanillaLSig $ tcdSigs c }
filterClass _ = error "expected TyClD"
--------------------------------------------------------------------------------
-- Collect docs
--
-- To be able to attach the right Haddock comment to the right declaration,
-- we sort the declarations by their SrcLoc and "collect" the docs for each
-- declaration.
--------------------------------------------------------------------------------
type MaybeDocStrings = [HsDocString]
-- avoid [] because we're appending from the left (quadratic),
-- and avoid adding another package dependency for haddock,
-- so use the difference-list pattern
type MaybeDocStringsFast = MaybeDocStrings -> MaybeDocStrings
docStringEmpty :: MaybeDocStringsFast
docStringEmpty = id
docStringSingleton :: HsDocString -> MaybeDocStringsFast
docStringSingleton = (:)
docStringAppend :: MaybeDocStringsFast -> MaybeDocStringsFast -> MaybeDocStringsFast
docStringAppend = (.)
docStringToList :: MaybeDocStringsFast -> MaybeDocStrings
docStringToList = ($ [])
-- | Collect the docs and attach them to the right declaration.
collectDocs :: [Decl] -> [(Decl, MaybeDocStrings)]
collectDocs = collect Nothing docStringEmpty
collect :: Maybe Decl -> MaybeDocStringsFast -> [Decl] -> [(Decl, MaybeDocStrings)]
collect d doc_so_far [] =
case d of
Nothing -> []
Just d0 -> finishedDoc d0 doc_so_far []
collect d doc_so_far (e:es) =
case e of
L _ (DocD (DocCommentNext str)) ->
case d of
Nothing -> collect d
(docStringAppend doc_so_far (docStringSingleton str))
es
Just d0 -> finishedDoc d0 doc_so_far (collect Nothing
(docStringSingleton str)
es)
L _ (DocD (DocCommentPrev str)) -> collect d
(docStringAppend doc_so_far (docStringSingleton str))
es
_ -> case d of
Nothing -> collect (Just e) doc_so_far es
Just d0 -> finishedDoc d0 doc_so_far (collect (Just e) docStringEmpty es)
-- This used to delete all DocD:s, unless doc was DocEmpty,
-- which I suppose means you could kill a DocCommentNamed
-- by:
--
-- > -- | killer
-- >
-- > -- $victim
--
-- Anyway I accidentally deleted the DocEmpty condition without
-- realizing it was necessary for retaining some DocDs (at least
-- DocCommentNamed), so I'm going to try just not testing any conditions
-- and see if anything breaks. It really shouldn't break anything
-- to keep more doc decls around, IMHO.
--
-- -Isaac
finishedDoc :: Decl -> MaybeDocStringsFast -> [(Decl, MaybeDocStrings)] -> [(Decl, MaybeDocStrings)]
finishedDoc d doc rest = (d, docStringToList doc) : rest
-- | Build the list of items that will become the documentation, from the
-- export list. At this point, the list of ExportItems is in terms of
-- original names.
--
-- We create the export items even if the module is hidden, since they
-- might be useful when creating the export items for other modules.
mkExportItems
:: IfaceMap
-> Module -- this module
-> GlobalRdrEnv
-> [Name] -- exported names (orig)
-> [DeclInfo]
-> Map Name DeclInfo -- maps local names to declarations
-> [DocOption]
-> Maybe [IE Name]
-> Bool -- --ignore-all-exports flag
-> [Instance]
-> InstIfaceMap
-> DynFlags
-> ErrMsgGhc [ExportItem Name]
mkExportItems modMap this_mod gre exported_names decls declMap
opts maybe_exps ignore_all_exports _ instIfaceMap dflags
| isNothing maybe_exps || ignore_all_exports || OptIgnoreExports `elem` opts
= everything_local_exported
| otherwise = liftM concat $ mapM lookupExport (fromJust maybe_exps)
where
everything_local_exported = -- everything exported
liftErrMsg $ fullContentsOfThisModule dflags gre decls
lookupExport (IEVar x) = declWith x
lookupExport (IEThingAbs t) = declWith t
lookupExport (IEThingAll t) = declWith t
lookupExport (IEThingWith t _) = declWith t
lookupExport (IEModuleContents m) = fullContentsOf m
lookupExport (IEGroup lev docStr) = liftErrMsg $
ifDoc (lexParseRnHaddockComment dflags DocSectionComment gre docStr)
(\doc -> return [ ExportGroup lev "" doc ])
lookupExport (IEDoc docStr) = liftErrMsg $
ifDoc (lexParseRnHaddockComment dflags NormalHaddockComment gre docStr)
(\doc -> return [ ExportDoc doc ])
lookupExport (IEDocNamed str) = liftErrMsg $
ifDoc (findNamedDoc str [ unL d | (d,_,_) <- decls ])
(\docStr ->
ifDoc (lexParseRnHaddockComment dflags NormalHaddockComment gre docStr)
(\doc -> return [ ExportDoc doc ]))
ifDoc :: (Monad m) => m (Maybe a) -> (a -> m [b]) -> m [b]
ifDoc parse finish = do
mbDoc <- parse
case mbDoc of Nothing -> return []; Just doc -> finish doc
declWith :: Name -> ErrMsgGhc [ ExportItem Name ]
declWith t =
case findDecl t of
Just x@(decl,_,_) ->
let declName_ =
case getMainDeclBinder (unL decl) of
Just n -> n
Nothing -> error "declWith: should not happen"
in case () of
_
-- temp hack: we filter out separately exported ATs, since we haven't decided how
-- to handle them yet. We should really give an warning message also, and filter the
-- name out in mkVisibleNames...
| t `elem` declATs (unL decl) -> return []
-- We should not show a subordinate by itself if any of its
-- parents is also exported. See note [1].
| t /= declName_,
Just p <- find isExported (parents t $ unL decl) ->
do liftErrMsg $ tell [
"Warning: " ++ moduleString this_mod ++ ": " ++
pretty (nameOccName t) ++ " is exported separately but " ++
"will be documented under " ++ pretty (nameOccName p) ++
". Consider exporting it together with its parent(s)" ++
" for code clarity." ]
return []
-- normal case
| otherwise -> return [ mkExportDecl t x ]
Nothing -> do
-- If we can't find the declaration, it must belong to
-- another package
mbTyThing <- liftGhcToErrMsgGhc $ lookupName t
-- show the name as exported as well as the name's
-- defining module (because the latter is where we
-- looked for the .hi/.haddock). It's to help people
-- debugging after all, so good to show more info.
let exportInfoString =
moduleString this_mod ++ "." ++ getOccString t
++ ": "
++ pretty (nameModule t) ++ "." ++ getOccString t
case mbTyThing of
Nothing -> do
liftErrMsg $ tell
["Warning: Couldn't find TyThing for exported "
++ exportInfoString ++ "; not documenting."]
-- Is getting to here a bug in Haddock?
-- Aren't the .hi files always present?
return [ ExportNoDecl t [] ]
Just tyThing -> do
let hsdecl = tyThingToLHsDecl tyThing
-- This is not the ideal way to implement haddockumentation
-- for functions/values without explicit type signatures.
--
-- However I didn't find an easy way to implement it properly,
-- and as long as we're using lookupName it is going to find
-- the types of local inferenced binds. If we don't check for
-- this at all, then we'll get the "warning: couldn't find
-- .haddock" which is wrong.
--
-- The reason this is not an ideal implementation
-- (besides that we take a trip to desugared syntax and back
-- unnecessarily)
-- is that Haddock won't be able to detect doc-strings being
-- attached to such a function, such as,
--
-- > -- | this is an identity function
-- > id a = a
--
-- . It's more difficult to say what it ought to mean in cases
-- where multiple exports are bound at once, like
--
-- > -- | comment...
-- > (a, b) = ...
--
-- especially since in the export-list they might not even
-- be next to each other. But a proper implementation would
-- really need to find the type of *all* exports as well as
-- addressing all these issues. This implementation works
-- adequately. Do you see a way to improve the situation?
-- Please go ahead! I got stuck trying to figure out how to
-- get the 'PostTcType's that we want for all the bindings
-- of an HsBind (you get 'LHsBinds' from 'GHC.typecheckedSource'
-- for example).
--
-- But I might be missing something obvious. What's important
-- /here/ is that we behave reasonably when we run into one of
-- those exported type-inferenced values.
isLocalAndTypeInferenced <- liftGhcToErrMsgGhc $ do
let mdl = nameModule t
if modulePackageId mdl == thisPackage dflags
then isLoaded (moduleName mdl)
else return False
if isLocalAndTypeInferenced
then do
-- I don't think there can be any subs in this case,
-- currently? But better not to rely on it.
let subs = subordinatesWithNoDocs (unLoc hsdecl)
return [ mkExportDecl t (hsdecl, noDocForDecl, subs) ]
else
-- We try to get the subs and docs
-- from the installed interface of that package.
case Map.lookup (nameModule t) instIfaceMap of
-- It's Nothing in the cases where I thought
-- Haddock has already warned the user: "Warning: The
-- documentation for the following packages are not
-- installed. No links will be generated to these packages:
-- ..."
-- But I guess it was Cabal creating that warning. Anyway,
-- this is more serious than links: it's exported decls where
-- we don't have the docs that they deserve!
-- We could use 'subordinates' to find the Names of the subs
-- (with no docs). Is that necessary? Yes it is, otherwise
-- e.g. classes will be shown without their exported subs.
Nothing -> do
liftErrMsg $ tell
["Warning: Couldn't find .haddock for exported "
++ exportInfoString]
let subs = subordinatesWithNoDocs (unLoc hsdecl)
return [ mkExportDecl t (hsdecl, noDocForDecl, subs) ]
Just iface -> do
let subs = case Map.lookup t (instSubMap iface) of
Nothing -> []
Just x -> x
return [ mkExportDecl t
( hsdecl
, fromMaybe noDocForDecl $
Map.lookup t (instDocMap iface)
, map (\subt ->
( subt ,
fromMaybe noDocForDecl $
Map.lookup subt (instDocMap iface)
)
) subs
)]
mkExportDecl :: Name -> DeclInfo -> ExportItem Name
mkExportDecl n (decl, doc, subs) = decl'
where
decl' = ExportDecl (restrictTo sub_names (extractDecl n mdl decl)) doc subs' []
mdl = nameModule n
subs' = filter ((`elem` exported_names) . fst) subs
sub_names = map fst subs'
isExported = (`elem` exported_names)
fullContentsOf modname
| m == this_mod = liftErrMsg $ fullContentsOfThisModule dflags gre decls
| otherwise =
case Map.lookup m modMap of
Just iface
| OptHide `elem` ifaceOptions iface -> return (ifaceExportItems iface)
| otherwise -> return [ ExportModule m ]
Nothing -> -- we have to try to find it in the installed interfaces
-- (external packages)
case Map.lookup modname (Map.mapKeys moduleName instIfaceMap) of
Just iface -> return [ ExportModule (instMod iface) ]
Nothing -> do
liftErrMsg $
tell ["Warning: " ++ pretty this_mod ++ ": Could not find " ++
"documentation for exported module: " ++ pretty modname]
return []
where
m = mkModule packageId modname
packageId = modulePackageId this_mod
findDecl :: Name -> Maybe DeclInfo
findDecl n
| m == this_mod = Map.lookup n declMap
| otherwise = case Map.lookup m modMap of
Just iface -> Map.lookup n (ifaceDeclMap iface)
Nothing -> Nothing
where
m = nameModule n
-- Note [1]:
------------
-- It is unnecessary to document a subordinate by itself at the top level if
-- any of its parents is also documented. Furthermore, if the subordinate is a
-- record field or a class method, documenting it under its parent
-- indicates its special status.
--
-- A user might expect that it should show up separately, so we issue a
-- warning. It's a fine opportunity to also tell the user she might want to
-- export the subordinate through the parent export item for clarity.
--
-- The code removes top-level subordinates also when the parent is exported
-- through a 'module' export. I think that is fine.
--
-- (For more information, see Trac #69)
fullContentsOfThisModule :: DynFlags -> GlobalRdrEnv -> [DeclInfo] -> ErrMsgM [ExportItem Name]
fullContentsOfThisModule dflags gre decls = liftM catMaybes $ mapM mkExportItem decls
where
mkExportItem (L _ (DocD (DocGroup lev docStr)), _, _) = do
mbDoc <- lexParseRnHaddockComment dflags DocSectionComment gre docStr
return $ fmap (ExportGroup lev "") mbDoc
mkExportItem (L _ (DocD (DocCommentNamed _ docStr)), _, _) = do
mbDoc <- lexParseRnHaddockComment dflags NormalHaddockComment gre docStr
return $ fmap ExportDoc mbDoc
mkExportItem (decl, doc, subs) = return $ Just $ ExportDecl decl doc subs []
-- | Sometimes the declaration we want to export is not the "main" declaration:
-- it might be an individual record selector or a class method. In these
-- cases we have to extract the required declaration (and somehow cobble
-- together a type signature for it...)
extractDecl :: Name -> Module -> Decl -> Decl
extractDecl name mdl decl
| Just n <- getMainDeclBinder (unLoc decl), n == name = decl
| otherwise =
case unLoc decl of
TyClD d | isClassDecl d ->
let matches = [ sig | sig <- tcdSigs d, sigName sig == Just name,
isVanillaLSig sig ] -- TODO: document fixity
in case matches of
[s0] -> let (n, tyvar_names) = name_and_tyvars d
L pos sig = extractClassDecl n tyvar_names s0
in L pos (SigD sig)
_ -> error "internal: extractDecl"
TyClD d | isDataDecl d ->
let (n, tyvar_names) = name_and_tyvars d
L pos sig = extractRecSel name mdl n tyvar_names (tcdCons d)
in L pos (SigD sig)
_ -> error "internal: extractDecl"
where
name_and_tyvars d = (unLoc (tcdLName d), hsLTyVarLocNames (tcdTyVars d))
toTypeNoLoc :: Located Name -> LHsType Name
toTypeNoLoc = noLoc . HsTyVar . unLoc
extractClassDecl :: Name -> [Located Name] -> LSig Name -> LSig Name
extractClassDecl c tvs0 (L pos (TypeSig lname ltype)) = case ltype of
L _ (HsForAllTy expl tvs (L _ preds) ty) ->
L pos (TypeSig lname (noLoc (HsForAllTy expl tvs (lctxt preds) ty)))
_ -> L pos (TypeSig lname (noLoc (mkImplicitHsForAllTy (lctxt []) ltype)))
where
lctxt = noLoc . ctxt
ctxt preds = noLoc (HsClassP c (map toTypeNoLoc tvs0)) : preds
extractClassDecl _ _ _ = error "extractClassDecl: unexpected decl"
extractRecSel :: Name -> Module -> Name -> [Located Name] -> [LConDecl Name]
-> LSig Name
extractRecSel _ _ _ _ [] = error "extractRecSel: selector not found"
extractRecSel nm mdl t tvs (L _ con : rest) =
case con_details con of
RecCon fields | (ConDeclField n ty _ : _) <- matching_fields fields ->
L (getLoc n) (TypeSig (noLoc nm) (noLoc (HsFunTy data_ty (getBangType ty))))
_ -> extractRecSel nm mdl t tvs rest
where
matching_fields flds = [ f | f@(ConDeclField n _ _) <- flds, unLoc n == nm ]
data_ty = foldl (\x y -> noLoc (HsAppTy x y)) (noLoc (HsTyVar t)) (map toTypeNoLoc tvs)
-- Pruning
pruneExportItems :: [ExportItem Name] -> [ExportItem Name]
pruneExportItems items = filter hasDoc items
where
hasDoc (ExportDecl{expItemMbDoc = (d, _)}) = isJust d
hasDoc _ = True
mkVisibleNames :: [ExportItem Name] -> [DocOption] -> [Name]
mkVisibleNames exports opts
| OptHide `elem` opts = []
| otherwise = concatMap exportName exports
where
exportName e@ExportDecl {} =
case getMainDeclBinder $ unL $ expItemDecl e of
Just n -> n : subs
Nothing -> subs
where subs = map fst (expItemSubDocs e)
exportName ExportNoDecl {} = [] -- we don't count these as visible, since
-- we don't want links to go to them.
exportName _ = []
-- | Find a stand-alone documentation comment by its name
findNamedDoc :: String -> [HsDecl Name] -> ErrMsgM (Maybe HsDocString)
findNamedDoc name decls = search decls
where
search [] = do
tell ["Cannot find documentation for: $" ++ name]
return Nothing
search ((DocD (DocCommentNamed name' doc)):rest)
| name == name' = return (Just doc)
| otherwise = search rest
search (_other_decl : rest) = search rest
|
nominolo/haddock2
|
src/Haddock/Interface/Create.hs
|
bsd-2-clause
| 31,862
| 35
| 36
| 9,183
| 7,060
| 3,667
| 3,393
| 447
| 19
|
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FunctionalDependencies #-}
module RSOI.FSMlib(FSM(..),
runFSM) where
import Prelude hiding (init)
import Database.HDBC
import Control.Monad (unless, liftM)
import Control.Concurrent (threadDelay)
import Control.Concurrent.RWLock
import Data.Maybe (fromJust, isJust)
import Data.Map (toList,fromList, difference)
import qualified Data.Map as M (map)
-- | Typeclass for finite state machine Класс коннечного автомата
--
-- Parameters: Параметры:
--
-- * FSM state Состояние автомата (s)
--
-- * request state (d)
--
-- * messages (m)
--
-- * answer (data of the message) (a)
class (Eq s, Show s, Read s,
Eq m, Show m, Read m, Ord m,
Eq d, Show d, Read d,
Show a, Read a) => FSM s d m a | s -> d, s -> m, s -> a, m -> s where
-- | State-transition function. Функция перехода автомата.
state :: s -- ^ previous FSM state предыдущее состояние автомата
-> m -- ^ message recieved полученное сообщение
-> d -- ^ previuos request state предыдущее состояние заявки
-> a -- ^ answer from remote system (data of the message)
-> Maybe (s, d) -- ^ new FSM and rewuest state новое состояние автомата и заявки
-- | Function defining timers which should be started when entering new state. Функция определяющая таймеры, которые необходимо запустить при переходе в новое состояние
-- Часть функции выхода
timeout :: s -- ^ new FSM state новое состояние автомата
-> [(m,Int)] -- ^ list of pairs (message,time) список пар (таймер, время)
-- | Output function. Функция выхода автомата
action :: s -- ^ new FSM state новое состояние автомата
-> m -- ^ message that changed state сообщение, по которому был выполнен переход
-> d -- ^ request state состояние заявки
-> a -- ^ answer from remote system (data of the message)
-> IO d -- ^ new request state + side effects (such as sending message to another system) новое состояние заявки + побочные эффекты (отправка сообщений другим системам, к примеру)
-- | initial FSM state and reques state
init :: (s,d)
-- | main function
runFSM :: (IConnection c,
FSM s d m a ) => c -- ^ coonection to databse
-> String -- ^ state table name
-> String -- ^ request table name
-> String -- ^ timer table name
-> Int -- ^ period in seconds
-> RWLock -- ^ reader-writer lock
-> IO (s,d,m,a)
runFSM conn stName rtName ttName pTime rwl =
do withWriteLock rwl $ checkTables conn stName rtName ttName
loopFSM conn stName rtName ttName pTime rwl
checkTables :: (IConnection c) => c -> String -> String -> String -> IO ()
checkTables conn stName rtName ttName = do
tables <- getTables conn
unless (stName `elem` tables) $
do run conn ("CREATE TABLE " ++ stName ++ "(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " ++
"state VARCHAR (25) NOT NULL, " ++
"data VARCHAR (1000) NOT NULL)") []
return ()
unless (rtName `elem` tables) $
do run conn ("CREATE TABLE " ++ rtName ++ "(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " ++
"fsm_id INTEGER NOT NULL, " ++
"msg VARCHAR (25) NOT NULL, " ++
"data VARCHAR (1000), " ++
"FOREIGN KEY (fsm_id) REFERENCES " ++ stName ++ "(id))") []
return ()
unless (ttName `elem` tables) $
do run conn ("CREATE TABLE " ++ ttName ++ "(id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, " ++
"fsm_id INTEGER NOT NULL, " ++
"msg VARCHAR (25) NOT NULL, " ++
"time INTEGER NOT NULL, " ++
"FOREIGN KEY (fsm_id) REFERENCES " ++ stName ++ "(id))") []
return ()
commit conn
loopFSM :: (IConnection c,
FSM s d m a) => c -> String -> String -> String -> Int -> RWLock -> IO (s,d,m,a)
loopFSM conn stName rtName ttName pTime rwl = do
withWriteLock rwl $ checkTimers conn rtName ttName
res <- withWriteLock rwl $ checkMessages conn stName rtName ttName
threadDelay $ pTime * 1000000
if True
then loopFSM conn stName rtName ttName pTime rwl
else return (fromJust res)
checkMessages :: (IConnection c,
FSM s d m a) => c -> String -> String -> String -> IO (Maybe (s,d,m,a))
checkMessages conn stName rtName ttName = do
message <- quickQuery' conn ("SELECT * FROM " ++ rtName ++ " ORDER BY id LIMIT 1") []
commit conn
if message==[]
then return Nothing
else do let [mid_s,fid_s,msg_s,mdat_s] = head message
st1 <- quickQuery' conn ("SELECT * FROM " ++ stName ++ " WHERE id=?") [fid_s]
(fid_s,st,fdat) <- if st1 == []
then do let (i_s,i_d) = init
run conn ("INSERT INTO " ++ stName ++ " (id,state,data) VALUES (?,?,?)") [fid_s,toSql $ show i_s, toSql $ show i_d]
return (fid_s,i_s,i_d)
else do let [fid_s,st_s,fdat_s] = head st1
st = read $ fromSql st_s
fdat = read $ fromSql fdat_s
return (fid_s,st,fdat)
let msg = read $ fromSql msg_s
mdat = read $ fromSql mdat_s
state_res = state st msg fdat mdat
res <- if isJust state_res
then do let Just (new_st, i_dat) = state_res
timers = timeout new_st
startTimers conn ttName fid_s timers
new_dat <- action new_st msg i_dat mdat
run conn ("UPDATE " ++ stName ++ " SET state=?, data=? WHERE id = ?") [toSql $ show new_st, toSql $ show new_dat, fid_s]
return (Just (new_st,new_dat,msg,mdat))
else return Nothing
run conn ("DELETE FROM " ++ rtName ++ " WHERE id=?") [mid_s]
commit conn
if True
then checkMessages conn stName rtName ttName
else return res
startTimers :: (IConnection c,
FSM s d m a) => c -> String -> SqlValue -> [(m,Int)] -> IO ()
startTimers conn ttName fid_s l = do
timeouts <- (fromList.unSql) `liftM` quickQuery' conn ("SELECT msg, id FROM " ++ ttName ++ " WHERE fsm_id=?") [fid_s]
let new_timeouts = fromList l
toStart = difference new_timeouts timeouts
toStop = difference timeouts new_timeouts
stop <- prepare conn ("DELETE FROM " ++ ttName ++ " WHERE id=?")
executeMany stop (map (\x -> [snd x]) $ toList toStop)
mapM_ (\(m,t) -> run conn ("INSERT INTO " ++ ttName ++ " (fsm_id,msg,time) VALUES (?,?," ++ toSqlTime t ++ ")") [fid_s,toSql $ show m]) $ toList toStart
where unSql [] = []
unSql ([msg_s,id_s]:ls) = (read $ fromSql msg_s,id_s) : unSql ls
toSqlTime sec = "datetime('now','+" ++ show sec ++ " seconds')"
checkTimers ::(IConnection c) => c -> String -> String -> IO ()
checkTimers conn rtName ttName =
do timeouts <- quickQuery' conn ("SELECT id, fsm_id, msg FROM " ++ ttName ++ " WHERE time < datetime('now') ORDER BY time") []
ins <- prepare conn ("INSERT INTO " ++ rtName ++ " (fsm_id, msg) VALUES (?,?)")
del <- prepare conn ("DELETE FROM " ++ ttName ++ " WHERE id=?")
executeMany ins (map tail timeouts)
executeMany del (map (\t -> [head t]) timeouts)
commit conn
|
Migorec/FSM_lib
|
RSOI/FSMlib.hs
|
bsd-3-clause
| 8,840
| 0
| 19
| 3,159
| 1,988
| 1,031
| 957
| 126
| 5
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE RankNTypes #-}
module StableMarriage.GaleShapley
( Men(..)
, Women(..)
, World
, meets
-- re-export
, PO.Ordering(..)
) where
import Prelude hiding (Ordering(..), compare)
import Control.Arrow ((&&&))
import Data.List (sortOn, groupBy, splitAt)
import Data.Poset as PO (Ordering(..), sortBy')
import Data.Function (on)
class Men m where
type W m :: *
loves :: m -> [W m]
forget :: m -> m
class (Ord w, Men m, w ~ W m) => Women m w where
acceptable :: w -> m -> Bool
compare :: w -> m -> m -> PO.Ordering
limit :: w -> [m] -> Int
limit _ _ = 1
type World w m = (Men m, Women m w, w ~ W m) => ([(w, [m])], [m])
marriage :: World w m -> World w m
marriage x = let x' = counter $ attack x
in if stable x'
then x'
else marriage x'
stable :: (Men m, Women m w, w ~ W m) => World w m -> Bool
stable (cs, ms) = all resigned ms
where
resigned :: Men m => m -> Bool
resigned = null . loves
satisfy :: (Men m, Women m w, w ~ W m) => (w, [m]) -> Bool
satisfy (w, ms) = limit w ms <= length ms
attack :: World w m -> World w m
attack (cs, ms) = (cs', ms')
where
cs' = join cs (propose ms)
ms' = despair ms
propose :: (Ord w, Men m, Women m w, w ~ W m) => [m] -> [(w, [m])]
propose = gather . competes
where
competes :: (Men m, Women m w, w ~ W m, Ord w) => [m] -> [[(w, m)]]
competes = groupBy ((==) `on` fst) . sortOn fst . concatMap next
where
next :: (Men m, Women m w, w ~ W m) => m -> [(w, m)]
next m = let xs = loves m
in if null xs
then []
else [(head xs, m)]
gather :: (Men m, Women m w, w ~ W m) => [[(w, m)]] -> [(w, [m])]
gather = map sub
where
sub :: (Men m, Women m w, w ~ W m) => [(w, m)] -> (w, [m])
sub cs@((w, m):_) = (w, map snd cs)
join :: (Men m, Women m w, w ~ W m) => [(w, [m])] -> [(w, [m])] -> [(w, [m])]
join cs xs = gather $ groupBy ((==) `on` fst) $ sortOn fst $ cs ++ xs
where
gather :: (Men m, Women m w, w ~ W m) => [[(w, [m])]] -> [(w, [m])]
gather = map sub
where
sub :: (Men m, Women m w, w ~ W m) => [(w, [m])] -> (w, [m])
sub cs@((w, m):_) = (w, concatMap snd cs)
despair :: Men m => [m] -> [m]
despair = filter (null . loves)
counter :: World w m -> World w m
counter (cs, ms) = (cs', ms'')
where
(cs', ms') = choice cs
ms'' = ms ++ heartbreak ms'
heartbreak :: Men m => [m] -> [m]
heartbreak = map forget
choice :: (Men m, Women m w, w ~ W m) => [(w, [m])] -> World w m
choice = gather . map judge
where
judge :: (Men m, Women m w, w ~ W m) => (w, [m]) -> ((w, [m]), [m])
judge (w, ms) = let (n, p, cmp) = (limit w ms, acceptable w, compare w)
(cs, rs) = splitAt n $ sortBy' (p, cmp) ms
out = filter (not . p) ms
in ((w, cs), rs ++ out)
gather :: (Men m, Women m w, w ~ W m) => [((w, [m]), [m])] -> World w m
gather = map fst &&& concatMap snd
meets :: (Men m, Women m w, w ~ W m) => [m] -> [w] -> World w m
meets ms ws = marriage (zip ws (repeat []), ms)
|
cutsea110/stable-marriage
|
src/StableMarriage/GaleShapley.hs
|
bsd-3-clause
| 3,397
| 0
| 14
| 1,164
| 1,843
| 1,015
| 828
| 78
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
module Cda.Types where
import Control.Lens
data CdaViewer = CdaViewer {
_tmpDir :: FilePath
}
makeLenses ''CdaViewer
|
SLikhachev/pureCdaViewer
|
snaplets/cda/src/Cda/Types.hs
|
bsd-3-clause
| 194
| 0
| 8
| 33
| 36
| 21
| 15
| 7
| 0
|
-- | The categorical distribution is used for discrete data. It is also sometimes called the discrete distribution or the multinomial distribution. For more, see the wikipedia entry: <https://en.wikipedia.org/wiki/Categorical_distribution>
module HLearn.Models.Distributions.Univariate.Categorical
(
-- * Data types
Categorical (Categorical)
-- * Helper functions
, dist2list
, pdfmap
, mostLikely
, map2cat
)
where
import Control.DeepSeq
import Control.Monad.Random
import Data.List
import Data.List.Extras
import Debug.Trace
import qualified Data.Map.Strict as Map
import qualified Data.Foldable as F
import qualified Control.ConstraintKinds as CK
import HLearn.Algebra
import HLearn.Models.Distributions.Common
import HLearn.Models.Distributions.Visualization.Gnuplot
-------------------------------------------------------------------------------
-- Categorical
newtype Categorical prob label = Categorical
{ pdfmap :: Map.Map label prob
}
deriving (Show,Read,Eq,Ord)
instance (NFData label, NFData prob) => NFData (Categorical prob label) where
rnf d = rnf $ pdfmap d
-- uniformNoise :: (Fractional prob, Ord label) => prob -> [label] -> label -> Categorical prob label
-- uniformNoise n xs dp = trainW xs'
-- where
-- xs' = (1-n,dp):(map (\x -> (weight,x)) xs)
-- weight = n/(fromIntegral $ length xs)
-------------------------------------------------------------------------------
-- Algebra
instance (Ord label, Num prob) => Abelian (Categorical prob label)
instance (Ord label, Num prob) => Monoid (Categorical prob label) where
mempty = Categorical Map.empty
mappend !d1 !d2 = Categorical $ res
where
res = Map.unionWith (+) (pdfmap d1) (pdfmap d2)
instance (Ord label, Num prob) => Group (Categorical prob label) where
inverse d1 = d1 {pdfmap=Map.map (0-) (pdfmap d1)}
type instance Scalar (Categorical prob label) = prob
instance (Ord label, Num prob) => Module (Categorical prob label) where
p .* (Categorical pdf) = Categorical $ Map.map (*p) pdf
---------------------------------------
instance CK.Functor (Categorical prob) where
type FunctorConstraint (Categorical prob) label = (Ord label, Num prob)
fmap f cat = Categorical $ Map.mapKeysWith (+) f $ pdfmap cat
-- instance (Num prob) => CK.Pointed (Categorical prob) where
-- point dp = Categorical $ Map.singleton dp 1
instance (Num prob, Ord prob) => CK.Monad (Categorical prob) where
return dp = Categorical $ Map.singleton dp 1
x >>= f = join $ CK.fmap f x
join :: (Num prob, Ord label) => Categorical prob (Categorical prob label) -> Categorical prob label
join cat = reduce . map f $ Map.assocs $ pdfmap cat
where
f (cat,v) = v .* cat
-------------------------------------------------------------------------------
-- Training
instance (Ord label, Num prob) => HomTrainer (Categorical prob label) where
type Datapoint (Categorical prob label) = label
train1dp dp = Categorical $ Map.singleton dp 1
instance (Num prob) => NumDP (Categorical prob label) where
numdp dist = F.foldl' (+) 0 $ pdfmap dist
-------------------------------------------------------------------------------
-- Distribution
instance Probabilistic (Categorical prob label) where
type Probability (Categorical prob label) = prob
instance (Ord label, Ord prob, Fractional prob) => PDF (Categorical prob label) where
{-# INLINE pdf #-}
pdf dist label = {-0.0001+-}(val/tot)
where
val = case Map.lookup label (pdfmap dist) of
Nothing -> 0
Just x -> x
tot = F.foldl' (+) 0 $ pdfmap dist
instance (Ord label, Ord prob, Fractional prob) => CDF (Categorical prob label) where
{-# INLINE cdf #-}
cdf dist label = (Map.foldl' (+) 0 $ Map.filterWithKey (\k a -> k<=label) $ pdfmap dist)
/ (Map.foldl' (+) 0 $ pdfmap dist)
{-# INLINE cdfInverse #-}
cdfInverse dist prob = go cdfL
where
cdfL = sortBy (\(k1,p1) (k2,p2) -> compare p2 p1) $ map (\k -> (k,pdf dist k)) $ Map.keys $ pdfmap dist
go (x:[]) = fst $ last cdfL
go (x:xs) = if prob < snd x -- && prob > (snd $ head xs)
then fst x
else go xs
-- cdfInverse dist prob = argmax (cdf dist) $ Map.keys $ pdfmap dist
-- {-# INLINE mean #-}
-- mean dist = fst $ argmax snd $ Map.toList $ pdfmap dist
--
-- {-# INLINE drawSample #-}
-- drawSample dist = do
-- x <- getRandomR (0,1)
-- return $ cdfInverse dist (x::prob)
instance (Num prob, Ord prob, Ord label) => Mean (Categorical prob label) where
mean dist = fst $ argmax snd $ Map.toList $ pdfmap dist
-- | Extracts the element in the distribution with the highest probability
mostLikely :: Ord prob => Categorical prob label -> label
mostLikely dist = fst $ argmax snd $ Map.toList $ pdfmap dist
-- | Converts a distribution into a list of (sample,probability) pai
dist2list :: Categorical prob label -> [(label,prob)]
dist2list (Categorical pdfmap) = Map.toList pdfmap
-- | Constructs a categorical distribution
map2cat :: Map.Map label prob -> Categorical prob label
map2cat = Categorical
instance
( Ord label, Show label
, Ord prob, Show prob, Fractional prob
) => PlottableDistribution (Categorical prob label)
where
samplePoints (Categorical dist) = Map.keys dist
plotType dist = Bar
-------------------------------------------------------------------------------
-- Morphisms
-- instance
-- ( Ord label
-- , Num prob
-- ) => Morphism (Categorical prob label) FreeModParams (FreeMod prob label)
-- where
-- Categorical pdf $> FreeModParams = FreeMod pdf
--
|
ehlemur/HLearn
|
src/HLearn/Models/Distributions/Univariate/Categorical.hs
|
bsd-3-clause
| 5,827
| 0
| 15
| 1,318
| 1,514
| 812
| 702
| -1
| -1
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Symbol where
import Control.Lens
import qualified Color as Color
import Data.Default
import GHC.Generics
import Prelude hiding (Either(..), id, (.))
-- Symbol
data Symbol = Symbol
{ _glyph :: Char
, _baseColor :: Color.Color
} deriving (Generic,Show)
makeLenses ''Symbol
instance Default Symbol where
def = Symbol '?' $ Color.byName "white"
|
fros1y/umbral
|
src/Symbol.hs
|
bsd-3-clause
| 433
| 0
| 9
| 79
| 116
| 70
| 46
| 15
| 0
|
---------------------------------------------------------
--
-- Module : Financing
-- Copyright : Bartosz Wójcik (2010)
-- License : All rights reserved
--
-- Maintainer : bartek@sudety.it
-- Stability : Unstable
-- Portability : portable
--
-- Financing rules.
---------------------------------------------------------
module Financing (initFullPlan
,nextDueDate1
,nextDueDate
,fstInstDate
-- ,amortizationPlan
)
where
import Data.Maybe (fromJust)
import Fee
import BasicType
import Parameters
import CalcConfigurationType (instList
,addPeriods
,ClassicLoan
)
import CalcCalendar
import FinancingType (Tranche (..)
,FullPlan
,FullPlanDay
,FullPlanLine (..)
,IntAdjustment
,fpdCapitalAfter
,fpdLateInterestAfter
,fpdIntAdjAfterAmt
,fpdIntAdjAfter
,fpdAdvInterestAfter
,isINT
)
import FinancingConfiguration
import CalcConstructors (Instalment (..)
,InstalmentPlanLine (..)
,InstalmentPlan
,newLoanRIL
,newLoanI
,newInstalmentPlanLine
,newLoanRCtlm
)
import Calculator (cE2N
)
import ErrorHandling
import Control.Monad.Reader
moduleName = "Financing"
-- | Gives first instalment date having finacing date, calendar type, due day and rule name.
fstInstDate :: Freq -- ^ instalment frequency
-> CalendarType -- ^ type of loan calendar
-> FstInstRule -- ^ Rule of 1st instalment calculation
-> Int -- ^ Number of the day in freq period when instalment matures
-> Day -- ^ last financing tranche date
-> Day
fstInstDate Daily _ _ _ date = addDays 1 date
fstInstDate Monthly Y360Specific r n d = fstInstDate Monthly Y360 r n d
fstInstDate Monthly Y360 FstInstFullFreqAfter n d = fstInstDate Monthly Y360 (FstInstDays 30) n d
fstInstDate Monthly Y360 (FstInstDays i) dueDay date
| d < dueDay = setDay dueDay newDate
| otherwise = setDay dueDay $ addMonths 1 newDate
where (y,m,d) = toGregorian newDate
newDate = addDays (fromIntegral i) date
fstInstDate Monthly RealCalendar (FstInstDays i) dueDay date
| d <= dueDay = fromGregorian y m dueDay
| otherwise = fromGregorian y (m+1) dueDay
where (y,m,d) = toGregorian dateN
dateN = addDays (fromIntegral i) date
fstInstDate Monthly RealCalendar FstInstFullFreqAfter dueDay date
| dn <= dueDay = fromGregorian yn mn dueDay
| otherwise = fromGregorian yn (mn+1) dueDay
where (y,m,d) = toGregorian date
dateN = fromGregorian y (m+1) d
(yn,mn,dn) = toGregorian dateN
fstInstDate Yearly _ FstInstFullFreqAfter dueDay date
| d <= dueDay = fromOrdinalDate (y+1) dueDay
| otherwise = fromOrdinalDate (y+2) dueDay
where (y,d) = toOrdinalDate date
-- All cases which are not foreseen return just the financing date.
fstInstDate _ _ _ _ d = d
-- | Completes interest amount of the tranche
completeTranche :: FinancingParameters
-> Int -- ^ 'fin1stInstDay'
-> Day -- ^ first instalment date
-> Day -- ^ date of tranche
-> Tranche -- ^ tranche with populated amount and date
-> Tranche
completeTranche fp n fstInstD date tr =
tr { trNbrDays = diffDays
, trInt = fstInstIntDelta fp (trAmount tr) (trRate tr) $ diffDays
}
where -- Number of days between tranche's date and 1st instalment date
diffDays = diffLoanCalendar fstInstD date (finCalendar fp)
-- | Adjustment of 1st instalment due to different number of days which are between
-- tranche and due date on one hand and usual interest period on the other.
-- For interest calculated daily there is no difference. Function returns 0.
-- If 'FstIntDaily' then there is easy formula 'intFreq' independent.
-- Otherwise formula aasumes certain number of days in usual interest period (30, 360 or 365) depending
-- on the 'intFreq'
fstInstIntDelta :: FinancingParameters
-> Amount -- ^ financing amount
-> Rate -- ^ yearly effective interest rate
-> Int -- ^ number of days of interest accrue
-> Amount
fstInstIntDelta fp c rE d1
| intFreq fp == Daily = 0
| fin1stIntRule fp == FstIntDaily = round $ c' * (1 + rD)**d1' - c'
-- | fin1stIntRule fp == FstIntDaily = round $ c' * (1 + rD)^d1
| otherwise = round $ c' * (1 + r)**(d1' / n' - 1) - c'
-- | otherwise = round $ c' * (1 + r)**(fromIntegral d1 / n' - n') - c' * (1 + r)
where c' = fromIntegral c
rD = cE2N Daily rE
r = cE2N (intFreq fp) rE
d1' = fromIntegral d1
n' = fromIntegral n
n | intFreq fp == Daily = 1
| intFreq fp == Monthly = 30
| intFreq fp == Yearly &&
finCalendar fp == RealCalendar = 365
| otherwise = 360
{-
amortizationPlan :: ClassicLoan a
=> [(Day,Tranche)] -- | List of scheduled tranches
-> Duration -- | Number of instalments
-> Duration -- | 1st instalment deferrment
-> Rate -- | Interest rate in yearly effective rate
-> Int -- | Day of instalment due (for Freq==Daily ignored)
-> a -- | Classic Loan type
-> ParamMonad FullPlan
amortizationPlan tr n d rE day loan = lift (newLoanI loan c n d rE) >>=
initFullPlan day rE tr
where c = sum $ map (trAmount . snd) tr
-}
-- | Initialized FullPlan from first till last financing.
initFullPlan :: Int -- ^ due day
-> Rate -- ^ yearly effective interest rate
-> [(Day,Tranche)] -- ^ list of tranches with dates
-> InstalmentPlan -- ^ abstract loan with fee
-> ParamMonad FullPlan
initFullPlan _ _ [] _ = errMsg moduleName "initFullPlan" "empty tranche"
initFullPlan _ _ _ [] = errMsg moduleName "initFullPlan" "empty instalment plan"
initFullPlan d rE tr absLoan = ask >>= \param ->
let -- fp, d and rE are used globaly in all the functions below.
-- Total capital financed
fp = fin param
cap = sum $ map (trAmount . snd) tr
r | fstIntDaily = cE2N Daily rE
| otherwise = cE2N (intFreq fp) rE
rInst = cE2N (instFreq fp) rE
-- 1st instalment date
fstInstD = fstInstDate (instFreq fp) (finCalendar fp) (fin1stInstRule fp) d (fst $ last tr)
-- Date of 1st inst > 0
fstInstDPlus = addPeriods (intFreq fp)
(fromIntegral $ length $ takeWhile (==0) $ map (iAmt . iplInst) absLoan)
fstInstD
-- Next interest due date > than given date
nextIntDate date | fstIntDaily = nextDueDate1 Daily d date
| otherwise = nextDueDate1 (intFreq fp) d date
-- Grace period is counted from first tranche date till
-- @instFreq - 1@ day before first instalment. Eg: instalment matures
-- monthly on each 15th, first one on 15th November, first and the only tranche on
-- 5th October, then grace period lasts from 6th till 15th October.
-- @fstUsualDay@ is one day after.
-- Grace period can be empty. TODO: check: Then @fstUsualDay@ == last tranche date + 1d
fstUsualDay = addDays 1 $ addPeriods (instFreq fp) (-1) fstInstD
-- max (addPeriods (instFreq fp) (-1) fstInstD)
-- (fst $ last tr)
fstIntWholePeriod = fin1stIntRule fp == FstIntTill1stInst
fstIntWholePeriodPlus = fin1stIntRule fp == FstIntTill1stInstGT0
fstIntCtlm = fin1stIntRule fp == FstIntCtlm
fstIntDaily = fin1stIntRule fp == FstIntDaily
-- ============================================
-- Creates TPL entry of 'FullPlanDay'
makeTPL :: FullPlanDay -- previous row in the full instalment plan
-> (Day,Tranche) -- next tranche
-> FullPlanDay
makeTPL fpd (dt,tt) = (dt, TPL newTr cNew iL mIANew)
where newTr | fstIntWholePeriod ||
fstIntWholePeriodPlus ||
fstIntCtlm = completeTranche fp d fstInstD dt tt
-- Daily interest in grace period need interest adjustment only if
-- first instalment is scheduled not full intrest period after last tranche.
| fstIntDaily &&
fstUsualDay < dt = completeTranche fp d fstUsualDay dt tt
| fstIntDaily = completeTranche fp d dt dt tt
| otherwise = completeTranche fp d (nextIntDate dt) dt tt
cNew = trAmount newTr + fpdCapitalAfter fpd
iL = fpdLateInterestAfter fpd -- + trIntLate newTr
mIANew | trInt newTr == 0 &&
iAA == 0 = Nothing
-- | fstIntWholePeriod = Just (fstInstD,trInt newTr + iAA)
| fstIntWholePeriodPlus ||
fstIntCtlm = Just (fstInstDPlus,trInt newTr + iAA)
| otherwise = Just (fstInstD,trInt newTr + iAA)
-- | otherwise = Just (nextIntDate dt,trInt newTr + iAA)
iAA | mIA == Nothing = 0
| otherwise = snd $ fromJust mIA
mIA = fpdIntAdjAfter fpd
-- ============================================
-- Creates instalment entry (INT) into FullPlan.
makeINT :: FullPlanDay
-> FullPlanDay
makeINT fpd = (nextIntD, INT mIA newIPL)
where -- Usage of laizyness: iAD and iAA are computable only if mIA /= Nothing
mIA = fpdIntAdjAfter fpd
iL = fpdLateInterestAfter fpd
c = fpdCapitalAfter fpd
newIPL = newInstalmentPlanLine c iL r i
date = fst fpd
nextIntD = nextIntDate date
nextInstD = nextDueDate1 (instFreq fp) d date
-- Instalment amount covers interest or ==0.
i | fin1stIntRule fp == FstIntTillNextDue &&
nextInstD == nextIntD = (-1)
| otherwise = 0
-- =============================================
-- Creates tranche entry (TPL) or interest entry (INT) into FullPlan.
-- TPL is created on date of tranche, INT on all due dates between tranches
-- and after last tranche and before first instalment.
-- Capital after and late interest have to be passed always to the next entry.
initFullPlan' :: FullPlanDay -- Previous row of full plan
-> [(Day,Tranche)] -- list of tranches with dates
-> FullPlan
initFullPlan' fpd []
-- After last tranche the treatment till first instalment is the same like during
-- tranches' phase. At this moment it is ensured that @regularPeriod iL@ is @Just x@ value,
-- so @fromJust@ is safe.
| mIA /= Nothing && date == iAD = newAPL : initFullPlan' newAPL []
| fstIntWholePeriod ||
fstIntWholePeriodPlus ||
nextIntDate date >= fstUsualDay = []
| otherwise = newINT : initFullPlan' newINT []
where newINT = makeINT fpd
newAPL = makeAPL fpd
date = fst fpd
(iAD,iAA) = fromJust mIA
mIA = fpdIntAdjAfter fpd
initFullPlan' fpd (t:ts)
-- Next tranche date is before next interest due date
-- or interest for 1st period are calculated for the whole period at once (then
-- there is no additional interest calculation before last tranche).
| mIA /= Nothing &&
date == iAD = newAPL : initFullPlan' newAPL (t:ts)
| nextIntDate date > fst t ||
fstIntDaily && fstUsualDay <= nextIntDate date ||
-- fstIntDaily && fstUsualDay < fst t ||
fstIntWholePeriod ||
fstIntWholePeriodPlus = newTPL : initFullPlan' newTPL ts
| otherwise = newINT : initFullPlan' newINT (t:ts)
where newTPL = makeTPL fpd t
newINT = makeINT fpd
newAPL = makeAPL fpd
date = fst fpd
(iAD,iAA) = fromJust mIA
mIA = fpdIntAdjAfter fpd
-- =============================================
-- Proprietary version of initFullPlan'
-- Exactly one tranche
-- Exactly one element in the output
initFullPlanCtlm :: FullPlanDay -- Previous row of full plan
-> [(Day,Tranche)] -- list of tranches with dates
-> ValidMonad FullPlan
initFullPlanCtlm fpd [t] = return $ [makeTPL fpd t]
initFullPlanCtlm fpd ts = errMsg moduleName "initFullPlanCtlm" $
"unexpected multi tranche case: " ++ show ts
dummyFPD = (fst $ head tr, APL 0 0 0)
in case fin1stIntRule fp of
FstIntCtlm -> lift $ lift $ initFullPlanCtlm dummyFPD tr >>=
regularPeriodCtlm cap absLoan fstInstD
_ -> lift $ lift $ regularPeriod fp cap absLoan fstInstD fstUsualDay $
initFullPlan' dummyFPD tr
-- initFullPlan ===================================================
-- =============================================
-- Initiates the regular period of the loan. To be called after all tranches are planed.
-- Recalculation of interest rate having list of instalments in frequency of interest maturity.
-- I.e. it takes 'InstalmentPlan' value in frequency of instalment and assigns instalment dates to them
-- additionally, if necessary, adds additional 'InstalmentPlanLine' entries into the list
-- which entires reflect interest maturity events (hence interest maturity frequency) (which have
-- instalment amount fixed to 0).
regularPeriod :: FinancingParameters
-> Amount -- ^ capital
-> InstalmentPlan -- ^ abstract loan, without dates and tranches
-> Day -- ^ first instalment date
-> Day -- ^ first day of usual period
-> FullPlan -- ^ entries of first period
-> ValidMonad FullPlan
regularPeriod fp cap ip fstInstD fstUsualDate fpl
| intFreq fp > instFreq fp = errMsg moduleName "regularPeriod" $
"interest frequency > instalment frequency " ++
show (intFreq fp) ++ ">" ++ show (instFreq fp)
| otherwise = newLoan >>= newIP >>= adjustRegularPeriod mIA
where -- At this point it's ensured that absLoan is Just x alternative.
-- List of instalment amounts retrived from InstalmentPlan and enriched with late interest
-- of grace period.
-- At the moment late intertest of grace period does not accrue interest!
is | lateIntRule fp == LateIntFstInst = head xs + round iL : tail xs
| lateIntRule fp == LateIntFstSignInst = zs ++ [head ys + round iL] ++ tail ys
| lateIntRule fp == LateIntLastInst = init xs ++ [last xs + round iL]
| otherwise = xs
where xs = instList ip
(zs,ys) = span (==0) xs
nNew = fromIntegral $ length is
-- List of dates of all instalments
ds = map (\i -> addPeriods (instFreq fp) i fstInstD) [0 .. (nNew-1)]
-- List of pairs of instalment's dates and amounts.
-- Completed by 0 amount instalments on dates where interest matures but there is no instalment due.
dis | intFreq fp == instFreq fp = zip ds is
| otherwise = dis' fstUsualDate ds is
where dis' _ [] _ = []
dis' date (d:ds) (i:is) | date >= d = (d, i) : dis' nextDate ds is
-- Additional INT entry which reflects interest
-- maturity - hence instalment amount 0.
| otherwise = (date, 0) : dis' nextDate (d:ds) (i:is)
where nextDate = addPeriods (intFreq fp) 1 date
newDs | intFreq fp == instFreq fp = ds
| otherwise = fst $ unzip dis
-- | Last line of grace period
lastFPL = last fpl
-- Late interest after first period
iL = fpdLateInterestAfter lastFPL
-- Advanced interest
iA = fpdAdvInterestAfter lastFPL
-- At this point nominal interest rate gets recalculated.
newLoan | intFreq fp == instFreq fp = newLoanRIL (fromIntegral iA + iL) cap is
| otherwise = newLoanRIL (fromIntegral iA + iL) cap (snd $ unzip dis)
mIA = fpdIntAdjAfter $ last fpl
newIP ip' = Right $ fpl ++ zip newDs (map (INT Nothing) ip')
-- | Interest adjustment comming from 1st instalment can be due within
-- regular period. There is max. one adjustment.
adjustRegularPeriod :: Maybe IntAdjustment -- ^ interest adjustment
-> FullPlan
-> ValidMonad FullPlan
adjustRegularPeriod Nothing fp = return fp
adjustRegularPeriod (Just (iAD,iAA)) fp = return $ adjInst iAD iAA fp
where adjInst iAD iAA (x:xs) | iAD > d = xNew : adjInst iAD iAA xs
| iAD == d = xNew : makeAPL xNew : xs
| iAD < d = makeAPL xNew : xNew : xs
where d = fst x
fpl = snd x
xNew | isINT fpl && intIntAdj fpl == Nothing = (d, fpl {intIntAdj = Just (iAD,iAA)})
| otherwise = x
-- | Reworks regural period recalculating first instalment amount,
-- first instalment interest rate and interest rate of the rest of the loan.
regularPeriodCtlm :: Amount
-> InstalmentPlan
-> Day
-> FullPlan
-> ValidMonad FullPlan
regularPeriodCtlm cap ip fstInstD fpl =
newLoanRCtlm cap isNew d1 >>= \loan -> (return $
fpl ++ zip ds (map (INT Nothing) loan))
where fstInst = head isFull + (iAA $ fpdIntAdjAfter fpd)
is = instList ip
(isNull,isFull) = span (==0) is
iAA Nothing = 0
iAA (Just iA) = snd iA
-- fst instalment gets recalculated
isNew = isNull ++ fstInst : tail isFull
-- At this point nominal interest rate gets recalculated.
n = fromIntegral $ length is
-- List of dates of all instalments
ds = map (\i -> addPeriods Monthly i fstInstD) [0 .. (n-1)]
d1 = (trNbrDays . tplTranche . snd) fpd
fpd = head fpl
-- ============================================
-- Creates APL entry of 'FullPlanDay'
-- Date == date of last @FullPlanDay@ entry.
-- Capital after and late interest after don't change and are taken from previous entry.
-- Amount of adjustment is taken from carried @IntAdjustment@.
makeAPL :: FullPlanDay -- previous row in the full instalment plan
-> FullPlanDay
makeAPL fpd = (fst fpd, APL cAfter iL iAA)
where cAfter = fpdCapitalAfter fpd
iL = fpdLateInterestAfter fpd
iAA = fpdIntAdjAfterAmt fpd
-- | Next due date >= than current one.
nextDueDate :: Freq -- ^ Instalment frequency
-> Int -- ^ due day (ignored when @freq == Daily@)
-> Day -- ^ tranche day
-> Day
nextDueDate Daily _ date = date
nextDueDate freq day date = nextDueDate' freq day date
-- | Next due date > than current one.
nextDueDate1 :: Freq -- ^ Instalment frequency
-> Int -- ^ due day (ignored when @freq == Daily@)
-> Day -- ^ tranche day
-> Day
nextDueDate1 Daily _ date = addDays 1 date
nextDueDate1 freq day date = nextDueDate' freq day $ addDays 1 date
-- Next due date >= than current one.
-- Always to be called by one of nextDueDate functions.
nextDueDate' Monthly day date | day >= d = fromGregorian y m day
| otherwise = addMonths 1 $ fromGregorian y m day
where (y,m,d) = toGregorian date
nextDueDate' Yearly day date | day >= d = fromOrdinalDate y day
| otherwise = fromOrdinalDate (y+1) day
where (y,d) = toOrdinalDate date
nextDueDate' freq _ _ = error $ "Incorrect input " ++ show freq
|
bartoszw/haslo
|
Haslo/Financing.hs
|
bsd-3-clause
| 22,844
| 0
| 20
| 9,112
| 4,014
| 2,062
| 1,952
| 283
| 4
|
{-# LANGUAGE FlexibleInstances, TypeSynonymInstances, TypeOperators #-}
-- | /Warning: I intend to remove this module. Please use 'command' or 'cmd' instead./
--
-- This module provides versions of the 'Development.Shake.Derived.system'' family of functions
-- which take a variable number of arguments.
--
-- All these functions take a variable number of arguments.
--
-- * @String@ arguments are treated as whitespace separated arguments.
--
-- * @[String]@ arguments are treated as literal arguments.
--
-- As an example, to run @ghc --make -O2 inputs -o output@:
--
-- @
-- 'sys' \"ghc --make -O2\" inputs \"-o\" [output]
-- @
--
-- Note that we enclose @output@ as a list so that if the output name contains spaces they are
-- appropriately escaped.
module Development.Shake.Sys(
sys, sysCwd, sysOutput, args
) where
import Development.Shake.Core
import Development.Shake.Derived
type a :-> t = a
-- | A variable arity version of 'system''.
sys :: SysArguments v => String -> v :-> Action ()
sys x = sys_ [] x
class SysArguments t where sys_ :: [String] -> t
instance (Arg a, SysArguments r) => SysArguments (a -> r) where
sys_ xs x = sys_ $ xs ++ arg x
instance SysArguments (Action ()) where
sys_ (x:xs) = system' x xs
sys_ [] = error "No executable or arguments given to sys"
-- | A variable arity version of 'systemCwd'.
sysCwd :: SysCwdArguments v => FilePath -> String -> v :-> Action ()
sysCwd dir x = sysCwd_ dir [] x
class SysCwdArguments t where sysCwd_ :: FilePath -> [String] -> t
instance (Arg a, SysCwdArguments r) => SysCwdArguments (a -> r) where
sysCwd_ dir xs x = sysCwd_ dir $ xs ++ arg x
instance SysCwdArguments (Action ()) where
sysCwd_ dir (x:xs) = systemCwd dir x xs
sysCwd_ dir [] = error "No executable or arguments given to sysCwd"
-- | A variable arity version of 'systemOutput'.
sysOutput :: SysOutputArguments v => String -> v :-> Action (String, String)
sysOutput x = sysOutput_ [] x
class SysOutputArguments t where sysOutput_ :: [String] -> t
instance (Arg a, SysOutputArguments r) => SysOutputArguments (a -> r) where
sysOutput_ xs x = sysOutput_ $ xs ++ arg x
instance SysOutputArguments (Action (String, String)) where
sysOutput_ (x:xs) = systemOutput x xs
sysOutput_ [] = error "No executable or arguments given to sys"
-- | A variable arity function to accumulate a list of arguments.
args :: ArgsArguments v => v :-> [String]
args = args_ []
class ArgsArguments t where args_ :: [String] -> t
instance (Arg a, ArgsArguments r) => ArgsArguments (a -> r) where
args_ xs x = args_ $ xs ++ arg x
instance ArgsArguments [String] where
args_ = id
class Arg a where arg :: a -> [String]
instance Arg String where arg = words
instance Arg [String] where arg = id
|
nh2/shake
|
Development/Shake/Sys.hs
|
bsd-3-clause
| 2,787
| 0
| 10
| 556
| 747
| 397
| 350
| 40
| 1
|
-- (c) The University of Glasgow 2006
-- (c) The GRASP/AQUA Project, Glasgow University, 1998
--
-- Type - public interface
{-# LANGUAGE CPP #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- | Main functions for manipulating types and type-related things
module Type (
-- Note some of this is just re-exports from TyCon..
-- * Main data types representing Types
-- $type_classification
-- $representation_types
TyThing(..), Type, VisibilityFlag(..), KindOrType, PredType, ThetaType,
Var, TyVar, isTyVar, TyCoVar, TyBinder,
-- ** Constructing and deconstructing types
mkTyVarTy, mkTyVarTys, getTyVar, getTyVar_maybe, repGetTyVar_maybe,
getCastedTyVar_maybe, tyVarKind,
mkAppTy, mkAppTys, splitAppTy, splitAppTys, repSplitAppTys,
splitAppTy_maybe, repSplitAppTy_maybe, tcRepSplitAppTy_maybe,
mkFunTy, mkFunTys, splitFunTy, splitFunTy_maybe,
splitFunTys, splitFunTysN,
funResultTy, funArgTy,
mkTyConApp, mkTyConTy,
tyConAppTyCon_maybe, tyConAppTyConPicky_maybe,
tyConAppArgs_maybe, tyConAppTyCon, tyConAppArgs,
splitTyConApp_maybe, splitTyConApp, tyConAppArgN, nextRole,
splitListTyConApp_maybe,
repSplitTyConApp_maybe,
mkForAllTy, mkForAllTys, mkInvForAllTys, mkSpecForAllTys,
mkVisForAllTys,
mkNamedForAllTy,
splitForAllTy_maybe, splitForAllTys, splitForAllTy,
splitPiTy_maybe, splitPiTys, splitPiTy,
splitNamedPiTys,
mkPiType, mkPiTypes, mkTyBindersPreferAnon,
piResultTy, piResultTys,
applyTysX, dropForAlls,
mkNumLitTy, isNumLitTy,
mkStrLitTy, isStrLitTy,
mkCastTy, mkCoercionTy, splitCastTy_maybe,
userTypeError_maybe, pprUserTypeErrorTy,
coAxNthLHS,
stripCoercionTy, splitCoercionType_maybe,
splitPiTysInvisible, filterOutInvisibleTypes,
filterOutInvisibleTyVars, partitionInvisibles,
synTyConResKind,
-- Analyzing types
TyCoMapper(..), mapType, mapCoercion,
-- (Newtypes)
newTyConInstRhs,
-- Pred types
mkFamilyTyConApp,
isDictLikeTy,
mkPrimEqPred, mkReprPrimEqPred, mkPrimEqPredRole,
equalityTyCon,
mkHeteroPrimEqPred, mkHeteroReprPrimEqPred,
mkClassPred,
isClassPred, isEqPred, isNomEqPred,
isIPPred, isIPPred_maybe, isIPTyCon, isIPClass,
isCTupleClass,
-- Deconstructing predicate types
PredTree(..), EqRel(..), eqRelRole, classifyPredType,
getClassPredTys, getClassPredTys_maybe,
getEqPredTys, getEqPredTys_maybe, getEqPredRole,
predTypeEqRel,
-- ** Binders
sameVis,
mkNamedBinder, mkAnonBinder, isNamedBinder, isAnonBinder,
isIdLikeBinder, binderVisibility, binderVar_maybe,
binderVar, binderRelevantType_maybe, caseBinder,
partitionBinders, partitionBindersIntoBinders,
binderType, isVisibleBinder, isInvisibleBinder,
-- ** Common type constructors
funTyCon,
-- ** Predicates on types
allDistinctTyVars,
isTyVarTy, isFunTy, isDictTy, isPredTy, isVoidTy, isCoercionTy,
isCoercionTy_maybe, isCoercionType, isForAllTy,
isPiTy,
-- (Lifting and boxity)
isUnliftedType, isUnboxedTupleType, isAlgType, isClosedAlgType,
isPrimitiveType, isStrictType,
isRuntimeRepTy, isRuntimeRepVar, isRuntimeRepKindedTy,
dropRuntimeRepArgs,
getRuntimeRep, getRuntimeRepFromKind,
-- * Main data types representing Kinds
Kind,
-- ** Finding the kind of a type
typeKind,
-- ** Common Kind
liftedTypeKind,
-- * Type free variables
tyCoVarsOfType, tyCoVarsOfTypes, tyCoVarsOfTypeAcc,
tyCoVarsOfTypeDSet,
coVarsOfType,
coVarsOfTypes, closeOverKinds,
splitDepVarsOfType, splitDepVarsOfTypes,
splitVisVarsOfType, splitVisVarsOfTypes,
expandTypeSynonyms,
typeSize,
-- * Well-scoped lists of variables
varSetElemsWellScoped, toposortTyVars, tyCoVarsOfTypeWellScoped,
-- * Type comparison
eqType, eqTypeX, eqTypes, cmpType, cmpTypes, cmpTypeX, cmpTypesX, cmpTc,
eqVarBndrs,
-- * Forcing evaluation of types
seqType, seqTypes,
-- * Other views onto Types
coreView, coreViewOneStarKind,
UnaryType, RepType(..), flattenRepType, repType,
tyConsOfType,
-- * Type representation for the code generator
typePrimRep, typeRepArity, kindPrimRep, tyConPrimRep,
-- * Main type substitution data types
TvSubstEnv, -- Representation widely visible
TCvSubst(..), -- Representation visible to a few friends
-- ** Manipulating type substitutions
emptyTvSubstEnv, emptyTCvSubst, mkEmptyTCvSubst,
mkTCvSubst, zipTvSubst, mkTvSubstPrs,
notElemTCvSubst,
getTvSubstEnv, setTvSubstEnv,
zapTCvSubst, getTCvInScope,
extendTCvInScope, extendTCvInScopeList, extendTCvInScopeSet,
extendTCvSubst, extendCvSubst,
extendTvSubst, extendTvSubstList, extendTvSubstAndInScope,
isInScope, composeTCvSubstEnv, composeTCvSubst, zipTyEnv, zipCoEnv,
isEmptyTCvSubst, unionTCvSubst,
-- ** Performing substitution on types and kinds
substTy, substTys, substTyWith, substTysWith, substTheta,
substTyAddInScope,
substTyUnchecked, substTysUnchecked, substThetaUnchecked,
substTyWithBindersUnchecked, substTyWithUnchecked,
substCoUnchecked, substCoWithUnchecked,
substTyVarBndr, substTyVar, substTyVars,
cloneTyVarBndr, cloneTyVarBndrs, lookupTyVar,
-- * Pretty-printing
pprType, pprParendType, pprTypeApp, pprTyThingCategory, pprTyThing,
pprTvBndr, pprTvBndrs, pprForAll, pprForAllImplicit, pprUserForAll,
pprSigmaType,
pprTheta, pprThetaArrowTy, pprClassPred,
pprKind, pprParendKind, pprSourceTyCon,
TyPrec(..), maybeParen,
pprTyVar, pprTcAppTy, pprPrefixApp, pprArrowChain,
-- * Tidying type related things up for printing
tidyType, tidyTypes,
tidyOpenType, tidyOpenTypes,
tidyOpenKind,
tidyTyCoVarBndr, tidyTyCoVarBndrs, tidyFreeTyCoVars,
tidyOpenTyCoVar, tidyOpenTyCoVars,
tidyTyVarOcc,
tidyTopType,
tidyKind
) where
#include "HsVersions.h"
-- We import the representation and primitive functions from TyCoRep.
-- Many things are reexported, but not the representation!
import Kind
import TyCoRep
-- friends:
import Var
import VarEnv
import VarSet
import NameEnv
import Class
import TyCon
import TysPrim
import {-# SOURCE #-} TysWiredIn ( listTyCon, typeNatKind
, typeSymbolKind, liftedTypeKind )
import PrelNames
import CoAxiom
import {-# SOURCE #-} Coercion
-- others
import BasicTypes ( Arity, RepArity )
import Util
import Outputable
import FastString
import Pair
import ListSetOps
import Digraph
import Maybes ( orElse )
import Data.Maybe ( isJust, mapMaybe )
import Control.Monad ( guard )
import Control.Arrow ( first, second )
-- $type_classification
-- #type_classification#
--
-- Types are one of:
--
-- [Unboxed] Iff its representation is other than a pointer
-- Unboxed types are also unlifted.
--
-- [Lifted] Iff it has bottom as an element.
-- Closures always have lifted types: i.e. any
-- let-bound identifier in Core must have a lifted
-- type. Operationally, a lifted object is one that
-- can be entered.
-- Only lifted types may be unified with a type variable.
--
-- [Algebraic] Iff it is a type with one or more constructors, whether
-- declared with @data@ or @newtype@.
-- An algebraic type is one that can be deconstructed
-- with a case expression. This is /not/ the same as
-- lifted types, because we also include unboxed
-- tuples in this classification.
--
-- [Data] Iff it is a type declared with @data@, or a boxed tuple.
--
-- [Primitive] Iff it is a built-in type that can't be expressed in Haskell.
--
-- Currently, all primitive types are unlifted, but that's not necessarily
-- the case: for example, @Int@ could be primitive.
--
-- Some primitive types are unboxed, such as @Int#@, whereas some are boxed
-- but unlifted (such as @ByteArray#@). The only primitive types that we
-- classify as algebraic are the unboxed tuples.
--
-- Some examples of type classifications that may make this a bit clearer are:
--
-- @
-- Type primitive boxed lifted algebraic
-- -----------------------------------------------------------------------------
-- Int# Yes No No No
-- ByteArray# Yes Yes No No
-- (\# a, b \#) Yes No No Yes
-- ( a, b ) No Yes Yes Yes
-- [a] No Yes Yes Yes
-- @
-- $representation_types
-- A /source type/ is a type that is a separate type as far as the type checker is
-- concerned, but which has a more low-level representation as far as Core-to-Core
-- passes and the rest of the back end is concerned.
--
-- You don't normally have to worry about this, as the utility functions in
-- this module will automatically convert a source into a representation type
-- if they are spotted, to the best of it's abilities. If you don't want this
-- to happen, use the equivalent functions from the "TcType" module.
{-
************************************************************************
* *
Type representation
* *
************************************************************************
-}
{-# INLINE coreView #-}
coreView :: Type -> Maybe Type
-- ^ This function Strips off the /top layer only/ of a type synonym
-- application (if any) its underlying representation type.
-- Returns Nothing if there is nothing to look through.
--
-- By being non-recursive and inlined, this case analysis gets efficiently
-- joined onto the case analysis that the caller is already doing
coreView (TyConApp tc tys) | Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
= Just (mkAppTys (substTy (mkTvSubstPrs tenv) rhs) tys')
-- The free vars of 'rhs' should all be bound by 'tenv', so it's
-- ok to use 'substTy' here.
-- See also Note [The substitution invariant] in TyCoRep.
-- Its important to use mkAppTys, rather than (foldl AppTy),
-- because the function part might well return a
-- partially-applied type constructor; indeed, usually will!
coreView _ = Nothing
-- | Like 'coreView', but it also "expands" @Constraint@ to become
-- @TYPE PtrRepLifted@.
{-# INLINE coreViewOneStarKind #-}
coreViewOneStarKind :: Type -> Maybe Type
coreViewOneStarKind ty
| Just ty' <- coreView ty = Just ty'
| TyConApp tc [] <- ty
, isStarKindSynonymTyCon tc = Just liftedTypeKind
| otherwise = Nothing
-----------------------------------------------
expandTypeSynonyms :: Type -> Type
-- ^ Expand out all type synonyms. Actually, it'd suffice to expand out
-- just the ones that discard type variables (e.g. type Funny a = Int)
-- But we don't know which those are currently, so we just expand all.
--
-- 'expandTypeSynonyms' only expands out type synonyms mentioned in the type,
-- not in the kinds of any TyCon or TyVar mentioned in the type.
expandTypeSynonyms ty
= go (mkEmptyTCvSubst (mkTyCoInScopeSet [ty] [])) ty
where
go subst (TyConApp tc tys)
| Just (tenv, rhs, tys') <- expandSynTyCon_maybe tc tys
= let subst' = unionTCvSubst subst (mkTvSubstPrs tenv) in
go subst' (mkAppTys rhs tys')
| otherwise
= TyConApp tc (map (go subst) tys)
go _ (LitTy l) = LitTy l
go subst (TyVarTy tv) = substTyVar subst tv
go subst (AppTy t1 t2) = mkAppTy (go subst t1) (go subst t2)
go subst (ForAllTy (Anon arg) res)
= mkFunTy (go subst arg) (go subst res)
go subst (ForAllTy (Named tv vis) t)
= let (subst', tv') = substTyVarBndrCallback go subst tv in
ForAllTy (Named tv' vis) (go subst' t)
go subst (CastTy ty co) = mkCastTy (go subst ty) (go_co subst co)
go subst (CoercionTy co) = mkCoercionTy (go_co subst co)
go_co subst (Refl r ty)
= mkReflCo r (go subst ty)
-- NB: coercions are always expanded upon creation
go_co subst (TyConAppCo r tc args)
= mkTyConAppCo r tc (map (go_co subst) args)
go_co subst (AppCo co arg)
= mkAppCo (go_co subst co) (go_co subst arg)
go_co subst (ForAllCo tv kind_co co)
= let (subst', tv', kind_co') = go_cobndr subst tv kind_co in
mkForAllCo tv' kind_co' (go_co subst' co)
go_co subst (CoVarCo cv)
= substCoVar subst cv
go_co subst (AxiomInstCo ax ind args)
= mkAxiomInstCo ax ind (map (go_co subst) args)
go_co subst (UnivCo p r t1 t2)
= mkUnivCo (go_prov subst p) r (go subst t1) (go subst t2)
go_co subst (SymCo co)
= mkSymCo (go_co subst co)
go_co subst (TransCo co1 co2)
= mkTransCo (go_co subst co1) (go_co subst co2)
go_co subst (NthCo n co)
= mkNthCo n (go_co subst co)
go_co subst (LRCo lr co)
= mkLRCo lr (go_co subst co)
go_co subst (InstCo co arg)
= mkInstCo (go_co subst co) (go_co subst arg)
go_co subst (CoherenceCo co1 co2)
= mkCoherenceCo (go_co subst co1) (go_co subst co2)
go_co subst (KindCo co)
= mkKindCo (go_co subst co)
go_co subst (SubCo co)
= mkSubCo (go_co subst co)
go_co subst (AxiomRuleCo ax cs) = AxiomRuleCo ax (map (go_co subst) cs)
go_prov _ UnsafeCoerceProv = UnsafeCoerceProv
go_prov subst (PhantomProv co) = PhantomProv (go_co subst co)
go_prov subst (ProofIrrelProv co) = ProofIrrelProv (go_co subst co)
go_prov _ p@(PluginProv _) = p
go_prov _ (HoleProv h) = pprPanic "expandTypeSynonyms hit a hole" (ppr h)
-- the "False" and "const" are to accommodate the type of
-- substForAllCoBndrCallback, which is general enough to
-- handle coercion optimization (which sometimes swaps the
-- order of a coercion)
go_cobndr subst = substForAllCoBndrCallback False (go_co subst) subst
{-
************************************************************************
* *
Analyzing types
* *
************************************************************************
These functions do a map-like operation over types, performing some operation
on all variables and binding sites. Primarily used for zonking.
Note [Efficiency for mapCoercion ForAllCo case]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
As noted in Note [Forall coercions] in TyCoRep, a ForAllCo is a bit redundant.
It stores a TyVar and a Coercion, where the kind of the TyVar always matches
the left-hand kind of the coercion. This is convenient lots of the time, but
not when mapping a function over a coercion.
The problem is that tcm_tybinder will affect the TyVar's kind and
mapCoercion will affect the Coercion, and we hope that the results will be
the same. Even if they are the same (which should generally happen with
correct algorithms), then there is an efficiency issue. In particular,
this problem seems to make what should be a linear algorithm into a potentially
exponential one. But it's only going to be bad in the case where there's
lots of foralls in the kinds of other foralls. Like this:
forall a : (forall b : (forall c : ...). ...). ...
This construction seems unlikely. So we'll do the inefficient, easy way
for now.
Note [Specialising mappers]
~~~~~~~~~~~~~~~~~~~~~~~~~~~
These INLINABLE pragmas are indispensable. mapType/mapCoercion are used
to implement zonking, and it's vital that they get specialised to the TcM
monad. This specialisation happens automatically (that is, without a
SPECIALISE pragma) as long as the definitions are INLINABLE. For example,
this one change made a 20% allocation difference in perf/compiler/T5030.
-}
-- | This describes how a "map" operation over a type/coercion should behave
data TyCoMapper env m
= TyCoMapper
{ tcm_smart :: Bool -- ^ Should the new type be created with smart
-- constructors?
, tcm_tyvar :: env -> TyVar -> m Type
, tcm_covar :: env -> CoVar -> m Coercion
, tcm_hole :: env -> CoercionHole -> Role
-> Type -> Type -> m Coercion
-- ^ What to do with coercion holes. See Note [Coercion holes] in
-- TyCoRep.
, tcm_tybinder :: env -> TyVar -> VisibilityFlag -> m (env, TyVar)
-- ^ The returned env is used in the extended scope
}
{-# INLINABLE mapType #-} -- See Note [Specialising mappers]
mapType :: Monad m => TyCoMapper env m -> env -> Type -> m Type
mapType mapper@(TyCoMapper { tcm_smart = smart, tcm_tyvar = tyvar
, tcm_tybinder = tybinder })
env ty
= go ty
where
go (TyVarTy tv) = tyvar env tv
go (AppTy t1 t2) = mkappty <$> go t1 <*> go t2
go (TyConApp tc tys) = mktyconapp tc <$> mapM go tys
go (ForAllTy (Anon arg) res) = mkfunty <$> go arg <*> go res
go (ForAllTy (Named tv vis) inner)
= do { (env', tv') <- tybinder env tv vis
; inner' <- mapType mapper env' inner
; return $ ForAllTy (Named tv' vis) inner' }
go ty@(LitTy {}) = return ty
go (CastTy ty co) = mkcastty <$> go ty <*> mapCoercion mapper env co
go (CoercionTy co) = CoercionTy <$> mapCoercion mapper env co
(mktyconapp, mkappty, mkcastty, mkfunty)
| smart = (mkTyConApp, mkAppTy, mkCastTy, mkFunTy)
| otherwise = (TyConApp, AppTy, CastTy, ForAllTy . Anon)
{-# INLINABLE mapCoercion #-} -- See Note [Specialising mappers]
mapCoercion :: Monad m
=> TyCoMapper env m -> env -> Coercion -> m Coercion
mapCoercion mapper@(TyCoMapper { tcm_smart = smart, tcm_covar = covar
, tcm_hole = cohole, tcm_tybinder = tybinder })
env co
= go co
where
go (Refl r ty) = Refl r <$> mapType mapper env ty
go (TyConAppCo r tc args)
= mktyconappco r tc <$> mapM go args
go (AppCo c1 c2) = mkappco <$> go c1 <*> go c2
go (ForAllCo tv kind_co co)
= do { kind_co' <- go kind_co
; (env', tv') <- tybinder env tv Invisible
; co' <- mapCoercion mapper env' co
; return $ mkforallco tv' kind_co' co' }
-- See Note [Efficiency for mapCoercion ForAllCo case]
go (CoVarCo cv) = covar env cv
go (AxiomInstCo ax i args)
= mkaxiominstco ax i <$> mapM go args
go (UnivCo (HoleProv hole) r t1 t2)
= cohole env hole r t1 t2
go (UnivCo p r t1 t2)
= mkunivco <$> go_prov p <*> pure r
<*> mapType mapper env t1 <*> mapType mapper env t2
go (SymCo co) = mksymco <$> go co
go (TransCo c1 c2) = mktransco <$> go c1 <*> go c2
go (AxiomRuleCo r cos) = AxiomRuleCo r <$> mapM go cos
go (NthCo i co) = mknthco i <$> go co
go (LRCo lr co) = mklrco lr <$> go co
go (InstCo co arg) = mkinstco <$> go co <*> go arg
go (CoherenceCo c1 c2) = mkcoherenceco <$> go c1 <*> go c2
go (KindCo co) = mkkindco <$> go co
go (SubCo co) = mksubco <$> go co
go_prov UnsafeCoerceProv = return UnsafeCoerceProv
go_prov (PhantomProv co) = PhantomProv <$> go co
go_prov (ProofIrrelProv co) = ProofIrrelProv <$> go co
go_prov p@(PluginProv _) = return p
go_prov (HoleProv _) = panic "mapCoercion"
( mktyconappco, mkappco, mkaxiominstco, mkunivco
, mksymco, mktransco, mknthco, mklrco, mkinstco, mkcoherenceco
, mkkindco, mksubco, mkforallco)
| smart
= ( mkTyConAppCo, mkAppCo, mkAxiomInstCo, mkUnivCo
, mkSymCo, mkTransCo, mkNthCo, mkLRCo, mkInstCo, mkCoherenceCo
, mkKindCo, mkSubCo, mkForAllCo )
| otherwise
= ( TyConAppCo, AppCo, AxiomInstCo, UnivCo
, SymCo, TransCo, NthCo, LRCo, InstCo, CoherenceCo
, KindCo, SubCo, ForAllCo )
{-
************************************************************************
* *
\subsection{Constructor-specific functions}
* *
************************************************************************
---------------------------------------------------------------------
TyVarTy
~~~~~~~
-}
-- | Attempts to obtain the type variable underlying a 'Type', and panics with the
-- given message if this is not a type variable type. See also 'getTyVar_maybe'
getTyVar :: String -> Type -> TyVar
getTyVar msg ty = case getTyVar_maybe ty of
Just tv -> tv
Nothing -> panic ("getTyVar: " ++ msg)
isTyVarTy :: Type -> Bool
isTyVarTy ty = isJust (getTyVar_maybe ty)
-- | Attempts to obtain the type variable underlying a 'Type'
getTyVar_maybe :: Type -> Maybe TyVar
getTyVar_maybe ty | Just ty' <- coreView ty = getTyVar_maybe ty'
| otherwise = repGetTyVar_maybe ty
-- | If the type is a tyvar, possibly under a cast, returns it, along
-- with the coercion. Thus, the co is :: kind tv ~R kind type
getCastedTyVar_maybe :: Type -> Maybe (TyVar, Coercion)
getCastedTyVar_maybe ty | Just ty' <- coreView ty = getCastedTyVar_maybe ty'
getCastedTyVar_maybe (CastTy (TyVarTy tv) co) = Just (tv, co)
getCastedTyVar_maybe (TyVarTy tv)
= Just (tv, mkReflCo Nominal (tyVarKind tv))
getCastedTyVar_maybe _ = Nothing
-- | Attempts to obtain the type variable underlying a 'Type', without
-- any expansion
repGetTyVar_maybe :: Type -> Maybe TyVar
repGetTyVar_maybe (TyVarTy tv) = Just tv
repGetTyVar_maybe _ = Nothing
allDistinctTyVars :: [KindOrType] -> Bool
allDistinctTyVars tkvs = go emptyVarSet tkvs
where
go _ [] = True
go so_far (ty : tys)
= case getTyVar_maybe ty of
Nothing -> False
Just tv | tv `elemVarSet` so_far -> False
| otherwise -> go (so_far `extendVarSet` tv) tys
{-
---------------------------------------------------------------------
AppTy
~~~~~
We need to be pretty careful with AppTy to make sure we obey the
invariant that a TyConApp is always visibly so. mkAppTy maintains the
invariant: use it.
Note [Decomposing fat arrow c=>t]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Can we unify (a b) with (Eq a => ty)? If we do so, we end up with
a partial application like ((=>) Eq a) which doesn't make sense in
source Haskell. In constrast, we *can* unify (a b) with (t1 -> t2).
Here's an example (Trac #9858) of how you might do it:
i :: (Typeable a, Typeable b) => Proxy (a b) -> TypeRep
i p = typeRep p
j = i (Proxy :: Proxy (Eq Int => Int))
The type (Proxy (Eq Int => Int)) is only accepted with -XImpredicativeTypes,
but suppose we want that. But then in the call to 'i', we end
up decomposing (Eq Int => Int), and we definitely don't want that.
This really only applies to the type checker; in Core, '=>' and '->'
are the same, as are 'Constraint' and '*'. But for now I've put
the test in repSplitAppTy_maybe, which applies throughout, because
the other calls to splitAppTy are in Unify, which is also used by
the type checker (e.g. when matching type-function equations).
-}
-- | Applies a type to another, as in e.g. @k a@
mkAppTy :: Type -> Type -> Type
mkAppTy (TyConApp tc tys) ty2 = mkTyConApp tc (tys ++ [ty2])
mkAppTy ty1 ty2 = AppTy ty1 ty2
-- Note that the TyConApp could be an
-- under-saturated type synonym. GHC allows that; e.g.
-- type Foo k = k a -> k a
-- type Id x = x
-- foo :: Foo Id -> Foo Id
--
-- Here Id is partially applied in the type sig for Foo,
-- but once the type synonyms are expanded all is well
mkAppTys :: Type -> [Type] -> Type
mkAppTys ty1 [] = ty1
mkAppTys (TyConApp tc tys1) tys2 = mkTyConApp tc (tys1 ++ tys2)
mkAppTys ty1 tys2 = foldl AppTy ty1 tys2
-------------
splitAppTy_maybe :: Type -> Maybe (Type, Type)
-- ^ Attempt to take a type application apart, whether it is a
-- function, type constructor, or plain type application. Note
-- that type family applications are NEVER unsaturated by this!
splitAppTy_maybe ty | Just ty' <- coreView ty
= splitAppTy_maybe ty'
splitAppTy_maybe ty = repSplitAppTy_maybe ty
-------------
repSplitAppTy_maybe :: Type -> Maybe (Type,Type)
-- ^ Does the AppTy split as in 'splitAppTy_maybe', but assumes that
-- any Core view stuff is already done
repSplitAppTy_maybe (ForAllTy (Anon ty1) ty2)
= Just (TyConApp funTyCon [ty1], ty2)
repSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
repSplitAppTy_maybe (TyConApp tc tys)
| mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
, Just (tys', ty') <- snocView tys
= Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps!
repSplitAppTy_maybe _other = Nothing
-- this one doesn't braek apart (c => t).
-- See Note [Decomposing fat arrow c=>t]
-- Defined here to avoid module loops between Unify and TcType.
tcRepSplitAppTy_maybe :: Type -> Maybe (Type,Type)
-- ^ Does the AppTy split as in 'tcSplitAppTy_maybe', but assumes that
-- any coreView stuff is already done. Refuses to look through (c => t)
tcRepSplitAppTy_maybe (ForAllTy (Anon ty1) ty2)
| isConstraintKind (typeKind ty1) = Nothing -- See Note [Decomposing fat arrow c=>t]
| otherwise = Just (TyConApp funTyCon [ty1], ty2)
tcRepSplitAppTy_maybe (AppTy ty1 ty2) = Just (ty1, ty2)
tcRepSplitAppTy_maybe (TyConApp tc tys)
| mightBeUnsaturatedTyCon tc || tys `lengthExceeds` tyConArity tc
, Just (tys', ty') <- snocView tys
= Just (TyConApp tc tys', ty') -- Never create unsaturated type family apps!
tcRepSplitAppTy_maybe _other = Nothing
-------------
splitAppTy :: Type -> (Type, Type)
-- ^ Attempts to take a type application apart, as in 'splitAppTy_maybe',
-- and panics if this is not possible
splitAppTy ty = case splitAppTy_maybe ty of
Just pr -> pr
Nothing -> panic "splitAppTy"
-------------
splitAppTys :: Type -> (Type, [Type])
-- ^ Recursively splits a type as far as is possible, leaving a residual
-- type being applied to and the type arguments applied to it. Never fails,
-- even if that means returning an empty list of type applications.
splitAppTys ty = split ty ty []
where
split orig_ty ty args | Just ty' <- coreView ty = split orig_ty ty' args
split _ (AppTy ty arg) args = split ty ty (arg:args)
split _ (TyConApp tc tc_args) args
= let -- keep type families saturated
n | mightBeUnsaturatedTyCon tc = 0
| otherwise = tyConArity tc
(tc_args1, tc_args2) = splitAt n tc_args
in
(TyConApp tc tc_args1, tc_args2 ++ args)
split _ (ForAllTy (Anon ty1) ty2) args = ASSERT( null args )
(TyConApp funTyCon [], [ty1,ty2])
split orig_ty _ args = (orig_ty, args)
-- | Like 'splitAppTys', but doesn't look through type synonyms
repSplitAppTys :: Type -> (Type, [Type])
repSplitAppTys ty = split ty []
where
split (AppTy ty arg) args = split ty (arg:args)
split (TyConApp tc tc_args) args
= let n | mightBeUnsaturatedTyCon tc = 0
| otherwise = tyConArity tc
(tc_args1, tc_args2) = splitAt n tc_args
in
(TyConApp tc tc_args1, tc_args2 ++ args)
split (ForAllTy (Anon ty1) ty2) args = ASSERT( null args )
(TyConApp funTyCon [], [ty1, ty2])
split ty args = (ty, args)
{-
LitTy
~~~~~
-}
mkNumLitTy :: Integer -> Type
mkNumLitTy n = LitTy (NumTyLit n)
-- | Is this a numeric literal. We also look through type synonyms.
isNumLitTy :: Type -> Maybe Integer
isNumLitTy ty | Just ty1 <- coreView ty = isNumLitTy ty1
isNumLitTy (LitTy (NumTyLit n)) = Just n
isNumLitTy _ = Nothing
mkStrLitTy :: FastString -> Type
mkStrLitTy s = LitTy (StrTyLit s)
-- | Is this a symbol literal. We also look through type synonyms.
isStrLitTy :: Type -> Maybe FastString
isStrLitTy ty | Just ty1 <- coreView ty = isStrLitTy ty1
isStrLitTy (LitTy (StrTyLit s)) = Just s
isStrLitTy _ = Nothing
-- | Is this type a custom user error?
-- If so, give us the kind and the error message.
userTypeError_maybe :: Type -> Maybe Type
userTypeError_maybe t
= do { (tc, _kind : msg : _) <- splitTyConApp_maybe t
-- There may be more than 2 arguments, if the type error is
-- used as a type constructor (e.g. at kind `Type -> Type`).
; guard (tyConName tc == errorMessageTypeErrorFamName)
; return msg }
-- | Render a type corresponding to a user type error into a SDoc.
pprUserTypeErrorTy :: Type -> SDoc
pprUserTypeErrorTy ty =
case splitTyConApp_maybe ty of
-- Text "Something"
Just (tc,[txt])
| tyConName tc == typeErrorTextDataConName
, Just str <- isStrLitTy txt -> ftext str
-- ShowType t
Just (tc,[_k,t])
| tyConName tc == typeErrorShowTypeDataConName -> ppr t
-- t1 :<>: t2
Just (tc,[t1,t2])
| tyConName tc == typeErrorAppendDataConName ->
pprUserTypeErrorTy t1 <> pprUserTypeErrorTy t2
-- t1 :$$: t2
Just (tc,[t1,t2])
| tyConName tc == typeErrorVAppendDataConName ->
pprUserTypeErrorTy t1 $$ pprUserTypeErrorTy t2
-- An uneavaluated type function
_ -> ppr ty
{-
---------------------------------------------------------------------
FunTy
~~~~~
Function types are represented with (ForAllTy (Anon ...) ...)
-}
isFunTy :: Type -> Bool
isFunTy ty = isJust (splitFunTy_maybe ty)
splitFunTy :: Type -> (Type, Type)
-- ^ Attempts to extract the argument and result types from a type, and
-- panics if that is not possible. See also 'splitFunTy_maybe'
splitFunTy ty | Just ty' <- coreView ty = splitFunTy ty'
splitFunTy (ForAllTy (Anon arg) res) = (arg, res)
splitFunTy other = pprPanic "splitFunTy" (ppr other)
splitFunTy_maybe :: Type -> Maybe (Type, Type)
-- ^ Attempts to extract the argument and result types from a type
splitFunTy_maybe ty | Just ty' <- coreView ty = splitFunTy_maybe ty'
splitFunTy_maybe (ForAllTy (Anon arg) res) = Just (arg, res)
splitFunTy_maybe _ = Nothing
splitFunTys :: Type -> ([Type], Type)
splitFunTys ty = split [] ty ty
where
split args orig_ty ty | Just ty' <- coreView ty = split args orig_ty ty'
split args _ (ForAllTy (Anon arg) res) = split (arg:args) res res
split args orig_ty _ = (reverse args, orig_ty)
splitFunTysN :: Int -> Type -> ([Type], Type)
-- ^ Split off exactly the given number argument types, and panics if that is not possible
splitFunTysN 0 ty = ([], ty)
splitFunTysN n ty = ASSERT2( isFunTy ty, int n <+> ppr ty )
case splitFunTy ty of { (arg, res) ->
case splitFunTysN (n-1) res of { (args, res) ->
(arg:args, res) }}
funResultTy :: Type -> Type
-- ^ Extract the function result type and panic if that is not possible
funResultTy ty | Just ty' <- coreView ty = funResultTy ty'
funResultTy (ForAllTy (Anon {}) res) = res
funResultTy ty = pprPanic "funResultTy" (ppr ty)
funArgTy :: Type -> Type
-- ^ Extract the function argument type and panic if that is not possible
funArgTy ty | Just ty' <- coreView ty = funArgTy ty'
funArgTy (ForAllTy (Anon arg) _res) = arg
funArgTy ty = pprPanic "funArgTy" (ppr ty)
piResultTy :: Type -> Type -> Type
-- ^ Just like 'piResultTys' but for a single argument
-- Try not to iterate 'piResultTy', because it's inefficient to substitute
-- one variable at a time; instead use 'piResultTys"
piResultTy ty arg
| Just ty' <- coreView ty = piResultTy ty' arg
| ForAllTy bndr res <- ty
= case bndr of
Anon {} -> res
Named tv _ -> substTy (extendTvSubst empty_subst tv arg) res
where
empty_subst = mkEmptyTCvSubst $ mkInScopeSet $
tyCoVarsOfTypes [arg,res]
| otherwise
= panic "piResultTys"
-- | (piResultTys f_ty [ty1, .., tyn]) gives the type of (f ty1 .. tyn)
-- where f :: f_ty
-- 'piResultTys' is interesting because:
-- 1. 'f_ty' may have more for-alls than there are args
-- 2. Less obviously, it may have fewer for-alls
-- For case 2. think of:
-- piResultTys (forall a.a) [forall b.b, Int]
-- This really can happen, but only (I think) in situations involving
-- undefined. For example:
-- undefined :: forall a. a
-- Term: undefined @(forall b. b->b) @Int
-- This term should have type (Int -> Int), but notice that
-- there are more type args than foralls in 'undefined's type.
-- If you edit this function, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
-- This is a heavily used function (e.g. from typeKind),
-- so we pay attention to efficiency, especially in the special case
-- where there are no for-alls so we are just dropping arrows from
-- a function type/kind.
piResultTys :: Type -> [Type] -> Type
piResultTys ty [] = ty
piResultTys ty orig_args@(arg:args)
| Just ty' <- coreView ty
= piResultTys ty' orig_args
| ForAllTy bndr res <- ty
= case bndr of
Anon {} -> piResultTys res args
Named tv _ -> go (extendVarEnv emptyTvSubstEnv tv arg) res args
| otherwise
= panic "piResultTys"
where
go :: TvSubstEnv -> Type -> [Type] -> Type
go tv_env ty [] = substTy (mkTvSubst in_scope tv_env) ty
where
in_scope = mkInScopeSet (tyCoVarsOfTypes (ty:orig_args))
go tv_env ty all_args@(arg:args)
| Just ty' <- coreView ty
= go tv_env ty' all_args
| ForAllTy bndr res <- ty
= case bndr of
Anon _ -> go tv_env res args
Named tv _ -> go (extendVarEnv tv_env tv arg) res args
| TyVarTy tv <- ty
, Just ty' <- lookupVarEnv tv_env tv
-- Deals with piResultTys (forall a. a) [forall b.b, Int]
= piResultTys ty' all_args
| otherwise
= panic "piResultTys"
{-
---------------------------------------------------------------------
TyConApp
~~~~~~~~
-}
-- | A key function: builds a 'TyConApp' or 'FunTy' as appropriate to
-- its arguments. Applies its arguments to the constructor from left to right.
mkTyConApp :: TyCon -> [Type] -> Type
mkTyConApp tycon tys
| isFunTyCon tycon, [ty1,ty2] <- tys
= ForAllTy (Anon ty1) ty2
| otherwise
= TyConApp tycon tys
-- splitTyConApp "looks through" synonyms, because they don't
-- mean a distinct type, but all other type-constructor applications
-- including functions are returned as Just ..
-- | Retrieve the tycon heading this type, if there is one. Does /not/
-- look through synonyms.
tyConAppTyConPicky_maybe :: Type -> Maybe TyCon
tyConAppTyConPicky_maybe (TyConApp tc _) = Just tc
tyConAppTyConPicky_maybe (ForAllTy (Anon _) _) = Just funTyCon
tyConAppTyConPicky_maybe _ = Nothing
-- | The same as @fst . splitTyConApp@
tyConAppTyCon_maybe :: Type -> Maybe TyCon
tyConAppTyCon_maybe ty | Just ty' <- coreView ty = tyConAppTyCon_maybe ty'
tyConAppTyCon_maybe (TyConApp tc _) = Just tc
tyConAppTyCon_maybe (ForAllTy (Anon _) _) = Just funTyCon
tyConAppTyCon_maybe _ = Nothing
tyConAppTyCon :: Type -> TyCon
tyConAppTyCon ty = tyConAppTyCon_maybe ty `orElse` pprPanic "tyConAppTyCon" (ppr ty)
-- | The same as @snd . splitTyConApp@
tyConAppArgs_maybe :: Type -> Maybe [Type]
tyConAppArgs_maybe ty | Just ty' <- coreView ty = tyConAppArgs_maybe ty'
tyConAppArgs_maybe (TyConApp _ tys) = Just tys
tyConAppArgs_maybe (ForAllTy (Anon arg) res) = Just [arg,res]
tyConAppArgs_maybe _ = Nothing
tyConAppArgs :: Type -> [Type]
tyConAppArgs ty = tyConAppArgs_maybe ty `orElse` pprPanic "tyConAppArgs" (ppr ty)
tyConAppArgN :: Int -> Type -> Type
-- Executing Nth
tyConAppArgN n ty
= case tyConAppArgs_maybe ty of
Just tys -> ASSERT2( n < length tys, ppr n <+> ppr tys ) tys `getNth` n
Nothing -> pprPanic "tyConAppArgN" (ppr n <+> ppr ty)
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor. Panics if that is not possible.
-- See also 'splitTyConApp_maybe'
splitTyConApp :: Type -> (TyCon, [Type])
splitTyConApp ty = case splitTyConApp_maybe ty of
Just stuff -> stuff
Nothing -> pprPanic "splitTyConApp" (ppr ty)
-- | Attempts to tease a type apart into a type constructor and the application
-- of a number of arguments to that constructor
splitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
splitTyConApp_maybe ty | Just ty' <- coreView ty = splitTyConApp_maybe ty'
splitTyConApp_maybe ty = repSplitTyConApp_maybe ty
-- | Like 'splitTyConApp_maybe', but doesn't look through synonyms. This
-- assumes the synonyms have already been dealt with.
repSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
repSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
repSplitTyConApp_maybe (ForAllTy (Anon arg) res) = Just (funTyCon, [arg,res])
repSplitTyConApp_maybe _ = Nothing
-- | Attempts to tease a list type apart and gives the type of the elements if
-- successful (looks through type synonyms)
splitListTyConApp_maybe :: Type -> Maybe Type
splitListTyConApp_maybe ty = case splitTyConApp_maybe ty of
Just (tc,[e]) | tc == listTyCon -> Just e
_other -> Nothing
-- | What is the role assigned to the next parameter of this type? Usually,
-- this will be 'Nominal', but if the type is a 'TyConApp', we may be able to
-- do better. The type does *not* have to be well-kinded when applied for this
-- to work!
nextRole :: Type -> Role
nextRole ty
| Just (tc, tys) <- splitTyConApp_maybe ty
, let num_tys = length tys
, num_tys < tyConArity tc
= tyConRoles tc `getNth` num_tys
| otherwise
= Nominal
newTyConInstRhs :: TyCon -> [Type] -> Type
-- ^ Unwrap one 'layer' of newtype on a type constructor and its
-- arguments, using an eta-reduced version of the @newtype@ if possible.
-- This requires tys to have at least @newTyConInstArity tycon@ elements.
newTyConInstRhs tycon tys
= ASSERT2( tvs `leLength` tys, ppr tycon $$ ppr tys $$ ppr tvs )
applyTysX tvs rhs tys
where
(tvs, rhs) = newTyConEtadRhs tycon
{-
---------------------------------------------------------------------
CastTy
~~~~~~
A casted type has its *kind* casted into something new.
Note [Weird typing rule for ForAllTy]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Here is the (truncated) typing rule for the dependent ForAllTy:
inner : kind
------------------------------------
ForAllTy (Named tv vis) inner : kind
Note that neither the inner type nor for ForAllTy itself have to have
kind *! But, it means that we should push any kind casts through the
ForAllTy. The only trouble is avoiding capture.
-}
splitCastTy_maybe :: Type -> Maybe (Type, Coercion)
splitCastTy_maybe ty | Just ty' <- coreView ty = splitCastTy_maybe ty'
splitCastTy_maybe (CastTy ty co) = Just (ty, co)
splitCastTy_maybe _ = Nothing
-- | Make a 'CastTy'. The Coercion must be nominal. This function looks
-- at the entire structure of the type and coercion in an attempt to
-- maintain representation invariance (that is, any two types that are `eqType`
-- look the same). Be very wary of calling this in a loop.
mkCastTy :: Type -> Coercion -> Type
-- Running example:
-- T :: forall k1. k1 -> forall k2. k2 -> Bool -> Maybe k1 -> *
-- co :: * ~R X (maybe X is a newtype around *)
-- ty = T Nat 3 Symbol "foo" True (Just 2)
--
-- We wish to "push" the cast down as far as possible. See also
-- Note [Pushing down casts] in TyCoRep. Here is where we end
-- up:
--
-- (T Nat 3 Symbol |> <Symbol> -> <Bool> -> <Maybe Nat> -> co)
-- "foo" True (Just 2)
--
mkCastTy ty co | isReflexiveCo co = ty
-- NB: Do the slow check here. This is important to keep the splitXXX
-- functions working properly. Otherwise, we may end up with something
-- like (((->) |> something_reflexive_but_not_obviously_so) biz baz)
-- fails under splitFunTy_maybe. This happened with the cheaper check
-- in test dependent/should_compile/dynamic-paper.
mkCastTy (CastTy ty co1) co2 = mkCastTy ty (co1 `mkTransCo` co2)
-- See Note [Weird typing rule for ForAllTy]
mkCastTy (ForAllTy (Named tv vis) inner_ty) co
= -- have to make sure that pushing the co in doesn't capture the bound var
let fvs = tyCoVarsOfCo co
empty_subst = mkEmptyTCvSubst (mkInScopeSet fvs)
(subst, tv') = substTyVarBndr empty_subst tv
in
ForAllTy (Named tv' vis) (substTy subst inner_ty `mkCastTy` co)
mkCastTy ty co = -- NB: don't check if the coercion "from" type matches here;
-- there may be unzonked variables about
let result = split_apps [] ty co in
ASSERT2( CastTy ty co `eqType` result
, ppr ty <+> dcolon <+> ppr (typeKind ty) $$
ppr co <+> dcolon <+> ppr (coercionKind co) $$
ppr result <+> dcolon <+> ppr (typeKind result) )
result
where
-- split_apps breaks apart any type applications, so we can see how far down
-- to push the cast
split_apps args (AppTy t1 t2) co
= split_apps (t2:args) t1 co
split_apps args (TyConApp tc tc_args) co
| mightBeUnsaturatedTyCon tc
= affix_co (tyConBinders tc) (mkTyConTy tc) (tc_args `chkAppend` args) co
| otherwise -- not decomposable... but it may still be oversaturated
= let (non_decomp_args, decomp_args) = splitAt (tyConArity tc) tc_args
saturated_tc = mkTyConApp tc non_decomp_args
in
affix_co (fst $ splitPiTys $ typeKind saturated_tc)
saturated_tc (decomp_args `chkAppend` args) co
split_apps args (ForAllTy (Anon arg) res) co
= affix_co (tyConBinders funTyCon) (mkTyConTy funTyCon)
(arg : res : args) co
split_apps args ty co
= affix_co (fst $ splitPiTys $ typeKind ty)
ty args co
-- having broken everything apart, this figures out the point at which there
-- are no more dependent quantifications, and puts the cast there
affix_co _ ty [] co = no_double_casts ty co
affix_co bndrs ty args co
-- if kind contains any dependent quantifications, we can't push.
-- apply arguments until it doesn't
= let (no_dep_bndrs, some_dep_bndrs) = spanEnd isAnonBinder bndrs
(some_dep_args, rest_args) = splitAtList some_dep_bndrs args
dep_subst = zipTyBinderSubst some_dep_bndrs some_dep_args
used_no_dep_bndrs = takeList rest_args no_dep_bndrs
rest_arg_tys = substTys dep_subst (map binderType used_no_dep_bndrs)
co' = mkFunCos Nominal
(map (mkReflCo Nominal) rest_arg_tys)
co
in
((ty `mkAppTys` some_dep_args) `no_double_casts` co') `mkAppTys` rest_args
no_double_casts (CastTy ty co1) co2 = CastTy ty (co1 `mkTransCo` co2)
no_double_casts ty co = CastTy ty co
{-
--------------------------------------------------------------------
CoercionTy
~~~~~~~~~~
CoercionTy allows us to inject coercions into types. A CoercionTy
should appear only in the right-hand side of an application.
-}
mkCoercionTy :: Coercion -> Type
mkCoercionTy = CoercionTy
isCoercionTy :: Type -> Bool
isCoercionTy (CoercionTy _) = True
isCoercionTy _ = False
isCoercionTy_maybe :: Type -> Maybe Coercion
isCoercionTy_maybe (CoercionTy co) = Just co
isCoercionTy_maybe _ = Nothing
stripCoercionTy :: Type -> Coercion
stripCoercionTy (CoercionTy co) = co
stripCoercionTy ty = pprPanic "stripCoercionTy" (ppr ty)
{-
---------------------------------------------------------------------
SynTy
~~~~~
Notes on type synonyms
~~~~~~~~~~~~~~~~~~~~~~
The various "split" functions (splitFunTy, splitRhoTy, splitForAllTy) try
to return type synonyms wherever possible. Thus
type Foo a = a -> a
we want
splitFunTys (a -> Foo a) = ([a], Foo a)
not ([a], a -> a)
The reason is that we then get better (shorter) type signatures in
interfaces. Notably this plays a role in tcTySigs in TcBinds.hs.
Representation types
~~~~~~~~~~~~~~~~~~~~
Note [Nullary unboxed tuple]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We represent the nullary unboxed tuple as the unary (but void) type
Void#. The reason for this is that the ReprArity is never
less than the Arity (as it would otherwise be for a function type like
(# #) -> Int).
As a result, ReprArity is always strictly positive if Arity is. This
is important because it allows us to distinguish at runtime between a
thunk and a function takes a nullary unboxed tuple as an argument!
-}
type UnaryType = Type
data RepType = UbxTupleRep [UnaryType] -- INVARIANT: never an empty list (see Note [Nullary unboxed tuple])
| UnaryRep UnaryType
instance Outputable RepType where
ppr (UbxTupleRep tys) = text "UbxTupleRep" <+> ppr tys
ppr (UnaryRep ty) = text "UnaryRep" <+> ppr ty
flattenRepType :: RepType -> [UnaryType]
flattenRepType (UbxTupleRep tys) = tys
flattenRepType (UnaryRep ty) = [ty]
-- | Looks through:
--
-- 1. For-alls
-- 2. Synonyms
-- 3. Predicates
-- 4. All newtypes, including recursive ones, but not newtype families
-- 5. Casts
--
-- It's useful in the back end of the compiler.
repType :: Type -> RepType
repType ty
= go initRecTc ty
where
go :: RecTcChecker -> Type -> RepType
go rec_nts ty -- Expand predicates and synonyms
| Just ty' <- coreView ty
= go rec_nts ty'
go rec_nts (ForAllTy (Named {}) ty2) -- Drop type foralls
= go rec_nts ty2
go rec_nts (TyConApp tc tys) -- Expand newtypes
| isNewTyCon tc
, tys `lengthAtLeast` tyConArity tc
, Just rec_nts' <- checkRecTc rec_nts tc -- See Note [Expanding newtypes] in TyCon
= go rec_nts' (newTyConInstRhs tc tys)
| isUnboxedTupleTyCon tc
= if null tys
then UnaryRep voidPrimTy -- See Note [Nullary unboxed tuple]
else UbxTupleRep (concatMap (flattenRepType . go rec_nts) non_rr_tys)
where
-- See Note [Unboxed tuple RuntimeRep vars] in TyCon
non_rr_tys = dropRuntimeRepArgs tys
go rec_nts (CastTy ty _)
= go rec_nts ty
go _ ty@(CoercionTy _)
= pprPanic "repType" (ppr ty)
go _ ty = UnaryRep ty
-- ToDo: this could be moved to the code generator, using splitTyConApp instead
-- of inspecting the type directly.
-- | Discovers the primitive representation of a more abstract 'UnaryType'
typePrimRep :: UnaryType -> PrimRep
typePrimRep ty = kindPrimRep (typeKind ty)
-- | Find the primitive representation of a 'TyCon'. Defined here to
-- avoid module loops. Call this only on unlifted tycons.
tyConPrimRep :: TyCon -> PrimRep
tyConPrimRep tc = kindPrimRep res_kind
where
res_kind = tyConResKind tc
-- | Take a kind (of shape @TYPE rr@) and produce the 'PrimRep' of values
-- of types of this kind.
kindPrimRep :: Kind -> PrimRep
kindPrimRep ki | Just ki' <- coreViewOneStarKind ki = kindPrimRep ki'
kindPrimRep (TyConApp typ [runtime_rep])
= ASSERT( typ `hasKey` tYPETyConKey )
go runtime_rep
where
go rr | Just rr' <- coreView rr = go rr'
go (TyConApp rr_dc args)
| RuntimeRep fun <- tyConRuntimeRepInfo rr_dc
= fun args
go rr = pprPanic "kindPrimRep.go" (ppr rr)
kindPrimRep ki = WARN( True
, text "kindPrimRep defaulting to PtrRep on" <+> ppr ki )
PtrRep -- this can happen legitimately for, e.g., Any
typeRepArity :: Arity -> Type -> RepArity
typeRepArity 0 _ = 0
typeRepArity n ty = case repType ty of
UnaryRep (ForAllTy bndr ty) -> length (flattenRepType (repType (binderType bndr))) + typeRepArity (n - 1) ty
_ -> pprPanic "typeRepArity: arity greater than type can handle" (ppr (n, ty, repType ty))
isVoidTy :: Type -> Bool
-- True if the type has zero width
isVoidTy ty = case repType ty of
UnaryRep (TyConApp tc _) -> isUnliftedTyCon tc &&
isVoidRep (tyConPrimRep tc)
_ -> False
{-
Note [AppTy rep]
~~~~~~~~~~~~~~~~
Types of the form 'f a' must be of kind *, not #, so we are guaranteed
that they are represented by pointers. The reason is that f must have
kind (kk -> kk) and kk cannot be unlifted; see Note [The kind invariant]
in TyCoRep.
---------------------------------------------------------------------
ForAllTy
~~~~~~~~
-}
mkForAllTy :: TyBinder -> Type -> Type
mkForAllTy = ForAllTy
-- | Make a dependent forall.
mkNamedForAllTy :: TyVar -> VisibilityFlag -> Type -> Type
mkNamedForAllTy tv vis = ASSERT( isTyVar tv )
ForAllTy (Named tv vis)
-- | Like mkForAllTys, but assumes all variables are dependent and invisible,
-- a common case
mkInvForAllTys :: [TyVar] -> Type -> Type
mkInvForAllTys tvs = ASSERT( all isTyVar tvs )
mkForAllTys (map (flip Named Invisible) tvs)
-- | Like mkForAllTys, but assumes all variables are dependent and specified,
-- a common case
mkSpecForAllTys :: [TyVar] -> Type -> Type
mkSpecForAllTys tvs = ASSERT( all isTyVar tvs )
mkForAllTys (map (flip Named Specified) tvs)
-- | Like mkForAllTys, but assumes all variables are dependent and visible
mkVisForAllTys :: [TyVar] -> Type -> Type
mkVisForAllTys tvs = ASSERT( all isTyVar tvs )
mkForAllTys (map (flip Named Visible) tvs)
mkPiType :: Var -> Type -> Type
-- ^ Makes a @(->)@ type or an implicit forall type, depending
-- on whether it is given a type variable or a term variable.
-- This is used, for example, when producing the type of a lambda.
-- Always uses Invisible binders.
mkPiTypes :: [Var] -> Type -> Type
-- ^ 'mkPiType' for multiple type or value arguments
mkPiType v ty
| isTyVar v = mkForAllTy (Named v Invisible) ty
| otherwise = mkForAllTy (Anon (varType v)) ty
mkPiTypes vs ty = foldr mkPiType ty vs
-- | Given a list of type-level vars and a result type, makes TyBinders, preferring
-- anonymous binders if the variable is, in fact, not dependent.
-- All binders are /visible/.
mkTyBindersPreferAnon :: [TyVar] -> Type -> [TyBinder]
mkTyBindersPreferAnon vars inner_ty = fst $ go vars inner_ty
where
go :: [TyVar] -> Type -> ([TyBinder], VarSet) -- also returns the free vars
go [] ty = ([], tyCoVarsOfType ty)
go (v:vs) ty | v `elemVarSet` fvs
= ( Named v Visible : binders
, fvs `delVarSet` v `unionVarSet` kind_vars )
| otherwise
= ( Anon (tyVarKind v) : binders
, fvs `unionVarSet` kind_vars )
where
(binders, fvs) = go vs ty
kind_vars = tyCoVarsOfType $ tyVarKind v
-- | Take a ForAllTy apart, returning the list of tyvars and the result type.
-- This always succeeds, even if it returns only an empty list. Note that the
-- result type returned may have free variables that were bound by a forall.
splitForAllTys :: Type -> ([TyVar], Type)
splitForAllTys ty = split ty ty []
where
split orig_ty ty tvs | Just ty' <- coreView ty = split orig_ty ty' tvs
split _ (ForAllTy (Named tv _) ty) tvs = split ty ty (tv:tvs)
split orig_ty _ tvs = (reverse tvs, orig_ty)
-- | Split off all TyBinders to a type, splitting both proper foralls
-- and functions
splitPiTys :: Type -> ([TyBinder], Type)
splitPiTys ty = split ty ty []
where
split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
split _ (ForAllTy b res) bs = split res res (b:bs)
split orig_ty _ bs = (reverse bs, orig_ty)
-- | Like 'splitPiTys' but split off only /named/ binders.
splitNamedPiTys :: Type -> ([TyBinder], Type)
splitNamedPiTys ty = split ty ty []
where
split orig_ty ty bs | Just ty' <- coreView ty = split orig_ty ty' bs
split _ (ForAllTy b@(Named {}) res) bs = split res res (b:bs)
split orig_ty _ bs = (reverse bs, orig_ty)
-- | Checks whether this is a proper forall (with a named binder)
isForAllTy :: Type -> Bool
isForAllTy (ForAllTy (Named {}) _) = True
isForAllTy _ = False
-- | Is this a function or forall?
isPiTy :: Type -> Bool
isPiTy (ForAllTy {}) = True
isPiTy _ = False
-- | Take a forall type apart, or panics if that is not possible.
splitForAllTy :: Type -> (TyVar, Type)
splitForAllTy ty
| Just answer <- splitForAllTy_maybe ty = answer
| otherwise = pprPanic "splitForAllTy" (ppr ty)
-- | Attempts to take a forall type apart, but only if it's a proper forall,
-- with a named binder
splitForAllTy_maybe :: Type -> Maybe (TyVar, Type)
splitForAllTy_maybe ty = splitFAT_m ty
where
splitFAT_m ty | Just ty' <- coreView ty = splitFAT_m ty'
splitFAT_m (ForAllTy (Named tv _) ty) = Just (tv, ty)
splitFAT_m _ = Nothing
-- | Attempts to take a forall type apart; works with proper foralls and
-- functions
splitPiTy_maybe :: Type -> Maybe (TyBinder, Type)
splitPiTy_maybe ty = go ty
where
go ty | Just ty' <- coreView ty = go ty'
go (ForAllTy bndr ty) = Just (bndr, ty)
go _ = Nothing
-- | Takes a forall type apart, or panics
splitPiTy :: Type -> (TyBinder, Type)
splitPiTy ty
| Just answer <- splitPiTy_maybe ty = answer
| otherwise = pprPanic "splitPiTy" (ppr ty)
-- | Drops all non-anonymous ForAllTys
dropForAlls :: Type -> Type
dropForAlls ty | Just ty' <- coreView ty = dropForAlls ty'
| otherwise = go ty
where
go (ForAllTy (Named {}) res) = go res
go res = res
-- | Given a tycon and its arguments, filters out any invisible arguments
filterOutInvisibleTypes :: TyCon -> [Type] -> [Type]
filterOutInvisibleTypes tc tys = snd $ partitionInvisibles tc id tys
-- | Like 'filterOutInvisibles', but works on 'TyVar's
filterOutInvisibleTyVars :: TyCon -> [TyVar] -> [TyVar]
filterOutInvisibleTyVars tc tvs = snd $ partitionInvisibles tc mkTyVarTy tvs
-- | Given a tycon and a list of things (which correspond to arguments),
-- partitions the things into the invisible ones and the visible ones.
-- The callback function is necessary for this scenario:
--
-- > T :: forall k. k -> k
-- > partitionInvisibles T [forall m. m -> m -> m, S, R, Q]
--
-- After substituting, we get
--
-- > T (forall m. m -> m -> m) :: (forall m. m -> m -> m) -> forall n. n -> n -> n
--
-- Thus, the first argument is invisible, @S@ is visible, @R@ is invisible again,
-- and @Q@ is visible.
--
-- If you're absolutely sure that your tycon's kind doesn't end in a variable,
-- it's OK if the callback function panics, as that's the only time it's
-- consulted.
partitionInvisibles :: TyCon -> (a -> Type) -> [a] -> ([a], [a])
partitionInvisibles tc get_ty = go emptyTCvSubst (tyConKind tc)
where
go _ _ [] = ([], [])
go subst (ForAllTy bndr res_ki) (x:xs)
| isVisibleBinder bndr = second (x :) (go subst' res_ki xs)
| otherwise = first (x :) (go subst' res_ki xs)
where
subst' = extendTvSubstBinder subst bndr (get_ty x)
go subst (TyVarTy tv) xs
| Just ki <- lookupTyVar subst tv = go subst ki xs
go _ _ xs = ([], xs) -- something is ill-kinded. But this can happen
-- when printing errors. Assume everything is visible.
-- like splitPiTys, but returns only *invisible* binders, including constraints
splitPiTysInvisible :: Type -> ([TyBinder], Type)
splitPiTysInvisible ty = split ty ty []
where
split orig_ty ty bndrs
| Just ty' <- coreView ty = split orig_ty ty' bndrs
split _ (ForAllTy bndr ty) bndrs
| isInvisibleBinder bndr
= split ty ty (bndr:bndrs)
split orig_ty _ bndrs
= (reverse bndrs, orig_ty)
applyTysX :: [TyVar] -> Type -> [Type] -> Type
-- applyTyxX beta-reduces (/\tvs. body_ty) arg_tys
-- Assumes that (/\tvs. body_ty) is closed
applyTysX tvs body_ty arg_tys
= ASSERT2( length arg_tys >= n_tvs, pp_stuff )
ASSERT2( tyCoVarsOfType body_ty `subVarSet` mkVarSet tvs, pp_stuff )
mkAppTys (substTyWith tvs (take n_tvs arg_tys) body_ty)
(drop n_tvs arg_tys)
where
pp_stuff = vcat [ppr tvs, ppr body_ty, ppr arg_tys]
n_tvs = length tvs
{-
%************************************************************************
%* *
TyBinders
%* *
%************************************************************************
-}
-- | Make a named binder
mkNamedBinder :: VisibilityFlag -> Var -> TyBinder
mkNamedBinder vis var = Named var vis
-- | Make an anonymous binder
mkAnonBinder :: Type -> TyBinder
mkAnonBinder = Anon
-- | Does this binder bind a variable that is /not/ erased? Returns
-- 'True' for anonymous binders.
isIdLikeBinder :: TyBinder -> Bool
isIdLikeBinder (Named {}) = False
isIdLikeBinder (Anon {}) = True
-- | Does this type, when used to the left of an arrow, require
-- a visible argument? This checks to see if the kind of the type
-- is constraint.
isVisibleType :: Type -> Bool
isVisibleType = not . isPredTy
binderVisibility :: TyBinder -> VisibilityFlag
binderVisibility (Named _ vis) = vis
binderVisibility (Anon ty)
| isVisibleType ty = Visible
| otherwise = Invisible
-- | Extract a bound variable in a binder, if any
binderVar_maybe :: TyBinder -> Maybe Var
binderVar_maybe (Named v _) = Just v
binderVar_maybe (Anon {}) = Nothing
-- | Extract a bound variable in a binder, or panics
binderVar :: String -- ^ printed if there is a panic
-> TyBinder -> Var
binderVar _ (Named v _) = v
binderVar e (Anon t) = pprPanic ("binderVar (" ++ e ++ ")") (ppr t)
-- | Extract a relevant type, if there is one.
binderRelevantType_maybe :: TyBinder -> Maybe Type
binderRelevantType_maybe (Named {}) = Nothing
binderRelevantType_maybe (Anon ty) = Just ty
-- | Like 'maybe', but for binders.
caseBinder :: TyBinder -- ^ binder to scrutinize
-> (TyVar -> a) -- ^ named case
-> (Type -> a) -- ^ anonymous case
-> a
caseBinder (Named v _) f _ = f v
caseBinder (Anon t) _ d = d t
-- | Break apart a list of binders into tyvars and anonymous types.
partitionBinders :: [TyBinder] -> ([TyVar], [Type])
partitionBinders = partitionWith named_or_anon
where
named_or_anon bndr = caseBinder bndr Left Right
-- | Break apart a list of binders into a list of named binders and
-- a list of anonymous types.
partitionBindersIntoBinders :: [TyBinder] -> ([TyBinder], [Type])
partitionBindersIntoBinders = partitionWith named_or_anon
where
named_or_anon bndr = caseBinder bndr (\_ -> Left bndr) Right
{-
%************************************************************************
%* *
Pred
* *
************************************************************************
Predicates on PredType
Note [isPredTy complications]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
You would think that we could define
isPredTy ty = isConstraintKind (typeKind ty)
But there are a number of complications:
* isPredTy is used when printing types, which can happen in debug
printing during type checking of not-fully-zonked types. So it's
not cool to say isConstraintKind (typeKind ty) because, absent
zonking, the type might be ill-kinded, and typeKind crashes. Hence the
rather tiresome story here
* isPredTy must return "True" to *unlifted* coercions, such as (t1 ~# t2)
and (t1 ~R# t2), which are not of kind Constraint! Currently they are
of kind #.
* If we do form the type '(C a => C [a]) => blah', then we'd like to
print it as such. But that means that isPredTy must return True for
(C a => C [a]). Admittedly that type is illegal in Haskell, but we
want to print it nicely in error messages.
-}
-- | Is the type suitable to classify a given/wanted in the typechecker?
isPredTy :: Type -> Bool
-- See Note [isPredTy complications]
isPredTy ty = go ty []
where
go :: Type -> [KindOrType] -> Bool
go (AppTy ty1 ty2) args = go ty1 (ty2 : args)
go (TyVarTy tv) args = go_k (tyVarKind tv) args
go (TyConApp tc tys) args = ASSERT( null args ) -- TyConApp invariant
go_tc tc tys
go (ForAllTy (Anon arg) res) []
| isPredTy arg = isPredTy res -- (Eq a => C a)
| otherwise = False -- (Int -> Bool)
go (ForAllTy (Named {}) ty) [] = go ty []
go _ _ = False
go_tc :: TyCon -> [KindOrType] -> Bool
go_tc tc args
| tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey
= length args == 4 -- ~# and ~R# sadly have result kind #
-- not Contraint; but we still want
-- isPredTy to reply True.
| otherwise = go_k (tyConKind tc) args
go_k :: Kind -> [KindOrType] -> Bool
-- True <=> ('k' applied to 'kts') = Constraint
go_k k args = isConstraintKind (piResultTys k args)
isClassPred, isEqPred, isNomEqPred, isIPPred :: PredType -> Bool
isClassPred ty = case tyConAppTyCon_maybe ty of
Just tyCon | isClassTyCon tyCon -> True
_ -> False
isEqPred ty = case tyConAppTyCon_maybe ty of
Just tyCon -> tyCon `hasKey` eqPrimTyConKey
|| tyCon `hasKey` eqReprPrimTyConKey
_ -> False
isNomEqPred ty = case tyConAppTyCon_maybe ty of
Just tyCon -> tyCon `hasKey` eqPrimTyConKey
_ -> False
isIPPred ty = case tyConAppTyCon_maybe ty of
Just tc -> isIPTyCon tc
_ -> False
isIPTyCon :: TyCon -> Bool
isIPTyCon tc = tc `hasKey` ipClassKey
-- Class and its corresponding TyCon have the same Unique
isIPClass :: Class -> Bool
isIPClass cls = cls `hasKey` ipClassKey
isCTupleClass :: Class -> Bool
isCTupleClass cls = isTupleTyCon (classTyCon cls)
isIPPred_maybe :: Type -> Maybe (FastString, Type)
isIPPred_maybe ty =
do (tc,[t1,t2]) <- splitTyConApp_maybe ty
guard (isIPTyCon tc)
x <- isStrLitTy t1
return (x,t2)
{-
Make PredTypes
--------------------- Equality types ---------------------------------
-}
-- | Makes a lifted equality predicate at the given role
mkPrimEqPredRole :: Role -> Type -> Type -> PredType
mkPrimEqPredRole Nominal = mkPrimEqPred
mkPrimEqPredRole Representational = mkReprPrimEqPred
mkPrimEqPredRole Phantom = panic "mkPrimEqPredRole phantom"
-- | Creates a primitive type equality predicate.
-- Invariant: the types are not Coercions
mkPrimEqPred :: Type -> Type -> Type
mkPrimEqPred ty1 ty2
= TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
where
k1 = typeKind ty1
k2 = typeKind ty2
-- | Creates a primite type equality predicate with explicit kinds
mkHeteroPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
mkHeteroPrimEqPred k1 k2 ty1 ty2 = TyConApp eqPrimTyCon [k1, k2, ty1, ty2]
-- | Creates a primitive representational type equality predicate
-- with explicit kinds
mkHeteroReprPrimEqPred :: Kind -> Kind -> Type -> Type -> Type
mkHeteroReprPrimEqPred k1 k2 ty1 ty2
= TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
-- | Try to split up a coercion type into the types that it coerces
splitCoercionType_maybe :: Type -> Maybe (Type, Type)
splitCoercionType_maybe ty
= do { (tc, [_, _, ty1, ty2]) <- splitTyConApp_maybe ty
; guard $ tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey
; return (ty1, ty2) }
mkReprPrimEqPred :: Type -> Type -> Type
mkReprPrimEqPred ty1 ty2
= TyConApp eqReprPrimTyCon [k1, k2, ty1, ty2]
where
k1 = typeKind ty1
k2 = typeKind ty2
equalityTyCon :: Role -> TyCon
equalityTyCon Nominal = eqPrimTyCon
equalityTyCon Representational = eqReprPrimTyCon
equalityTyCon Phantom = eqPhantPrimTyCon
-- --------------------- Dictionary types ---------------------------------
mkClassPred :: Class -> [Type] -> PredType
mkClassPred clas tys = TyConApp (classTyCon clas) tys
isDictTy :: Type -> Bool
isDictTy = isClassPred
isDictLikeTy :: Type -> Bool
-- Note [Dictionary-like types]
isDictLikeTy ty | Just ty' <- coreView ty = isDictLikeTy ty'
isDictLikeTy ty = case splitTyConApp_maybe ty of
Just (tc, tys) | isClassTyCon tc -> True
| isTupleTyCon tc -> all isDictLikeTy tys
_other -> False
{-
Note [Dictionary-like types]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Being "dictionary-like" means either a dictionary type or a tuple thereof.
In GHC 6.10 we build implication constraints which construct such tuples,
and if we land up with a binding
t :: (C [a], Eq [a])
t = blah
then we want to treat t as cheap under "-fdicts-cheap" for example.
(Implication constraints are normally inlined, but sadly not if the
occurrence is itself inside an INLINE function! Until we revise the
handling of implication constraints, that is.) This turned out to
be important in getting good arities in DPH code. Example:
class C a
class D a where { foo :: a -> a }
instance C a => D (Maybe a) where { foo x = x }
bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
{-# INLINE bar #-}
bar x y = (foo (Just x), foo (Just y))
Then 'bar' should jolly well have arity 4 (two dicts, two args), but
we ended up with something like
bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
in \x,y. <blah>)
This is all a bit ad-hoc; eg it relies on knowing that implication
constraints build tuples.
Decomposing PredType
-}
-- | A choice of equality relation. This is separate from the type 'Role'
-- because 'Phantom' does not define a (non-trivial) equality relation.
data EqRel = NomEq | ReprEq
deriving (Eq, Ord)
instance Outputable EqRel where
ppr NomEq = text "nominal equality"
ppr ReprEq = text "representational equality"
eqRelRole :: EqRel -> Role
eqRelRole NomEq = Nominal
eqRelRole ReprEq = Representational
data PredTree = ClassPred Class [Type]
| EqPred EqRel Type Type
| IrredPred PredType
classifyPredType :: PredType -> PredTree
classifyPredType ev_ty = case splitTyConApp_maybe ev_ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqReprPrimTyConKey -> EqPred ReprEq ty1 ty2
| tc `hasKey` eqPrimTyConKey -> EqPred NomEq ty1 ty2
Just (tc, tys)
| Just clas <- tyConClass_maybe tc -> ClassPred clas tys
_ -> IrredPred ev_ty
getClassPredTys :: PredType -> (Class, [Type])
getClassPredTys ty = case getClassPredTys_maybe ty of
Just (clas, tys) -> (clas, tys)
Nothing -> pprPanic "getClassPredTys" (ppr ty)
getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
getClassPredTys_maybe ty = case splitTyConApp_maybe ty of
Just (tc, tys) | Just clas <- tyConClass_maybe tc -> Just (clas, tys)
_ -> Nothing
getEqPredTys :: PredType -> (Type, Type)
getEqPredTys ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqPrimTyConKey
|| tc `hasKey` eqReprPrimTyConKey
-> (ty1, ty2)
_ -> pprPanic "getEqPredTys" (ppr ty)
getEqPredTys_maybe :: PredType -> Maybe (Role, Type, Type)
getEqPredTys_maybe ty
= case splitTyConApp_maybe ty of
Just (tc, [_, _, ty1, ty2])
| tc `hasKey` eqPrimTyConKey -> Just (Nominal, ty1, ty2)
| tc `hasKey` eqReprPrimTyConKey -> Just (Representational, ty1, ty2)
_ -> Nothing
getEqPredRole :: PredType -> Role
getEqPredRole ty = eqRelRole (predTypeEqRel ty)
-- | Get the equality relation relevant for a pred type.
predTypeEqRel :: PredType -> EqRel
predTypeEqRel ty
| Just (tc, _) <- splitTyConApp_maybe ty
, tc `hasKey` eqReprPrimTyConKey
= ReprEq
| otherwise
= NomEq
{-
%************************************************************************
%* *
Size
* *
************************************************************************
-}
-- NB: This function does not respect `eqType`, in that two types that
-- are `eqType` may return different sizes. This is OK, because this
-- function is used only in reporting, not decision-making.
typeSize :: Type -> Int
typeSize (LitTy {}) = 1
typeSize (TyVarTy {}) = 1
typeSize (AppTy t1 t2) = typeSize t1 + typeSize t2
typeSize (ForAllTy b t) = typeSize (binderType b) + typeSize t
typeSize (TyConApp _ ts) = 1 + sum (map typeSize ts)
typeSize (CastTy ty co) = typeSize ty + coercionSize co
typeSize (CoercionTy co) = coercionSize co
{-
%************************************************************************
%* *
Well-scoped tyvars
* *
************************************************************************
-}
-- | Do a topological sort on a list of tyvars. This is a deterministic
-- sorting operation (that is, doesn't depend on Uniques).
toposortTyVars :: [TyVar] -> [TyVar]
toposortTyVars tvs = reverse $
[ tv | (tv, _, _) <- topologicalSortG $
graphFromEdgedVertices nodes ]
where
var_ids :: VarEnv Int
var_ids = mkVarEnv (zip tvs [1..])
nodes = [ ( tv
, lookupVarEnv_NF var_ids tv
, mapMaybe (lookupVarEnv var_ids)
(tyCoVarsOfTypeList (tyVarKind tv)) )
| tv <- tvs ]
-- | Extract a well-scoped list of variables from a set of variables.
varSetElemsWellScoped :: VarSet -> [Var]
varSetElemsWellScoped = toposortTyVars . varSetElems
-- | Get the free vars of a type in scoped order
tyCoVarsOfTypeWellScoped :: Type -> [TyVar]
tyCoVarsOfTypeWellScoped = toposortTyVars . tyCoVarsOfTypeList
{-
************************************************************************
* *
\subsection{Type families}
* *
************************************************************************
-}
mkFamilyTyConApp :: TyCon -> [Type] -> Type
-- ^ Given a family instance TyCon and its arg types, return the
-- corresponding family type. E.g:
--
-- > data family T a
-- > data instance T (Maybe b) = MkT b
--
-- Where the instance tycon is :RTL, so:
--
-- > mkFamilyTyConApp :RTL Int = T (Maybe Int)
mkFamilyTyConApp tc tys
| Just (fam_tc, fam_tys) <- tyConFamInst_maybe tc
, let tvs = tyConTyVars tc
fam_subst = ASSERT2( length tvs == length tys, ppr tc <+> ppr tys )
zipTvSubst tvs tys
= mkTyConApp fam_tc (substTys fam_subst fam_tys)
| otherwise
= mkTyConApp tc tys
-- | Get the type on the LHS of a coercion induced by a type/data
-- family instance.
coAxNthLHS :: CoAxiom br -> Int -> Type
coAxNthLHS ax ind =
mkTyConApp (coAxiomTyCon ax) (coAxBranchLHS (coAxiomNthBranch ax ind))
-- | Pretty prints a 'TyCon', using the family instance in case of a
-- representation tycon. For example:
--
-- > data T [a] = ...
--
-- In that case we want to print @T [a]@, where @T@ is the family 'TyCon'
pprSourceTyCon :: TyCon -> SDoc
pprSourceTyCon tycon
| Just (fam_tc, tys) <- tyConFamInst_maybe tycon
= ppr $ fam_tc `TyConApp` tys -- can't be FunTyCon
| otherwise
= ppr tycon
{-
************************************************************************
* *
\subsection{Liftedness}
* *
************************************************************************
-}
-- | See "Type#type_classification" for what an unlifted type is
isUnliftedType :: Type -> Bool
-- isUnliftedType returns True for forall'd unlifted types:
-- x :: forall a. Int#
-- I found bindings like these were getting floated to the top level.
-- They are pretty bogus types, mind you. It would be better never to
-- construct them
isUnliftedType ty | Just ty' <- coreView ty = isUnliftedType ty'
isUnliftedType (ForAllTy (Named {}) ty) = isUnliftedType ty
isUnliftedType (TyConApp tc _) = isUnliftedTyCon tc
isUnliftedType _ = False
-- | Extract the RuntimeRep classifier of a type. Panics if this is not possible.
getRuntimeRep :: String -- ^ Printed in case of an error
-> Type -> Type
getRuntimeRep err ty = getRuntimeRepFromKind err (typeKind ty)
-- | Extract the RuntimeRep classifier of a type from its kind.
-- For example, getRuntimeRepFromKind * = PtrRepLifted;
-- getRuntimeRepFromKind # = PtrRepUnlifted.
-- Panics if this is not possible.
getRuntimeRepFromKind :: String -- ^ Printed in case of an error
-> Type -> Type
getRuntimeRepFromKind err = go
where
go k | Just k' <- coreViewOneStarKind k = go k'
go k
| Just (tc, [arg]) <- splitTyConApp_maybe k
, tc `hasKey` tYPETyConKey
= arg
go k = pprPanic "getRuntimeRep" (text err $$
ppr k <+> dcolon <+> ppr (typeKind k))
isUnboxedTupleType :: Type -> Bool
isUnboxedTupleType ty = case tyConAppTyCon_maybe ty of
Just tc -> isUnboxedTupleTyCon tc
_ -> False
-- | See "Type#type_classification" for what an algebraic type is.
-- Should only be applied to /types/, as opposed to e.g. partially
-- saturated type constructors
isAlgType :: Type -> Bool
isAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isAlgTyCon tc
_other -> False
-- | See "Type#type_classification" for what an algebraic type is.
-- Should only be applied to /types/, as opposed to e.g. partially
-- saturated type constructors. Closed type constructors are those
-- with a fixed right hand side, as opposed to e.g. associated types
isClosedAlgType :: Type -> Bool
isClosedAlgType ty
= case splitTyConApp_maybe ty of
Just (tc, ty_args) | isAlgTyCon tc && not (isFamilyTyCon tc)
-> ASSERT2( ty_args `lengthIs` tyConArity tc, ppr ty ) True
_other -> False
-- | Computes whether an argument (or let right hand side) should
-- be computed strictly or lazily, based only on its type.
-- Currently, it's just 'isUnliftedType'.
isStrictType :: Type -> Bool
isStrictType = isUnliftedType
isPrimitiveType :: Type -> Bool
-- ^ Returns true of types that are opaque to Haskell.
isPrimitiveType ty = case splitTyConApp_maybe ty of
Just (tc, ty_args) -> ASSERT( ty_args `lengthIs` tyConArity tc )
isPrimTyCon tc
_ -> False
{-
************************************************************************
* *
\subsection{Sequencing on types}
* *
************************************************************************
-}
seqType :: Type -> ()
seqType (LitTy n) = n `seq` ()
seqType (TyVarTy tv) = tv `seq` ()
seqType (AppTy t1 t2) = seqType t1 `seq` seqType t2
seqType (TyConApp tc tys) = tc `seq` seqTypes tys
seqType (ForAllTy bndr ty) = seqType (binderType bndr) `seq` seqType ty
seqType (CastTy ty co) = seqType ty `seq` seqCo co
seqType (CoercionTy co) = seqCo co
seqTypes :: [Type] -> ()
seqTypes [] = ()
seqTypes (ty:tys) = seqType ty `seq` seqTypes tys
{-
************************************************************************
* *
Comparison for types
(We don't use instances so that we know where it happens)
* *
************************************************************************
Note [Equality on AppTys]
~~~~~~~~~~~~~~~~~~~~~~~~~
In our cast-ignoring equality, we want to say that the following two
are equal:
(Maybe |> co) (Int |> co') ~? Maybe Int
But the left is an AppTy while the right is a TyConApp. The solution is
to use repSplitAppTy_maybe to break up the TyConApp into its pieces and
then continue. Easy to do, but also easy to forget to do.
-}
eqType :: Type -> Type -> Bool
-- ^ Type equality on source types. Does not look through @newtypes@ or
-- 'PredType's, but it does look through type synonyms.
-- This first checks that the kinds of the types are equal and then
-- checks whether the types are equal, ignoring casts and coercions.
-- (The kind check is a recursive call, but since all kinds have type
-- @Type@, there is no need to check the types of kinds.)
-- See also Note [Non-trivial definitional equality] in TyCoRep.
eqType t1 t2 = isEqual $ cmpType t1 t2
-- | Compare types with respect to a (presumably) non-empty 'RnEnv2'.
eqTypeX :: RnEnv2 -> Type -> Type -> Bool
eqTypeX env t1 t2 = isEqual $ cmpTypeX env t1 t2
-- | Type equality on lists of types, looking through type synonyms
-- but not newtypes.
eqTypes :: [Type] -> [Type] -> Bool
eqTypes tys1 tys2 = isEqual $ cmpTypes tys1 tys2
eqVarBndrs :: RnEnv2 -> [Var] -> [Var] -> Maybe RnEnv2
-- Check that the var lists are the same length
-- and have matching kinds; if so, extend the RnEnv2
-- Returns Nothing if they don't match
eqVarBndrs env [] []
= Just env
eqVarBndrs env (tv1:tvs1) (tv2:tvs2)
| eqTypeX env (tyVarKind tv1) (tyVarKind tv2)
= eqVarBndrs (rnBndr2 env tv1 tv2) tvs1 tvs2
eqVarBndrs _ _ _= Nothing
-- Now here comes the real worker
cmpType :: Type -> Type -> Ordering
cmpType t1 t2
-- we know k1 and k2 have the same kind, because they both have kind *.
= cmpTypeX rn_env t1 t2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes [t1, t2]))
cmpTypes :: [Type] -> [Type] -> Ordering
cmpTypes ts1 ts2 = cmpTypesX rn_env ts1 ts2
where
rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfTypes (ts1 ++ ts2)))
-- | An ordering relation between two 'Type's (known below as @t1 :: k1@
-- and @t2 :: k2@)
data TypeOrdering = TLT -- ^ @t1 < t2@
| TEQ -- ^ @t1 ~ t2@ and there are no casts in either,
-- therefore we can conclude @k1 ~ k2@
| TEQX -- ^ @t1 ~ t2@ yet one of the types contains a cast so
-- they may differ in kind.
| TGT -- ^ @t1 > t2@
deriving (Eq, Ord, Enum, Bounded)
cmpTypeX :: RnEnv2 -> Type -> Type -> Ordering -- Main workhorse
-- See Note [Non-trivial definitional equality] in TyCoRep
cmpTypeX env orig_t1 orig_t2 =
case go env orig_t1 orig_t2 of
-- If there are casts then we also need to do a comparison of the kinds of
-- the types being compared
TEQX -> toOrdering $ go env k1 k2
ty_ordering -> toOrdering ty_ordering
where
k1 = typeKind orig_t1
k2 = typeKind orig_t2
toOrdering :: TypeOrdering -> Ordering
toOrdering TLT = LT
toOrdering TEQ = EQ
toOrdering TEQX = EQ
toOrdering TGT = GT
liftOrdering :: Ordering -> TypeOrdering
liftOrdering LT = TLT
liftOrdering EQ = TEQ
liftOrdering GT = TGT
thenCmpTy :: TypeOrdering -> TypeOrdering -> TypeOrdering
thenCmpTy TEQ rel = rel
thenCmpTy TEQX rel = hasCast rel
thenCmpTy rel _ = rel
hasCast :: TypeOrdering -> TypeOrdering
hasCast TEQ = TEQX
hasCast rel = rel
-- Returns both the resulting ordering relation between the two types
-- and whether either contains a cast.
go :: RnEnv2 -> Type -> Type -> TypeOrdering
go env t1 t2
| Just t1' <- coreViewOneStarKind t1 = go env t1' t2
| Just t2' <- coreViewOneStarKind t2 = go env t1 t2'
go env (TyVarTy tv1) (TyVarTy tv2)
= liftOrdering $ rnOccL env tv1 `compare` rnOccR env tv2
go env (ForAllTy (Named tv1 _) t1) (ForAllTy (Named tv2 _) t2)
= go env (tyVarKind tv1) (tyVarKind tv2)
`thenCmpTy` go (rnBndr2 env tv1 tv2) t1 t2
-- See Note [Equality on AppTys]
go env (AppTy s1 t1) ty2
| Just (s2, t2) <- repSplitAppTy_maybe ty2
= go env s1 s2 `thenCmpTy` go env t1 t2
go env ty1 (AppTy s2 t2)
| Just (s1, t1) <- repSplitAppTy_maybe ty1
= go env s1 s2 `thenCmpTy` go env t1 t2
go env (ForAllTy (Anon s1) t1) (ForAllTy (Anon s2) t2)
= go env s1 s2 `thenCmpTy` go env t1 t2
go env (TyConApp tc1 tys1) (TyConApp tc2 tys2)
= liftOrdering (tc1 `cmpTc` tc2) `thenCmpTy` gos env tys1 tys2
go _ (LitTy l1) (LitTy l2) = liftOrdering (compare l1 l2)
go env (CastTy t1 _) t2 = hasCast $ go env t1 t2
go env t1 (CastTy t2 _) = hasCast $ go env t1 t2
go _ (CoercionTy {}) (CoercionTy {}) = TEQ
-- Deal with the rest: TyVarTy < CoercionTy < AppTy < LitTy < TyConApp < ForAllTy
go _ ty1 ty2
= liftOrdering $ (get_rank ty1) `compare` (get_rank ty2)
where get_rank :: Type -> Int
get_rank (CastTy {})
= pprPanic "cmpTypeX.get_rank" (ppr [ty1,ty2])
get_rank (TyVarTy {}) = 0
get_rank (CoercionTy {}) = 1
get_rank (AppTy {}) = 3
get_rank (LitTy {}) = 4
get_rank (TyConApp {}) = 5
get_rank (ForAllTy (Anon {}) _) = 6
get_rank (ForAllTy (Named {}) _) = 7
gos :: RnEnv2 -> [Type] -> [Type] -> TypeOrdering
gos _ [] [] = TEQ
gos _ [] _ = TLT
gos _ _ [] = TGT
gos env (ty1:tys1) (ty2:tys2) = go env ty1 ty2 `thenCmpTy` gos env tys1 tys2
-------------
cmpTypesX :: RnEnv2 -> [Type] -> [Type] -> Ordering
cmpTypesX _ [] [] = EQ
cmpTypesX env (t1:tys1) (t2:tys2) = cmpTypeX env t1 t2
`thenCmp` cmpTypesX env tys1 tys2
cmpTypesX _ [] _ = LT
cmpTypesX _ _ [] = GT
-------------
-- | Compare two 'TyCon's. NB: This should /never/ see the "star synonyms",
-- as recognized by Kind.isStarKindSynonymTyCon. See Note
-- [Kind Constraint and kind *] in Kind.
cmpTc :: TyCon -> TyCon -> Ordering
cmpTc tc1 tc2
= ASSERT( not (isStarKindSynonymTyCon tc1) && not (isStarKindSynonymTyCon tc2) )
u1 `compare` u2
where
u1 = tyConUnique tc1
u2 = tyConUnique tc2
{-
************************************************************************
* *
The kind of a type
* *
************************************************************************
-}
typeKind :: Type -> Kind
typeKind (TyConApp tc tys) = piResultTys (tyConKind tc) tys
typeKind (AppTy fun arg) = piResultTy (typeKind fun) arg
typeKind (LitTy l) = typeLiteralKind l
typeKind (ForAllTy (Anon _) _) = liftedTypeKind
typeKind (ForAllTy _ ty) = typeKind ty
typeKind (TyVarTy tyvar) = tyVarKind tyvar
typeKind (CastTy _ty co) = pSnd $ coercionKind co
typeKind (CoercionTy co) = coercionType co
typeLiteralKind :: TyLit -> Kind
typeLiteralKind l =
case l of
NumTyLit _ -> typeNatKind
StrTyLit _ -> typeSymbolKind
-- | Print a tyvar with its kind
pprTyVar :: TyVar -> SDoc
pprTyVar tv = ppr tv <+> dcolon <+> ppr (tyVarKind tv)
{-
%************************************************************************
%* *
Miscellaneous functions
%* *
%************************************************************************
-}
-- | All type constructors occurring in the type; looking through type
-- synonyms, but not newtypes.
-- When it finds a Class, it returns the class TyCon.
tyConsOfType :: Type -> NameEnv TyCon
tyConsOfType ty
= go ty
where
go :: Type -> NameEnv TyCon -- The NameEnv does duplicate elim
go ty | Just ty' <- coreView ty = go ty'
go (TyVarTy {}) = emptyNameEnv
go (LitTy {}) = emptyNameEnv
go (TyConApp tc tys) = go_tc tc `plusNameEnv` go_s tys
go (AppTy a b) = go a `plusNameEnv` go b
go (ForAllTy (Anon a) b) = go a `plusNameEnv` go b `plusNameEnv` go_tc funTyCon
go (ForAllTy (Named tv _) ty) = go ty `plusNameEnv` go (tyVarKind tv)
go (CastTy ty co) = go ty `plusNameEnv` go_co co
go (CoercionTy co) = go_co co
go_co (Refl _ ty) = go ty
go_co (TyConAppCo _ tc args) = go_tc tc `plusNameEnv` go_cos args
go_co (AppCo co arg) = go_co co `plusNameEnv` go_co arg
go_co (ForAllCo _ kind_co co) = go_co kind_co `plusNameEnv` go_co co
go_co (CoVarCo {}) = emptyNameEnv
go_co (AxiomInstCo ax _ args) = go_ax ax `plusNameEnv` go_cos args
go_co (UnivCo p _ t1 t2) = go_prov p `plusNameEnv` go t1 `plusNameEnv` go t2
go_co (SymCo co) = go_co co
go_co (TransCo co1 co2) = go_co co1 `plusNameEnv` go_co co2
go_co (NthCo _ co) = go_co co
go_co (LRCo _ co) = go_co co
go_co (InstCo co arg) = go_co co `plusNameEnv` go_co arg
go_co (CoherenceCo co1 co2) = go_co co1 `plusNameEnv` go_co co2
go_co (KindCo co) = go_co co
go_co (SubCo co) = go_co co
go_co (AxiomRuleCo _ cs) = go_cos cs
go_prov UnsafeCoerceProv = emptyNameEnv
go_prov (PhantomProv co) = go_co co
go_prov (ProofIrrelProv co) = go_co co
go_prov (PluginProv _) = emptyNameEnv
go_prov (HoleProv h) = pprPanic "tyConsOfType hit a hole" (ppr h)
go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys
go_cos cos = foldr (plusNameEnv . go_co) emptyNameEnv cos
go_tc tc = unitNameEnv (tyConName tc) tc
go_ax ax = go_tc $ coAxiomTyCon ax
-- | Find the result 'Kind' of a type synonym,
-- after applying it to its 'arity' number of type variables
-- Actually this function works fine on data types too,
-- but they'd always return '*', so we never need to ask
synTyConResKind :: TyCon -> Kind
synTyConResKind tycon = piResultTys (tyConKind tycon) (mkTyVarTys (tyConTyVars tycon))
-- | Retrieve the free variables in this type, splitting them based
-- on whether the variable was used in a dependent context. It's possible
-- for a variable to be reported twice, if it's used both dependently
-- and non-dependently. (This isn't the most precise analysis, because
-- it's used in the typechecking knot. It might list some dependent
-- variables as also non-dependent.)
splitDepVarsOfType :: Type -> Pair TyCoVarSet
splitDepVarsOfType = go
where
go (TyVarTy tv) = Pair (tyCoVarsOfType $ tyVarKind tv)
(unitVarSet tv)
go (AppTy t1 t2) = go t1 `mappend` go t2
go (TyConApp _ tys) = foldMap go tys
go (ForAllTy (Anon arg) res) = go arg `mappend` go res
go (ForAllTy (Named tv _) ty)
= let Pair kvs tvs = go ty in
Pair (kvs `delVarSet` tv `unionVarSet` tyCoVarsOfType (tyVarKind tv))
(tvs `delVarSet` tv)
go (LitTy {}) = mempty
go (CastTy ty co) = go ty `mappend` Pair (tyCoVarsOfCo co)
emptyVarSet
go (CoercionTy co) = go_co co
go_co co = let Pair ty1 ty2 = coercionKind co in
go ty1 `mappend` go ty2 -- NB: the Pairs separate along different
-- dimensions here. Be careful!
-- | Like 'splitDepVarsOfType', but over a list of types
splitDepVarsOfTypes :: [Type] -> Pair TyCoVarSet
splitDepVarsOfTypes = foldMap splitDepVarsOfType
-- | Retrieve the free variables in this type, splitting them based
-- on whether they are used visibly or invisibly. Invisible ones come
-- first.
splitVisVarsOfType :: Type -> Pair TyCoVarSet
splitVisVarsOfType orig_ty = Pair invis_vars vis_vars
where
Pair invis_vars1 vis_vars = go orig_ty
invis_vars = invis_vars1 `minusVarSet` vis_vars
go (TyVarTy tv) = Pair (tyCoVarsOfType $ tyVarKind tv) (unitVarSet tv)
go (AppTy t1 t2) = go t1 `mappend` go t2
go (TyConApp tc tys) = go_tc tc tys
go (ForAllTy (Anon t1) t2) = go t1 `mappend` go t2
go (ForAllTy (Named tv _) ty)
= ((`delVarSet` tv) <$> go ty) `mappend`
(invisible (tyCoVarsOfType $ tyVarKind tv))
go (LitTy {}) = mempty
go (CastTy ty co) = go ty `mappend` invisible (tyCoVarsOfCo co)
go (CoercionTy co) = invisible $ tyCoVarsOfCo co
invisible vs = Pair vs emptyVarSet
go_tc tc tys = let (invis, vis) = partitionInvisibles tc id tys in
invisible (tyCoVarsOfTypes invis) `mappend` foldMap go vis
splitVisVarsOfTypes :: [Type] -> Pair TyCoVarSet
splitVisVarsOfTypes = foldMap splitVisVarsOfType
|
oldmanmike/ghc
|
compiler/types/Type.hs
|
bsd-3-clause
| 91,851
| 0
| 18
| 25,335
| 19,340
| 10,083
| 9,257
| -1
| -1
|
{- |
Module : $Header$
Description : Describes the functions related to the clusterification of names
Copyright : None
License : None
Maintainer : tydax@protonmail.ch
Stability : unstable
The $Header$ module describes the different functions used to eveluate the
gender of a name.
-}
module NameGender (
findGenderBase
) where
import Data.Char
import Types
{-|
Finds a gender for the specified list of names using the specified base.
The result can be a 'Types.GenderedName' if the name was found in the
specified base, or just the name else.
-}
findGenderBase :: [GenderedName] -> [Name] -> [Either GenderedName Name]
findGenderBase base ns =
let
untainedBase = [x | GenderedName x <- base]
look name =
let
lowerName = map toLower name
res = lookup lowerName untainedBase
in
case res of
Just gender-> Left (GenderedName (name, gender))
Nothing -> Right name
in map look ns
|
Tydax/ou-sont-les-femmes
|
src/NameGender.hs
|
bsd-3-clause
| 992
| 0
| 17
| 260
| 157
| 81
| 76
| 16
| 2
|
-- Polling implementation. This isn't intended to be super efficient,
-- just a decent fallback in case there is no OS implementation.
--
-- To alleviate race conditions, files younger than ten seconds are
-- reported with existence events for any new subscription.
--
module Sirea.Filesystem.Polling
( newPollingManager
) where
import Prelude hiding (FilePath)
import Control.Monad (void,unless)
import Control.Concurrent
import Data.IORef
import Data.Maybe (catMaybes)
import Data.List (sort)
import Data.Function (on)
import qualified Data.Map as M
import qualified Filesystem.Path as FS
import qualified Filesystem as FS
import qualified Control.Exception as E
import qualified System.IO.Error as IOE
import Sirea.Filesystem.Manager
import Sirea.Time
import Debug.Trace (traceIO)
data P = P
{ p_dtPoll :: !DT
, p_sigup :: !(MVar ()) -- signal watchlist update.
, p_watch :: !(IORef [FilePath])
, p_action :: !(EventsHandler)
}
type FilePath = FS.FilePath
-- Polling keeps a simple memory for comparing results. The Event is
-- used as a file records, since it's close enough to what I need. A
-- 'Nothing' value indicates this is the first time we're polling a
-- path, so no changes are reported for that initial effort.
--
-- The lists in PMem will have been sorted by contents.
type PMem = M.Map FilePath (Maybe [FileRec])
-- for a FileRec, the FilePath is local to directory
data FileRec = FileRec
{ fr_path :: !FilePath
, fr_isdir :: !Bool
, fr_mod :: {-# UNPACK #-} !T
}
-- if a file is younger than dtYoung, we'll report it for any new
-- subscriptions as a new file, i.e. to make sure the subscriber
-- doesn't miss it due to a race condition.
dtYoung :: DT
dtYoung = 15 -- seconds
newPollingManager :: DT -> MkManager
newPollingManager dtPoll eh =
newEmptyMVar >>= \ w ->
newIORef [] >>= \ rfL ->
let p = P dtPoll w rfL eh in
forkIO (pollInit p) >>
return (Manager (setWatch p))
-- setWatch simply records the watchlist then signals the change.
-- This will be handled the next time the poll thread tests for
-- the signal. Does not block.
setWatch :: P -> [FilePath] -> IO ()
setWatch (P _ u w _) wl = void $ writeIORef w wl >> tryPutMVar u ()
-- pollInit is the state when we don't have any active watches.
pollInit :: P -> IO ()
pollInit p = takeMVar (p_sigup p) >> updateWatchList p M.empty
-- if we receive a watch-list update, we'll need to adjust the
-- memory and polling effort.
updateWatchList :: P -> PMem -> IO ()
updateWatchList p m =
readIORef (p_watch p) >>= \ wl ->
if (null wl) then pollInit p else
pollCycle p (pollMemTransfer wl m)
-- pollMemTransfer will keep information on paths in the original
-- map after a change in the watchlist.
pollMemTransfer :: [FilePath] -> PMem -> PMem
pollMemTransfer wl mOrig = foldl addPath M.empty wl where
addPath m dir =
case M.lookup dir mOrig of
Nothing -> M.insert dir Nothing m
Just x -> M.insert dir x m
-- the main polling cycle
pollCycle :: P -> PMem -> IO ()
pollCycle p oldMem =
tryTakeMVar (p_sigup p) >>= \ mbu ->
case mbu of
Just () -> updateWatchList p oldMem
Nothing -> do
tNow <- getTime
newMem <- mainPollingAction tNow p oldMem
threadDelay (dtToUsec (p_dtPoll p))
pollCycle p newMem
dtToUsec :: DT -> Int
dtToUsec = fromIntegral . (`div` 1000) . dtToNanos
expectedError :: IOE.IOError -> Bool
expectedError ioe =
IOE.isDoesNotExistError ioe ||
IOE.isPermissionError ioe
printError :: FilePath -> IOE.IOError -> IO ()
printError d ioe = traceIO ("error @ " ++ show d ++ ": " ++ show ioe)
-- obtain a FilePath-sorted list of file records.
listDirectory :: FilePath -> IO [FileRec]
listDirectory dir = happyPath `E.catch` sadPath where
sadPath ioe =
unless (expectedError ioe) (printError dir ioe) >>
return []
happyPath = do
dl <- sort `fmap` FS.listDirectory dir
dlRec <- mapM pathToRecord dl
return (catMaybes dlRec)
-- pathToRecord will return Nothing if there is any exception.
-- The input path should already be canonicalized.
pathToRecord :: FilePath -> IO (Maybe FileRec)
pathToRecord path = happyPath `E.catch` sadPath where
sadPath ioe = printError path ioe >> return Nothing
happyPath = do
bDir <- FS.isDirectory path
tMod <- fromUTC `fmap` FS.getModified path
return $ Just (FileRec path bDir tMod)
mainPollingAction :: T -> P -> PMem -> IO PMem
mainPollingAction tNow p = M.traverseWithKey dirAction where
dirAction dir Nothing = do
dlExists <- listDirectory dir
let tY = tNow `subtractTime` dtYoung
let dly = filter ((> tY) . fr_mod) dlExists
p_action p (map (existsEvent dir) dly)
return (Just dlExists)
dirAction dir (Just dlOld) = do
dlNew <- listDirectory dir
let evs = diffEvents dir tNow dlOld dlNew
p_action p evs
return (Just dlNew)
-- diff of two sorted lists. The given tNow is necessary for file
-- removal events.
diffEvents :: FilePath -> T -> [FileRec] -> [FileRec] -> [Event]
diffEvents d _ [] newFiles = map (existsEvent d) newFiles
diffEvents d t oldFiles [] = map (removedEvent d t) oldFiles
diffEvents d t os@(o:os') ns@(n:ns') =
case (compare `on` fr_path) o n of
LT -> removedEvent d t o : diffEvents d t os' ns
GT -> existsEvent d n : diffEvents d t os ns'
EQ -> let rest = diffEvents d t os' ns' in
if (fr_isdir o /= fr_isdir n)
then let tRem = fr_mod n `subtractTime` 0.01 in
removedEvent d tRem o : existsEvent d n : rest
else if (fr_mod n /= fr_mod o)
then existsEvent d n : rest
else rest
existsEvent :: FilePath -> FileRec -> Event
existsEvent dir (FileRec p d tMod) = Event True dir p d tMod
removedEvent :: FilePath -> T -> FileRec -> Event
removedEvent dir tNow (FileRec p d _) = Event False dir p d tNow
|
dmbarbour/Sirea
|
sirea-filesystem/src/Sirea/Filesystem/Polling.hs
|
bsd-3-clause
| 6,083
| 0
| 16
| 1,512
| 1,711
| 887
| 824
| 129
| 5
|
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Eval where
import Control.Monad.IO.Class (MonadIO, liftIO)
import qualified Data.Map as Map
import Data.Monoid ((<>))
import qualified Data.Text as T
import Model
import Job
type JobThunk = Either WorkerProfile JobResult
countRemotes :: Map.Map T.Text (Expr a) -> Expr a -> Int
countRemotes env e = case e of
ELit _ _ -> 0
EVar _ varName -> maybe 0 (countRemotes env) (Map.lookup varName env)
ELambda _ _ b -> countRemotes env b
ERemote _ _ -> 1
EApp _ f a -> countRemotes env f + countRemotes env a
EPrim1 _ _ e -> countRemotes env e
EPrim2 _ _ a b -> countRemotes env a + countRemotes env b
-- evalStepSimple :: MonadIO m
-- => ((WorkerProfileId, WorkerProfile, T.Text) -> m (Either T.Text (Expr a)))
-- -> Map.Map T.Text (Expr a)
-- -> Expr a
-- -> m (Either T.Text (Map.Map T.Text (Expr a), Expr a))
-- evalStepSimple runRemote env e = case e of
-- l@(ELit _ _) -> return (Right (env, l))
-- EVar _ vName ->
-- maybe (return $ Left $ "No variable found named " <> vName)
-- (\e -> return $ Right (env,e))
-- (Map.lookup vName env)
-- lam@(ELambda _ _ _) -> return (Right (env, lam))
-- ERemote _ r -> do
-- v <- runRemote r
-- case v of
-- Left e -> return $ Left $ "Error running remote worker: " <> e
-- Right exp' -> return $ Right (env, exp')
-- EApp (ELambda _ pName bod) a = substitute pName a bod
-- EPrim1 _ prim a = case a of
-- ELit v -> return $ Right (env, evalPrim1 prim v)
-- (map "label" "getListOfPictures")
-- evalStep :: Map.Map T.Text (Expr JobThunk)
-- -> Expr JobThunk
-- -> (Map.Map T.Text (Expr JobThunk), Either [WorkerProfile] (Expr JobThunk))
-- evalStep env expr = case expr of
-- EVar _ varName = note ("Undefined value: " <> varName) (Map.lookup varName env)
-- ELit _ l = Right $ l
-- ELambda a n bod = Right $ ELambda a n bod -- No progress to be made
-- ERemote t = case t of
-- Left j
|
CBMM/CBaaS
|
cbaas-lib/src/Eval.hs
|
bsd-3-clause
| 2,135
| 0
| 11
| 576
| 290
| 165
| 125
| 20
| 7
|
module Control.Distributed.Task.TaskSpawning.TaskSpawning (
processTasks, TasksExecutionResult,
fullBinarySerializationOnMaster, executeFullBinaryArg, executionWithinSlaveProcessForFullBinaryDeployment,
serializedThunkSerializationOnMaster, executeSerializedThunkArg, executionWithinSlaveProcessForThunkSerialization,
objectCodeSerializationOnMaster
) where
import qualified Data.ByteString.Lazy as BL
import Data.List (intersperse)
import qualified Control.Distributed.Task.TaskSpawning.BinaryStorage as RemoteStore
import qualified Control.Distributed.Task.TaskSpawning.DeployFullBinary as DFB
import qualified Control.Distributed.Task.TaskSpawning.DeploySerializedThunk as DST
import qualified Control.Distributed.Task.TaskSpawning.DeployObjectCodeRelinked as DOC
import Control.Distributed.Task.TaskSpawning.FunctionSerialization (serializeFunction, deserializeFunction)
import Control.Distributed.Task.TaskSpawning.SourceCodeExecution (processSourceCodeTasks)
import Control.Distributed.Task.TaskSpawning.TaskDefinition
import Control.Distributed.Task.TaskSpawning.TaskDescription
import Control.Distributed.Task.TaskSpawning.TaskSpawningTypes
import Control.Distributed.Task.Types.TaskTypes
import Control.Distributed.Task.Util.ErrorHandling
import Control.Distributed.Task.Util.Logging
executeFullBinaryArg, executeSerializedThunkArg :: String
executeFullBinaryArg = "executefullbinary"
executeSerializedThunkArg = "executeserializedthunk"
type TasksExecutionResult = DFB.ExternalExecutionResult
{-|
Apply the task on the data, producing either a location, where the results are stored, or the results directly.
Which of those depends on the distribution type, when external programs are spawned the former can be more efficient,
but if there is no such intermediate step, a direct result is better.
|-}
processTasks :: TaskDef -> [DataDef] -> ResultDef -> IO TasksExecutionResult
-- source code distribution behaves a bit different and only supports collectonmaster
processTasks (SourceCodeModule moduleName moduleContent) dataDefs _ = processSourceCodeTasks moduleName moduleContent dataDefs
processTasks taskDef dataDefs resultDef = do
logInfo $ "spawning task for: "++(concat $ intersperse ", " $ map describe dataDefs)
spawnExternalTask taskDef dataDefs resultDef
spawnExternalTask :: TaskDef -> [DataDef] -> ResultDef -> IO DFB.ExternalExecutionResult
spawnExternalTask (SourceCodeModule _ _) _ _ = error "source code distribution is handled differently"
-- Full binary deployment step 2/3: run within slave process to deploy the distributed task binary
spawnExternalTask (DeployFullBinary program) dataDefs resultDef =
DFB.deployAndRunFullBinary executeFullBinaryArg (IOHandling dataDefs resultDef) program
spawnExternalTask (PreparedDeployFullBinary hash) dataDefs resultDef = do
filePath_ <- RemoteStore.get hash
maybe (error $ "no such program: "++show hash) (DFB.runExternalBinary [executeFullBinaryArg] (IOHandling dataDefs resultDef)) filePath_
-- Serialized thunk deployment step 2/3: run within slave process to deploy the distributed task binary
spawnExternalTask (UnevaluatedThunk function program) dataDefs resultDef =
DST.deployAndRunSerializedThunk executeSerializedThunkArg function (IOHandling dataDefs resultDef) program
-- Partial binary deployment step 2/2: receive distribution on slave, link object file and spawn slave process, read its output,
-- the third step (accepting runtime arguments) is linked into the task executable (see RemoteExecutor)
spawnExternalTask (ObjectCodeModule objectCode) dataDefs resultDef =
DOC.deployAndRunObjectCodeRelinked objectCode (IOHandling dataDefs resultDef)
-- Full binary deployment step 1/3
fullBinarySerializationOnMaster :: FilePath -> IO TaskDef
fullBinarySerializationOnMaster programPath = do
currentExecutable <- BL.readFile programPath
return $ DeployFullBinary currentExecutable
-- Serialized thunk deployment step 1/3: run within the client/master process to serialize itself.
serializedThunkSerializationOnMaster :: FilePath -> (TaskInput -> TaskResult) -> IO TaskDef
serializedThunkSerializationOnMaster programPath function = do
program <- BL.readFile programPath -- TODO ByteString serialization should be contained within DST module
taskFn <- serializeFunction function
return $ UnevaluatedThunk taskFn program
-- Full binary deployment step 3/3: run within the spawned process for the distributed executable, applies data to distributed task.
executionWithinSlaveProcessForFullBinaryDeployment :: IOHandling -> (TaskInput -> TaskResult) -> IO ()
executionWithinSlaveProcessForFullBinaryDeployment = DFB.fullBinaryExecution
-- Serialized thunk deployment step 3/3: run within the spawned process for the distributed executable, applies data to distributed task.
executionWithinSlaveProcessForThunkSerialization :: IOHandling -> String -> IO ()
executionWithinSlaveProcessForThunkSerialization ioHandling taskFnArg = do
taskFn <- withErrorAction logError ("Could not read task logic: " ++(show taskFnArg)) $ return $ (read taskFnArg :: BL.ByteString)
logInfo "slave: deserializing task logic"
logDebug $ "slave: got this task function: " ++ (show taskFn)
function <- deserializeFunction taskFn :: IO (TaskInput -> TaskResult)
serializeFunction function >>= \s -> logDebug $ "task deserialization done for: " ++ (show $ BL.unpack s)
DST.serializedThunkExecution ioHandling function
-- Partial binary deployment step 1/2: start distribution of task on master
objectCodeSerializationOnMaster :: IO TaskDef
objectCodeSerializationOnMaster = DOC.loadObjectCode >>= \objectCode -> return $ ObjectCodeModule objectCode
|
michaxm/task-distribution
|
src/Control/Distributed/Task/TaskSpawning/TaskSpawning.hs
|
bsd-3-clause
| 5,665
| 0
| 14
| 635
| 882
| 481
| 401
| 60
| 1
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ExtendedDefaultRules #-}
module Lucid.Foundation.Content.Dropdown where
import Lucid.Base
import Lucid.Html5
import qualified Data.Text as T
import Data.Monoid
data_dropdown_ :: T.Text -> Attribute
data_dropdown_ = data_ "dropdown"
f_dropdown_ :: T.Text
f_dropdown_ = " f-dropdown "
data_dropdown_content_ :: Attribute
data_dropdown_content_ = data_ "dropdown-content" ""
|
athanclark/lucid-foundation
|
src/Lucid/Foundation/Content/Dropdown.hs
|
bsd-3-clause
| 429
| 0
| 6
| 56
| 79
| 48
| 31
| 13
| 1
|
module Network.CrawlChain.Crawling (
crawl,
crawlAndStore, CrawlActionDescriber,
Crawler
) where
import qualified Data.ByteString.Char8 as BC
import qualified Network.Http.Client as C
import Network.CrawlChain.CrawlAction
import Network.CrawlChain.CrawlResult
import Network.CrawlChain.Util
import Network.Http.ClientFacade
type Crawler = CrawlAction -> IO CrawlResult
type CrawlActionDescriber = CrawlAction -> String
{-|
Processes one step of a crawl chain: does the actual loading.
-}
crawl :: Crawler
crawl action = delaySeconds 1 >> crawlInternal action
{-|
Used for preparation of integration tests: additionally stores the crawl result
using the given file name strategy.
-}
crawlAndStore :: CrawlActionDescriber -> Crawler
crawlAndStore describer = (>>= store) . crawl
where
store :: CrawlResult -> IO CrawlResult
store cr = store' (crawlingResultStatus cr)
where
store' CrawlingOk = storeResult (crawlingContent cr)
store' (CrawlingFailed msg) = storeResult msg
store' status = error $ "unexpected status: " ++ (show status)
storeResult filecontent'= do
writeFile' (describer $ crawlingAction cr) filecontent'
return cr
where
writeFile' n c = do
putStrLn $ "writing to " ++ n
writeFile n c
crawlInternal :: CrawlAction -> IO CrawlResult
crawlInternal action = do
-- print request
response <- doRequest action
-- print response
logMsg $ "Crawled " ++ (show action)
return $ CrawlResult action (BC.unpack response) CrawlingOk
where
doRequest :: CrawlAction -> IO (BC.ByteString)
doRequest (GetRequest url) = getRequest (BC.pack url)
doRequest (PostRequest urlString ps pType) = doPost (BC.pack urlString) formParams pType where
formParams = map (\(a, b) -> (BC.pack a, BC.pack b)) ps
doPost :: BC.ByteString -> [(BC.ByteString, BC.ByteString)] -> PostType -> IO BC.ByteString
doPost url params postType = doPost' postType where
doPost' :: PostType -> IO BC.ByteString
doPost' Undefined = doPost' PostForm
doPost' PostForm = C.postForm url params C.concatHandler
doPost' PostAJAX = ajaxRequest url params
|
michaxm/crawlchain
|
src/Network/CrawlChain/Crawling.hs
|
bsd-3-clause
| 2,251
| 0
| 14
| 513
| 589
| 305
| 284
| 42
| 4
|
{-
(c) The University of Glasgow 2006
(c) The GRASP/AQUA Project, Glasgow University, 1992-1998
The @TyCon@ datatype
-}
{-# LANGUAGE CPP, DeriveDataTypeable #-}
module TyCon(
-- * Main TyCon data types
TyCon,
AlgTyConRhs(..), visibleDataCons,
AlgTyConFlav(..), isNoParent,
FamTyConFlav(..), Role(..), Injectivity(..),
-- ** Field labels
tyConFieldLabels, tyConFieldLabelEnv,
-- ** Constructing TyCons
mkAlgTyCon,
mkClassTyCon,
mkFunTyCon,
mkPrimTyCon,
mkKindTyCon,
mkLiftedPrimTyCon,
mkTupleTyCon,
mkSynonymTyCon,
mkFamilyTyCon,
mkPromotedDataCon,
mkTcTyCon,
-- ** Predicates on TyCons
isAlgTyCon, isVanillaAlgTyCon,
isClassTyCon, isFamInstTyCon,
isFunTyCon,
isPrimTyCon,
isTupleTyCon, isUnboxedTupleTyCon, isBoxedTupleTyCon,
isTypeSynonymTyCon,
mightBeUnsaturatedTyCon,
isPromotedDataCon, isPromotedDataCon_maybe,
isKindTyCon, isLiftedTypeKindTyConName,
isDataTyCon, isProductTyCon, isDataProductTyCon_maybe,
isEnumerationTyCon,
isNewTyCon, isAbstractTyCon,
isFamilyTyCon, isOpenFamilyTyCon,
isTypeFamilyTyCon, isDataFamilyTyCon,
isOpenTypeFamilyTyCon, isClosedSynFamilyTyConWithAxiom_maybe,
familyTyConInjectivityInfo,
isBuiltInSynFamTyCon_maybe,
isUnliftedTyCon,
isGadtSyntaxTyCon, isInjectiveTyCon, isGenerativeTyCon, isGenInjAlgRhs,
isTyConAssoc, tyConAssoc_maybe,
isRecursiveTyCon,
isImplicitTyCon,
isTyConWithSrcDataCons,
isTcTyCon,
-- ** Extracting information out of TyCons
tyConName,
tyConKind,
tyConUnique,
tyConTyVars,
tyConCType, tyConCType_maybe,
tyConDataCons, tyConDataCons_maybe,
tyConSingleDataCon_maybe, tyConSingleDataCon,
tyConSingleAlgDataCon_maybe,
tyConFamilySize,
tyConStupidTheta,
tyConArity,
tyConRoles,
tyConFlavour,
tyConTuple_maybe, tyConClass_maybe, tyConATs,
tyConFamInst_maybe, tyConFamInstSig_maybe, tyConFamilyCoercion_maybe,
tyConFamilyResVar_maybe,
synTyConDefn_maybe, synTyConRhs_maybe,
famTyConFlav_maybe, famTcResVar,
algTyConRhs,
newTyConRhs, newTyConEtadArity, newTyConEtadRhs,
unwrapNewTyCon_maybe, unwrapNewTyConEtad_maybe,
algTcFields,
-- ** Manipulating TyCons
expandSynTyCon_maybe,
makeTyConAbstract,
newTyConCo, newTyConCo_maybe,
pprPromotionQuote,
-- * Runtime type representation
TyConRepName, tyConRepName_maybe,
mkPrelTyConRepName,
tyConRepModOcc,
-- * Primitive representations of Types
PrimRep(..), PrimElemRep(..),
tyConPrimRep, isVoidRep, isGcPtrRep,
primRepSizeW, primElemRepSizeB,
primRepIsFloat,
-- * Recursion breaking
RecTcChecker, initRecTc, checkRecTc
) where
#include "HsVersions.h"
import {-# SOURCE #-} TyCoRep ( Kind, Type, PredType )
import {-# SOURCE #-} DataCon ( DataCon, dataConExTyVars, dataConFieldLabels )
import Binary
import Var
import Class
import BasicTypes
import DynFlags
import ForeignCall
import Name
import NameEnv
import CoAxiom
import PrelNames
import Maybes
import Outputable
import FastStringEnv
import FieldLabel
import Constants
import Util
import Unique( tyConRepNameUnique, dataConRepNameUnique )
import Module
import qualified Data.Data as Data
import Data.Typeable (Typeable)
{-
-----------------------------------------------
Notes about type families
-----------------------------------------------
Note [Type synonym families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Type synonym families, also known as "type functions", map directly
onto the type functions in FC:
type family F a :: *
type instance F Int = Bool
..etc...
* Reply "yes" to isTypeFamilyTyCon, and isFamilyTyCon
* From the user's point of view (F Int) and Bool are simply
equivalent types.
* A Haskell 98 type synonym is a degenerate form of a type synonym
family.
* Type functions can't appear in the LHS of a type function:
type instance F (F Int) = ... -- BAD!
* Translation of type family decl:
type family F a :: *
translates to
a FamilyTyCon 'F', whose FamTyConFlav is OpenSynFamilyTyCon
type family G a :: * where
G Int = Bool
G Bool = Char
G a = ()
translates to
a FamilyTyCon 'G', whose FamTyConFlav is ClosedSynFamilyTyCon, with the
appropriate CoAxiom representing the equations
We also support injective type families -- see Note [Injective type families]
Note [Data type families]
~~~~~~~~~~~~~~~~~~~~~~~~~
See also Note [Wrappers for data instance tycons] in MkId.hs
* Data type families are declared thus
data family T a :: *
data instance T Int = T1 | T2 Bool
Here T is the "family TyCon".
* Reply "yes" to isDataFamilyTyCon, and isFamilyTyCon
* The user does not see any "equivalent types" as he did with type
synonym families. He just sees constructors with types
T1 :: T Int
T2 :: Bool -> T Int
* Here's the FC version of the above declarations:
data T a
data R:TInt = T1 | T2 Bool
axiom ax_ti : T Int ~R R:TInt
Note that this is a *representational* coercion
The R:TInt is the "representation TyCons".
It has an AlgTyConFlav of
DataFamInstTyCon T [Int] ax_ti
* The axiom ax_ti may be eta-reduced; see
Note [Eta reduction for data family axioms] in TcInstDcls
* The data contructor T2 has a wrapper (which is what the
source-level "T2" invokes):
$WT2 :: Bool -> T Int
$WT2 b = T2 b `cast` sym ax_ti
* A data instance can declare a fully-fledged GADT:
data instance T (a,b) where
X1 :: T (Int,Bool)
X2 :: a -> b -> T (a,b)
Here's the FC version of the above declaration:
data R:TPair a where
X1 :: R:TPair Int Bool
X2 :: a -> b -> R:TPair a b
axiom ax_pr :: T (a,b) ~R R:TPair a b
$WX1 :: forall a b. a -> b -> T (a,b)
$WX1 a b (x::a) (y::b) = X2 a b x y `cast` sym (ax_pr a b)
The R:TPair are the "representation TyCons".
We have a bit of work to do, to unpick the result types of the
data instance declaration for T (a,b), to get the result type in the
representation; e.g. T (a,b) --> R:TPair a b
The representation TyCon R:TList, has an AlgTyConFlav of
DataFamInstTyCon T [(a,b)] ax_pr
* Notice that T is NOT translated to a FC type function; it just
becomes a "data type" with no constructors, which can be coerced inot
into R:TInt, R:TPair by the axioms. These axioms
axioms come into play when (and *only* when) you
- use a data constructor
- do pattern matching
Rather like newtype, in fact
As a result
- T behaves just like a data type so far as decomposition is concerned
- (T Int) is not implicitly converted to R:TInt during type inference.
Indeed the latter type is unknown to the programmer.
- There *is* an instance for (T Int) in the type-family instance
environment, but it is only used for overlap checking
- It's fine to have T in the LHS of a type function:
type instance F (T a) = [a]
It was this last point that confused me! The big thing is that you
should not think of a data family T as a *type function* at all, not
even an injective one! We can't allow even injective type functions
on the LHS of a type function:
type family injective G a :: *
type instance F (G Int) = Bool
is no good, even if G is injective, because consider
type instance G Int = Bool
type instance F Bool = Char
So a data type family is not an injective type function. It's just a
data type with some axioms that connect it to other data types.
* The tyConTyVars of the representation tycon are the tyvars that the
user wrote in the patterns. This is important in TcDeriv, where we
bring these tyvars into scope before type-checking the deriving
clause. This fact is arranged for in TcInstDecls.tcDataFamInstDecl.
Note [Associated families and their parent class]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*Associated* families are just like *non-associated* families, except
that they have a famTcParent field of (Just cls), which identifies the
parent class.
However there is an important sharing relationship between
* the tyConTyVars of the parent Class
* the tyConTyvars of the associated TyCon
class C a b where
data T p a
type F a q b
Here the 'a' and 'b' are shared with the 'Class'; that is, they have
the same Unique.
This is important. In an instance declaration we expect
* all the shared variables to be instantiated the same way
* the non-shared variables of the associated type should not
be instantiated at all
instance C [x] (Tree y) where
data T p [x] = T1 x | T2 p
type F [x] q (Tree y) = (x,y,q)
Note [TyCon Role signatures]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Every tycon has a role signature, assigning a role to each of the tyConTyVars
(or of equal length to the tyConArity, if there are no tyConTyVars). An
example demonstrates these best: say we have a tycon T, with parameters a at
nominal, b at representational, and c at phantom. Then, to prove
representational equality between T a1 b1 c1 and T a2 b2 c2, we need to have
nominal equality between a1 and a2, representational equality between b1 and
b2, and nothing in particular (i.e., phantom equality) between c1 and c2. This
might happen, say, with the following declaration:
data T a b c where
MkT :: b -> T Int b c
Data and class tycons have their roles inferred (see inferRoles in TcTyDecls),
as do vanilla synonym tycons. Family tycons have all parameters at role N,
though it is conceivable that we could relax this restriction. (->)'s and
tuples' parameters are at role R. Each primitive tycon declares its roles;
it's worth noting that (~#)'s parameters are at role N. Promoted data
constructors' type arguments are at role R. All kind arguments are at role
N.
Note [Unboxed tuple levity vars]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The contents of an unboxed tuple may be boxed or unboxed. Accordingly,
the kind of the unboxed tuple constructor is sort-polymorphic. For example,
(#,#) :: forall (v :: Levity) (w :: Levity). TYPE v -> TYPE w -> #
These extra tyvars (v and w) cause some delicate processing around tuples,
where we used to be able to assume that the tycon arity and the
datacon arity were the same.
Note [Injective type families]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We allow injectivity annotations for type families (both open and closed):
type family F (a :: k) (b :: k) = r | r -> a
type family G a b = res | res -> a b where ...
Injectivity information is stored in the `famTcInj` field of `FamilyTyCon`.
`famTcInj` maybe stores a list of Bools, where each entry corresponds to a
single element of `tyConTyVars` (both lists should have identical length). If no
injectivity annotation was provided `famTcInj` is Nothing. From this follows an
invariant that if `famTcInj` is a Just then at least one element in the list
must be True.
See also:
* [Injectivity annotation] in HsDecls
* [Renaming injectivity annotation] in RnSource
* [Verifying injectivity annotation] in FamInstEnv
* [Type inference for type families with injectivity] in TcInteract
************************************************************************
* *
\subsection{The data type}
* *
************************************************************************
-}
-- | TyCons represent type constructors. Type constructors are introduced by
-- things such as:
--
-- 1) Data declarations: @data Foo = ...@ creates the @Foo@ type constructor of
-- kind @*@
--
-- 2) Type synonyms: @type Foo = ...@ creates the @Foo@ type constructor
--
-- 3) Newtypes: @newtype Foo a = MkFoo ...@ creates the @Foo@ type constructor
-- of kind @* -> *@
--
-- 4) Class declarations: @class Foo where@ creates the @Foo@ type constructor
-- of kind @*@
--
-- This data type also encodes a number of primitive, built in type constructors
-- such as those for function and tuple types.
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data TyCon
= -- | The function type constructor, @(->)@
FunTyCon {
tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
-- identical to Unique of Name stored in
-- tyConName field.
tyConName :: Name, -- ^ Name of the constructor
tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just
-- the return kind)
tyConArity :: Arity, -- ^ Number of arguments this TyCon must
-- receive to be considered saturated
-- (including implicit kind variables)
tcRepName :: TyConRepName
}
-- | Algebraic data types, from
-- - @data@ declararations
-- - @newtype@ declarations
-- - data instance declarations
-- - type instance declarations
-- - the TyCon generated by a class declaration
-- - boxed tuples
-- - unboxed tuples
-- - constraint tuples
-- All these constructors are lifted and boxed except unboxed tuples
-- which should have an 'UnboxedAlgTyCon' parent.
-- Data/newtype/type /families/ are handled by 'FamilyTyCon'.
-- See 'AlgTyConRhs' for more information.
| AlgTyCon {
tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
-- identical to Unique of Name stored in
-- tyConName field.
tyConName :: Name, -- ^ Name of the constructor
tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just
-- the return kind)
tyConArity :: Arity, -- ^ Number of arguments this TyCon must
-- receive to be considered saturated
-- (including implicit kind variables)
tyConTyVars :: [TyVar], -- ^ The kind and type variables used in the
-- type constructor.
-- Invariant: length tyvars = arity
-- Precisely, this list scopes over:
--
-- 1. The 'algTcStupidTheta'
-- 2. The cached types in algTyConRhs.NewTyCon
-- 3. The family instance types if present
--
-- Note that it does /not/ scope over the data
-- constructors.
tcRoles :: [Role], -- ^ The role for each type variable
-- This list has the same length as tyConTyVars
-- See also Note [TyCon Role signatures]
tyConCType :: Maybe CType,-- ^ The C type that should be used
-- for this type when using the FFI
-- and CAPI
algTcGadtSyntax :: Bool, -- ^ Was the data type declared with GADT
-- syntax? If so, that doesn't mean it's a
-- true GADT; only that the "where" form
-- was used. This field is used only to
-- guide pretty-printing
algTcStupidTheta :: [PredType], -- ^ The \"stupid theta\" for the data
-- type (always empty for GADTs). A
-- \"stupid theta\" is the context to
-- the left of an algebraic type
-- declaration, e.g. @Eq a@ in the
-- declaration @data Eq a => T a ...@.
algTcRhs :: AlgTyConRhs, -- ^ Contains information about the
-- data constructors of the algebraic type
algTcFields :: FieldLabelEnv, -- ^ Maps a label to information
-- about the field
algTcRec :: RecFlag, -- ^ Tells us whether the data type is part
-- of a mutually-recursive group or not
algTcParent :: AlgTyConFlav -- ^ Gives the class or family declaration
-- 'TyCon' for derived 'TyCon's representing
-- class or family instances, respectively.
}
-- | Represents type synonyms
| SynonymTyCon {
tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
-- identical to Unique of Name stored in
-- tyConName field.
tyConName :: Name, -- ^ Name of the constructor
tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just
-- the return kind)
tyConArity :: Arity, -- ^ Number of arguments this TyCon must
-- receive to be considered saturated
-- (including implicit kind variables)
tyConTyVars :: [TyVar], -- ^ List of type and kind variables in this
-- TyCon. Includes implicit kind variables.
-- Invariant: length tyConTyVars = tyConArity
tcRoles :: [Role], -- ^ The role for each type variable
-- This list has the same length as tyConTyVars
-- See also Note [TyCon Role signatures]
synTcRhs :: Type -- ^ Contains information about the expansion
-- of the synonym
}
-- | Represents families (both type and data)
-- Argument roles are all Nominal
| FamilyTyCon {
tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
-- identical to Unique of Name stored in
-- tyConName field.
tyConName :: Name, -- ^ Name of the constructor
tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just
-- the return kind)
tyConArity :: Arity, -- ^ Number of arguments this TyCon must
-- receive to be considered saturated
-- (including implicit kind variables)
tyConTyVars :: [TyVar], -- ^ The kind and type variables used in the
-- type constructor.
-- Invariant: length tyvars = arity
-- Precisely, this list scopes over:
--
-- 1. The 'algTcStupidTheta'
-- 2. The cached types in 'algTyConRhs.NewTyCon'
-- 3. The family instance types if present
--
-- Note that it does /not/ scope over the data
-- constructors.
famTcResVar :: Maybe Name, -- ^ Name of result type variable, used
-- for pretty-printing with --show-iface
-- and for reifying TyCon in Template
-- Haskell
famTcFlav :: FamTyConFlav, -- ^ Type family flavour: open, closed,
-- abstract, built-in. See comments for
-- FamTyConFlav
famTcParent :: Maybe Class, -- ^ For *associated* type/data families
-- The class in whose declaration the family is declared
-- See Note [Associated families and their parent class]
famTcInj :: Injectivity -- ^ is this a type family injective in
-- its type variables? Nothing if no
-- injectivity annotation was given
}
-- | Primitive types; cannot be defined in Haskell. This includes
-- the usual suspects (such as @Int#@) as well as foreign-imported
-- types and kinds (@*@, @#@, and @?@)
| PrimTyCon {
tyConUnique :: Unique, -- ^ A Unique of this TyCon. Invariant:
-- identical to Unique of Name stored in
-- tyConName field.
tyConName :: Name, -- ^ Name of the constructor
tyConKind :: Kind, -- ^ Kind of this TyCon (full kind, not just
-- the return kind)
tyConArity :: Arity, -- ^ Number of arguments this TyCon must
-- receive to be considered saturated
-- (including implicit kind variables)
tcRoles :: [Role], -- ^ The role for each type variable
-- This list has the same length as tyConTyVars
-- See also Note [TyCon Role signatures]
primTyConRep :: PrimRep,-- ^ Many primitive tycons are unboxed, but
-- some are boxed (represented by
-- pointers). This 'PrimRep' holds that
-- information. Only relevant if tyConKind = #
isUnlifted :: Bool, -- ^ Most primitive tycons are unlifted (may
-- not contain bottom) but other are lifted,
-- e.g. @RealWorld@
-- Only relevant if tyConKind = *
primRepName :: Maybe TyConRepName -- Only relevant for kind TyCons
-- i.e, *, #, ?
}
-- | Represents promoted data constructor.
| PromotedDataCon { -- See Note [Promoted data constructors]
tyConUnique :: Unique, -- ^ Same Unique as the data constructor
tyConName :: Name, -- ^ Same Name as the data constructor
tyConArity :: Arity,
tyConKind :: Kind, -- ^ Translated type of the data constructor
tcRoles :: [Role], -- ^ Roles: N for kind vars, R for type vars
dataCon :: DataCon,-- ^ Corresponding data constructor
tcRepName :: TyConRepName
}
-- | These exist only during a recursive type/class type-checking knot.
| TcTyCon {
tyConUnique :: Unique,
tyConName :: Name,
tyConKind :: Kind
}
deriving Typeable
-- | Represents right-hand-sides of 'TyCon's for algebraic types
data AlgTyConRhs
-- | Says that we know nothing about this data type, except that
-- it's represented by a pointer. Used when we export a data type
-- abstractly into an .hi file.
= AbstractTyCon
Bool -- True <=> It's definitely a distinct data type,
-- equal only to itself; ie not a newtype
-- False <=> Not sure
-- | Information about those 'TyCon's derived from a @data@
-- declaration. This includes data types with no constructors at
-- all.
| DataTyCon {
data_cons :: [DataCon],
-- ^ The data type constructors; can be empty if the
-- user declares the type to have no constructors
--
-- INVARIANT: Kept in order of increasing 'DataCon'
-- tag (see the tag assignment in DataCon.mkDataCon)
is_enum :: Bool -- ^ Cached value: is this an enumeration type?
-- See Note [Enumeration types]
}
| TupleTyCon { -- A boxed, unboxed, or constraint tuple
data_con :: DataCon, -- NB: it can be an *unboxed* tuple
tup_sort :: TupleSort -- ^ Is this a boxed, unboxed or constraint
-- tuple?
}
-- | Information about those 'TyCon's derived from a @newtype@ declaration
| NewTyCon {
data_con :: DataCon, -- ^ The unique constructor for the @newtype@.
-- It has no existentials
nt_rhs :: Type, -- ^ Cached value: the argument type of the
-- constructor, which is just the representation
-- type of the 'TyCon' (remember that @newtype@s
-- do not exist at runtime so need a different
-- representation type).
--
-- The free 'TyVar's of this type are the
-- 'tyConTyVars' from the corresponding 'TyCon'
nt_etad_rhs :: ([TyVar], Type),
-- ^ Same as the 'nt_rhs', but this time eta-reduced.
-- Hence the list of 'TyVar's in this field may be
-- shorter than the declared arity of the 'TyCon'.
-- See Note [Newtype eta]
nt_co :: CoAxiom Unbranched
-- The axiom coercion that creates the @newtype@
-- from the representation 'Type'.
-- See Note [Newtype coercions]
-- Invariant: arity = #tvs in nt_etad_rhs;
-- See Note [Newtype eta]
-- Watch out! If any newtypes become transparent
-- again check Trac #1072.
}
-- | Extract those 'DataCon's that we are able to learn about. Note
-- that visibility in this sense does not correspond to visibility in
-- the context of any particular user program!
visibleDataCons :: AlgTyConRhs -> [DataCon]
visibleDataCons (AbstractTyCon {}) = []
visibleDataCons (DataTyCon{ data_cons = cs }) = cs
visibleDataCons (NewTyCon{ data_con = c }) = [c]
visibleDataCons (TupleTyCon{ data_con = c }) = [c]
-- ^ Both type classes as well as family instances imply implicit
-- type constructors. These implicit type constructors refer to their parent
-- structure (ie, the class or family from which they derive) using a type of
-- the following form.
data AlgTyConFlav
= -- | An ordinary type constructor has no parent.
VanillaAlgTyCon
TyConRepName
-- | An unboxed type constructor. Note that this carries no TyConRepName
-- as it is not representable.
| UnboxedAlgTyCon
-- | Type constructors representing a class dictionary.
-- See Note [ATyCon for classes] in TyCoRep
| ClassTyCon
Class -- INVARIANT: the classTyCon of this Class is the
-- current tycon
TyConRepName
-- | Type constructors representing an *instance* of a *data* family.
-- Parameters:
--
-- 1) The type family in question
--
-- 2) Instance types; free variables are the 'tyConTyVars'
-- of the current 'TyCon' (not the family one). INVARIANT:
-- the number of types matches the arity of the family 'TyCon'
--
-- 3) A 'CoTyCon' identifying the representation
-- type with the type instance family
| DataFamInstTyCon -- See Note [Data type families]
(CoAxiom Unbranched) -- The coercion axiom.
-- A *Representational* coercion,
-- of kind T ty1 ty2 ~R R:T a b c
-- where T is the family TyCon,
-- and R:T is the representation TyCon (ie this one)
-- and a,b,c are the tyConTyVars of this TyCon
--
-- BUT may be eta-reduced; see TcInstDcls
-- Note [Eta reduction for data family axioms]
-- Cached fields of the CoAxiom, but adjusted to
-- use the tyConTyVars of this TyCon
TyCon -- The family TyCon
[Type] -- Argument types (mentions the tyConTyVars of this TyCon)
-- Match in length the tyConTyVars of the family TyCon
-- E.g. data intance T [a] = ...
-- gives a representation tycon:
-- data R:TList a = ...
-- axiom co a :: T [a] ~ R:TList a
-- with R:TList's algTcParent = DataFamInstTyCon T [a] co
instance Outputable AlgTyConFlav where
ppr (VanillaAlgTyCon {}) = text "Vanilla ADT"
ppr (UnboxedAlgTyCon {}) = text "Unboxed ADT"
ppr (ClassTyCon cls _) = text "Class parent" <+> ppr cls
ppr (DataFamInstTyCon _ tc tys) =
text "Family parent (family instance)" <+> ppr tc <+> sep (map ppr tys)
-- | Checks the invariants of a 'AlgTyConFlav' given the appropriate type class
-- name, if any
okParent :: Name -> AlgTyConFlav -> Bool
okParent _ (VanillaAlgTyCon {}) = True
okParent _ (UnboxedAlgTyCon) = True
okParent tc_name (ClassTyCon cls _) = tc_name == tyConName (classTyCon cls)
okParent _ (DataFamInstTyCon _ fam_tc tys) = tyConArity fam_tc == length tys
isNoParent :: AlgTyConFlav -> Bool
isNoParent (VanillaAlgTyCon {}) = True
isNoParent _ = False
--------------------
data Injectivity
= NotInjective
| Injective [Bool] -- 1-1 with tyConTyVars (incl kind vars)
deriving( Eq )
-- | Information pertaining to the expansion of a type synonym (@type@)
data FamTyConFlav
= -- | Represents an open type family without a fixed right hand
-- side. Additional instances can appear at any time.
--
-- These are introduced by either a top level declaration:
--
-- > data family T a :: *
--
-- Or an associated data type declaration, within a class declaration:
--
-- > class C a b where
-- > data T b :: *
DataFamilyTyCon
TyConRepName
-- | An open type synonym family e.g. @type family F x y :: * -> *@
| OpenSynFamilyTyCon
-- | A closed type synonym family e.g.
-- @type family F x where { F Int = Bool }@
| ClosedSynFamilyTyCon (Maybe (CoAxiom Branched))
-- See Note [Closed type families]
-- | A closed type synonym family declared in an hs-boot file with
-- type family F a where ..
| AbstractClosedSynFamilyTyCon
-- | Built-in type family used by the TypeNats solver
| BuiltInSynFamTyCon BuiltInSynFamily
{-
Note [Closed type families]
~~~~~~~~~~~~~~~~~~~~~~~~~
* In an open type family you can add new instances later. This is the
usual case.
* In a closed type family you can only put equations where the family
is defined.
A non-empty closed type family has a single axiom with multiple
branches, stored in the 'ClosedSynFamilyTyCon' constructor. A closed
type family with no equations does not have an axiom, because there is
nothing for the axiom to prove!
Note [Promoted data constructors]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
All data constructors can be promoted to become a type constructor,
via the PromotedDataCon alternative in TyCon.
* The TyCon promoted from a DataCon has the *same* Name and Unique as
the DataCon. Eg. If the data constructor Data.Maybe.Just(unique 78,
say) is promoted to a TyCon whose name is Data.Maybe.Just(unique 78)
* Small note: We promote the *user* type of the DataCon. Eg
data T = MkT {-# UNPACK #-} !(Bool, Bool)
The promoted kind is
MkT :: (Bool,Bool) -> T
*not*
MkT :: Bool -> Bool -> T
Note [Enumeration types]
~~~~~~~~~~~~~~~~~~~~~~~~
We define datatypes with no constructors to *not* be
enumerations; this fixes trac #2578, Otherwise we
end up generating an empty table for
<mod>_<type>_closure_tbl
which is used by tagToEnum# to map Int# to constructors
in an enumeration. The empty table apparently upset
the linker.
Moreover, all the data constructor must be enumerations, meaning
they have type (forall abc. T a b c). GADTs are not enumerations.
For example consider
data T a where
T1 :: T Int
T2 :: T Bool
T3 :: T a
What would [T1 ..] be? [T1,T3] :: T Int? Easiest thing is to exclude them.
See Trac #4528.
Note [Newtype coercions]
~~~~~~~~~~~~~~~~~~~~~~~~
The NewTyCon field nt_co is a CoAxiom which is used for coercing from
the representation type of the newtype, to the newtype itself. For
example,
newtype T a = MkT (a -> a)
the NewTyCon for T will contain nt_co = CoT where CoT t : T t ~ t -> t.
In the case that the right hand side is a type application
ending with the same type variables as the left hand side, we
"eta-contract" the coercion. So if we had
newtype S a = MkT [a]
then we would generate the arity 0 axiom CoS : S ~ []. The
primary reason we do this is to make newtype deriving cleaner.
In the paper we'd write
axiom CoT : (forall t. T t) ~ (forall t. [t])
and then when we used CoT at a particular type, s, we'd say
CoT @ s
which encodes as (TyConApp instCoercionTyCon [TyConApp CoT [], s])
Note [Newtype eta]
~~~~~~~~~~~~~~~~~~
Consider
newtype Parser a = MkParser (IO a) deriving Monad
Are these two types equal (to Core)?
Monad Parser
Monad IO
which we need to make the derived instance for Monad Parser.
Well, yes. But to see that easily we eta-reduce the RHS type of
Parser, in this case to ([], Froogle), so that even unsaturated applications
of Parser will work right. This eta reduction is done when the type
constructor is built, and cached in NewTyCon.
Here's an example that I think showed up in practice
Source code:
newtype T a = MkT [a]
newtype Foo m = MkFoo (forall a. m a -> Int)
w1 :: Foo []
w1 = ...
w2 :: Foo T
w2 = MkFoo (\(MkT x) -> case w1 of MkFoo f -> f x)
After desugaring, and discarding the data constructors for the newtypes,
we get:
w2 = w1 `cast` Foo CoT
so the coercion tycon CoT must have
kind: T ~ []
and arity: 0
************************************************************************
* *
TyConRepName
* *
********************************************************************* -}
type TyConRepName = Name -- The Name of the top-level declaration
-- $tcMaybe :: Data.Typeable.Internal.TyCon
-- $tcMaybe = TyCon { tyConName = "Maybe", ... }
tyConRepName_maybe :: TyCon -> Maybe TyConRepName
tyConRepName_maybe (FunTyCon { tcRepName = rep_nm })
= Just rep_nm
tyConRepName_maybe (PrimTyCon { primRepName = mb_rep_nm })
= mb_rep_nm
tyConRepName_maybe (AlgTyCon { algTcParent = parent })
| VanillaAlgTyCon rep_nm <- parent = Just rep_nm
| ClassTyCon _ rep_nm <- parent = Just rep_nm
tyConRepName_maybe (FamilyTyCon { famTcFlav = DataFamilyTyCon rep_nm })
= Just rep_nm
tyConRepName_maybe (PromotedDataCon { tcRepName = rep_nm })
= Just rep_nm
tyConRepName_maybe _ = Nothing
-- | Make a 'Name' for the 'Typeable' representation of the given wired-in type
mkPrelTyConRepName :: Name -> TyConRepName
-- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
mkPrelTyConRepName tc_name -- Prelude tc_name is always External,
-- so nameModule will work
= mkExternalName rep_uniq rep_mod rep_occ (nameSrcSpan tc_name)
where
name_occ = nameOccName tc_name
name_mod = nameModule tc_name
name_uniq = nameUnique tc_name
rep_uniq | isTcOcc name_occ = tyConRepNameUnique name_uniq
| otherwise = dataConRepNameUnique name_uniq
(rep_mod, rep_occ) = tyConRepModOcc name_mod name_occ
-- | The name (and defining module) for the Typeable representation (TyCon) of a
-- type constructor.
--
-- See Note [Grand plan for Typeable] in 'TcTypeable' in TcTypeable.
tyConRepModOcc :: Module -> OccName -> (Module, OccName)
tyConRepModOcc tc_module tc_occ = (rep_module, mkTyConRepOcc tc_occ)
where
rep_module
| tc_module == gHC_PRIM = gHC_TYPES
| otherwise = tc_module
{- *********************************************************************
* *
PrimRep
* *
************************************************************************
Note [rep swamp]
GHC has a rich selection of types that represent "primitive types" of
one kind or another. Each of them makes a different set of
distinctions, and mostly the differences are for good reasons,
although it's probably true that we could merge some of these.
Roughly in order of "includes more information":
- A Width (cmm/CmmType) is simply a binary value with the specified
number of bits. It may represent a signed or unsigned integer, a
floating-point value, or an address.
data Width = W8 | W16 | W32 | W64 | W80 | W128
- Size, which is used in the native code generator, is Width +
floating point information.
data Size = II8 | II16 | II32 | II64 | FF32 | FF64 | FF80
it is necessary because e.g. the instruction to move a 64-bit float
on x86 (movsd) is different from the instruction to move a 64-bit
integer (movq), so the mov instruction is parameterised by Size.
- CmmType wraps Width with more information: GC ptr, float, or
other value.
data CmmType = CmmType CmmCat Width
data CmmCat -- "Category" (not exported)
= GcPtrCat -- GC pointer
| BitsCat -- Non-pointer
| FloatCat -- Float
It is important to have GcPtr information in Cmm, since we generate
info tables containing pointerhood for the GC from this. As for
why we have float (and not signed/unsigned) here, see Note [Signed
vs unsigned].
- ArgRep makes only the distinctions necessary for the call and
return conventions of the STG machine. It is essentially CmmType
+ void.
- PrimRep makes a few more distinctions than ArgRep: it divides
non-GC-pointers into signed/unsigned and addresses, information
that is necessary for passing these values to foreign functions.
There's another tension here: whether the type encodes its size in
bytes, or whether its size depends on the machine word size. Width
and CmmType have the size built-in, whereas ArgRep and PrimRep do not.
This means to turn an ArgRep/PrimRep into a CmmType requires DynFlags.
On the other hand, CmmType includes some "nonsense" values, such as
CmmType GcPtrCat W32 on a 64-bit machine.
-}
-- | A 'PrimRep' is an abstraction of a type. It contains information that
-- the code generator needs in order to pass arguments, return results,
-- and store values of this type.
data PrimRep
= VoidRep
| PtrRep
| IntRep -- ^ Signed, word-sized value
| WordRep -- ^ Unsigned, word-sized value
| Int64Rep -- ^ Signed, 64 bit value (with 32-bit words only)
| Word64Rep -- ^ Unsigned, 64 bit value (with 32-bit words only)
| AddrRep -- ^ A pointer, but /not/ to a Haskell value (use 'PtrRep')
| FloatRep
| DoubleRep
| VecRep Int PrimElemRep -- ^ A vector
deriving( Eq, Show )
data PrimElemRep
= Int8ElemRep
| Int16ElemRep
| Int32ElemRep
| Int64ElemRep
| Word8ElemRep
| Word16ElemRep
| Word32ElemRep
| Word64ElemRep
| FloatElemRep
| DoubleElemRep
deriving( Eq, Show )
instance Outputable PrimRep where
ppr r = text (show r)
instance Outputable PrimElemRep where
ppr r = text (show r)
isVoidRep :: PrimRep -> Bool
isVoidRep VoidRep = True
isVoidRep _other = False
isGcPtrRep :: PrimRep -> Bool
isGcPtrRep PtrRep = True
isGcPtrRep _ = False
-- | Find the size of a 'PrimRep', in words
primRepSizeW :: DynFlags -> PrimRep -> Int
primRepSizeW _ IntRep = 1
primRepSizeW _ WordRep = 1
primRepSizeW dflags Int64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
primRepSizeW dflags Word64Rep = wORD64_SIZE `quot` wORD_SIZE dflags
primRepSizeW _ FloatRep = 1 -- NB. might not take a full word
primRepSizeW dflags DoubleRep = dOUBLE_SIZE dflags `quot` wORD_SIZE dflags
primRepSizeW _ AddrRep = 1
primRepSizeW _ PtrRep = 1
primRepSizeW _ VoidRep = 0
primRepSizeW dflags (VecRep len rep) = len * primElemRepSizeB rep `quot` wORD_SIZE dflags
primElemRepSizeB :: PrimElemRep -> Int
primElemRepSizeB Int8ElemRep = 1
primElemRepSizeB Int16ElemRep = 2
primElemRepSizeB Int32ElemRep = 4
primElemRepSizeB Int64ElemRep = 8
primElemRepSizeB Word8ElemRep = 1
primElemRepSizeB Word16ElemRep = 2
primElemRepSizeB Word32ElemRep = 4
primElemRepSizeB Word64ElemRep = 8
primElemRepSizeB FloatElemRep = 4
primElemRepSizeB DoubleElemRep = 8
-- | Return if Rep stands for floating type,
-- returns Nothing for vector types.
primRepIsFloat :: PrimRep -> Maybe Bool
primRepIsFloat FloatRep = Just True
primRepIsFloat DoubleRep = Just True
primRepIsFloat (VecRep _ _) = Nothing
primRepIsFloat _ = Just False
{-
************************************************************************
* *
Field labels
* *
************************************************************************
-}
-- | The labels for the fields of this particular 'TyCon'
tyConFieldLabels :: TyCon -> [FieldLabel]
tyConFieldLabels tc = fsEnvElts $ tyConFieldLabelEnv tc
-- | The labels for the fields of this particular 'TyCon'
tyConFieldLabelEnv :: TyCon -> FieldLabelEnv
tyConFieldLabelEnv tc
| isAlgTyCon tc = algTcFields tc
| otherwise = emptyFsEnv
-- | Make a map from strings to FieldLabels from all the data
-- constructors of this algebraic tycon
fieldsOfAlgTcRhs :: AlgTyConRhs -> FieldLabelEnv
fieldsOfAlgTcRhs rhs = mkFsEnv [ (flLabel fl, fl)
| fl <- dataConsFields (visibleDataCons rhs) ]
where
-- Duplicates in this list will be removed by 'mkFsEnv'
dataConsFields dcs = concatMap dataConFieldLabels dcs
{-
************************************************************************
* *
\subsection{TyCon Construction}
* *
************************************************************************
Note: the TyCon constructors all take a Kind as one argument, even though
they could, in principle, work out their Kind from their other arguments.
But to do so they need functions from Types, and that makes a nasty
module mutual-recursion. And they aren't called from many places.
So we compromise, and move their Kind calculation to the call site.
-}
-- | Given the name of the function type constructor and it's kind, create the
-- corresponding 'TyCon'. It is reccomended to use 'TyCoRep.funTyCon' if you want
-- this functionality
mkFunTyCon :: Name -> Kind -> Name -> TyCon
mkFunTyCon name kind rep_nm
= FunTyCon {
tyConUnique = nameUnique name,
tyConName = name,
tyConKind = kind,
tyConArity = 2,
tcRepName = rep_nm
}
-- | This is the making of an algebraic 'TyCon'. Notably, you have to
-- pass in the generic (in the -XGenerics sense) information about the
-- type constructor - you can get hold of it easily (see Generics
-- module)
mkAlgTyCon :: Name
-> Kind -- ^ Kind of the resulting 'TyCon'
-> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'.
-- Arity is inferred from the length of this
-- list
-> [Role] -- ^ The roles for each TyVar
-> Maybe CType -- ^ The C type this type corresponds to
-- when using the CAPI FFI
-> [PredType] -- ^ Stupid theta: see 'algTcStupidTheta'
-> AlgTyConRhs -- ^ Information about data constructors
-> AlgTyConFlav -- ^ What flavour is it?
-- (e.g. vanilla, type family)
-> RecFlag -- ^ Is the 'TyCon' recursive?
-> Bool -- ^ Was the 'TyCon' declared with GADT syntax?
-> TyCon
mkAlgTyCon name kind tyvars roles cType stupid rhs parent is_rec gadt_syn
= AlgTyCon {
tyConName = name,
tyConUnique = nameUnique name,
tyConKind = kind,
tyConArity = length tyvars,
tyConTyVars = tyvars,
tcRoles = roles,
tyConCType = cType,
algTcStupidTheta = stupid,
algTcRhs = rhs,
algTcFields = fieldsOfAlgTcRhs rhs,
algTcParent = ASSERT2( okParent name parent, ppr name $$ ppr parent ) parent,
algTcRec = is_rec,
algTcGadtSyntax = gadt_syn
}
-- | Simpler specialization of 'mkAlgTyCon' for classes
mkClassTyCon :: Name -> Kind -> [TyVar] -> [Role] -> AlgTyConRhs -> Class
-> RecFlag -> Name -> TyCon
mkClassTyCon name kind tyvars roles rhs clas is_rec tc_rep_name
= mkAlgTyCon name kind tyvars roles Nothing [] rhs
(ClassTyCon clas tc_rep_name)
is_rec False
mkTupleTyCon :: Name
-> Kind -- ^ Kind of the resulting 'TyCon'
-> Arity -- ^ Arity of the tuple
-> [TyVar] -- ^ 'TyVar's scoped over: see 'tyConTyVars'
-> DataCon
-> TupleSort -- ^ Whether the tuple is boxed or unboxed
-> AlgTyConFlav
-> TyCon
mkTupleTyCon name kind arity tyvars con sort parent
= AlgTyCon {
tyConName = name,
tyConUnique = nameUnique name,
tyConKind = kind,
tyConArity = arity,
tyConTyVars = tyvars,
tcRoles = replicate arity Representational,
tyConCType = Nothing,
algTcStupidTheta = [],
algTcRhs = TupleTyCon { data_con = con,
tup_sort = sort },
algTcFields = emptyFsEnv,
algTcParent = parent,
algTcRec = NonRecursive,
algTcGadtSyntax = False
}
-- | Makes a tycon suitable for use during type-checking.
-- The only real need for this is for printing error messages during
-- a recursive type/class type-checking knot. It has a kind because
-- TcErrors sometimes calls typeKind.
-- See also Note [Kind checking recursive type and class declarations]
-- in TcTyClsDecls.
mkTcTyCon :: Name -> Kind -> TyCon
mkTcTyCon name kind
= TcTyCon { tyConUnique = getUnique name
, tyConName = name
, tyConKind = kind }
-- | Create an unlifted primitive 'TyCon', such as @Int#@
mkPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon
mkPrimTyCon name kind roles rep
= mkPrimTyCon' name kind roles rep True (Just $ mkPrelTyConRepName name)
-- | Kind constructors
mkKindTyCon :: Name -> Kind -> [Role] -> Name -> TyCon
mkKindTyCon name kind roles rep_nm
= tc
where
tc = mkPrimTyCon' name kind roles PtrRep False (Just rep_nm)
-- PtrRep because kinds have kind *.
-- | Create a lifted primitive 'TyCon' such as @RealWorld@
mkLiftedPrimTyCon :: Name -> Kind -> [Role] -> PrimRep -> TyCon
mkLiftedPrimTyCon name kind roles rep
= mkPrimTyCon' name kind roles rep False Nothing
mkPrimTyCon' :: Name -> Kind -> [Role] -> PrimRep
-> Bool -> Maybe TyConRepName -> TyCon
mkPrimTyCon' name kind roles rep is_unlifted rep_nm
= PrimTyCon {
tyConName = name,
tyConUnique = nameUnique name,
tyConKind = kind,
tyConArity = length roles,
tcRoles = roles,
primTyConRep = rep,
isUnlifted = is_unlifted,
primRepName = rep_nm
}
-- | Create a type synonym 'TyCon'
mkSynonymTyCon :: Name -> Kind -> [TyVar] -> [Role] -> Type -> TyCon
mkSynonymTyCon name kind tyvars roles rhs
= SynonymTyCon {
tyConName = name,
tyConUnique = nameUnique name,
tyConKind = kind,
tyConArity = length tyvars,
tyConTyVars = tyvars,
tcRoles = roles,
synTcRhs = rhs
}
-- | Create a type family 'TyCon'
mkFamilyTyCon:: Name -> Kind -> [TyVar] -> Maybe Name -> FamTyConFlav
-> Maybe Class -> Injectivity -> TyCon
mkFamilyTyCon name kind tyvars resVar flav parent inj
= FamilyTyCon
{ tyConUnique = nameUnique name
, tyConName = name
, tyConKind = kind
, tyConArity = length tyvars
, tyConTyVars = tyvars
, famTcResVar = resVar
, famTcFlav = flav
, famTcParent = parent
, famTcInj = inj
}
-- | Create a promoted data constructor 'TyCon'
-- Somewhat dodgily, we give it the same Name
-- as the data constructor itself; when we pretty-print
-- the TyCon we add a quote; see the Outputable TyCon instance
mkPromotedDataCon :: DataCon -> Name -> TyConRepName -> Kind -> [Role] -> TyCon
mkPromotedDataCon con name rep_name kind roles
= PromotedDataCon {
tyConUnique = nameUnique name,
tyConName = name,
tyConArity = arity,
tcRoles = roles,
tyConKind = kind,
dataCon = con,
tcRepName = rep_name
}
where
arity = length roles
isFunTyCon :: TyCon -> Bool
isFunTyCon (FunTyCon {}) = True
isFunTyCon _ = False
-- | Test if the 'TyCon' is algebraic but abstract (invisible data constructors)
isAbstractTyCon :: TyCon -> Bool
isAbstractTyCon (AlgTyCon { algTcRhs = AbstractTyCon {} }) = True
isAbstractTyCon _ = False
-- | Make an fake, abstract 'TyCon' from an existing one.
-- Used when recovering from errors
makeTyConAbstract :: TyCon -> TyCon
makeTyConAbstract tc
= PrimTyCon { tyConName = name,
tyConUnique = nameUnique name,
tyConKind = tyConKind tc,
tyConArity = tyConArity tc,
tcRoles = tyConRoles tc,
primTyConRep = PtrRep,
isUnlifted = False,
primRepName = Nothing }
where
name = tyConName tc
-- | Does this 'TyCon' represent something that cannot be defined in Haskell?
isPrimTyCon :: TyCon -> Bool
isPrimTyCon (PrimTyCon {}) = True
isPrimTyCon _ = False
-- | Is this 'TyCon' unlifted (i.e. cannot contain bottom)? Note that this can
-- only be true for primitive and unboxed-tuple 'TyCon's
isUnliftedTyCon :: TyCon -> Bool
isUnliftedTyCon (PrimTyCon {isUnlifted = is_unlifted})
= is_unlifted
isUnliftedTyCon (AlgTyCon { algTcRhs = rhs } )
| TupleTyCon { tup_sort = sort } <- rhs
= not (isBoxed (tupleSortBoxity sort))
isUnliftedTyCon _ = False
-- | Returns @True@ if the supplied 'TyCon' resulted from either a
-- @data@ or @newtype@ declaration
isAlgTyCon :: TyCon -> Bool
isAlgTyCon (AlgTyCon {}) = True
isAlgTyCon _ = False
-- | Returns @True@ for vanilla AlgTyCons -- that is, those created
-- with a @data@ or @newtype@ declaration.
isVanillaAlgTyCon :: TyCon -> Bool
isVanillaAlgTyCon (AlgTyCon { algTcParent = VanillaAlgTyCon _ }) = True
isVanillaAlgTyCon _ = False
isDataTyCon :: TyCon -> Bool
-- ^ Returns @True@ for data types that are /definitely/ represented by
-- heap-allocated constructors. These are scrutinised by Core-level
-- @case@ expressions, and they get info tables allocated for them.
--
-- Generally, the function will be true for all @data@ types and false
-- for @newtype@s, unboxed tuples and type family 'TyCon's. But it is
-- not guaranteed to return @True@ in all cases that it could.
--
-- NB: for a data type family, only the /instance/ 'TyCon's
-- get an info table. The family declaration 'TyCon' does not
isDataTyCon (AlgTyCon {algTcRhs = rhs})
= case rhs of
TupleTyCon { tup_sort = sort }
-> isBoxed (tupleSortBoxity sort)
DataTyCon {} -> True
NewTyCon {} -> False
AbstractTyCon {} -> False -- We don't know, so return False
isDataTyCon _ = False
-- | 'isInjectiveTyCon' is true of 'TyCon's for which this property holds
-- (where X is the role passed in):
-- If (T a1 b1 c1) ~X (T a2 b2 c2), then (a1 ~X1 a2), (b1 ~X2 b2), and (c1 ~X3 c2)
-- (where X1, X2, and X3, are the roles given by tyConRolesX tc X)
-- See also Note [Decomposing equalities] in TcCanonical
isInjectiveTyCon :: TyCon -> Role -> Bool
isInjectiveTyCon _ Phantom = False
isInjectiveTyCon (FunTyCon {}) _ = True
isInjectiveTyCon (AlgTyCon {}) Nominal = True
isInjectiveTyCon (AlgTyCon {algTcRhs = rhs}) Representational
= isGenInjAlgRhs rhs
isInjectiveTyCon (SynonymTyCon {}) _ = False
isInjectiveTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ })
Nominal = True
isInjectiveTyCon (FamilyTyCon { famTcInj = Injective inj }) _ = and inj
isInjectiveTyCon (FamilyTyCon {}) _ = False
isInjectiveTyCon (PrimTyCon {}) _ = True
isInjectiveTyCon (PromotedDataCon {}) _ = True
isInjectiveTyCon tc@(TcTyCon {}) _
= pprPanic "isInjectiveTyCon sees a TcTyCon" (ppr tc)
-- | 'isGenerativeTyCon' is true of 'TyCon's for which this property holds
-- (where X is the role passed in):
-- If (T tys ~X t), then (t's head ~X T).
-- See also Note [Decomposing equalities] in TcCanonical
isGenerativeTyCon :: TyCon -> Role -> Bool
isGenerativeTyCon (FamilyTyCon { famTcFlav = DataFamilyTyCon _ }) Nominal = True
isGenerativeTyCon (FamilyTyCon {}) _ = False
-- in all other cases, injectivity implies generativitiy
isGenerativeTyCon tc r = isInjectiveTyCon tc r
-- | Is this an 'AlgTyConRhs' of a 'TyCon' that is generative and injective
-- with respect to representational equality?
isGenInjAlgRhs :: AlgTyConRhs -> Bool
isGenInjAlgRhs (TupleTyCon {}) = True
isGenInjAlgRhs (DataTyCon {}) = True
isGenInjAlgRhs (AbstractTyCon distinct) = distinct
isGenInjAlgRhs (NewTyCon {}) = False
-- | Is this 'TyCon' that for a @newtype@
isNewTyCon :: TyCon -> Bool
isNewTyCon (AlgTyCon {algTcRhs = NewTyCon {}}) = True
isNewTyCon _ = False
-- | Take a 'TyCon' apart into the 'TyVar's it scopes over, the 'Type' it expands
-- into, and (possibly) a coercion from the representation type to the @newtype@.
-- Returns @Nothing@ if this is not possible.
unwrapNewTyCon_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
unwrapNewTyCon_maybe (AlgTyCon { tyConTyVars = tvs,
algTcRhs = NewTyCon { nt_co = co,
nt_rhs = rhs }})
= Just (tvs, rhs, co)
unwrapNewTyCon_maybe _ = Nothing
unwrapNewTyConEtad_maybe :: TyCon -> Maybe ([TyVar], Type, CoAxiom Unbranched)
unwrapNewTyConEtad_maybe (AlgTyCon { algTcRhs = NewTyCon { nt_co = co,
nt_etad_rhs = (tvs,rhs) }})
= Just (tvs, rhs, co)
unwrapNewTyConEtad_maybe _ = Nothing
isProductTyCon :: TyCon -> Bool
-- True of datatypes or newtypes that have
-- one, non-existential, data constructor
-- See Note [Product types]
isProductTyCon tc@(AlgTyCon {})
= case algTcRhs tc of
TupleTyCon {} -> True
DataTyCon{ data_cons = [data_con] }
-> null (dataConExTyVars data_con)
NewTyCon {} -> True
_ -> False
isProductTyCon _ = False
isDataProductTyCon_maybe :: TyCon -> Maybe DataCon
-- True of datatypes (not newtypes) with
-- one, vanilla, data constructor
-- See Note [Product types]
isDataProductTyCon_maybe (AlgTyCon { algTcRhs = rhs })
= case rhs of
DataTyCon { data_cons = [con] }
| null (dataConExTyVars con) -- non-existential
-> Just con
TupleTyCon { data_con = con }
-> Just con
_ -> Nothing
isDataProductTyCon_maybe _ = Nothing
{- Note [Product types]
~~~~~~~~~~~~~~~~~~~~~~~
A product type is
* A data type (not a newtype)
* With one, boxed data constructor
* That binds no existential type variables
The main point is that product types are amenable to unboxing for
* Strict function calls; we can transform
f (D a b) = e
to
fw a b = e
via the worker/wrapper transformation. (Question: couldn't this
work for existentials too?)
* CPR for function results; we can transform
f x y = let ... in D a b
to
fw x y = let ... in (# a, b #)
Note that the data constructor /can/ have evidence arguments: equality
constraints, type classes etc. So it can be GADT. These evidence
arguments are simply value arguments, and should not get in the way.
-}
-- | Is this a 'TyCon' representing a regular H98 type synonym (@type@)?
isTypeSynonymTyCon :: TyCon -> Bool
isTypeSynonymTyCon (SynonymTyCon {}) = True
isTypeSynonymTyCon _ = False
-- As for newtypes, it is in some contexts important to distinguish between
-- closed synonyms and synonym families, as synonym families have no unique
-- right hand side to which a synonym family application can expand.
--
-- | True iff we can decompose (T a b c) into ((T a b) c)
-- I.e. is it injective and generative w.r.t nominal equality?
-- That is, if (T a b) ~N d e f, is it always the case that
-- (T ~N d), (a ~N e) and (b ~N f)?
-- Specifically NOT true of synonyms (open and otherwise)
--
-- It'd be unusual to call mightBeUnsaturatedTyCon on a regular H98
-- type synonym, because you should probably have expanded it first
-- But regardless, it's not decomposable
mightBeUnsaturatedTyCon :: TyCon -> Bool
mightBeUnsaturatedTyCon (SynonymTyCon {}) = False
mightBeUnsaturatedTyCon (FamilyTyCon { famTcFlav = flav}) = isDataFamFlav flav
mightBeUnsaturatedTyCon _other = True
-- | Is this an algebraic 'TyCon' declared with the GADT syntax?
isGadtSyntaxTyCon :: TyCon -> Bool
isGadtSyntaxTyCon (AlgTyCon { algTcGadtSyntax = res }) = res
isGadtSyntaxTyCon _ = False
-- | Is this an algebraic 'TyCon' which is just an enumeration of values?
isEnumerationTyCon :: TyCon -> Bool
-- See Note [Enumeration types] in TyCon
isEnumerationTyCon (AlgTyCon { tyConArity = arity, algTcRhs = rhs })
= case rhs of
DataTyCon { is_enum = res } -> res
TupleTyCon {} -> arity == 0
_ -> False
isEnumerationTyCon _ = False
-- | Is this a 'TyCon', synonym or otherwise, that defines a family?
isFamilyTyCon :: TyCon -> Bool
isFamilyTyCon (FamilyTyCon {}) = True
isFamilyTyCon _ = False
-- | Is this a 'TyCon', synonym or otherwise, that defines a family with
-- instances?
isOpenFamilyTyCon :: TyCon -> Bool
isOpenFamilyTyCon (FamilyTyCon {famTcFlav = flav })
| OpenSynFamilyTyCon <- flav = True
| DataFamilyTyCon {} <- flav = True
isOpenFamilyTyCon _ = False
-- | Is this a synonym 'TyCon' that can have may have further instances appear?
isTypeFamilyTyCon :: TyCon -> Bool
isTypeFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = not (isDataFamFlav flav)
isTypeFamilyTyCon _ = False
-- | Is this a synonym 'TyCon' that can have may have further instances appear?
isDataFamilyTyCon :: TyCon -> Bool
isDataFamilyTyCon (FamilyTyCon { famTcFlav = flav }) = isDataFamFlav flav
isDataFamilyTyCon _ = False
-- | Is this an open type family TyCon?
isOpenTypeFamilyTyCon :: TyCon -> Bool
isOpenTypeFamilyTyCon (FamilyTyCon {famTcFlav = OpenSynFamilyTyCon }) = True
isOpenTypeFamilyTyCon _ = False
-- | Is this a non-empty closed type family? Returns 'Nothing' for
-- abstract or empty closed families.
isClosedSynFamilyTyConWithAxiom_maybe :: TyCon -> Maybe (CoAxiom Branched)
isClosedSynFamilyTyConWithAxiom_maybe
(FamilyTyCon {famTcFlav = ClosedSynFamilyTyCon mb}) = mb
isClosedSynFamilyTyConWithAxiom_maybe _ = Nothing
-- | Try to read the injectivity information from a FamilyTyCon.
-- For every other TyCon this function panics.
familyTyConInjectivityInfo :: TyCon -> Injectivity
familyTyConInjectivityInfo (FamilyTyCon { famTcInj = inj }) = inj
familyTyConInjectivityInfo _ = panic "familyTyConInjectivityInfo"
isBuiltInSynFamTyCon_maybe :: TyCon -> Maybe BuiltInSynFamily
isBuiltInSynFamTyCon_maybe
(FamilyTyCon {famTcFlav = BuiltInSynFamTyCon ops }) = Just ops
isBuiltInSynFamTyCon_maybe _ = Nothing
isDataFamFlav :: FamTyConFlav -> Bool
isDataFamFlav (DataFamilyTyCon {}) = True -- Data family
isDataFamFlav _ = False -- Type synonym family
-- | Are we able to extract information 'TyVar' to class argument list
-- mapping from a given 'TyCon'?
isTyConAssoc :: TyCon -> Bool
isTyConAssoc tc = isJust (tyConAssoc_maybe tc)
tyConAssoc_maybe :: TyCon -> Maybe Class
tyConAssoc_maybe (FamilyTyCon { famTcParent = mb_cls }) = mb_cls
tyConAssoc_maybe _ = Nothing
-- The unit tycon didn't used to be classed as a tuple tycon
-- but I thought that was silly so I've undone it
-- If it can't be for some reason, it should be a AlgTyCon
isTupleTyCon :: TyCon -> Bool
-- ^ Does this 'TyCon' represent a tuple?
--
-- NB: when compiling @Data.Tuple@, the tycons won't reply @True@ to
-- 'isTupleTyCon', because they are built as 'AlgTyCons'. However they
-- get spat into the interface file as tuple tycons, so I don't think
-- it matters.
isTupleTyCon (AlgTyCon { algTcRhs = TupleTyCon {} }) = True
isTupleTyCon _ = False
tyConTuple_maybe :: TyCon -> Maybe TupleSort
tyConTuple_maybe (AlgTyCon { algTcRhs = rhs })
| TupleTyCon { tup_sort = sort} <- rhs = Just sort
tyConTuple_maybe _ = Nothing
-- | Is this the 'TyCon' for an unboxed tuple?
isUnboxedTupleTyCon :: TyCon -> Bool
isUnboxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
| TupleTyCon { tup_sort = sort } <- rhs
= not (isBoxed (tupleSortBoxity sort))
isUnboxedTupleTyCon _ = False
-- | Is this the 'TyCon' for a boxed tuple?
isBoxedTupleTyCon :: TyCon -> Bool
isBoxedTupleTyCon (AlgTyCon { algTcRhs = rhs })
| TupleTyCon { tup_sort = sort } <- rhs
= isBoxed (tupleSortBoxity sort)
isBoxedTupleTyCon _ = False
-- | Is this a recursive 'TyCon'?
isRecursiveTyCon :: TyCon -> Bool
isRecursiveTyCon (AlgTyCon {algTcRec = Recursive}) = True
isRecursiveTyCon _ = False
-- | Is this a PromotedDataCon?
isPromotedDataCon :: TyCon -> Bool
isPromotedDataCon (PromotedDataCon {}) = True
isPromotedDataCon _ = False
-- | Retrieves the promoted DataCon if this is a PromotedDataCon;
isPromotedDataCon_maybe :: TyCon -> Maybe DataCon
isPromotedDataCon_maybe (PromotedDataCon { dataCon = dc }) = Just dc
isPromotedDataCon_maybe _ = Nothing
-- | Is this tycon really meant for use at the kind level? That is,
-- should it be permitted without -XDataKinds?
isKindTyCon :: TyCon -> Bool
isKindTyCon tc = isLiftedTypeKindTyConName (tyConName tc) ||
tc `hasKey` constraintKindTyConKey ||
tc `hasKey` tYPETyConKey ||
tc `hasKey` levityTyConKey ||
tc `hasKey` liftedDataConKey ||
tc `hasKey` unliftedDataConKey
isLiftedTypeKindTyConName :: Name -> Bool
isLiftedTypeKindTyConName
= (`hasKey` liftedTypeKindTyConKey) <||>
(`hasKey` starKindTyConKey) <||>
(`hasKey` unicodeStarKindTyConKey)
-- | Identifies implicit tycons that, in particular, do not go into interface
-- files (because they are implicitly reconstructed when the interface is
-- read).
--
-- Note that:
--
-- * Associated families are implicit, as they are re-constructed from
-- the class declaration in which they reside, and
--
-- * Family instances are /not/ implicit as they represent the instance body
-- (similar to a @dfun@ does that for a class instance).
--
-- * Tuples are implicit iff they have a wired-in name
-- (namely: boxed and unboxed tupeles are wired-in and implicit,
-- but constraint tuples are not)
isImplicitTyCon :: TyCon -> Bool
isImplicitTyCon (FunTyCon {}) = True
isImplicitTyCon (PrimTyCon {}) = True
isImplicitTyCon (PromotedDataCon {}) = True
isImplicitTyCon (AlgTyCon { algTcRhs = rhs, tyConName = name })
| TupleTyCon {} <- rhs = isWiredInName name
| otherwise = False
isImplicitTyCon (FamilyTyCon { famTcParent = parent }) = isJust parent
isImplicitTyCon (SynonymTyCon {}) = False
isImplicitTyCon tc@(TcTyCon {})
= pprPanic "isImplicitTyCon sees a TcTyCon" (ppr tc)
tyConCType_maybe :: TyCon -> Maybe CType
tyConCType_maybe tc@(AlgTyCon {}) = tyConCType tc
tyConCType_maybe _ = Nothing
-- | Is this a TcTyCon? (That is, one only used during type-checking?)
isTcTyCon :: TyCon -> Bool
isTcTyCon (TcTyCon {}) = True
isTcTyCon _ = False
{-
-----------------------------------------------
-- Expand type-constructor applications
-----------------------------------------------
-}
expandSynTyCon_maybe
:: TyCon
-> [tyco] -- ^ Arguments to 'TyCon'
-> Maybe ([(TyVar,tyco)],
Type,
[tyco]) -- ^ Returns a 'TyVar' substitution, the body
-- type of the synonym (not yet substituted)
-- and any arguments remaining from the
-- application
-- ^ Expand a type synonym application, if any
expandSynTyCon_maybe tc tys
| SynonymTyCon { tyConTyVars = tvs, synTcRhs = rhs } <- tc
, let n_tvs = length tvs
= case n_tvs `compare` length tys of
LT -> Just (tvs `zip` tys, rhs, drop n_tvs tys)
EQ -> Just (tvs `zip` tys, rhs, [])
GT -> Nothing
| otherwise
= Nothing
----------------
-- | Check if the tycon actually refers to a proper `data` or `newtype`
-- with user defined constructors rather than one from a class or other
-- construction.
isTyConWithSrcDataCons :: TyCon -> Bool
isTyConWithSrcDataCons (AlgTyCon { algTcRhs = rhs, algTcParent = parent }) =
case rhs of
DataTyCon {} -> isSrcParent
NewTyCon {} -> isSrcParent
TupleTyCon {} -> isSrcParent
_ -> False
where
isSrcParent = isNoParent parent
isTyConWithSrcDataCons _ = False
-- | As 'tyConDataCons_maybe', but returns the empty list of constructors if no
-- constructors could be found
tyConDataCons :: TyCon -> [DataCon]
-- It's convenient for tyConDataCons to return the
-- empty list for type synonyms etc
tyConDataCons tycon = tyConDataCons_maybe tycon `orElse` []
-- | Determine the 'DataCon's originating from the given 'TyCon', if the 'TyCon'
-- is the sort that can have any constructors (note: this does not include
-- abstract algebraic types)
tyConDataCons_maybe :: TyCon -> Maybe [DataCon]
tyConDataCons_maybe (AlgTyCon {algTcRhs = rhs})
= case rhs of
DataTyCon { data_cons = cons } -> Just cons
NewTyCon { data_con = con } -> Just [con]
TupleTyCon { data_con = con } -> Just [con]
_ -> Nothing
tyConDataCons_maybe _ = Nothing
-- | If the given 'TyCon' has a /single/ data constructor, i.e. it is a @data@
-- type with one alternative, a tuple type or a @newtype@ then that constructor
-- is returned. If the 'TyCon' has more than one constructor, or represents a
-- primitive or function type constructor then @Nothing@ is returned. In any
-- other case, the function panics
tyConSingleDataCon_maybe :: TyCon -> Maybe DataCon
tyConSingleDataCon_maybe (AlgTyCon { algTcRhs = rhs })
= case rhs of
DataTyCon { data_cons = [c] } -> Just c
TupleTyCon { data_con = c } -> Just c
NewTyCon { data_con = c } -> Just c
_ -> Nothing
tyConSingleDataCon_maybe _ = Nothing
tyConSingleDataCon :: TyCon -> DataCon
tyConSingleDataCon tc
= case tyConSingleDataCon_maybe tc of
Just c -> c
Nothing -> pprPanic "tyConDataCon" (ppr tc)
tyConSingleAlgDataCon_maybe :: TyCon -> Maybe DataCon
-- Returns (Just con) for single-constructor
-- *algebraic* data types *not* newtypes
tyConSingleAlgDataCon_maybe (AlgTyCon { algTcRhs = rhs })
= case rhs of
DataTyCon { data_cons = [c] } -> Just c
TupleTyCon { data_con = c } -> Just c
_ -> Nothing
tyConSingleAlgDataCon_maybe _ = Nothing
-- | Determine the number of value constructors a 'TyCon' has. Panics if the
-- 'TyCon' is not algebraic or a tuple
tyConFamilySize :: TyCon -> Int
tyConFamilySize tc@(AlgTyCon { algTcRhs = rhs })
= case rhs of
DataTyCon { data_cons = cons } -> length cons
NewTyCon {} -> 1
TupleTyCon {} -> 1
_ -> pprPanic "tyConFamilySize 1" (ppr tc)
tyConFamilySize tc = pprPanic "tyConFamilySize 2" (ppr tc)
-- | Extract an 'AlgTyConRhs' with information about data constructors from an
-- algebraic or tuple 'TyCon'. Panics for any other sort of 'TyCon'
algTyConRhs :: TyCon -> AlgTyConRhs
algTyConRhs (AlgTyCon {algTcRhs = rhs}) = rhs
algTyConRhs other = pprPanic "algTyConRhs" (ppr other)
-- | Extract type variable naming the result of injective type family
tyConFamilyResVar_maybe :: TyCon -> Maybe Name
tyConFamilyResVar_maybe (FamilyTyCon {famTcResVar = res}) = res
tyConFamilyResVar_maybe _ = Nothing
-- | Get the list of roles for the type parameters of a TyCon
tyConRoles :: TyCon -> [Role]
-- See also Note [TyCon Role signatures]
tyConRoles tc
= case tc of
{ FunTyCon {} -> const_role Representational
; AlgTyCon { tcRoles = roles } -> roles
; SynonymTyCon { tcRoles = roles } -> roles
; FamilyTyCon {} -> const_role Nominal
; PrimTyCon { tcRoles = roles } -> roles
; PromotedDataCon { tcRoles = roles } -> roles
; TcTyCon {} -> pprPanic "tyConRoles sees a TcTyCon" (ppr tc)
}
where
const_role r = replicate (tyConArity tc) r
-- | Extract the bound type variables and type expansion of a type synonym
-- 'TyCon'. Panics if the 'TyCon' is not a synonym
newTyConRhs :: TyCon -> ([TyVar], Type)
newTyConRhs (AlgTyCon {tyConTyVars = tvs, algTcRhs = NewTyCon { nt_rhs = rhs }})
= (tvs, rhs)
newTyConRhs tycon = pprPanic "newTyConRhs" (ppr tycon)
-- | The number of type parameters that need to be passed to a newtype to
-- resolve it. May be less than in the definition if it can be eta-contracted.
newTyConEtadArity :: TyCon -> Int
newTyConEtadArity (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }})
= length (fst tvs_rhs)
newTyConEtadArity tycon = pprPanic "newTyConEtadArity" (ppr tycon)
-- | Extract the bound type variables and type expansion of an eta-contracted
-- type synonym 'TyCon'. Panics if the 'TyCon' is not a synonym
newTyConEtadRhs :: TyCon -> ([TyVar], Type)
newTyConEtadRhs (AlgTyCon {algTcRhs = NewTyCon { nt_etad_rhs = tvs_rhs }}) = tvs_rhs
newTyConEtadRhs tycon = pprPanic "newTyConEtadRhs" (ppr tycon)
-- | Extracts the @newtype@ coercion from such a 'TyCon', which can be used to
-- construct something with the @newtype@s type from its representation type
-- (right hand side). If the supplied 'TyCon' is not a @newtype@, returns
-- @Nothing@
newTyConCo_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
newTyConCo_maybe (AlgTyCon {algTcRhs = NewTyCon { nt_co = co }}) = Just co
newTyConCo_maybe _ = Nothing
newTyConCo :: TyCon -> CoAxiom Unbranched
newTyConCo tc = case newTyConCo_maybe tc of
Just co -> co
Nothing -> pprPanic "newTyConCo" (ppr tc)
-- | Find the primitive representation of a 'TyCon'
tyConPrimRep :: TyCon -> PrimRep
tyConPrimRep (PrimTyCon {primTyConRep = rep}) = rep
tyConPrimRep tc = ASSERT(not (isUnboxedTupleTyCon tc)) PtrRep
-- | Find the \"stupid theta\" of the 'TyCon'. A \"stupid theta\" is the context
-- to the left of an algebraic type declaration, e.g. @Eq a@ in the declaration
-- @data Eq a => T a ...@
tyConStupidTheta :: TyCon -> [PredType]
tyConStupidTheta (AlgTyCon {algTcStupidTheta = stupid}) = stupid
tyConStupidTheta tycon = pprPanic "tyConStupidTheta" (ppr tycon)
-- | Extract the 'TyVar's bound by a vanilla type synonym
-- and the corresponding (unsubstituted) right hand side.
synTyConDefn_maybe :: TyCon -> Maybe ([TyVar], Type)
synTyConDefn_maybe (SynonymTyCon {tyConTyVars = tyvars, synTcRhs = ty})
= Just (tyvars, ty)
synTyConDefn_maybe _ = Nothing
-- | Extract the information pertaining to the right hand side of a type synonym
-- (@type@) declaration.
synTyConRhs_maybe :: TyCon -> Maybe Type
synTyConRhs_maybe (SynonymTyCon {synTcRhs = rhs}) = Just rhs
synTyConRhs_maybe _ = Nothing
-- | Extract the flavour of a type family (with all the extra information that
-- it carries)
famTyConFlav_maybe :: TyCon -> Maybe FamTyConFlav
famTyConFlav_maybe (FamilyTyCon {famTcFlav = flav}) = Just flav
famTyConFlav_maybe _ = Nothing
-- | Is this 'TyCon' that for a class instance?
isClassTyCon :: TyCon -> Bool
isClassTyCon (AlgTyCon {algTcParent = ClassTyCon {}}) = True
isClassTyCon _ = False
-- | If this 'TyCon' is that for a class instance, return the class it is for.
-- Otherwise returns @Nothing@
tyConClass_maybe :: TyCon -> Maybe Class
tyConClass_maybe (AlgTyCon {algTcParent = ClassTyCon clas _}) = Just clas
tyConClass_maybe _ = Nothing
-- | Return the associated types of the 'TyCon', if any
tyConATs :: TyCon -> [TyCon]
tyConATs (AlgTyCon {algTcParent = ClassTyCon clas _}) = classATs clas
tyConATs _ = []
----------------------------------------------------------------------------
-- | Is this 'TyCon' that for a data family instance?
isFamInstTyCon :: TyCon -> Bool
isFamInstTyCon (AlgTyCon {algTcParent = DataFamInstTyCon {} })
= True
isFamInstTyCon _ = False
tyConFamInstSig_maybe :: TyCon -> Maybe (TyCon, [Type], CoAxiom Unbranched)
tyConFamInstSig_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax f ts })
= Just (f, ts, ax)
tyConFamInstSig_maybe _ = Nothing
-- | If this 'TyCon' is that of a data family instance, return the family in question
-- and the instance types. Otherwise, return @Nothing@
tyConFamInst_maybe :: TyCon -> Maybe (TyCon, [Type])
tyConFamInst_maybe (AlgTyCon {algTcParent = DataFamInstTyCon _ f ts })
= Just (f, ts)
tyConFamInst_maybe _ = Nothing
-- | If this 'TyCon' is that of a data family instance, return a 'TyCon' which
-- represents a coercion identifying the representation type with the type
-- instance family. Otherwise, return @Nothing@
tyConFamilyCoercion_maybe :: TyCon -> Maybe (CoAxiom Unbranched)
tyConFamilyCoercion_maybe (AlgTyCon {algTcParent = DataFamInstTyCon ax _ _ })
= Just ax
tyConFamilyCoercion_maybe _ = Nothing
{-
************************************************************************
* *
\subsection[TyCon-instances]{Instance declarations for @TyCon@}
* *
************************************************************************
@TyCon@s are compared by comparing their @Unique@s.
The strictness analyser needs @Ord@. It is a lexicographic order with
the property @(a<=b) || (b<=a)@.
-}
instance Eq TyCon where
a == b = case (a `compare` b) of { EQ -> True; _ -> False }
a /= b = case (a `compare` b) of { EQ -> False; _ -> True }
instance Ord TyCon where
a <= b = case (a `compare` b) of { LT -> True; EQ -> True; GT -> False }
a < b = case (a `compare` b) of { LT -> True; EQ -> False; GT -> False }
a >= b = case (a `compare` b) of { LT -> False; EQ -> True; GT -> True }
a > b = case (a `compare` b) of { LT -> False; EQ -> False; GT -> True }
compare a b = getUnique a `compare` getUnique b
instance Uniquable TyCon where
getUnique tc = tyConUnique tc
instance Outputable TyCon where
-- At the moment a promoted TyCon has the same Name as its
-- corresponding TyCon, so we add the quote to distinguish it here
ppr tc = pprPromotionQuote tc <> ppr (tyConName tc)
tyConFlavour :: TyCon -> String
tyConFlavour (AlgTyCon { algTcParent = parent, algTcRhs = rhs })
| ClassTyCon _ _ <- parent = "class"
| otherwise = case rhs of
TupleTyCon { tup_sort = sort }
| isBoxed (tupleSortBoxity sort) -> "tuple"
| otherwise -> "unboxed tuple"
DataTyCon {} -> "data type"
NewTyCon {} -> "newtype"
AbstractTyCon {} -> "abstract type"
tyConFlavour (FamilyTyCon { famTcFlav = flav })
| isDataFamFlav flav = "data family"
| otherwise = "type family"
tyConFlavour (SynonymTyCon {}) = "type synonym"
tyConFlavour (FunTyCon {}) = "built-in type"
tyConFlavour (PrimTyCon {}) = "built-in type"
tyConFlavour (PromotedDataCon {}) = "promoted data constructor"
tyConFlavour tc@(TcTyCon {})
= pprPanic "tyConFlavour sees a TcTyCon" (ppr tc)
pprPromotionQuote :: TyCon -> SDoc
-- Promoted data constructors already have a tick in their OccName
pprPromotionQuote tc
= case tc of
PromotedDataCon {} -> char '\'' -- Always quote promoted DataCons in types
_ -> empty
instance NamedThing TyCon where
getName = tyConName
instance Data.Data TyCon where
-- don't traverse?
toConstr _ = abstractConstr "TyCon"
gunfold _ _ = error "gunfold"
dataTypeOf _ = mkNoRepType "TyCon"
instance Binary Injectivity where
put_ bh NotInjective = putByte bh 0
put_ bh (Injective xs) = putByte bh 1 >> put_ bh xs
get bh = do { h <- getByte bh
; case h of
0 -> return NotInjective
_ -> do { xs <- get bh
; return (Injective xs) } }
{-
************************************************************************
* *
Walking over recursive TyCons
* *
************************************************************************
Note [Expanding newtypes and products]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When expanding a type to expose a data-type constructor, we need to be
careful about newtypes, lest we fall into an infinite loop. Here are
the key examples:
newtype Id x = MkId x
newtype Fix f = MkFix (f (Fix f))
newtype T = MkT (T -> T)
Type Expansion
--------------------------
T T -> T
Fix Maybe Maybe (Fix Maybe)
Id (Id Int) Int
Fix Id NO NO NO
Notice that
* We can expand T, even though it's recursive.
* We can expand Id (Id Int), even though the Id shows up
twice at the outer level, because Id is non-recursive
So, when expanding, we keep track of when we've seen a recursive
newtype at outermost level; and bale out if we see it again.
We sometimes want to do the same for product types, so that the
strictness analyser doesn't unbox infinitely deeply.
More precisely, we keep a *count* of how many times we've seen it.
This is to account for
data instance T (a,b) = MkT (T a) (T b)
Then (Trac #10482) if we have a type like
T (Int,(Int,(Int,(Int,Int))))
we can still unbox deeply enough during strictness analysis.
We have to treat T as potentially recursive, but it's still
good to be able to unwrap multiple layers.
The function that manages all this is checkRecTc.
-}
data RecTcChecker = RC !Int (NameEnv Int)
-- The upper bound, and the number of times
-- we have encountered each TyCon
initRecTc :: RecTcChecker
-- Intialise with a fixed max bound of 100
-- We should probably have a flag for this
initRecTc = RC 100 emptyNameEnv
checkRecTc :: RecTcChecker -> TyCon -> Maybe RecTcChecker
-- Nothing => Recursion detected
-- Just rec_tcs => Keep going
checkRecTc rc@(RC bound rec_nts) tc
| not (isRecursiveTyCon tc)
= Just rc -- Tuples are a common example here
| otherwise
= case lookupNameEnv rec_nts tc_name of
Just n | n >= bound -> Nothing
| otherwise -> Just (RC bound (extendNameEnv rec_nts tc_name (n+1)))
Nothing -> Just (RC bound (extendNameEnv rec_nts tc_name 1))
where
tc_name = tyConName tc
|
nushio3/ghc
|
compiler/types/TyCon.hs
|
bsd-3-clause
| 81,838
| 1
| 18
| 24,227
| 9,719
| 5,512
| 4,207
| 849
| 7
|
module PTS.Syntax.Diff where
import Control.Arrow ((***))
import Data.List (intersperse)
import Data.Set (Set)
import qualified Data.Set as Set
import PTS.Syntax.Algebra
import PTS.Syntax.Names
import PTS.Syntax.Pretty
import PTS.Syntax.Term
import PTS.Syntax.Substitution (freshCommonVar)
data Diff
= DEqual Term
| DDifferent Term Term
| DIntOp BinOp Diff Diff
| DIfZero Diff Diff Diff
| DApp Diff Diff
| DLam Name Diff Diff
| DPi Name Diff Diff Bool Bool
allEqual :: [Diff] -> Bool
allEqual = all isEqual where
isEqual (DEqual _) = True
isEqual _ = False
diff :: Structure t => t -> t -> Diff
diff t1 t2 = case (structure t1, structure t2) of
(Int n1, Int n2)
| n1 == n2 -> DEqual (strip t1)
| otherwise -> DDifferent (strip t1) (strip t2)
(IntOp op1 x1 y1, IntOp op2 x2 y2)
| op1 == op2 -> let x = diff x1 x2; y = diff y1 y2 in
if allEqual [x, y] then DEqual (strip t1) else DIntOp op1 x y
| otherwise -> DDifferent (strip t1) (strip t2)
(IfZero n1 x1 y1, IfZero n2 x2 y2)
-> let n = diff n1 n2; x = diff x1 x2; y = diff y1 y2 in
if allEqual [n, x, y] then DEqual (strip t1) else DIfZero n x y
(Const c1, Const c2)
| c1 == c2 -> DEqual (strip t1)
| otherwise -> DDifferent (strip t1) (strip t2)
(Var v1, Var v2)
| v1 == v2 -> DEqual (strip t1)
| otherwise -> DDifferent (strip t1) (strip t2)
(App f1 a1, App f2 a2)
-> let f = diff f1 f2; a = diff a1 a2 in
if allEqual [f, a] then DEqual (strip t1) else DApp f a
(Lam n1 q1 b1, Lam n2 q2 b2)
-> let (n, b1', b2') = freshCommonVar n1 n2 (strip b1) (strip b2)
q = diff q1 q2
b = diff b1' b2' in
if allEqual [q, b]
then DEqual (mkLam n (strip q1) b1')
else DLam n q b
(Pi n1 q1 b1 _, Pi n2 q2 b2 _)
-> let (n, b1', b2') = freshCommonVar n1 n2 (strip b1) (strip b2)
q = diff q1 q2
b = diff b1' b2' in
if allEqual [q, b]
then DEqual (mkPi n (strip q1) b1')
else DPi n q b (n `Set.member` freevars b1') (n `Set.member` freevars b2')
(Pos p t, _)
-> diff t t2
(_, Pos p t)
-> diff t1 t
(_, _)
-> DDifferent (strip t1) (strip t2)
showToplevel :: Int -> Term -> String
showToplevel p t = singleLine (pretty p t)
showNothing :: Int -> Term -> String
showNothing p t = if null (drop 5 s) then s else "..." where
s = singleLine (pretty p t)
prio :: Int -> Int -> (String, String) -> (String, String)
prio m n (x, y) | m < n = ("(" ++ x ++ ")", "(" ++ y ++ ")")
| otherwise = (x, y)
type LamChain = [(Name, Diff)]
findLamChain :: Diff -> (LamChain, Diff)
findLamChain (DLam n q b) = ((n, q) : args, body) where
(args, body) = findLamChain b
findLamChain x = ([], x)
showLamChain :: LamChain -> (String, String)
showLamChain = (concat *** concat) . unzip . intersperse (" ", " ") . map showElement where
showElement (name, DEqual _) = (show name, show name)
showElement (name, d) = ("(" ++ show name ++ " : " ++ q1 ++ ")",
"(" ++ show name ++ " : " ++ q2 ++ ")") where
(q1, q2) = showDiff 0 d
showDiff :: Int -> Diff -> (String, String)
showDiff p (DEqual t) = (showNothing p t, showNothing p t)
showDiff p (DDifferent t1 t2) = (t1' ++ spaces1,
t2' ++ spaces2) where
spaces1 = replicate (max 0 (length t2' - length t1')) ' '
spaces2 = replicate (max 0 (length t1' - length t2')) ' '
t1' = showToplevel p t1
t2' = showToplevel p t2
showDiff p (DIntOp n x y) = prio 2 p
(show n ++ " " ++ x1 ++ " " ++ y1,
show n ++ " " ++ x2 ++ " " ++ y2) where
(x1, x2) = showDiff 3 x
(y1, y2) = showDiff 3 y
showDiff p (DIfZero n x y) = prio 2 p
("if0 " ++ n1 ++ " " ++ x1 ++ " " ++ y1,
"if0 " ++ n2 ++ " " ++ x2 ++ " " ++ y2) where
(n1, n2) = showDiff 3 n
(x1, x2) = showDiff 3 x
(y1, y2) = showDiff 3 y
showDiff p (DApp f a) = prio 2 p
(f1 ++ " " ++ a1,
f2 ++ " " ++ a2) where
(f1, f2) = showDiff 2 f
(a1, a2) = showDiff 3 a
showDiff p (DLam n q b) = prio 0 p
("lambda " ++ q1 ++ " . " ++ b1,
"lambda " ++ q2 ++ " . " ++ b2) where
(chain, body) = findLamChain b
(q1, q2) = showLamChain ((n, q) : chain)
(b1, b2) = showDiff 0 body
showDiff p (DPi n q b True True) = prio 0 p
("Pi " ++ show n ++ " : " ++ q1 ++ " . " ++ b1,
"Pi " ++ show n ++ " : " ++ q2 ++ " . " ++ b2) where
(q1, q2) = showDiff 0 q
(b1, b2) = showDiff 0 b
showDiff p (DPi n q b True False) = prio 1 p
("Pi " ++ show n ++ " : " ++ q1 ++ " . " ++ b1,
" " ++ n2 ++ " " ++ q2 ++ " -> " ++ b2) where
(q1, q2) = showDiff 2 q
(b1, b2) = showDiff 1 b
n2 = replicate (length (show n)) ' '
showDiff p (DPi n q b False True) = prio 1 p
(" " ++ n1 ++ " " ++ q1 ++ " -> " ++ b1,
"Pi " ++ show n ++ " : " ++ q2 ++ " . " ++ b2) where
(q1, q2) = showDiff 2 q
(b1, b2) = showDiff 1 b
n1 = replicate (length (show n)) ' '
showDiff p (DPi n q b False False) = prio 1 p
(q1 ++ " -> " ++ b1,
q2 ++ " -> " ++ b2) where
(q1, q2) = showDiff 2 q
(b1, b2) = showDiff 1 b
|
Toxaris/pts
|
src-lib/PTS/Syntax/Diff.hs
|
bsd-3-clause
| 5,556
| 0
| 15
| 1,990
| 2,627
| 1,356
| 1,271
| 134
| 16
|
#### No longer used
{-# LANGUAGE CPP, FlexibleContexts, FlexibleInstances, ScopedTypeVariables #-}
{-# LANGUAGE UndecidableInstances #-} -- See below
{-# OPTIONS_GHC -Wall #-}
-- {-# OPTIONS_GHC -fno-warn-unused-imports #-} -- TEMP
-- {-# OPTIONS_GHC -fno-warn-unused-binds #-} -- TEMP
----------------------------------------------------------------------
-- |
-- Module : Circat.If
-- Copyright : (c) 2014 Tabula, Inc.
--
-- Maintainer : conal@tabula.com
-- Stability : experimental
--
-- Class for conditionals
----------------------------------------------------------------------
module Circat.If (HasIf(..), muxBool, muxInt, repIf) where
import TypeUnary.Vec (Vec,Z,S)
import Circat.Classes (muxB,muxI)
import Circat.Rep
-- | Conditional on boolean values, uncurried and with then/else swapped (for
-- trie consistency).
muxBool :: (Bool,(Bool,Bool)) -> Bool
muxBool = muxB
{-# NOINLINE muxBool #-}
-- Don't inline muxBool, since we have a primitive for it.
-- | Conditional on Int values, uncurried and with then/else swapped (for
-- trie consistency).
muxInt :: (Bool,(Int,Int)) -> Int
muxInt = muxI
{-# NOINLINE muxInt #-}
-- Don't inline muxInt, since we have a primitive for it.
class HasIf a where
if_then_else :: Bool -> a -> a -> a
-- TEMP hack
temp_hack_HasIf :: a
temp_hack_HasIf = undefined
instance HasIf Bool where
if_then_else c a a' = muxBool (c,(a',a)) -- note reversal
{-# INLINE if_then_else #-}
instance HasIf Int where
if_then_else c a a' = muxInt (c,(a',a)) -- note reversal
{-# INLINE if_then_else #-}
instance HasIf () where
if_then_else _ () () = ()
{-# INLINE if_then_else #-}
instance (HasIf s, HasIf t) => HasIf (s,t) where
if_then_else c (s,t) (s',t') = (if_then_else c s s', if_then_else c t t')
{-# INLINE if_then_else #-}
instance (HasIf s, HasIf t, HasIf u) => HasIf (s,t,u) where
if_then_else = repIf
instance (HasIf s, HasIf t, HasIf u, HasIf v) => HasIf (s,t,u,v) where
if_then_else = repIf
instance (HasIf s, HasIf t) => HasIf (s -> t) where
if_then_else c f f' = \ s -> if_then_else c (f s) (f' s)
{-# INLINE if_then_else #-}
repIf :: (HasRep a, HasIf (Rep a)) => Bool -> a -> a -> a
repIf c a a' = abst (if_then_else c (repr a) (repr a'))
{-# INLINE repIf #-}
#define RepIf(ab,re) \
instance HasIf (re) => HasIf (ab) where \
{ if_then_else c a a' = abst (if_then_else c (repr a) (repr a') :: re) ;\
{-# INLINE if_then_else #-} \
}
-- instance (HasIf (Rep (Vec n a)), HasRep (Vec n a)) => HasIf (Vec n a) where
-- if_then_else = repIf
-- instance HasIf a => HasIf (Maybe a) where
-- if_then_else = repIf
-- {-# INLINE if_then_else #-}
RepIf(Vec Z a, ())
RepIf(Vec (S n) a,(a,Vec n a))
-- Sorry about the repeated information between the HasRep and HasIf instances!
-- Can I get the compiler to try the Rep approach if it doesn't find a HasIf
-- instance? Seems tricky, since some (many) of the explicit HasIf instances are
-- recursive and so rely on there being other `HasIf` instances.
--
-- If before Rep?
--
-- What about a fundep in HasRep?
-- Constraint is no smaller than the instance head
-- in the constraint: HasIf (Rep (Vec n a))
-- (Use UndecidableInstances to permit this)
-- instance HasIf (Vec Z a) where if_then_else = repIf
-- instance (HasIf (Vec n a), HasIf a) => HasIf (Vec (S n) a) where if_then_else = repIf
RepIf(Maybe a,(a,Bool))
-- instance HasIf a => HasIf (Maybe a) where
-- #if 0
-- if_then_else = repIf
-- #else
-- if_then_else c a a' = abst (if_then_else c (repr a) (repr a') :: (a,Bool))
-- -- if_then_else c a a' = abst (if_then_else c ((repr :: Maybe a -> (a,Bool)) a) (repr a'))
-- #endif
-- {-# INLINE if_then_else #-}
|
capn-freako/circat
|
src/Circat/If.hs
|
bsd-3-clause
| 3,708
| 0
| 9
| 716
| 688
| 403
| 285
| -1
| -1
|
{-# LANGUAGE QuasiQuotes, OverloadedStrings, TypeSynonymInstances,
MultiParamTypeClasses, ScopedTypeVariables,
FlexibleContexts #-}
module PostgREST.PgStructure where
import PostgREST.PgQuery (QualifiedTable(..))
import Data.Text hiding (foldl, map, zipWith, concat)
import Data.Aeson
import Data.Functor.Identity
import Data.String.Conversions (cs)
import Data.Maybe (fromMaybe)
import Control.Applicative
import qualified Data.Map as Map
import qualified Hasql as H
import qualified Hasql.Postgres as P
import Prelude
foreignKeys :: QualifiedTable -> H.Tx P.Postgres s (Map.Map Text ForeignKey)
foreignKeys table = do
r <- H.listEx $ [H.stmt|
select kcu.column_name, ccu.table_name AS foreign_table_name,
ccu.column_name AS foreign_column_name
from information_schema.table_constraints AS tc
join information_schema.key_column_usage AS kcu
on tc.constraint_name = kcu.constraint_name
join information_schema.constraint_column_usage AS ccu
on ccu.constraint_name = tc.constraint_name
where constraint_type = 'FOREIGN KEY'
and tc.table_name=? and tc.table_schema = ?
order by kcu.column_name
|] (qtName table) (qtSchema table)
return $ foldl addKey Map.empty r
where
addKey :: Map.Map Text ForeignKey -> (Text, Text, Text) -> Map.Map Text ForeignKey
addKey m (col, ftab, fcol) = Map.insert col (ForeignKey ftab fcol) m
tables :: Text -> H.Tx P.Postgres s [Table]
tables schema = do
rows <- H.listEx $
[H.stmt|
select
n.nspname as table_schema,
relname as table_name,
c.relkind = 'r' or (c.relkind IN ('v', 'f')) and (pg_relation_is_updatable(c.oid::regclass, false) & 8) = 8
or (exists (
select 1
from pg_trigger
where pg_trigger.tgrelid = c.oid and (pg_trigger.tgtype::integer & 69) = 69)
) as insertable
from
pg_class c
join pg_namespace n on n.oid = c.relnamespace
where
c.relkind in ('v', 'r', 'm')
and n.nspname = ?
and (
pg_has_role(c.relowner, 'USAGE'::text)
or has_table_privilege(c.oid, 'SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES, TRIGGER'::text) or has_any_column_privilege(c.oid, 'SELECT, INSERT, UPDATE, REFERENCES'::text)
)
order by relname
|] schema
return $ map tableFromRow rows
columns :: QualifiedTable -> H.Tx P.Postgres s [Column]
columns table = do
cols <- H.listEx $ [H.stmt|
select info.table_schema as schema, info.table_name as table_name,
info.column_name as name, info.ordinal_position as position,
info.is_nullable::boolean as nullable, info.data_type as col_type,
info.is_updatable::boolean as updatable,
info.character_maximum_length as max_len,
info.numeric_precision as precision,
info.column_default as default_value,
array_to_string(enum_info.vals, ',') as enum
from (
select table_schema, table_name, column_name, ordinal_position,
is_nullable, data_type, is_updatable,
character_maximum_length, numeric_precision,
column_default, udt_name
from information_schema.columns
where table_schema = ? and table_name = ?
) as info
left outer join (
select n.nspname as s,
t.typname as n,
array_agg(e.enumlabel ORDER BY e.enumsortorder) as vals
from pg_type t
join pg_enum e on t.oid = e.enumtypid
join pg_catalog.pg_namespace n ON n.oid = t.typnamespace
group by s, n
) as enum_info
on (info.udt_name = enum_info.n)
order by position |]
(qtSchema table) (qtName table)
fks <- foreignKeys table
return $ map (addFK fks . columnFromRow) cols
where
addFK fks col = col { colFK = Map.lookup (cs . colName $ col) fks }
primaryKeyColumns :: QualifiedTable -> H.Tx P.Postgres s [Text]
primaryKeyColumns table = do
r <- H.listEx $ [H.stmt|
select kc.column_name
from
information_schema.table_constraints tc,
information_schema.key_column_usage kc
where
tc.constraint_type = 'PRIMARY KEY'
and kc.table_name = tc.table_name and kc.table_schema = tc.table_schema
and kc.constraint_name = tc.constraint_name
and kc.table_schema = ?
and kc.table_name = ? |] (qtSchema table) (qtName table)
return $ map runIdentity r
data Table = Table {
tableSchema :: Text
, tableName :: Text
, tableInsertable :: Bool
} deriving (Show)
data ForeignKey = ForeignKey {
fkTable::Text, fkCol::Text
} deriving (Eq, Show)
data Column = Column {
colSchema :: Text
, colTable :: Text
, colName :: Text
, colPosition :: Int
, colNullable :: Bool
, colType :: Text
, colUpdatable :: Bool
, colMaxLen :: Maybe Int
, colPrecision :: Maybe Int
, colDefault :: Maybe Text
, colEnum :: [Text]
, colFK :: Maybe ForeignKey
} deriving (Show)
tableFromRow :: (Text, Text, Bool) -> Table
tableFromRow (s, n, i) = Table s n i
columnFromRow :: (Text, Text, Text,
Int, Bool, Text,
Bool, Maybe Int, Maybe Int,
Maybe Text, Maybe Text)
-> Column
columnFromRow (s, t, n, pos, nul, typ, u, l, p, d, e) =
Column s t n pos nul typ u l p d (parseEnum e) Nothing
where
parseEnum :: Maybe Text -> [Text]
parseEnum str = fromMaybe [] $ split (==',') <$> str
instance ToJSON Column where
toJSON c = object [
"schema" .= colSchema c
, "name" .= colName c
, "position" .= colPosition c
, "nullable" .= colNullable c
, "type" .= colType c
, "updatable" .= colUpdatable c
, "maxLen" .= colMaxLen c
, "precision" .= colPrecision c
, "references".= colFK c
, "default" .= colDefault c
, "enum" .= colEnum c ]
instance ToJSON ForeignKey where
toJSON fk = object ["table".=fkTable fk, "column".=fkCol fk]
instance ToJSON Table where
toJSON v = object [
"schema" .= tableSchema v
, "name" .= tableName v
, "insertable" .= tableInsertable v ]
|
acrispin/postgrest
|
src/PostgREST/PgStructure.hs
|
mit
| 6,304
| 2
| 12
| 1,739
| 1,147
| 624
| 523
| 93
| 1
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.Route53.DisassociateVPCFromHostedZone
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | This action disassociates a VPC from an hosted zone.
--
-- To disassociate a VPC to a hosted zone, send a 'POST' request to the '2013-04-01/hostedzone//hosted zone ID//disassociatevpc resource. The request body must include an XML
-- document with a 'DisassociateVPCFromHostedZoneRequest' element. The response
-- returns the 'DisassociateVPCFromHostedZoneResponse' element that contains 'ChangeInfo' for you to track the progress of the 'DisassociateVPCFromHostedZoneRequest'
-- you made. See 'GetChange' operation for how to track the progress of your
-- change.
--
-- <http://docs.aws.amazon.com/Route53/latest/APIReference/API_DisassociateVPCFromHostedZone.html>
module Network.AWS.Route53.DisassociateVPCFromHostedZone
(
-- * Request
DisassociateVPCFromHostedZone
-- ** Request constructor
, disassociateVPCFromHostedZone
-- ** Request lenses
, dvpcfhzComment
, dvpcfhzHostedZoneId
, dvpcfhzVPC
-- * Response
, DisassociateVPCFromHostedZoneResponse
-- ** Response constructor
, disassociateVPCFromHostedZoneResponse
-- ** Response lenses
, dvpcfhzrChangeInfo
) where
import Network.AWS.Prelude
import Network.AWS.Request.RestXML
import Network.AWS.Route53.Types
import qualified GHC.Exts
data DisassociateVPCFromHostedZone = DisassociateVPCFromHostedZone
{ _dvpcfhzComment :: Maybe Text
, _dvpcfhzHostedZoneId :: Text
, _dvpcfhzVPC :: VPC
} deriving (Eq, Read, Show)
-- | 'DisassociateVPCFromHostedZone' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dvpcfhzComment' @::@ 'Maybe' 'Text'
--
-- * 'dvpcfhzHostedZoneId' @::@ 'Text'
--
-- * 'dvpcfhzVPC' @::@ 'VPC'
--
disassociateVPCFromHostedZone :: Text -- ^ 'dvpcfhzHostedZoneId'
-> VPC -- ^ 'dvpcfhzVPC'
-> DisassociateVPCFromHostedZone
disassociateVPCFromHostedZone p1 p2 = DisassociateVPCFromHostedZone
{ _dvpcfhzHostedZoneId = p1
, _dvpcfhzVPC = p2
, _dvpcfhzComment = Nothing
}
-- | /Optional:/ Any comments you want to include about a 'DisassociateVPCFromHostedZoneRequest'.
dvpcfhzComment :: Lens' DisassociateVPCFromHostedZone (Maybe Text)
dvpcfhzComment = lens _dvpcfhzComment (\s a -> s { _dvpcfhzComment = a })
-- | The ID of the hosted zone you want to disassociate your VPC from.
--
-- Note that you cannot disassociate the last VPC from a hosted zone.
dvpcfhzHostedZoneId :: Lens' DisassociateVPCFromHostedZone Text
dvpcfhzHostedZoneId =
lens _dvpcfhzHostedZoneId (\s a -> s { _dvpcfhzHostedZoneId = a })
-- | The VPC that you want your hosted zone to be disassociated from.
dvpcfhzVPC :: Lens' DisassociateVPCFromHostedZone VPC
dvpcfhzVPC = lens _dvpcfhzVPC (\s a -> s { _dvpcfhzVPC = a })
newtype DisassociateVPCFromHostedZoneResponse = DisassociateVPCFromHostedZoneResponse
{ _dvpcfhzrChangeInfo :: ChangeInfo
} deriving (Eq, Read, Show)
-- | 'DisassociateVPCFromHostedZoneResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'dvpcfhzrChangeInfo' @::@ 'ChangeInfo'
--
disassociateVPCFromHostedZoneResponse :: ChangeInfo -- ^ 'dvpcfhzrChangeInfo'
-> DisassociateVPCFromHostedZoneResponse
disassociateVPCFromHostedZoneResponse p1 = DisassociateVPCFromHostedZoneResponse
{ _dvpcfhzrChangeInfo = p1
}
-- | A complex type that contains the ID, the status, and the date and time of
-- your 'DisassociateVPCFromHostedZoneRequest'.
dvpcfhzrChangeInfo :: Lens' DisassociateVPCFromHostedZoneResponse ChangeInfo
dvpcfhzrChangeInfo =
lens _dvpcfhzrChangeInfo (\s a -> s { _dvpcfhzrChangeInfo = a })
instance ToPath DisassociateVPCFromHostedZone where
toPath DisassociateVPCFromHostedZone{..} = mconcat
[ "/2013-04-01/hostedzone/"
, toText _dvpcfhzHostedZoneId
, "/disassociatevpc"
]
instance ToQuery DisassociateVPCFromHostedZone where
toQuery = const mempty
instance ToHeaders DisassociateVPCFromHostedZone
instance ToXMLRoot DisassociateVPCFromHostedZone where
toXMLRoot DisassociateVPCFromHostedZone{..} = namespaced ns "DisassociateVPCFromHostedZone"
[ "VPC" =@ _dvpcfhzVPC
, "Comment" =@ _dvpcfhzComment
]
instance ToXML DisassociateVPCFromHostedZone
instance AWSRequest DisassociateVPCFromHostedZone where
type Sv DisassociateVPCFromHostedZone = Route53
type Rs DisassociateVPCFromHostedZone = DisassociateVPCFromHostedZoneResponse
request = post
response = xmlResponse
instance FromXML DisassociateVPCFromHostedZoneResponse where
parseXML x = DisassociateVPCFromHostedZoneResponse
<$> x .@ "ChangeInfo"
|
romanb/amazonka
|
amazonka-route53/gen/Network/AWS/Route53/DisassociateVPCFromHostedZone.hs
|
mpl-2.0
| 5,769
| 0
| 9
| 1,152
| 591
| 359
| 232
| 74
| 1
|
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
-- Module : Network.AWS.S3.Internal
-- Copyright : (c) 2013-2015 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
module Network.AWS.S3.Internal
( module Network.AWS.S3.Internal
, Region
) where
import Data.String
import GHC.Generics
import Network.AWS.Prelude
import Network.AWS.Types (Region)
newtype BucketName = BucketName Text
deriving
( Eq
, Ord
, Show
, Generic
, IsString
, FromText
, ToText
, ToByteString
, FromXML
, ToXML
, ToQuery
)
newtype ObjectKey = ObjectKey Text
deriving
( Eq
, Ord
, Show
, Generic
, IsString
, FromText
, ToText
, ToByteString
, FromXML
, ToXML
, ToQuery
)
newtype ObjectVersionId = ObjectVersionId Text
deriving
( Eq
, Ord
, Show
, Generic
, IsString
, FromText
, ToText
, ToByteString
, FromXML
, ToXML
, ToQuery
)
newtype ETag = ETag Text
deriving
( Eq
, Ord
, Show
, Generic
, IsString
, FromText
, ToText
, ToByteString
, FromXML
, ToXML
, ToQuery
)
|
romanb/amazonka
|
amazonka-s3/src/Network/AWS/S3/Internal.hs
|
mpl-2.0
| 1,783
| 0
| 6
| 699
| 279
| 159
| 120
| 61
| 0
|
{-
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-}
{-# LANGUAGE PackageImports #-}
{-# LANGUAGE NoImplicitPrelude #-}
module Data.STRef.Strict (module M) where
import "base" Data.STRef.Strict as M
|
xwysp/codeworld
|
codeworld-base/src/Data/STRef/Strict.hs
|
apache-2.0
| 749
| 0
| 4
| 136
| 25
| 19
| 6
| 4
| 0
|
{-# LANGUAGE DataKinds, TypeOperators, OverloadedStrings #-}
module LinearRegression5 where
import Prelude (print, length, IO)
import Language.Hakaru.Syntax.Prelude
import Language.Hakaru.Disintegrate
import Language.Hakaru.Syntax.ABT
import Language.Hakaru.Syntax.AST
import Language.Hakaru.Types.DataKind
import Language.Hakaru.Types.Sing
type Model a b = TrivialABT Term '[] ('HMeasure (HPair a b))
type Cond a b = TrivialABT Term '[] (a ':-> 'HMeasure b)
linearRegression :: Model (HPair 'HReal
(HPair 'HReal
(HPair 'HReal
(HPair 'HReal
'HReal))))
HUnit
linearRegression =
normal (real_ 0) (prob_ 1) >>= \a ->
normal (real_ 5) (prob_ 1.825) >>= \b ->
gamma (prob_ 1) (prob_ 1) >>= \invNoise ->
normal (a * (dataX ! (nat_ 0))) (recip (sqrt invNoise)) >>= \y0 ->
normal (a * (dataX ! (nat_ 1))) (recip (sqrt invNoise)) >>= \y1 ->
normal (a * (dataX ! (nat_ 2))) (recip (sqrt invNoise)) >>= \y2 ->
normal (a * (dataX ! (nat_ 3))) (recip (sqrt invNoise)) >>= \y3 ->
normal (a * (dataX ! (nat_ 4))) (recip (sqrt invNoise)) >>= \y4 ->
dirac (pair (pair y0
(pair y1
(pair y2
(pair y3
y4))))
unit)
where dataX = var (Variable "dataX" 73 (SArray SReal))
main :: IO ()
main = print (length (disintegrate linearRegression))
|
zachsully/hakaru
|
haskell/Tests/Unroll/LinearRegression5.hs
|
bsd-3-clause
| 1,490
| 0
| 31
| 458
| 592
| 316
| 276
| 35
| 1
|
-----------------------------------------------------------------------------
-- |
-- Module : XMonad.Actions.FocusNth
-- Copyright : (c) Karsten Schoelzel <kuser@gmx.de>
-- License : BSD
--
-- Maintainer : Karsten Schoelzel <kuser@gmx.de>
-- Stability : stable
-- Portability : unportable
--
-- Focus the nth window of the current workspace.
-----------------------------------------------------------------------------
module XMonad.Actions.FocusNth (
-- * Usage
-- $usage
focusNth,focusNth',
swapNth,swapNth') where
import XMonad.StackSet
import XMonad
-- $usage
-- Add the import to your @~\/.xmonad\/xmonad.hs@:
--
-- > import XMonad.Actions.FocusNth
--
-- Then add appropriate keybindings, for example:
--
-- > -- mod4-[1..9] @@ Switch to window N
-- > ++ [((modm, k), focusNth i)
-- > | (i, k) <- zip [0 .. 8] [xK_1 ..]]
--
-- For detailed instructions on editing your key bindings, see
-- "XMonad.Doc.Extending#Editing_key_bindings".
-- | Give focus to the nth window of the current workspace.
focusNth :: Int -> X ()
focusNth = windows . modify' . focusNth'
focusNth' :: Int -> Stack a -> Stack a
focusNth' n s@(Stack _ ls rs) | (n < 0) || (n > length(ls) + length(rs)) = s
| otherwise = listToStack n (integrate s)
-- | Swap current window with nth. Focus stays in the same position
swapNth :: Int -> X ()
swapNth = windows . modify' . swapNth'
swapNth' :: Int -> Stack a -> Stack a
swapNth' n s@(Stack c l r)
| (n < 0) || (n > length l + length r) || (n == length l) = s
| n < length l = let (nl, nc:nr) = splitAt (length l - n - 1) l in Stack nc (nl ++ c : nr) r
| otherwise = let (nl, nc:nr) = splitAt (n - length l - 1) r in Stack nc l (nl ++ c : nr)
listToStack :: Int -> [a] -> Stack a
listToStack n l = Stack t ls rs
where
(t:rs) = drop n l
ls = reverse (take n l)
|
f1u77y/xmonad-contrib
|
XMonad/Actions/FocusNth.hs
|
bsd-3-clause
| 2,017
| 0
| 14
| 556
| 519
| 275
| 244
| 21
| 1
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Language.Haskell.Refact.Refactoring.SwapArgs (swapArgs) where
import qualified Data.Generics.Aliases as SYB
import qualified GHC.SYB.Utils as SYB
import qualified Name as GHC
import qualified GHC
import qualified GhcMod as GM (Options(..))
import Language.Haskell.Refact.API
import Data.Generics.Schemes
import Language.Haskell.GHC.ExactPrint.Types
import System.Directory
-- TODO: replace args with specific parameters
swapArgs :: RefactSettings -> GM.Options -> [String] -> IO [FilePath]
swapArgs settings opts args
= do let fileName = args!!0
row = (read (args!!1)::Int)
col = (read (args!!2)::Int)
absFileName <- canonicalizePath fileName
runRefacSession settings opts (comp absFileName (row,col))
comp :: String -> SimpPos
-> RefactGhc [ApplyRefacResult]
comp fileName (row, col) = do
parseSourceFileGhc fileName
parsed <- getRefactParsed
nm <- getRefactNameMap
let name = locToNameRdrPure nm (row, col) parsed
case name of
-- (Just pn) -> do refactoredMod@(_, (_t, s)) <- applyRefac (doSwap pnt pn) (Just modInfo) fileName
(Just pn) -> do
(refactoredMod,_) <- applyRefac (doSwap pn) (RSFile fileName)
return [refactoredMod]
Nothing -> error "Incorrect identifier selected!"
--if isFunPNT pnt mod -- Add this back in ++ CMB +++
-- then do
-- rs <-if isExported pnt exps
-- then applyRefacToClientMods (doSwap pnt) fileName
-- else return []
-- writeRefactoredFiles False (r:rs)
-- else error "\nInvalid cursor position!"
-- putStrLn (showToks t)
-- writeRefactoredFiles False [refactoredMod]
-- putStrLn ("here" ++ (SYB.showData SYB.Parser 0 mod)) -- $ show [fileName, beginPos, endPos]
-- putStrLn "Completd"
doSwap :: GHC.Name -> RefactGhc ()
doSwap n1 = do
parsed <- getRefactParsed
logm $ "doSwap:parsed=" ++ SYB.showData SYB.Parser 0 parsed
nm <- getRefactNameMap
parsed' <- everywhereM (SYB.mkM (inMod nm)
`SYB.extM` (inExp nm)
`SYB.extM` (inType nm)
`SYB.extM` (inTypeDecl nm)
) parsed
-- this needs to be bottom up +++ CMB +++
putRefactParsed parsed' emptyAnns
return ()
where
-- 1. The definition is at top level...
#if __GLASGOW_HASKELL__ <= 710
inMod nm ((GHC.FunBind ln2 infixity (GHC.MG matches p m1 m2) a locals tick)::GHC.HsBind GHC.RdrName)
#else
inMod nm ((GHC.FunBind ln2 (GHC.MG (GHC.L lm matches) p m1 m2) a locals tick)::GHC.HsBind GHC.RdrName)
#endif
| GHC.nameUnique n1 == GHC.nameUnique (rdrName2NamePure nm ln2)
= do logm ("inMatch>" ++ SYB.showData SYB.Parser 0 ln2 ++ "<")
newMatches <- updateMatches matches
#if __GLASGOW_HASKELL__ <= 710
return (GHC.FunBind ln2 infixity (GHC.MG newMatches p m1 m2) a locals tick)
#else
return (GHC.FunBind ln2 (GHC.MG (GHC.L lm newMatches) p m1 m2) a locals tick)
#endif
inMod _ func = return func
-- 2. All call sites of the function...
inExp nm ((GHC.L l (GHC.HsApp (GHC.L e0 (GHC.HsApp e e1)) e2))::GHC.LHsExpr GHC.RdrName)
| cond
-- = update e2 e1 =<< update e1 e2 expr
= do
-- expr1 <- update e1 e2 expr
-- expr2 <- update e2 e1 expr1
-- return expr2
return (GHC.L l (GHC.HsApp (GHC.L e0 (GHC.HsApp e e2)) e1))
where
cond = case (expToNameRdr nm e) of
Nothing -> False
Just n2 -> GHC.nameUnique n2 == GHC.nameUnique n1
inExp _ e = return e
-- 3. Type signature...
#if __GLASGOW_HASKELL__ <= 710
inType nm (GHC.L x (GHC.TypeSig [lname] types pns)::GHC.LSig GHC.RdrName)
#else
inType nm (GHC.L x (GHC.TypeSig [lname] (GHC.HsIB ivs (GHC.HsWC wcs mwc types)))::GHC.LSig GHC.RdrName)
#endif
| GHC.nameUnique (rdrName2NamePure nm lname) == GHC.nameUnique n1
= do
logm $ "doSwap.inType"
let (t1:t2:ts) = tyFunToList types
-- t1' <- update t1 t2 t1
-- t2' <- update t2 t1 t2
let t1' = t2
let t2' = t1
#if __GLASGOW_HASKELL__ <= 710
return (GHC.L x (GHC.TypeSig [lname] (tyListToFun (t1':t2':ts)) pns))
#else
return (GHC.L x (GHC.TypeSig [lname] (GHC.HsIB ivs (GHC.HsWC wcs mwc (tyListToFun (t1':t2':ts))))))
#endif
#if __GLASGOW_HASKELL__ <= 710
inType nm (GHC.L _x (GHC.TypeSig (n:ns) _types _)::GHC.LSig GHC.RdrName)
#else
inType nm (GHC.L _x (GHC.TypeSig (n:ns) _types )::GHC.LSig GHC.RdrName)
#endif
| GHC.nameUnique n1 `elem` (map (\n' -> GHC.nameUnique (rdrName2NamePure nm n')) (n:ns))
= error "Error in swapping arguments in type signature: signature bound to muliple entities!"
inType _ ty = return ty
inTypeDecl nm (GHC.L l (GHC.SigD s)) = do
(GHC.L _ s') <- inType nm (GHC.L l s)
return (GHC.L l (GHC.SigD s'))
inTypeDecl _ x = return x
#if __GLASGOW_HASKELL__ <= 710
tyFunToList (GHC.L _ (GHC.HsForAllTy _ _ _ _ (GHC.L _ (GHC.HsFunTy t1 t2)))) = t1 : (tyFunToList t2)
#else
tyFunToList (GHC.L _ (GHC.HsForAllTy _ (GHC.L _ (GHC.HsFunTy t1 t2)))) = t1 : (tyFunToList t2)
#endif
tyFunToList (GHC.L _ (GHC.HsFunTy t1 t2)) = t1 : (tyFunToList t2)
tyFunToList t = [t]
tyListToFun [] = error "SwapArgs.tyListToFun" -- Keep the exhaustiveness checker happy
tyListToFun [t1] = t1
tyListToFun (t1:ts) = GHC.noLoc (GHC.HsFunTy t1 (tyListToFun ts))
updateMatches [] = return []
updateMatches ((GHC.L x (GHC.Match mfn pats nothing rhs)::GHC.LMatch GHC.RdrName (GHC.LHsExpr GHC.RdrName)):matches)
= case pats of
(p1:p2:ps) -> do
-- p1' <- update p1 p2 p1
-- p2' <- update p2 p1 p2
let p1' = p2
let p2' = p1
matches' <- updateMatches matches
return ((GHC.L x (GHC.Match mfn (p1':p2':ps) nothing rhs)):matches')
[p] -> return [GHC.L x (GHC.Match mfn [p] nothing rhs)]
[] -> return [GHC.L x (GHC.Match mfn [] nothing rhs)]
|
RefactoringTools/HaRe
|
src/Language/Haskell/Refact/Refactoring/SwapArgs.hs
|
bsd-3-clause
| 6,857
| 4
| 17
| 2,314
| 1,693
| 877
| 816
| 89
| 14
|
-- (c) The University of Glasgow 2006
{-# LANGUAGE CPP, DeriveDataTypeable #-}
-- | 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(..), Var, CoVar,
LeftOrRight(..), pickLR,
Role(..), ltRole,
-- ** Functions over coercions
coVarKind, coVarRole,
coercionType, coercionKind, coercionKinds, isReflCo,
isReflCo_maybe, coercionRole, coercionKindRole,
mkCoercionType,
-- ** Constructing coercions
mkReflCo, mkCoVarCo,
mkAxInstCo, mkUnbranchedAxInstCo, mkAxInstLHS, mkAxInstRHS,
mkUnbranchedAxInstRHS,
mkPiCo, mkPiCos, mkCoCast,
mkSymCo, mkTransCo, mkNthCo, mkNthCoRole, mkLRCo,
mkInstCo, mkAppCo, mkAppCoFlexible, mkTyConAppCo, mkFunCo,
mkForAllCo, mkUnsafeCo, mkUnivCo, mkSubCo, mkPhantomCo,
mkNewTypeCo, downgradeRole,
mkAxiomRuleCo,
-- ** Decomposition
instNewTyCon_maybe,
NormaliseStepper, NormaliseStepResult(..), composeSteppers,
modifyStepResultCo, unwrapNewTypeStepper,
topNormaliseNewType_maybe, topNormaliseTypeX_maybe,
decomposeCo, getCoVar_maybe,
splitAppCo_maybe,
splitForAllCo_maybe,
nthRole, tyConRolesX,
setNominalRole_maybe,
-- ** Coercion variables
mkCoVar, isCoVar, isCoVarType, coVarName, setCoVarName, setCoVarUnique,
-- ** Free variables
tyCoVarsOfCo, tyCoVarsOfCos, coVarsOfCo, coercionSize,
-- ** Substitution
CvSubstEnv, emptyCvSubstEnv,
CvSubst(..), emptyCvSubst, Coercion.lookupTyVar, lookupCoVar,
isEmptyCvSubst, zapCvSubstEnv, getCvInScope,
substCo, substCos, substCoVar, substCoVars,
substCoWithTy, substCoWithTys,
cvTvSubst, tvCvSubst, mkCvSubst, zipOpenCvSubst,
substTy, extendTvSubst,
extendCvSubstAndInScope, extendTvSubstAndInScope,
substTyVarBndr, substCoVarBndr,
-- ** Lifting
liftCoMatch, liftCoSubstTyVar, liftCoSubstWith,
-- ** Comparison
coreEqCoercion, coreEqCoercion2,
-- ** Forcing evaluation of coercions
seqCo,
-- * Pretty-printing
pprCo, pprParendCo,
pprCoAxiom, pprCoAxBranch, pprCoAxBranchHdr,
-- * Tidying
tidyCo, tidyCos,
-- * Other
applyCo,
) where
#include "HsVersions.h"
import Unify ( MatchEnv(..), matchList )
import TypeRep
import qualified Type
import Type hiding( substTy, substTyVarBndr, extendTvSubst )
import TyCon
import CoAxiom
import Var
import VarEnv
import VarSet
import Binary
import Maybes ( orElse )
import Name ( Name, NamedThing(..), nameUnique, nameModule, getSrcSpan )
import OccName ( parenSymOcc )
import Util
import BasicTypes
import Outputable
import Unique
import Pair
import SrcLoc
import PrelNames ( funTyConKey, eqPrimTyConKey, eqReprPrimTyConKey )
#if __GLASGOW_HASKELL__ < 709
import Control.Applicative hiding ( empty )
import Data.Traversable (traverse, sequenceA)
#endif
import FastString
import ListSetOps
import qualified Data.Data as Data hiding ( TyCon )
import Control.Arrow ( first )
{-
************************************************************************
* *
Coercions
* *
************************************************************************
-}
-- | A 'Coercion' is concrete evidence of the equality/convertibility
-- of two types.
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data Coercion
-- Each constructor has a "role signature", indicating the way roles are
-- propagated through coercions. P, N, and R stand for coercions of the
-- given role. e stands for a coercion of a specific unknown role (think
-- "role polymorphism"). "e" stands for an explicit role parameter
-- indicating role e. _ stands for a parameter that is not a Role or
-- Coercion.
-- These ones mirror the shape of types
= -- Refl :: "e" -> _ -> e
Refl Role Type -- See Note [Refl invariant]
-- Invariant: applications of (Refl T) to a bunch of identity coercions
-- always show up as Refl.
-- For example (Refl T) (Refl a) (Refl b) shows up as (Refl (T a b)).
-- Applications of (Refl T) to some coercions, at least one of
-- which is NOT the identity, show up as TyConAppCo.
-- (They may not be fully saturated however.)
-- ConAppCo coercions (like all coercions other than Refl)
-- are NEVER the identity.
-- Use (Refl Representational _), not (SubCo (Refl Nominal _))
-- These ones simply lift the correspondingly-named
-- Type constructors into Coercions
-- TyConAppCo :: "e" -> _ -> ?? -> e
-- See Note [TyConAppCo roles]
| TyConAppCo Role TyCon [Coercion] -- lift TyConApp
-- The TyCon is never a synonym;
-- we expand synonyms eagerly
-- But it can be a type function
| AppCo Coercion Coercion -- lift AppTy
-- AppCo :: e -> N -> e
-- See Note [Forall coercions]
| ForAllCo TyVar Coercion -- forall a. g
-- :: _ -> e -> e
-- These are special
| CoVarCo CoVar -- :: _ -> (N or R)
-- result role depends on the tycon of the variable's type
-- AxiomInstCo :: e -> _ -> [N] -> e
| AxiomInstCo (CoAxiom Branched) BranchIndex [Coercion]
-- See also [CoAxiom index]
-- 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]
-- see Note [UnivCo]
| UnivCo FastString Role Type Type -- :: "e" -> _ -> _ -> e
-- the FastString is just a note for provenance
| SymCo Coercion -- :: e -> e
| TransCo Coercion Coercion -- :: e -> e -> e
-- The number of types and coercions should match exactly the expectations
-- of the CoAxiomRule (i.e., the rule is fully saturated).
| AxiomRuleCo CoAxiomRule [Type] [Coercion]
-- These are destructors
| NthCo Int Coercion -- Zero-indexed; decomposes (T t0 ... tn)
-- and (F t0 ... tn), assuming F is injective.
-- :: _ -> e -> ?? (inverse of TyConAppCo, see Note [TyConAppCo roles])
-- See Note [NthCo and newtypes]
| LRCo LeftOrRight Coercion -- Decomposes (t_left t_right)
-- :: _ -> N -> N
| InstCo Coercion Type
-- :: e -> _ -> e
| SubCo Coercion -- Turns a ~N into a ~R
-- :: N -> R
deriving (Data.Data, Data.Typeable)
-- If you edit this type, you may need to update the GHC formalism
-- See Note [GHC Formalism] in coreSyn/CoreLint.hs
data LeftOrRight = CLeft | CRight
deriving( Eq, Data.Data, Data.Typeable )
instance Binary LeftOrRight where
put_ bh CLeft = putByte bh 0
put_ bh CRight = putByte bh 1
get bh = do { h <- getByte bh
; case h of
0 -> return CLeft
_ -> return CRight }
pickLR :: LeftOrRight -> (a,a) -> a
pickLR CLeft (l,_) = l
pickLR CRight (_,r) = r
{-
Note [Refl invariant]
~~~~~~~~~~~~~~~~~~~~~
Coercions have the following invariant
Refl is always lifted as far as possible.
You might think that a consequencs is:
Every identity coercions has Refl at the root
But that's not quite true because of coercion variables. Consider
g where g :: Int~Int
Left h where h :: Maybe Int ~ Maybe Int
etc. So the consequence is only true of coercions that
have no coercion variables.
Note [Coercion axioms applied to coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The reason coercion axioms can be applied to coercions and not just
types is to allow for better optimization. There are some cases where
we need to be able to "push transitivity inside" an axiom in order to
expose further opportunities for optimization.
For example, suppose we have
C a : t[a] ~ F a
g : b ~ c
and we want to optimize
sym (C b) ; t[g] ; C c
which has the kind
F b ~ F c
(stopping through t[b] and t[c] along the way).
We'd like to optimize this to just F g -- but how? The key is
that we need to allow axioms to be instantiated by *coercions*,
not just by types. Then we can (in certain cases) push
transitivity inside the axiom instantiations, and then react
opposite-polarity instantiations of the same axiom. In this
case, e.g., we match t[g] against the LHS of (C c)'s kind, to
obtain the substitution a |-> g (note this operation is sort
of the dual of lifting!) and hence end up with
C g : t[b] ~ F c
which indeed has the same kind as t[g] ; C c.
Now we have
sym (C b) ; C g
which can be optimized to F g.
Note [CoAxiom index]
~~~~~~~~~~~~~~~~~~~~
A CoAxiom has 1 or more branches. Each branch has contains a list
of the free type variables in that branch, the LHS type patterns,
and the RHS type for that branch. When we apply an axiom to a list
of coercions, we must choose which branch of the axiom we wish to
use, as the different branches may have different numbers of free
type variables. (The number of type patterns is always the same
among branches, but that doesn't quite concern us here.)
The Int in the AxiomInstCo constructor is the 0-indexed number
of the chosen branch.
Note [Forall coercions]
~~~~~~~~~~~~~~~~~~~~~~~
Constructing coercions between forall-types can be a bit tricky.
Currently, the situation is as follows:
ForAllCo TyVar Coercion
represents a coercion between polymorphic types, with the rule
v : k g : t1 ~ t2
----------------------------------------------
ForAllCo v g : (all v:k . t1) ~ (all v:k . t2)
Note that it's only necessary to coerce between polymorphic types
where the type variables have identical kinds, because equality on
kinds is trivial.
Note [Predicate coercions]
~~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
g :: a~b
How can we coerce between types
([c]~a) => [a] -> c
and
([c]~b) => [b] -> c
where the equality predicate *itself* differs?
Answer: we simply treat (~) as an ordinary type constructor, so these
types really look like
((~) [c] a) -> [a] -> c
((~) [c] b) -> [b] -> c
So the coercion between the two is obviously
((~) [c] g) -> [g] -> c
Another way to see this to say that we simply collapse predicates to
their representation type (see Type.coreView and Type.predTypeRep).
This collapse is done by mkPredCo; there is no PredCo constructor
in Coercion. This is important because we need Nth to work on
predicates too:
Nth 1 ((~) [c] g) = g
See Simplify.simplCoercionF, which generates such selections.
Note [Kind coercions]
~~~~~~~~~~~~~~~~~~~~~
Suppose T :: * -> *, and g :: A ~ B
Then the coercion
TyConAppCo T [g] T g : T A ~ T B
Now suppose S :: forall k. k -> *, and g :: A ~ B
Then the coercion
TyConAppCo S [Refl *, g] T <*> g : T * A ~ T * B
Notice that the arguments to TyConAppCo are coercions, but the first
represents a *kind* coercion. Now, we don't allow any non-trivial kind
coercions, so it's an invariant that any such kind coercions are Refl.
Lint checks this.
However it's inconvenient to insist that these kind coercions are always
*structurally* (Refl k), because the key function exprIsConApp_maybe
pushes coercions into constructor arguments, so
C k ty e |> g
may turn into
C (Nth 0 g) ....
Now (Nth 0 g) will optimise to Refl, but perhaps not instantly.
Note [Roles]
~~~~~~~~~~~~
Roles are a solution to the GeneralizedNewtypeDeriving problem, articulated
in Trac #1496. The full story is in docs/core-spec/core-spec.pdf. Also, see
http://ghc.haskell.org/trac/ghc/wiki/RolesImplementation
Here is one way to phrase the problem:
Given:
newtype Age = MkAge Int
type family F x
type instance F Age = Bool
type instance F Int = Char
This compiles down to:
axAge :: Age ~ Int
axF1 :: F Age ~ Bool
axF2 :: F Int ~ Char
Then, we can make:
(sym (axF1) ; F axAge ; axF2) :: Bool ~ Char
Yikes!
The solution is _roles_, as articulated in "Generative Type Abstraction and
Type-level Computation" (POPL 2010), available at
http://www.seas.upenn.edu/~sweirich/papers/popl163af-weirich.pdf
The specification for roles has evolved somewhat since that paper. For the
current full details, see the documentation in docs/core-spec. Here are some
highlights.
We label every equality with a notion of type equivalence, of which there are
three options: Nominal, Representational, and Phantom. A ground type is
nominally equivalent only with itself. A newtype (which is considered a ground
type in Haskell) is representationally equivalent to its representation.
Anything is "phantomly" equivalent to anything else. We use "N", "R", and "P"
to denote the equivalences.
The axioms above would be:
axAge :: Age ~R Int
axF1 :: F Age ~N Bool
axF2 :: F Age ~N Char
Then, because transitivity applies only to coercions proving the same notion
of equivalence, the above construction is impossible.
However, there is still an escape hatch: we know that any two types that are
nominally equivalent are representationally equivalent as well. This is what
the form SubCo proves -- it "demotes" a nominal equivalence into a
representational equivalence. So, it would seem the following is possible:
sub (sym axF1) ; F axAge ; sub axF2 :: Bool ~R Char -- WRONG
What saves us here is that the arguments to a type function F, lifted into a
coercion, *must* prove nominal equivalence. So, (F axAge) is ill-formed, and
we are safe.
Roles are attached to parameters to TyCons. When lifting a TyCon into a
coercion (through TyConAppCo), we need to ensure that the arguments to the
TyCon respect their roles. For example:
data T a b = MkT a (F b)
If we know that a1 ~R a2, then we know (T a1 b) ~R (T a2 b). But, if we know
that b1 ~R b2, we know nothing about (T a b1) and (T a b2)! This is because
the type function F branches on b's *name*, not representation. So, we say
that 'a' has role Representational and 'b' has role Nominal. The third role,
Phantom, is for parameters not used in the type's definition. Given the
following definition
data Q a = MkQ Int
the Phantom role allows us to say that (Q Bool) ~R (Q Char), because we
can construct the coercion Bool ~P Char (using UnivCo).
See the paper cited above for more examples and information.
Note [UnivCo]
~~~~~~~~~~~~~
The UnivCo ("universal coercion") serves two rather separate functions:
- the implementation for unsafeCoerce#
- placeholder for phantom parameters in a TyConAppCo
At Representational, it asserts that two (possibly unrelated)
types have the same representation and can be casted to one another.
This form is necessary for unsafeCoerce#.
For optimisation purposes, it is convenient to allow UnivCo to appear
at Nominal role. If we have
data Foo a = MkFoo (F a) -- F is a type family
and we want an unsafe coercion from Foo Int to Foo Bool, then it would
be nice to have (TyConAppCo Foo (UnivCo Nominal Int Bool)). So, we allow
Nominal UnivCo's.
At Phantom role, it is used as an argument to TyConAppCo in the place
of a phantom parameter (a type parameter unused in the type definition).
For example:
data Q a = MkQ Int
We want a coercion for (Q Bool) ~R (Q Char).
(TyConAppCo Representational Q [UnivCo Phantom Bool Char]) does the trick.
Note [TyConAppCo roles]
~~~~~~~~~~~~~~~~~~~~~~~
The TyConAppCo constructor has a role parameter, indicating the role at
which the coercion proves equality. The choice of this parameter affects
the required roles of the arguments of the TyConAppCo. To help explain
it, assume the following definition:
type instance F Int = Bool -- Axiom axF : F Int ~N Bool
newtype Age = MkAge Int -- Axiom axAge : Age ~R Int
data Foo a = MkFoo a -- Role on Foo's parameter is Representational
TyConAppCo Nominal Foo axF : Foo (F Int) ~N Foo Bool
For (TyConAppCo Nominal) all arguments must have role Nominal. Why?
So that Foo Age ~N Foo Int does *not* hold.
TyConAppCo Representational Foo (SubCo axF) : Foo (F Int) ~R Foo Bool
TyConAppCo Representational Foo axAge : Foo Age ~R Foo Int
For (TyConAppCo Representational), all arguments must have the roles
corresponding to the result of tyConRoles on the TyCon. This is the
whole point of having roles on the TyCon to begin with. So, we can
have Foo Age ~R Foo Int, if Foo's parameter has role R.
If a Representational TyConAppCo is over-saturated (which is otherwise fine),
the spill-over arguments must all be at Nominal. This corresponds to the
behavior for AppCo.
TyConAppCo Phantom Foo (UnivCo Phantom Int Bool) : Foo Int ~P Foo Bool
All arguments must have role Phantom. This one isn't strictly
necessary for soundness, but this choice removes ambiguity.
The rules here dictate the roles of the parameters to mkTyConAppCo
(should be checked by Lint).
Note [NthCo and newtypes]
~~~~~~~~~~~~~~~~~~~~~~~~~
Suppose we have
newtype N a = MkN Int
type role N representational
This yields axiom
NTCo:N :: forall a. N a ~R Int
We can then build
co :: forall a b. N a ~R N b
co = NTCo:N a ; sym (NTCo:N b)
for any `a` and `b`. Because of the role annotation on N, if we use
NthCo, we'll get out a representational coercion. That is:
NthCo 0 co :: forall a b. a ~R b
Yikes! Clearly, this is terrible. The solution is simple: forbid
NthCo to be used on newtypes if the internal coercion is representational.
This is not just some corner case discovered by a segfault somewhere;
it was discovered in the proof of soundness of roles and described
in the "Safe Coercions" paper (ICFP '14).
************************************************************************
* *
\subsection{Coercion variables}
* *
************************************************************************
-}
coVarName :: CoVar -> Name
coVarName = varName
setCoVarUnique :: CoVar -> Unique -> CoVar
setCoVarUnique = setVarUnique
setCoVarName :: CoVar -> Name -> CoVar
setCoVarName = setVarName
isCoVar :: Var -> Bool
isCoVar v = isCoVarType (varType v)
isCoVarType :: Type -> Bool
isCoVarType ty -- Tests for t1 ~# t2, the unboxed equality
= case splitTyConApp_maybe ty of
Just (tc,tys) -> (tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey)
&& tys `lengthAtLeast` 2
Nothing -> False
tyCoVarsOfCo :: Coercion -> VarSet
-- Extracts type and coercion variables from a coercion
tyCoVarsOfCo (Refl _ ty) = tyVarsOfType ty
tyCoVarsOfCo (TyConAppCo _ _ cos) = tyCoVarsOfCos cos
tyCoVarsOfCo (AppCo co1 co2) = tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2
tyCoVarsOfCo (ForAllCo tv co) = tyCoVarsOfCo co `delVarSet` tv
tyCoVarsOfCo (CoVarCo v) = unitVarSet v
tyCoVarsOfCo (AxiomInstCo _ _ cos) = tyCoVarsOfCos cos
tyCoVarsOfCo (UnivCo _ _ ty1 ty2) = tyVarsOfType ty1 `unionVarSet` tyVarsOfType ty2
tyCoVarsOfCo (SymCo co) = tyCoVarsOfCo co
tyCoVarsOfCo (TransCo co1 co2) = tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2
tyCoVarsOfCo (NthCo _ co) = tyCoVarsOfCo co
tyCoVarsOfCo (LRCo _ co) = tyCoVarsOfCo co
tyCoVarsOfCo (InstCo co ty) = tyCoVarsOfCo co `unionVarSet` tyVarsOfType ty
tyCoVarsOfCo (SubCo co) = tyCoVarsOfCo co
tyCoVarsOfCo (AxiomRuleCo _ ts cs) = tyVarsOfTypes ts `unionVarSet` tyCoVarsOfCos cs
tyCoVarsOfCos :: [Coercion] -> VarSet
tyCoVarsOfCos = mapUnionVarSet tyCoVarsOfCo
coVarsOfCo :: Coercion -> VarSet
-- Extract *coerction* variables only. Tiresome to repeat the code, but easy.
coVarsOfCo (Refl _ _) = emptyVarSet
coVarsOfCo (TyConAppCo _ _ cos) = coVarsOfCos cos
coVarsOfCo (AppCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2
coVarsOfCo (ForAllCo _ co) = coVarsOfCo co
coVarsOfCo (CoVarCo v) = unitVarSet v
coVarsOfCo (AxiomInstCo _ _ cos) = coVarsOfCos cos
coVarsOfCo (UnivCo _ _ _ _) = emptyVarSet
coVarsOfCo (SymCo co) = coVarsOfCo co
coVarsOfCo (TransCo co1 co2) = coVarsOfCo co1 `unionVarSet` coVarsOfCo co2
coVarsOfCo (NthCo _ co) = coVarsOfCo co
coVarsOfCo (LRCo _ co) = coVarsOfCo co
coVarsOfCo (InstCo co _) = coVarsOfCo co
coVarsOfCo (SubCo co) = coVarsOfCo co
coVarsOfCo (AxiomRuleCo _ _ cos) = coVarsOfCos cos
coVarsOfCos :: [Coercion] -> VarSet
coVarsOfCos = mapUnionVarSet coVarsOfCo
coercionSize :: Coercion -> Int
coercionSize (Refl _ ty) = typeSize ty
coercionSize (TyConAppCo _ _ cos) = 1 + sum (map coercionSize cos)
coercionSize (AppCo co1 co2) = coercionSize co1 + coercionSize co2
coercionSize (ForAllCo _ co) = 1 + coercionSize co
coercionSize (CoVarCo _) = 1
coercionSize (AxiomInstCo _ _ cos) = 1 + sum (map coercionSize cos)
coercionSize (UnivCo _ _ ty1 ty2) = typeSize ty1 + typeSize ty2
coercionSize (SymCo co) = 1 + coercionSize co
coercionSize (TransCo co1 co2) = 1 + coercionSize co1 + coercionSize co2
coercionSize (NthCo _ co) = 1 + coercionSize co
coercionSize (LRCo _ co) = 1 + coercionSize co
coercionSize (InstCo co ty) = 1 + coercionSize co + typeSize ty
coercionSize (SubCo co) = 1 + coercionSize co
coercionSize (AxiomRuleCo _ tys cos) = 1 + sum (map typeSize tys)
+ sum (map coercionSize cos)
{-
************************************************************************
* *
Tidying coercions
* *
************************************************************************
-}
tidyCo :: TidyEnv -> Coercion -> Coercion
tidyCo env@(_, subst) co
= go co
where
go (Refl r ty) = Refl r (tidyType env ty)
go (TyConAppCo r tc cos) = let args = map go cos
in args `seqList` TyConAppCo r tc args
go (AppCo co1 co2) = (AppCo $! go co1) $! go co2
go (ForAllCo tv co) = ForAllCo tvp $! (tidyCo envp co)
where
(envp, tvp) = tidyTyVarBndr env tv
go (CoVarCo cv) = case lookupVarEnv subst cv of
Nothing -> CoVarCo cv
Just cv' -> CoVarCo cv'
go (AxiomInstCo con ind cos) = let args = tidyCos env cos
in args `seqList` AxiomInstCo con ind args
go (UnivCo s r ty1 ty2) = (UnivCo s r $! tidyType env ty1) $! tidyType env ty2
go (SymCo co) = SymCo $! go co
go (TransCo co1 co2) = (TransCo $! go co1) $! go co2
go (NthCo d co) = NthCo d $! go co
go (LRCo lr co) = LRCo lr $! go co
go (InstCo co ty) = (InstCo $! go co) $! tidyType env ty
go (SubCo co) = SubCo $! go co
go (AxiomRuleCo ax tys cos) = let tys1 = map (tidyType env) tys
cos1 = tidyCos env cos
in tys1 `seqList` cos1 `seqList`
AxiomRuleCo ax tys1 cos1
tidyCos :: TidyEnv -> [Coercion] -> [Coercion]
tidyCos env = map (tidyCo env)
{-
************************************************************************
* *
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.
-}
instance Outputable Coercion where
ppr = pprCo
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) = pprTcApp TyConPrec ppr_co tc cos <> ppr_role r
ppr_co p (AppCo co1 co2) = maybeParen p TyConPrec $
pprCo co1 <+> ppr_co TyConPrec co2
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 cos)
= pprPrefixApp p (ppr (getName con) <> brackets (ppr index))
(map (ppr_co TyConPrec) cos)
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 ty) = maybeParen p TyConPrec $
pprParendCo co <> ptext (sLit "@") <> pprType ty
ppr_co p (UnivCo s r ty1 ty2) = pprPrefixApp p (ptext (sLit "UnivCo") <+> ftext s <+> ppr r)
[pprParendType ty1, pprParendType ty2]
ppr_co p (SymCo co) = pprPrefixApp p (ptext (sLit "Sym")) [pprParendCo co]
ppr_co p (NthCo n co) = pprPrefixApp p (ptext (sLit "Nth:") <> int n) [pprParendCo co]
ppr_co p (LRCo sel co) = pprPrefixApp p (ppr sel) [pprParendCo co]
ppr_co p (SubCo co) = pprPrefixApp p (ptext (sLit "Sub")) [pprParendCo co]
ppr_co p (AxiomRuleCo co ts cs) = maybeParen p TopPrec $
ppr_axiom_rule_co co ts cs
ppr_axiom_rule_co :: CoAxiomRule -> [Type] -> [Coercion] -> SDoc
ppr_axiom_rule_co co ts ps = ppr (coaxrName co) <> ppTs ts $$ nest 2 (ppPs ps)
where
ppTs [] = Outputable.empty
ppTs [t] = ptext (sLit "@") <> ppr_type TopPrec t
ppTs ts = ptext (sLit "@") <>
parens (hsep $ punctuate comma $ map pprType ts)
ppPs [] = Outputable.empty
ppPs [p] = pprParendCo p
ppPs (p : ps) = ptext (sLit "(") <+> pprCo p $$
vcat [ ptext (sLit ",") <+> pprCo q | q <- ps ] $$
ptext (sLit ")")
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
instance Outputable LeftOrRight where
ppr CLeft = ptext (sLit "Left")
ppr CRight = ptext (sLit "Right")
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 ty
= maybeParen p FunPrec $
sep [pprForAll tvs, ppr_co TopPrec rho]
where
(tvs, rho) = split1 [] ty
split1 tvs (ForAllCo tv ty) = split1 (tv:tvs) ty
split1 tvs ty = (reverse tvs, ty)
pprCoAxiom :: CoAxiom br -> SDoc
pprCoAxiom ax@(CoAxiom { co_ax_tc = tc, co_ax_branches = branches })
= hang (ptext (sLit "axiom") <+> ppr ax <+> dcolon)
2 (vcat (map (pprCoAxBranch tc) $ fromBranchList branches))
pprCoAxBranch :: TyCon -> CoAxBranch -> SDoc
pprCoAxBranch fam_tc (CoAxBranch { cab_tvs = tvs
, cab_lhs = lhs
, cab_rhs = rhs })
= hang (pprUserForAll tvs)
2 (hang (pprTypeApp fam_tc lhs) 2 (equals <+> (ppr rhs)))
pprCoAxBranchHdr :: CoAxiom br -> BranchIndex -> SDoc
pprCoAxBranchHdr ax@(CoAxiom { co_ax_tc = fam_tc, co_ax_name = name }) index
| CoAxBranch { cab_lhs = tys, cab_loc = loc } <- coAxiomNthBranch ax index
= hang (pprTypeApp fam_tc tys)
2 (ptext (sLit "-- Defined") <+> ppr_loc loc)
where
ppr_loc loc
| isGoodSrcSpan loc
= ptext (sLit "at") <+> ppr (srcSpanStart loc)
| otherwise
= ptext (sLit "in") <+>
quotes (ppr (nameModule name))
{-
************************************************************************
* *
Functions over Kinds
* *
************************************************************************
-}
-- | 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
-- first result has role equal to input; second result is Nominal
splitAppCo_maybe :: Coercion -> Maybe (Coercion, Coercion)
-- ^ Attempt to take a coercion application apart.
splitAppCo_maybe (AppCo co1 co2) = Just (co1, co2)
splitAppCo_maybe (TyConAppCo r tc cos)
| mightBeUnsaturatedTyCon tc || cos `lengthExceeds` tyConArity tc
, Just (cos', co') <- snocView cos
, Just co'' <- setNominalRole_maybe co'
= Just (mkTyConAppCo r tc cos', co'') -- Never create unsaturated type family apps!
-- 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 (Refl r ty1, Refl Nominal ty2)
splitAppCo_maybe _ = Nothing
splitForAllCo_maybe :: Coercion -> Maybe (TyVar, Coercion)
splitForAllCo_maybe (ForAllCo tv co) = Just (tv, co)
splitForAllCo_maybe _ = Nothing
-------------------------------------------------------
-- and some coercion kind stuff
coVarKind :: CoVar -> (Type,Type)
coVarKind cv
| Just (tc, [_kind,ty1,ty2]) <- splitTyConApp_maybe (varType cv)
= ASSERT(tc `hasKey` eqPrimTyConKey || tc `hasKey` eqReprPrimTyConKey)
(ty1,ty2)
| otherwise = panic "coVarKind, non coercion variable"
coVarRole :: CoVar -> Role
coVarRole cv
| tc `hasKey` eqPrimTyConKey
= Nominal
| tc `hasKey` eqReprPrimTyConKey
= Representational
| otherwise
= pprPanic "coVarRole: unknown tycon" (ppr 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 = panic "mkCoercionType"
isReflCo :: Coercion -> Bool
isReflCo (Refl {}) = True
isReflCo _ = False
isReflCo_maybe :: Coercion -> Maybe Type
isReflCo_maybe (Refl _ ty) = Just ty
isReflCo_maybe _ = Nothing
{-
************************************************************************
* *
Building coercions
* *
************************************************************************
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.
-}
mkCoVarCo :: CoVar -> Coercion
-- cv :: s ~# t
mkCoVarCo cv
| ty1 `eqType` ty2 = Refl (coVarRole cv) ty1
| otherwise = CoVarCo cv
where
(ty1, ty2) = ASSERT( isCoVar cv ) coVarKind cv
mkReflCo :: Role -> Type -> Coercion
mkReflCo = Refl
mkAxInstCo :: Role -> CoAxiom br -> BranchIndex -> [Type] -> Coercion
-- mkAxInstCo can legitimately be called over-staturated;
-- i.e. with more type arguments than the coercion requires
mkAxInstCo role ax index tys
| arity == n_tys = downgradeRole role ax_role $ AxiomInstCo ax_br index rtys
| otherwise = ASSERT( arity < n_tys )
downgradeRole role ax_role $
foldl AppCo (AxiomInstCo ax_br index (take arity rtys))
(drop arity rtys)
where
n_tys = length tys
ax_br = toBranchedAxiom ax
branch = coAxiomNthBranch ax_br index
arity = length $ coAxBranchTyVars branch
arg_roles = coAxBranchRoles branch
rtys = zipWith mkReflCo (arg_roles ++ repeat Nominal) tys
ax_role = coAxiomRole ax
-- to be used only with unbranched axioms
mkUnbranchedAxInstCo :: Role -> CoAxiom Unbranched -> [Type] -> Coercion
mkUnbranchedAxInstCo role ax tys
= mkAxInstCo role ax 0 tys
mkAxInstLHS, mkAxInstRHS :: CoAxiom br -> BranchIndex -> [Type] -> 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))
mkAxInstLHS ax index tys
| CoAxBranch { cab_tvs = tvs, cab_lhs = lhs } <- coAxiomNthBranch ax index
, (tys1, tys2) <- splitAtList tvs tys
= ASSERT( tvs `equalLength` tys1 )
mkTyConApp (coAxiomTyCon ax) (substTysWith tvs tys1 lhs ++ tys2)
mkAxInstRHS ax index tys
| CoAxBranch { cab_tvs = tvs, cab_rhs = rhs } <- coAxiomNthBranch ax index
, (tys1, tys2) <- splitAtList tvs tys
= ASSERT( tvs `equalLength` tys1 )
mkAppTys (substTyWith tvs tys1 rhs) tys2
mkUnbranchedAxInstRHS :: CoAxiom Unbranched -> [Type] -> Type
mkUnbranchedAxInstRHS ax = mkAxInstRHS ax 0
-- | 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 -> Coercion -> Coercion
mkAppCo co1 co2 = mkAppCoFlexible co1 Nominal co2
-- 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 types/TypeRep.hs.
-- | Apply a 'Coercion' to another 'Coercion'.
-- The second 'Coercion's role is given, making this more flexible than
-- 'mkAppCo'.
mkAppCoFlexible :: Coercion -> Role -> Coercion -> Coercion
mkAppCoFlexible (Refl r ty1) _ (Refl _ ty2)
= Refl r (mkAppTy ty1 ty2)
mkAppCoFlexible (Refl r ty1) r2 co2
| 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 r2 co2]
zip_roles (r1:rs) (ty1:tys) = mkReflCo r1 ty1 : zip_roles rs tys
zip_roles _ _ = panic "zip_roles" -- but the roles are infinite...
mkAppCoFlexible (TyConAppCo r tc cos) r2 co
= case r of
Nominal -> ASSERT( r2 == Nominal )
TyConAppCo Nominal tc (cos ++ [co])
Representational -> TyConAppCo Representational tc (cos ++ [co'])
where new_role = (tyConRolesX Representational tc) !! (length cos)
co' = downgradeRole new_role r2 co
Phantom -> TyConAppCo Phantom tc (cos ++ [mkPhantomCo co])
mkAppCoFlexible co1 _r2 co2 = ASSERT( _r2 == Nominal )
AppCo co1 co2
-- | 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
-- | 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 tv_co_prs rhs_ty) leftover_cos
| Just tys <- traverse isReflCo_maybe cos
= Refl r (mkTyConApp tc tys) -- 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 a 'Coercion' which binds a variable within an inner 'Coercion'
mkForAllCo :: Var -> Coercion -> Coercion
-- note that a TyVar should be used here, not a CoVar (nor a TcTyVar)
mkForAllCo tv (Refl r ty) = ASSERT( isTyVar tv ) Refl r (mkForAllTy tv ty)
mkForAllCo tv co = ASSERT( isTyVar tv ) ForAllCo tv co
-------------------------------
-- | 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 (UnivCo s r ty1 ty2) = UnivCo s r ty2 ty1
mkSymCo (SymCo co) = co
mkSymCo co = SymCo co
-- | Create a new 'Coercion' by composing the two given 'Coercion's transitively.
mkTransCo :: Coercion -> Coercion -> Coercion
mkTransCo (Refl {}) co = co
mkTransCo co (Refl {}) = co
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 n (Refl r ty) = ASSERT( ok_tc_app ty n )
Refl r' (tyConAppArgN n ty)
where tc = tyConAppTyCon ty
r' = nthRole r tc n
mkNthCo n co = ASSERT( ok_tc_app _ty1 n && ok_tc_app _ty2 n )
NthCo n co
where
Pair _ty1 _ty2 = coercionKind co
mkLRCo :: LeftOrRight -> Coercion -> Coercion
mkLRCo lr (Refl eq ty) = Refl eq (pickLR lr (splitAppTy ty))
mkLRCo lr co = LRCo lr co
ok_tc_app :: Type -> Int -> Bool
ok_tc_app ty n = case splitTyConApp_maybe ty of
Just (_, tys) -> tys `lengthExceeds` n
Nothing -> False
-- | Instantiates a 'Coercion' with a 'Type' argument.
mkInstCo :: Coercion -> Type -> Coercion
mkInstCo co ty = InstCo co ty
-- | 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 :: Type -> Type -> Coercion
mkUnsafeCo = mkUnivCo (fsLit "mkUnsafeCo") Representational
mkUnivCo :: FastString -> Role -> Type -> Type -> Coercion
mkUnivCo prov role ty1 ty2
| ty1 `eqType` ty2 = Refl role ty1
| otherwise = UnivCo prov role ty1 ty2
mkAxiomRuleCo :: CoAxiomRule -> [Type] -> [Coercion] -> Coercion
mkAxiomRuleCo = AxiomRuleCo
-- 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 (UnivCo s Nominal ty1 ty2) = UnivCo s Representational ty1 ty2
mkSubCo co = ASSERT2( coercionRole co == Nominal, ppr co <+> ppr (coercionRole co) )
SubCo co
-- only *downgrades* a role. 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 (mkPhantomCo co)
downgradeRole_maybe _ Phantom _ = Nothing
downgradeRole_maybe _ _ co = Just co
-- panics if the requested conversion is not a downgrade.
-- See also 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)
-- Converts a coercion to be nominal, if possible.
-- See also 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 coes)
= do { cos' <- mapM setNominalRole_maybe coes
; return $ TyConAppCo Nominal tc cos' }
setNominalRole_maybe (UnivCo s Representational ty1 ty2) = Just $ UnivCo s Nominal ty1 ty2
-- We do *not* promote UnivCo Phantom, as that's unsafe.
-- UnivCo Nominal is no more unsafe than UnivCo Representational
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 co)
= ForAllCo tv <$> setNominalRole_maybe co
setNominalRole_maybe (NthCo n co)
= NthCo n <$> setNominalRole_maybe co
setNominalRole_maybe (InstCo co ty)
= InstCo <$> setNominalRole_maybe co <*> pure ty
setNominalRole_maybe _ = Nothing
-- takes any coercion and turns it into a Phantom coercion
mkPhantomCo :: Coercion -> Coercion
mkPhantomCo co
| Just ty <- isReflCo_maybe co = Refl Phantom ty
| Pair ty1 ty2 <- coercionKind co = UnivCo (fsLit "mkPhantomCo") Phantom ty1 ty2
-- don't optimise here... wait for OptCoercion
-- All input coercions are assumed to be Nominal,
-- or, if Role is Phantom, the Coercion can be Phantom, too.
applyRole :: Role -> Coercion -> Coercion
applyRole Nominal = id
applyRole Representational = mkSubCo
applyRole Phantom = mkPhantomCo
-- Convert args to a TyConAppCo Nominal to the same TyConAppCo Representational
applyRoles :: TyCon -> [Coercion] -> [Coercion]
applyRoles tc cos
= zipWith applyRole (tyConRolesX Representational 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 = tyConRoles tc ++ repeat Nominal
tyConRolesX role _ = repeat role
nthRole :: Role -> TyCon -> Int -> Role
nthRole Nominal _ _ = Nominal
nthRole Phantom _ _ = Phantom
nthRole Representational tc n
= (tyConRolesX Representational tc) !! 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
-- See note [Newtype coercions] in TyCon
-- | Create a coercion constructor (axiom) suitable for the given
-- newtype 'TyCon'. The 'Name' should be that of a new coercion
-- 'CoAxiom', the 'TyVar's the arguments expected by the @newtype@ and
-- the type the appropriate right hand side of the @newtype@, with
-- the free variables a subset of those 'TyVar's.
mkNewTypeCo :: Name -> TyCon -> [TyVar] -> [Role] -> Type -> CoAxiom Unbranched
mkNewTypeCo name tycon tvs roles rhs_ty
= CoAxiom { co_ax_unique = nameUnique name
, co_ax_name = name
, co_ax_implicit = True -- See Note [Implicit axioms] in TyCon
, co_ax_role = Representational
, co_ax_tc = tycon
, co_ax_branches = FirstBranch branch }
where branch = CoAxBranch { cab_loc = getSrcSpan name
, cab_tvs = tvs
, cab_lhs = mkTyVarTys tvs
, cab_roles = roles
, cab_rhs = rhs_ty
, cab_incomps = [] }
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 = mkForAllCo v co
| otherwise = mkFunCo r (mkReflCo r (varType v)) co
-- The first coercion *must* be Nominal.
mkCoCast :: Coercion -> Coercion -> Coercion
-- (mkCoCast (c :: s1 ~# t1) (g :: (s1 ~# t1) ~# (s2 ~# t2)
mkCoCast c g
= mkSymCo g1 `mkTransCo` c `mkTransCo` g2
where
-- g :: (s1 ~# s2) ~# (t1 ~# t2)
-- g1 :: s1 ~# t1
-- g2 :: s2 ~# t2
[_reflk, g1, g2] = decomposeCo 3 g
-- Remember, (~#) :: forall k. k -> k -> *
-- so it takes *three* arguments, not two
{-
************************************************************************
* *
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_maybe'.
type NormaliseStepper = RecTcChecker
-> TyCon -- tc
-> [Type] -- tys
-> NormaliseStepResult
-- | The result of stepping in a normalisation function.
-- See 'topNormaliseTypeX_maybe'.
data NormaliseStepResult
= NS_Done -- ^ Nothing more to do
| NS_Abort -- ^ Utter failure. The outer function should fail too.
| NS_Step RecTcChecker Type Coercion -- ^ We stepped, yielding new bits;
-- ^ co :: old type ~ new type
modifyStepResultCo :: (Coercion -> Coercion)
-> NormaliseStepResult -> NormaliseStepResult
modifyStepResultCo f (NS_Step rec_nts ty co) = NS_Step rec_nts ty (f co)
modifyStepResultCo _ result = result
-- | 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 -> NormaliseStepper
-> NormaliseStepper
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
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_maybe'.
topNormaliseTypeX_maybe :: NormaliseStepper -> Type -> Maybe (Coercion, Type)
topNormaliseTypeX_maybe stepper
= go initRecTc Nothing
where
go rec_nts mb_co1 ty
| Just (tc, tys) <- splitTyConApp_maybe ty
= case stepper rec_nts tc tys of
NS_Step rec_nts' ty' co2
-> go rec_nts' (mb_co1 `trans` co2) ty'
NS_Done -> all_done
NS_Abort -> Nothing
| otherwise
= all_done
where
all_done | Just co <- mb_co1 = Just (co, ty)
| otherwise = Nothing
Nothing `trans` co2 = Just co2
(Just co1) `trans` co2 = Just (co1 `mkTransCo` co2)
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@, or responds False to ok_tc. Specifically, here's the invariant:
--
-- > topNormaliseNewType_maybe 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
--
topNormaliseNewType_maybe ty
= topNormaliseTypeX_maybe unwrapNewTypeStepper ty
{-
************************************************************************
* *
Equality of coercions
* *
************************************************************************
-}
-- | Determines syntactic equality of coercions
coreEqCoercion :: Coercion -> Coercion -> Bool
coreEqCoercion co1 co2 = coreEqCoercion2 rn_env co1 co2
where rn_env = mkRnEnv2 (mkInScopeSet (tyCoVarsOfCo co1 `unionVarSet` tyCoVarsOfCo co2))
coreEqCoercion2 :: RnEnv2 -> Coercion -> Coercion -> Bool
coreEqCoercion2 env (Refl eq1 ty1) (Refl eq2 ty2) = eq1 == eq2 && eqTypeX env ty1 ty2
coreEqCoercion2 env (TyConAppCo eq1 tc1 cos1) (TyConAppCo eq2 tc2 cos2)
= eq1 == eq2 && tc1 == tc2 && all2 (coreEqCoercion2 env) cos1 cos2
coreEqCoercion2 env (AppCo co11 co12) (AppCo co21 co22)
= coreEqCoercion2 env co11 co21 && coreEqCoercion2 env co12 co22
coreEqCoercion2 env (ForAllCo v1 co1) (ForAllCo v2 co2)
= coreEqCoercion2 (rnBndr2 env v1 v2) co1 co2
coreEqCoercion2 env (CoVarCo cv1) (CoVarCo cv2)
= rnOccL env cv1 == rnOccR env cv2
coreEqCoercion2 env (AxiomInstCo con1 ind1 cos1) (AxiomInstCo con2 ind2 cos2)
= con1 == con2
&& ind1 == ind2
&& all2 (coreEqCoercion2 env) cos1 cos2
-- the provenance string is just a note, so don't use in comparisons
coreEqCoercion2 env (UnivCo _ r1 ty11 ty12) (UnivCo _ r2 ty21 ty22)
= r1 == r2 && eqTypeX env ty11 ty21 && eqTypeX env ty12 ty22
coreEqCoercion2 env (SymCo co1) (SymCo co2)
= coreEqCoercion2 env co1 co2
coreEqCoercion2 env (TransCo co11 co12) (TransCo co21 co22)
= coreEqCoercion2 env co11 co21 && coreEqCoercion2 env co12 co22
coreEqCoercion2 env (NthCo d1 co1) (NthCo d2 co2)
= d1 == d2 && coreEqCoercion2 env co1 co2
coreEqCoercion2 env (LRCo d1 co1) (LRCo d2 co2)
= d1 == d2 && coreEqCoercion2 env co1 co2
coreEqCoercion2 env (InstCo co1 ty1) (InstCo co2 ty2)
= coreEqCoercion2 env co1 co2 && eqTypeX env ty1 ty2
coreEqCoercion2 env (SubCo co1) (SubCo co2)
= coreEqCoercion2 env co1 co2
coreEqCoercion2 env (AxiomRuleCo a1 ts1 cs1) (AxiomRuleCo a2 ts2 cs2)
= a1 == a2 && all2 (eqTypeX env) ts1 ts2 && all2 (coreEqCoercion2 env) cs1 cs2
coreEqCoercion2 _ _ _ = False
{-
************************************************************************
* *
Substitution of coercions
* *
************************************************************************
-}
-- | A substitution of 'Coercion's for 'CoVar's (OR 'TyVar's, when
-- doing a \"lifting\" substitution)
type CvSubstEnv = VarEnv Coercion
emptyCvSubstEnv :: CvSubstEnv
emptyCvSubstEnv = emptyVarEnv
data CvSubst
= CvSubst InScopeSet -- The in-scope type variables
TvSubstEnv -- Substitution of types
CvSubstEnv -- Substitution of coercions
instance Outputable CvSubst where
ppr (CvSubst ins tenv cenv)
= brackets $ sep[ ptext (sLit "CvSubst"),
nest 2 (ptext (sLit "In scope:") <+> ppr ins),
nest 2 (ptext (sLit "Type env:") <+> ppr tenv),
nest 2 (ptext (sLit "Coercion env:") <+> ppr cenv) ]
emptyCvSubst :: CvSubst
emptyCvSubst = CvSubst emptyInScopeSet emptyVarEnv emptyVarEnv
isEmptyCvSubst :: CvSubst -> Bool
isEmptyCvSubst (CvSubst _ tenv cenv) = isEmptyVarEnv tenv && isEmptyVarEnv cenv
getCvInScope :: CvSubst -> InScopeSet
getCvInScope (CvSubst in_scope _ _) = in_scope
zapCvSubstEnv :: CvSubst -> CvSubst
zapCvSubstEnv (CvSubst in_scope _ _) = CvSubst in_scope emptyVarEnv emptyVarEnv
cvTvSubst :: CvSubst -> TvSubst
cvTvSubst (CvSubst in_scope tvs _) = TvSubst in_scope tvs
tvCvSubst :: TvSubst -> CvSubst
tvCvSubst (TvSubst in_scope tenv) = CvSubst in_scope tenv emptyCvSubstEnv
extendTvSubst :: CvSubst -> TyVar -> Type -> CvSubst
extendTvSubst (CvSubst in_scope tenv cenv) tv ty
= CvSubst in_scope (extendVarEnv tenv tv ty) cenv
extendTvSubstAndInScope :: CvSubst -> TyVar -> Type -> CvSubst
extendTvSubstAndInScope (CvSubst in_scope tenv cenv) tv ty
= CvSubst (in_scope `extendInScopeSetSet` tyVarsOfType ty)
(extendVarEnv tenv tv ty)
cenv
extendCvSubstAndInScope :: CvSubst -> CoVar -> Coercion -> CvSubst
-- Also extends the in-scope set
extendCvSubstAndInScope (CvSubst in_scope tenv cenv) cv co
= CvSubst (in_scope `extendInScopeSetSet` tyCoVarsOfCo co)
tenv
(extendVarEnv cenv cv co)
substCoVarBndr :: CvSubst -> CoVar -> (CvSubst, CoVar)
substCoVarBndr subst@(CvSubst in_scope tenv cenv) old_var
= ASSERT( isCoVar old_var )
(CvSubst (in_scope `extendInScopeSet` new_var) tenv new_cenv, new_var)
where
-- When we substitute (co :: t1 ~ t2) we may get the identity (co :: t ~ t)
-- In that case, mkCoVarCo will return a ReflCoercion, and
-- we want to substitute that (not new_var) for old_var
new_co = mkCoVarCo new_var
no_change = new_var == old_var && not (isReflCo new_co)
new_cenv | no_change = delVarEnv cenv old_var
| otherwise = extendVarEnv cenv old_var new_co
new_var = uniqAway in_scope subst_old_var
subst_old_var = mkCoVar (varName old_var) (substTy subst (varType old_var))
-- It's important to do the substitution for coercions,
-- because they can have free type variables
substTyVarBndr :: CvSubst -> TyVar -> (CvSubst, TyVar)
substTyVarBndr (CvSubst in_scope tenv cenv) old_var
= case Type.substTyVarBndr (TvSubst in_scope tenv) old_var of
(TvSubst in_scope' tenv', new_var) -> (CvSubst in_scope' tenv' cenv, new_var)
mkCvSubst :: InScopeSet -> [(Var,Coercion)] -> CvSubst
mkCvSubst in_scope prs = CvSubst in_scope Type.emptyTvSubstEnv (mkVarEnv prs)
zipOpenCvSubst :: [Var] -> [Coercion] -> CvSubst
zipOpenCvSubst vs cos
| debugIsOn && (length vs /= length cos)
= pprTrace "zipOpenCvSubst" (ppr vs $$ ppr cos) emptyCvSubst
| otherwise
= CvSubst (mkInScopeSet (tyCoVarsOfCos cos)) emptyTvSubstEnv (zipVarEnv vs cos)
substCoWithTy :: InScopeSet -> TyVar -> Type -> Coercion -> Coercion
substCoWithTy in_scope tv ty = substCoWithTys in_scope [tv] [ty]
substCoWithTys :: InScopeSet -> [TyVar] -> [Type] -> Coercion -> Coercion
substCoWithTys in_scope tvs tys co
| debugIsOn && (length tvs /= length tys)
= pprTrace "substCoWithTys" (ppr tvs $$ ppr tys) co
| otherwise
= ASSERT( length tvs == length tys )
substCo (CvSubst in_scope (zipVarEnv tvs tys) emptyVarEnv) co
-- | Substitute within a 'Coercion'
substCo :: CvSubst -> Coercion -> Coercion
substCo subst co | isEmptyCvSubst subst = co
| otherwise = subst_co subst co
-- | Substitute within several 'Coercion's
substCos :: CvSubst -> [Coercion] -> [Coercion]
substCos subst cos | isEmptyCvSubst subst = cos
| otherwise = map (substCo subst) cos
substTy :: CvSubst -> Type -> Type
substTy subst = Type.substTy (cvTvSubst subst)
subst_co :: CvSubst -> Coercion -> Coercion
subst_co subst co
= go co
where
go_ty :: Type -> Type
go_ty = Coercion.substTy subst
go :: Coercion -> Coercion
go (Refl eq ty) = Refl eq $! go_ty ty
go (TyConAppCo eq tc cos) = let args = map go cos
in args `seqList` TyConAppCo eq tc args
go (AppCo co1 co2) = mkAppCo (go co1) $! go co2
go (ForAllCo tv co) = case substTyVarBndr subst tv of
(subst', tv') ->
ForAllCo tv' $! subst_co subst' co
go (CoVarCo cv) = substCoVar subst cv
go (AxiomInstCo con ind cos) = AxiomInstCo con ind $! map go cos
go (UnivCo s r ty1 ty2) = (UnivCo s r $! go_ty ty1) $! go_ty ty2
go (SymCo co) = mkSymCo (go co)
go (TransCo co1 co2) = mkTransCo (go co1) (go co2)
go (NthCo d co) = mkNthCo d (go co)
go (LRCo lr co) = mkLRCo lr (go co)
go (InstCo co ty) = mkInstCo (go co) $! go_ty ty
go (SubCo co) = mkSubCo (go co)
go (AxiomRuleCo co ts cs) = let ts1 = map go_ty ts
cs1 = map go cs
in ts1 `seqList` cs1 `seqList`
AxiomRuleCo co ts1 cs1
substCoVar :: CvSubst -> CoVar -> Coercion
substCoVar (CvSubst in_scope _ cenv) cv
| Just co <- lookupVarEnv cenv cv = co
| Just cv1 <- lookupInScope in_scope cv = ASSERT( isCoVar cv1 ) CoVarCo cv1
| otherwise = WARN( True, ptext (sLit "substCoVar not in scope") <+> ppr cv $$ ppr in_scope)
ASSERT( isCoVar cv ) CoVarCo cv
substCoVars :: CvSubst -> [CoVar] -> [Coercion]
substCoVars subst cvs = map (substCoVar subst) cvs
lookupTyVar :: CvSubst -> TyVar -> Maybe Type
lookupTyVar (CvSubst _ tenv _) tv = lookupVarEnv tenv tv
lookupCoVar :: CvSubst -> Var -> Maybe Coercion
lookupCoVar (CvSubst _ _ cenv) v = lookupVarEnv cenv v
{-
************************************************************************
* *
"Lifting" substitution
[(TyVar,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.
Note [Substituting kinds in liftCoSubst]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
We need to take care with kind polymorphism. Suppose
K :: forall k (a:k). (forall b:k. a -> b) -> T k a
Now given (K @kk1 @ty1 v) |> g) where
g :: T kk1 ty1 ~ T kk2 ty2
we want to compute
(forall b:k a->b) [ Nth 0 g/k, Nth 1 g/a ]
Notice that we MUST substitute for 'k'; this happens in
liftCoSubstTyVarBndr. But what should we substitute?
We need to take b's kind 'k' and return a Kind, not a Coercion!
Happily we can do this because we know that all kind coercions
((Nth 0 g) in this case) are Refl. So we need a special purpose
subst_kind: LiftCoSubst -> Kind -> Kind
that expects a Refl coercion (or something equivalent to Refl)
when it looks up a kind variable.
-}
-- ----------------------------------------------------
-- See Note [Lifting coercions over types: liftCoSubst]
-- ----------------------------------------------------
data LiftCoSubst = LCS InScopeSet LiftCoEnv
type LiftCoEnv = VarEnv Coercion
-- Maps *type variables* to *coercions*
-- That's the whole point of this function!
liftCoSubstWith :: Role -> [TyVar] -> [Coercion] -> Type -> Coercion
liftCoSubstWith r tvs cos ty
= liftCoSubst r (zipEqual "liftCoSubstWith" tvs cos) ty
liftCoSubst :: Role -> [(TyVar,Coercion)] -> Type -> Coercion
liftCoSubst r prs ty
| null prs = Refl r ty
| otherwise = ty_co_subst (LCS (mkInScopeSet (tyCoVarsOfCos (map snd prs)))
(mkVarEnv prs)) r ty
-- | The \"lifting\" operation which substitutes coercions for type
-- variables in a type to produce a coercion.
--
-- For the inverse operation, see 'liftCoMatch'
-- The Role parameter is the _desired_ role
ty_co_subst :: LiftCoSubst -> Role -> Type -> Coercion
ty_co_subst subst role ty
= go role ty
where
go Phantom ty = lift_phantom ty
go role (TyVarTy tv) = liftCoSubstTyVar subst role tv
`orElse` Refl role (TyVarTy tv)
-- A type variable from a non-cloned forall
-- won't be in the substitution
go role (AppTy ty1 ty2) = mkAppCo (go role ty1) (go Nominal ty2)
go role (TyConApp tc tys) = mkTyConAppCo role tc
(zipWith go (tyConRolesX role tc) tys)
-- IA0_NOTE: Do we need to do anything
-- about kind instantiations? I don't think
-- so. see Note [Kind coercions]
go role (FunTy ty1 ty2) = mkFunCo role (go role ty1) (go role ty2)
go role (ForAllTy v ty) = mkForAllCo v' $! (ty_co_subst subst' role ty)
where
(subst', v') = liftCoSubstTyVarBndr subst v
go role ty@(LitTy {}) = ASSERT( role == Nominal )
mkReflCo role ty
lift_phantom ty = mkUnivCo (fsLit "lift_phantom")
Phantom (liftCoSubstLeft subst ty)
(liftCoSubstRight subst ty)
{-
Note [liftCoSubstTyVar]
~~~~~~~~~~~~~~~~~~~~~~~
This function can fail (i.e., return Nothing) for two separate reasons:
1) The variable is not in the substutition
2) The coercion found 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 for reason 2) in this
case, we really should panic -- something is deeply wrong. But, in matchAxiom,
failing for reason 2) is fine. matchAxiom is trying to find a set of coercions
that match, but it may fail, and this is healthy behavior. Bottom line: if
you find that liftCoSubst is doing weird things (like leaving out-of-scope
variables lying around), disable coercion optimization (bypassing matchAxiom)
and use downgradeRole instead of downgradeRole_maybe. The panic will then happen,
and you may learn something useful.
-}
liftCoSubstTyVar :: LiftCoSubst -> Role -> TyVar -> Maybe Coercion
liftCoSubstTyVar (LCS _ cenv) r tv
= do { co <- lookupVarEnv cenv tv
; let co_role = coercionRole co -- could theoretically take this as
-- a parameter, but painful
; downgradeRole_maybe r co_role co } -- see Note [liftCoSubstTyVar]
liftCoSubstTyVarBndr :: LiftCoSubst -> TyVar -> (LiftCoSubst, TyVar)
liftCoSubstTyVarBndr subst@(LCS in_scope cenv) old_var
= (LCS (in_scope `extendInScopeSet` new_var) new_cenv, new_var)
where
new_cenv | no_change = delVarEnv cenv old_var
| otherwise = extendVarEnv cenv old_var (Refl Nominal (TyVarTy new_var))
no_change = no_kind_change && (new_var == old_var)
new_var1 = uniqAway in_scope old_var
old_ki = tyVarKind old_var
no_kind_change = isEmptyVarSet (tyVarsOfType old_ki)
new_var | no_kind_change = new_var1
| otherwise = setTyVarKind new_var1 (subst_kind subst old_ki)
-- map every variable to the type on the *left* of its mapped coercion
liftCoSubstLeft :: LiftCoSubst -> Type -> Type
liftCoSubstLeft (LCS in_scope cenv) ty
= Type.substTy (mkTvSubst in_scope (mapVarEnv (pFst . coercionKind) cenv)) ty
-- same, but to the type on the right
liftCoSubstRight :: LiftCoSubst -> Type -> Type
liftCoSubstRight (LCS in_scope cenv) ty
= Type.substTy (mkTvSubst in_scope (mapVarEnv (pSnd . coercionKind) cenv)) ty
subst_kind :: LiftCoSubst -> Kind -> Kind
-- See Note [Substituting kinds in liftCoSubst]
subst_kind subst@(LCS _ cenv) kind
= go kind
where
go (LitTy n) = n `seq` LitTy n
go (TyVarTy kv) = subst_kv kv
go (TyConApp tc tys) = let args = map go tys
in args `seqList` TyConApp tc args
go (FunTy arg res) = (FunTy $! (go arg)) $! (go res)
go (AppTy fun arg) = mkAppTy (go fun) $! (go arg)
go (ForAllTy tv ty) = case liftCoSubstTyVarBndr subst tv of
(subst', tv') ->
ForAllTy tv' $! (subst_kind subst' ty)
subst_kv kv
| Just co <- lookupVarEnv cenv kv
, let co_kind = coercionKind co
= ASSERT2( pFst co_kind `eqKind` pSnd co_kind, ppr kv $$ ppr co )
pFst co_kind
| otherwise
= TyVarTy kv
-- | 'liftCoMatch' is sort of inverse to 'liftCoSubst'. In particular, if
-- @liftCoMatch vars ty co == Just s@, then @tyCoSubst s ty == co@.
-- That is, it matches a type against a coercion of the same
-- "shape", and returns a lifting substitution which could have been
-- used to produce the given coercion from the given type.
liftCoMatch :: TyVarSet -> Type -> Coercion -> Maybe LiftCoSubst
liftCoMatch tmpls ty co
= case ty_co_match menv emptyVarEnv ty co of
Just cenv -> Just (LCS in_scope cenv)
Nothing -> Nothing
where
menv = ME { me_tmpls = tmpls, me_env = mkRnEnv2 in_scope }
in_scope = mkInScopeSet (tmpls `unionVarSet` tyCoVarsOfCo co)
-- Like tcMatchTy, assume all the interesting variables
-- in ty are in tmpls
-- | 'ty_co_match' does all the actual work for 'liftCoMatch'.
ty_co_match :: MatchEnv -> LiftCoEnv -> Type -> Coercion -> Maybe LiftCoEnv
ty_co_match menv subst ty co
| Just ty' <- coreView ty = ty_co_match menv subst ty' co
-- Match a type variable against a non-refl coercion
ty_co_match menv cenv (TyVarTy tv1) co
| Just co1' <- lookupVarEnv cenv tv1' -- tv1' is already bound to co1
= if coreEqCoercion2 (nukeRnEnvL rn_env) co1' co
then Just cenv
else Nothing -- no match since tv1 matches two different coercions
| tv1' `elemVarSet` me_tmpls menv -- tv1' is a template var
= if any (inRnEnvR rn_env) (varSetElems (tyCoVarsOfCo co))
then Nothing -- occurs check failed
else return (extendVarEnv cenv tv1' co)
-- BAY: I don't think we need to do any kind matching here yet
-- (compare 'match'), but we probably will when moving to SHE.
| otherwise -- tv1 is not a template ty var, so the only thing it
-- can match is a reflexivity coercion for itself.
-- But that case is dealt with already
= Nothing
where
rn_env = me_env menv
tv1' = rnOccL rn_env tv1
ty_co_match menv subst (AppTy ty1 ty2) co
| Just (co1, co2) <- splitAppCo_maybe co -- c.f. Unify.match on AppTy
= do { subst' <- ty_co_match menv subst ty1 co1
; ty_co_match menv subst' ty2 co2 }
ty_co_match menv subst (TyConApp tc1 tys) (TyConAppCo _ tc2 cos)
| tc1 == tc2 = ty_co_matches menv subst tys cos
ty_co_match menv subst (FunTy ty1 ty2) (TyConAppCo _ tc cos)
| tc == funTyCon = ty_co_matches menv subst [ty1,ty2] cos
ty_co_match menv subst (ForAllTy tv1 ty) (ForAllCo tv2 co)
= ty_co_match menv' subst ty co
where
menv' = menv { me_env = rnBndr2 (me_env menv) tv1 tv2 }
ty_co_match menv subst ty co
| Just co' <- pushRefl co = ty_co_match menv subst ty co'
| otherwise = Nothing
ty_co_matches :: MatchEnv -> LiftCoEnv -> [Type] -> [Coercion] -> Maybe LiftCoEnv
ty_co_matches menv = matchList (ty_co_match menv)
pushRefl :: Coercion -> Maybe Coercion
pushRefl (Refl Nominal (AppTy ty1 ty2))
= Just (AppCo (Refl Nominal ty1) (Refl Nominal ty2))
pushRefl (Refl r (FunTy ty1 ty2))
= Just (TyConAppCo r funTyCon [Refl r ty1, Refl r ty2])
pushRefl (Refl r (TyConApp tc tys))
= Just (TyConAppCo r tc (zipWith mkReflCo (tyConRolesX r tc) tys))
pushRefl (Refl r (ForAllTy tv ty)) = Just (ForAllCo tv (Refl r ty))
pushRefl _ = Nothing
{-
************************************************************************
* *
Sequencing on coercions
* *
************************************************************************
-}
seqCo :: Coercion -> ()
seqCo (Refl eq ty) = eq `seq` seqType ty
seqCo (TyConAppCo eq tc cos) = eq `seq` tc `seq` seqCos cos
seqCo (AppCo co1 co2) = seqCo co1 `seq` seqCo co2
seqCo (ForAllCo tv co) = seqType (tyVarKind tv) `seq` seqCo co
seqCo (CoVarCo cv) = cv `seq` ()
seqCo (AxiomInstCo con ind cos) = con `seq` ind `seq` seqCos cos
seqCo (UnivCo s r ty1 ty2) = s `seq` r `seq` seqType ty1 `seq` seqType ty2
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 ty) = seqCo co `seq` seqType ty
seqCo (SubCo co) = seqCo co
seqCo (AxiomRuleCo _ ts cs) = seqTypes ts `seq` seqCos cs
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 tv co) = mkForAllTy tv <$> go co
go (CoVarCo cv) = toPair $ coVarKind cv
go (AxiomInstCo ax ind cos)
| CoAxBranch { cab_tvs = tvs, cab_lhs = lhs, cab_rhs = rhs } <- coAxiomNthBranch ax ind
, Pair tys1 tys2 <- sequenceA (map go cos)
= ASSERT( cos `equalLength` tvs ) -- Invariant of AxiomInstCo: cos should
-- exactly saturate the axiom branch
Pair (substTyWith tvs tys1 (mkTyConApp (coAxiomTyCon ax) lhs))
(substTyWith tvs tys2 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 (NthCo d co) = tyConAppArgN d <$> go co
go (LRCo lr co) = (pickLR lr . splitAppTy) <$> go co
go (InstCo aco ty) = go_app aco [ty]
go (SubCo co) = go co
go (AxiomRuleCo ax tys cos) =
case coaxrProves ax tys (map go cos) of
Just res -> res
Nothing -> panic "coercionKind: Malformed coercion"
go_app :: Coercion -> [Type] -> Pair Type
-- Collect up all the arguments and apply all at once
-- See Note [Nested InstCos]
go_app (InstCo co ty) tys = go_app co (ty:tys)
go_app co tys = (`applyTys` tys) <$> go 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 tv co)
= let (tys, r) = go co in
(mkForAllTy tv <$> tys, r)
go (CoVarCo cv) = (toPair $ coVarKind 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)
= let (Pair t1 t2, r) = go co
(tc1, args1) = splitTyConApp t1
(_tc2, args2) = splitTyConApp t2
in
ASSERT( tc1 == _tc2 )
((`getNth` d) <$> Pair args1 args2, nthRole r tc1 d)
go co@(LRCo {}) = (coercionKind co, Nominal)
go (InstCo co ty) = go_app co [ty]
go (SubCo co) = (coercionKind co, Representational)
go co@(AxiomRuleCo ax _ _) = (coercionKind co, coaxrRole ax)
go_app :: Coercion -> [Type] -> (Pair Type, Role)
-- Collect up all the arguments and apply all at once
-- See Note [Nested InstCos]
go_app (InstCo co ty) tys = go_app co (ty:tys)
go_app co tys
= let (pair, r) = go co in
((`applyTys` tys) <$> pair, 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.applyTys (which in fact we call here)
-}
applyCo :: Type -> Coercion -> Type
-- Gives the type of (e co) where e :: (a~b) => ty
applyCo ty co | Just ty' <- coreView ty = applyCo ty' co
applyCo (FunTy _ ty) _ = ty
applyCo _ _ = panic "applyCo"
{-
Note [Kind coercions]
~~~~~~~~~~~~~~~~~~~~~
Kind coercions are only of the form: Refl kind. They are only used to
instantiate kind polymorphic type constructors in TyConAppCo. Remember
that kind instantiation only happens with TyConApp, not AppTy.
-}
|
acowley/ghc
|
compiler/types/Coercion.hs
|
bsd-3-clause
| 80,443
| 1,008
| 12
| 21,251
| 11,670
| 7,228
| 4,442
| 938
| 16
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE TemplateHaskell #-}
module Ros.Test_msgs.StringConst where
import qualified Prelude as P
import Prelude ((.), (+), (*))
import qualified Data.Typeable as T
import Control.Applicative
import Ros.Internal.RosBinary
import Ros.Internal.Msg.MsgInfo
import qualified GHC.Generics as G
import qualified Data.Default.Generics as D
import Lens.Family.TH (makeLenses)
import Lens.Family (view, set)
data StringConst = StringConst { _link_name :: P.String
} deriving (P.Show, P.Eq, P.Ord, T.Typeable, G.Generic)
$(makeLenses ''StringConst)
instance RosBinary StringConst where
put obj' = put (_link_name obj')
get = StringConst <$> get
instance MsgInfo StringConst where
sourceMD5 _ = "a8e1a25e612660c2e8d3d161e9e91950"
msgTypeName _ = "test_msgs/StringConst"
instance D.Default StringConst
remove_all_attached_objects :: P.String
remove_all_attached_objects = "\"all\""
embedded_quotes :: P.String
embedded_quotes = "here \"we\" go"
|
bitemyapp/roshask
|
Tests/test_msgs/golden/StringConst.hs
|
bsd-3-clause
| 1,086
| 1
| 9
| 165
| 227
| 136
| 91
| 29
| 1
|
module Simple2 where
-- f1 :: Int -> Int -> Int
f1 x y = x + y
f2 x y = y - x
|
kmate/HaRe
|
old/testing/merging/Simple2.hs
|
bsd-3-clause
| 79
| 0
| 5
| 26
| 33
| 18
| 15
| 3
| 1
|
module Names where
import MarshalFixup (cTypeNameToHSType, fixCFunctionName)
import Utils (splitBy, lowerCaseFirstWord, upperCaseFirstChar)
import Data.Char as Char (toLower, isUpper, isLower)
cFuncNameToHsName :: String -> String
cFuncNameToHsName =
lowerCaseFirstWord
. MarshalFixup.cTypeNameToHSType
. toStudlyCapsWithFixups
. takeWhile ('('/=)
cParamNameToHsName :: String -> String
cParamNameToHsName = --change "gtk_foo_bar" to "gtkFooBar"
lowerCaseFirstWord
. toStudlyCaps
cConstNameToHsName :: String -> String
cConstNameToHsName = --change "GTK_UPDATE_DISCONTINUOUS" to "UpdateDiscontinuous"
MarshalFixup.cTypeNameToHSType
. toStudlyCaps
. map Char.toLower
cFuncNameToHsPropName :: String -> String
cFuncNameToHsPropName =
concatMap upperCaseFirstChar
. map fixCFunctionName
. tail
. dropWhile (/="get")
. filter (not.null)
. splitBy '_'
cAttrNametoHsName :: String -> String
cAttrNametoHsName = --change "label-xalign" to "LabelXAlign"
toStudlyCapsWithFixups
. map dashToUnderscore
where dashToUnderscore '-' = '_'
dashToUnderscore c = c
toStudlyCaps :: String -> String
toStudlyCaps = --change "gtk_foo_bar" to "GtkFooBar"
concatMap upperCaseFirstChar
. filter (not.null) --to ignore tailing underscores
. splitBy '_'
toStudlyCapsWithFixups :: String -> String
toStudlyCapsWithFixups = --change "gtk_foo_bar" to "GtkFooBar"
concatMap upperCaseFirstChar
. map MarshalFixup.fixCFunctionName
. filter (not.null) --to ignore tailing underscores
. splitBy '_'
hsTypeNameToCGetType :: String -> String
hsTypeNameToCGetType hsTypeName =
convert False hsTypeName ++ "_get_type"
where convert _ [] = []
convert True (c:cs) | isUpper c = '_' : convert False (c:cs)
convert lastLower (c:cs) = toLower c : convert (isLower c) cs
|
k0001/gtk2hs
|
tools/apiGen/src/Names.hs
|
gpl-3.0
| 1,935
| 0
| 11
| 410
| 433
| 229
| 204
| 50
| 3
|
module Prelude where
data Bool = False | True
data Int
data Maybe a = Nothing | Just a
data (,) a b = (,) a b
not False = True
not True = False
data [] a = [] | a : [a]
map f [] = []
map f (x:xs) = f x:map f xs
null = f
where
f [] = True
f _ = False
t = null []
f = not t
{-
data P = P { x,y::Int }
origin P{x=0,y=0} = True
origin _ = False
-}
class Functor f where
fmap :: (a->b) -> f a -> f b
instance Functor [] where fmap = map
ys = fmap id []
(id,const) = (\x->x,\x y->x)
error s = undefined
undefined | False = undefined
|
forste/haReFork
|
tools/base/tests/tiTest5.hs
|
bsd-3-clause
| 554
| 27
| 8
| 159
| 288
| 153
| 135
| -1
| -1
|
{-# LANGUAGE EmptyCase #-}
{-# OPTIONS -Wincomplete-patterns #-}
module T15584 where
import Data.Void
data V = MkV !Void
data S1 = MkS1 !V
newtype S2 = MkS2 V
s1 :: S1 -> a
s1 x = case x of {}
s2 :: S2 -> a
s2 x = case x of {}
|
sdiehl/ghc
|
testsuite/tests/pmcheck/should_compile/T15584.hs
|
bsd-3-clause
| 234
| 0
| 7
| 59
| 85
| 49
| 36
| 15
| 0
|
{-# LANGUAGE TemplateHaskell #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
{-| Unittests for query aliases.
-}
{-
Copyright (C) 2013 Google Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Test.Ganeti.Query.Aliases
( testQuery_Aliases
) where
import Data.List
import Test.Ganeti.TestHelper
import Test.HUnit
import Ganeti.Query.Common ()
import qualified Ganeti.Query.Instance as I
import Ganeti.Query.Language
import Ganeti.Query.Types
{-# ANN module "HLint: ignore Use camelCase" #-}
-- | Converts field list to field name list
toFieldNameList :: FieldList a b -> [FieldName]
toFieldNameList = map (\(x,_,_) -> fdefName x)
-- | Converts alias list to alias name list
toAliasNameList :: [(FieldName, FieldName)] -> [FieldName]
toAliasNameList = map fst
-- | Converts alias list to alias target list
toAliasTargetList :: [(FieldName, FieldName)] -> [FieldName]
toAliasTargetList = map snd
-- | Checks for shadowing
checkShadowing :: String
-> FieldList a b
-> [(FieldName, FieldName)]
-> Assertion
checkShadowing name fields aliases =
assertBool (name ++ " aliases do not shadow fields") .
null $ toFieldNameList fields `intersect` toAliasNameList aliases
-- | Checks for target existence
checkTargets :: String
-> FieldList a b
-> [(FieldName, FieldName)]
-> Assertion
checkTargets name fields aliases =
assertBool (name ++ " alias targets exist") .
null $ toAliasTargetList aliases \\ toFieldNameList fields
-- | Check that instance aliases do not shadow existing fields
case_instanceAliasesNoShadowing :: Assertion
case_instanceAliasesNoShadowing =
checkShadowing "Instance" I.instanceFields I.instanceAliases
-- | Check that instance alias targets exist
case_instanceAliasesTargetsExist :: Assertion
case_instanceAliasesTargetsExist =
checkTargets "Instance" I.instanceFields I.instanceAliases
testSuite "Query/Aliases"
[ 'case_instanceAliasesNoShadowing,
'case_instanceAliasesTargetsExist
]
|
leshchevds/ganeti
|
test/hs/Test/Ganeti/Query/Aliases.hs
|
bsd-2-clause
| 3,246
| 0
| 10
| 556
| 376
| 216
| 160
| 41
| 1
|
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE UndecidableInstances #-}
module T9371 where
import Data.Monoid
class C x where
data D x :: *
makeD :: D x
instance {-# OVERLAPPABLE #-} Monoid x => C x where
data D x = D1 (Either x ())
makeD = D1 (Left mempty)
instance (Monoid x, Monoid y) => C (x, y) where
data D (x,y) = D2 (x,y)
makeD = D2 (mempty, mempty)
instance Show x => Show (D x) where
show (D1 x) = show x
main = print (makeD :: D (String, String))
|
urbanslug/ghc
|
testsuite/tests/indexed-types/should_fail/T9371.hs
|
bsd-3-clause
| 525
| 6
| 10
| 132
| 218
| 117
| 101
| 17
| 1
|
{-# LANGUAGE OverloadedStrings #-}
module Comic.Translate where
import Control.Exception as E
import Control.Lens
import Data.Aeson
import Data.Aeson.Lens (_Array, key)
import qualified Data.Text as T
import Data.Vector ((!))
import Network.HTTP.Base (urlEncodeVars)
import Network.Wreq (get, responseBody)
import Network.HTTP.Client (HttpException)
type SourceLanguage = T.Text
type DestinationLanguage = T.Text
type OriginalText = T.Text
class Translator a where
-- | Translate text from the source language to the destination language.
translate
:: a
-> SourceLanguage
-> DestinationLanguage
-> OriginalText
-> IO T.Text
-- | Translator which returns the text in its original form. A dummy translator implementation.
data NoopTranslator =
NoopTranslator
instance Translator NoopTranslator where
translate _ _ _ originalText = return originalText
-- | Translate text from the source language to the destination language using Yandex web service.
data YandexClient = YandexClient
{ apiKey :: String
}
instance Translator YandexClient where
translate translator = yandexTranslate apiKey
where
(YandexClient apiKey) = translator
yandexTranslate apiKey sourceLang destLang text =
(do let translateParams =
urlEncodeVars
[ ("key", apiKey)
, ( "lang"
, (T.unpack sourceLang) ++ "-" ++ (T.unpack destLang))
, ("text", T.unpack text)]
r <-
get $ "https://translate.yandex.net/api/v1.5/tr.json/translate?" ++
translateParams
let textVec = r ^. responseBody . key "text" . _Array
return $ unpackString $ textVec ! 0) `E.catch`
handler
where
unpackString (String s) = s
handler :: HttpException -> IO T.Text
handler _ = return ""
|
ivan444/comic-translate
|
src/Comic/Translate.hs
|
mit
| 1,889
| 0
| 19
| 488
| 423
| 233
| 190
| -1
| -1
|
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE DeriveGeneric #-}
module Block where
import Data.Map as M
import Data.List as L
import Data.Maybe (fromJust)
import Debug.Trace
import Graphics.Gloss
import Data.Aeson
import Data.Aeson.Types
import qualified Data.Text as T (pack, unpack, split, Text)
import GHC.Generics
-- constants
bSize, innerBSide :: Float
bSize = 20
innerBSide = 18
blockBorderColor, boardBackground, boardBorderColor, settledBlockColor :: Color
blockBorderColor = white
boardBackground = makeColorI 0xF0 0xF0 0xF0 0xF0
boardBorderColor = makeColorI 0xFA 0xFA 0xFA 0xFA
settledBlockColor = greyN 0.2
data Action = AUp | ADown | ALeft | ARight | AA | AS | AD
deriving (Show, Eq, Generic)
instance ToJSON Action where
toEncoding = genericToEncoding defaultOptions
instance FromJSON Action
data BlockType = Background | Active | Settled | Hint
deriving (Show, Eq, Generic)
instance ToJSON BlockType where
toEncoding = genericToEncoding defaultOptions
instance FromJSON BlockType where
parseJSON = genericParseJSON defaultOptions
instance ToJSON Color where
toJSON c = String (T.pack $ show c)
instance FromJSON Color where
parseJSON = withText "Color" $ textToColor
where spl :: T.Text -> [Float]
spl t = read . (T.unpack) <$> ( tail $ T.split (\c -> c == ' ') t)
colr [] = Nothing
colr (r:g:b:a:_) = Just (makeColor r g b a)
textToColor :: T.Text -> Parser Color
textToColor t = return $ fromJust $ colr (spl t)
data Block = Block
{ blockType :: BlockType
, coordinate :: (Int, Int)
, blockColor :: Color
} deriving (Generic)
instance ToJSON Block where
toEncoding = genericToEncoding defaultOptions
instance FromJSON Block
instance Eq Block where
x == y = a && b
where a = (blockType x) == (blockType y)
b = (coordinate x) == (coordinate y)
-- | Order Blocks by the natural ordering of their coordinates. This helps line up
-- | blocks to state delta coordinates for zipping when performing a rotation.
instance Ord Block where
x `compare` y = compare (coordinate x) (coordinate y)
instance Show Block where
show x = show $ coordinate x
makeActiveBlock :: Color -> (Int, Int) -> Block
makeActiveBlock c (x,y) = Block { blockType = Active
, coordinate = (x,y)
, blockColor = c
}
makeSettledBlock :: (Int, Int) -> Block
makeSettledBlock (x,y) = Block { blockType = Settled
, coordinate = (x,y)
, blockColor = settledBlockColor
}
makeBackgroundBlock :: Int -> Int -> Block
makeBackgroundBlock x y = Block
{ blockType = Background
, blockColor = boardBackground
, coordinate = (x,y)
}
makeHintBlock :: Color -> (Int,Int) -> Block
makeHintBlock c coor = Block
{ blockType = Hint
, blockColor = c
, coordinate = coor
}
renderHint :: Float -> Float -> [Block] -> Picture
renderHint xOffset yOffset h = pictures $ (renderBlock xOffset yOffset) <$> h
-- | Renders a block by a given offset and a possible color. If the line is currently
-- | being cleared then this color might be a transitional state for animation.
renderBlock :: Float -> Float -> Block -> Picture
renderBlock xOffset yOffset b = pictures [borderBlock, innerBlock]
where innerBlockColor = case (blockType b) of
Hint -> color boardBackground
_ -> color (blockColor b)
innerBlock = translate (xPixel) (yPixel) $ innerBlockColor $ rectangleSolid innerBSide innerBSide
borderBlockColor = case (blockType b) of
Background -> color boardBorderColor
Hint -> color $ blockColor b
_ -> color blockBorderColor
borderBlock = translate xPixel yPixel $ borderBlockColor $ rectangleSolid bSize bSize
(xPixel,yPixel) = convertCoordinate xOffset yOffset (coordinate b)
convertCoordinate :: Float -> Float -> (Int,Int) -> (Float,Float)
convertCoordinate xOffset yOffset (x,y) = (xPixel, yPixel)
where xPixel = ((fromIntegral (-x)) * 20.0) + xOffset
yPixel = ((fromIntegral (-y)) * 20.0) + yOffset
-- | Takes a delta coordinate and moves block by delta, no collision detection is occurring in this method.
-- | The assumption is that collision detection has already been vetted.
moveBlock :: (Int, Int) -> (Int,Int) -> Block -> Block
moveBlock (x,y) (deltaX,deltaY) b =
b { coordinate = (potentialX,potentialY) }
where (potentialX,potentialY) = ((x + deltaX),(y + deltaY))
moveBlockAbsolute :: (Int,Int) -> Block -> Block
moveBlockAbsolute c b = b { coordinate = c }
moveBlockFlipped :: Block -> (Int,Int) -> (Int,Int) -> Block
moveBlockFlipped a b c = moveBlock b c a
moveBlockDown :: Block -> Block
moveBlockDown b = b { coordinate = (x,y+1) }
where (x,y) = coordinate b
moveBlockDownI :: Int -> Block -> Block
moveBlockDownI i b = b { coordinate = (x,y+i) }
where (x,y) = coordinate b
moveBlocksDown :: Map (Int,Int) Block -> Map (Int,Int) Block
moveBlocksDown blocks = trace (show f) $ f --M.map moveBlockDown blocks
where movedBlocks = L.map moveBlockDown (M.elems blocks)
f = L.foldr (\x acc -> M.insert (coordinate x) x acc) M.empty movedBlocks
moveBlocksDownI :: Int -> Map (Int,Int) Block -> Map (Int,Int) Block
moveBlocksDownI i blocks = trace (show f) $ f --M.map moveBlockDown blocks
where movedBlocks = L.map (moveBlockDownI i) (M.elems blocks)
f = L.foldr (\x acc -> M.insert (coordinate x) x acc) M.empty movedBlocks
|
maple-shaft/HaskellTetris
|
src/Block.hs
|
mit
| 6,044
| 0
| 14
| 1,760
| 1,789
| 984
| 805
| 115
| 4
|
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveFunctor #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE TypeFamilies #-}
module Web.Apiary.Authenticate.Internal where
import Control.Applicative((<$>), (<*>))
import Control.Monad(mzero)
import Control.Monad.Trans.Resource(runResourceT)
import Control.Monad.Apiary(ApiaryT, action)
import Control.Monad.Apiary.Filter(focus)
import Control.Monad.Apiary.Action(ActionT, getRequest, redirect)
import qualified Network.Wai as Wai
import qualified Network.HTTP.Types as HTTP
import qualified Network.HTTP.Client as Client
import qualified Web.Authenticate.OpenId as OpenId
import Web.Apiary(MonadIO(..))
import Web.Apiary.Session(Session, deleteSession, setSession)
import Data.Apiary.Extension(Has, Extension)
import Data.Proxy.Compat(Proxy(..))
import Data.Typeable(Typeable)
import Data.Apiary.Method(Method(GET))
import qualified Network.Routing as R
import qualified Data.Serialize as Serialize
import Data.Data (Data)
import Data.Maybe(mapMaybe)
import Data.Default.Class(Default(..))
import Blaze.ByteString.Builder(toByteString)
import qualified Data.ByteString.Char8 as S
import qualified Data.Text as T
import qualified Data.Text.Encoding as T
data AuthConfig = AuthConfig
{ authSuccessPage :: S.ByteString
, authUrl :: T.Text
, authPrefix :: [T.Text]
, authReturnToPath :: [T.Text]
, authLogoutPath :: [T.Text]
, providers :: [(T.Text, Provider)]
}
data Provider = Provider
{ providerUrl :: T.Text
, realm :: Maybe T.Text
, parameters :: [(T.Text, T.Text)]
}
instance Default AuthConfig where
def = AuthConfig "/" "http://localhost:3000" ["auth"] ["return_to"] ["logout"] $
[ ("google", Provider "https://www.google.com/accounts/o8/id" Nothing [])
, ("yahoo", Provider "http://me.yahoo.com/" Nothing [])
]
data Auth = Auth
{ manager :: Client.Manager
, config :: AuthConfig
}
instance Extension Auth
authHandler :: (Monad m, MonadIO actM, Has (Session OpenId actM) exts)
=> Auth -> ApiaryT exts prms actM m ()
authHandler Auth{..} = retH >> mapM_ (uncurry go) (providers config)
where
pfxPath p = focus id (Just GET) $ R.raw "" $ \d t -> do
if t == p
then return (d, [])
else mzero
retH = pfxPath (authPrefix config ++ authReturnToPath config) . action $
returnAction manager (authSuccessPage config)
go name Provider{..} = pfxPath (authPrefix config ++ [name]) . action $
authAction manager providerUrl returnTo realm parameters
returnTo = T.decodeUtf8 $ T.encodeUtf8 (authUrl config) `S.append`
toByteString (HTTP.encodePathSegments (authPrefix config ++ authReturnToPath config))
authConfig :: Auth -> AuthConfig
authConfig = config
authProviders :: Auth -> [(T.Text, Provider)]
authProviders = providers . config
authRoutes :: Auth -> [(T.Text, S.ByteString)]
authRoutes auth =
map (\(k,_) -> (k, toByteString . HTTP.encodePathSegments $ authPrefix (config auth) ++ [k])) $
providers (config auth)
-- | delete session. since 0.7.0.0.
authLogout :: (Has (Session OpenId m) exts, Monad m) => ActionT exts prms m ()
authLogout = deleteSession (Proxy :: Proxy OpenId)
authAction :: MonadIO m => Client.Manager -> T.Text -> T.Text
-> Maybe T.Text -> [(T.Text, T.Text)] -> ActionT exts prms m ()
authAction mgr uri returnTo realm prm = do
fw <- liftIO . runResourceT $ OpenId.getForwardUrl uri returnTo realm prm mgr
redirect $ T.encodeUtf8 fw
data OpenId_ a = OpenId_
{ opLocal :: a
, params :: [(a, a)]
, claimed :: Maybe a
} deriving (Show, Read, Eq, Ord, Data, Typeable, Functor)
instance Serialize.Serialize (OpenId_ S.ByteString) where
put (OpenId_ loc prm cld) = do
Serialize.put loc
Serialize.put prm
Serialize.put cld
get = OpenId_ <$> Serialize.get <*> Serialize.get <*> Serialize.get
instance Serialize.Serialize (OpenId_ T.Text) where
get = fmap (fmap T.decodeUtf8) Serialize.get
put = Serialize.put . fmap T.encodeUtf8
type OpenId = OpenId_ T.Text
toOpenId :: OpenId.OpenIdResponse -> OpenId
toOpenId r = OpenId_
(OpenId.identifier $ OpenId.oirOpLocal r)
(OpenId.oirParams r)
(OpenId.identifier <$> OpenId.oirClaimed r)
returnAction :: (MonadIO m, Has (Session OpenId m) exts)
=> Client.Manager -> S.ByteString -> ActionT exts prms m ()
returnAction mgr to = do
q <- Wai.queryString <$> getRequest
r <- liftIO . runResourceT $ OpenId.authenticateClaimed (mapMaybe queryElem q) mgr
setSession Proxy (toOpenId r)
redirect to
where
queryElem (_, Nothing) = Nothing
queryElem (k, Just v) = Just (T.decodeUtf8 k, T.decodeUtf8 v)
|
philopon/apiary
|
apiary-authenticate/src/Web/Apiary/Authenticate/Internal.hs
|
mit
| 5,001
| 0
| 14
| 1,009
| 1,610
| 892
| 718
| 112
| 2
|
{-# LANGUAGE OverloadedStrings #-}
{-
Most code of this file is copied from one of the samples of Takahiro Himura's twitter-conduit.
https://github.com/himura/twitter-conduit/blob/4e0d58b5d7da3cee1b52995dfe4be8b98d29c970/sample/oauth_pin.hs
Copyright (c)2011-2014, Takahiro Himura
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-}
module Twitter.Authentication
( getCredential
) where
import qualified Data.ByteString.Char8 as BSC8
import System.IO
import Web.Twitter.Conduit.Monad (twitterOAuth)
import qualified Web.Authenticate.OAuth as OA
import Control.Monad.IO.Class
import Network.HTTP.Conduit
getCredential
:: String -- consumerKey
-> String -- consumerSecret
-> IO OA.Credential
getCredential consumerKey consumerSecret =
withManager $ \mgr -> do
cred <- OA.getTemporaryCredential oauth mgr
pin <- getPIN $ OA.authorizeUrl oauth cred
OA.getAccessToken oauth (OA.insert "oauth_verifier" pin cred) mgr
where
oauth = twitterOAuth
{ OA.oauthConsumerKey = BSC8.pack consumerKey
, OA.oauthConsumerSecret = BSC8.pack consumerSecret
}
getPIN url = liftIO $ do
putStrLn $ "Open " ++ url ++ " with your browser."
putStr "> What PIN code did twitter show you? "
hFlush stdout
BSC8.getLine
|
igrep/plus2tweet
|
Twitter/Authentication.hs
|
mit
| 2,518
| 0
| 12
| 452
| 235
| 127
| 108
| 26
| 1
|
{-# LANGUAGE CPP,
QuasiQuotes,
TemplateHaskell,
TypeSynonymInstances,
FlexibleInstances,
TupleSections,
OverloadedStrings #-}
module Gen2.RtsTypes where
import DynFlags
import Encoding
import Id
import Module
import Name
import Outputable hiding ((<>))
import StgSyn
import Unique
import UniqFM
import SrcLoc
import qualified Control.Exception as Ex
import Control.Lens
import Control.Monad.State.Strict
import Data.Array (Array, (!), listArray)
import Data.Bits
import Data.Char (toLower)
import Data.Default
import Data.Ix
import qualified Data.List as L
import qualified Data.Map as M
import Data.Maybe (fromMaybe)
import Data.Monoid
import Data.Set (Set)
import qualified Data.Set as S
import Data.Text (Text)
import qualified Data.Text as T
import Compiler.Compat
import Compiler.JMacro
import Compiler.Utils
import Gen2.ClosureInfo
import Gen2.Utils
traceRts :: ToJExpr a => CgSettings -> a -> JStat
traceRts s e = jStatIf (csTraceRts s) [j| h$log(`e`); |]
assertRts :: ToJExpr a => CgSettings -> JExpr -> a -> JStat
assertRts s e m = jStatIf (csAssertRts s) [j| if(!`e`) { throw `m`; } |]
jStatIf :: Bool -> JStat -> JStat
jStatIf True s = s
jStatIf _ _ = mempty
clName :: JExpr -> JExpr
clName c = [je| `c`.n |]
clTypeName :: JExpr -> JExpr
clTypeName c = [je| h$closureTypeName(`c`.t) |]
infixr 1 |+
infixr 1 |-
infixl 3 |.
infixl 2 |!
infixl 2 |!!
-- a + b
(|+) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|+) e1 e2 = [je| `e1` + `e2` |]
-- a - b
(|-) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|-) e1 e2 = [je| `e1` - `e2` |]
-- a & b
(|&) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|&) e1 e2 = [je| `e1` & `e2` |]
-- a.b
(|.) :: ToJExpr a => a -> Text -> JExpr
(|.) e i = SelExpr (toJExpr e) (TxtI i)
-- a[b]
(|!) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|!) e i = [je| `e`[`i`] |]
-- a[b] with b int
(|!!) :: ToJExpr a => a -> Int -> JExpr
(|!!) = (|!)
-- a(b1,b2,...)
(|^) :: ToJExpr a => a -> [JExpr] -> JExpr
(|^) a bs = ApplExpr (toJExpr a) bs
(|^^) :: Text -> [JExpr] -> JExpr
(|^^) a bs = ApplExpr (jsv a) bs
(|||) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|||) a b = [je| `a` || `b` |]
(|&&) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|&&) a b = [je| `a` && `b` |]
(|===) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|===) a b = [je| `a` === `b` |]
(|!==) :: (ToJExpr a, ToJExpr b) => a -> b -> JExpr
(|!==) a b = [je| `a` !== `b` |]
infix 7 |=
(|=) :: ToJExpr a => Ident -> a -> JStat
(|=) i b = AssignStat (toJExpr i) (toJExpr b)
infix 7 ||=
(||=) :: ToJExpr a => Ident -> a -> JStat
(||=) i b = decl i <> i |= b
showPpr' :: Outputable a => a -> G String
showPpr' a = do
df <- _gsDynFlags <$> get
return (showPpr df a)
showSDoc' :: SDoc -> G String
showSDoc' a = do
df <- _gsDynFlags <$> get
return (showSDoc df a)
-- fixme this is getting out of hand...
data StgReg = R1 | R2 | R3 | R4 | R5 | R6 | R7 | R8
| R9 | R10 | R11 | R12 | R13 | R14 | R15 | R16
| R17 | R18 | R19 | R20 | R21 | R22 | R23 | R24
| R25 | R26 | R27 | R28 | R29 | R30 | R31 | R32
| R33 | R34 | R35 | R36 | R37 | R38 | R39 | R40
| R41 | R42 | R43 | R44 | R45 | R46 | R47 | R48
| R49 | R50 | R51 | R52 | R53 | R54 | R55 | R56
| R57 | R58 | R59 | R60 | R61 | R62 | R63 | R64
| R65 | R66 | R67 | R68 | R69 | R70 | R71 | R72
| R73 | R74 | R75 | R76 | R77 | R78 | R79 | R80
| R81 | R82 | R83 | R84 | R85 | R86 | R87 | R88
| R89 | R90 | R91 | R92 | R93 | R94 | R95 | R96
| R97 | R98 | R99 | R100 | R101 | R102 | R103 | R104
| R105 | R106 | R107 | R108 | R109 | R110 | R111 | R112
| R113 | R114 | R115 | R116 | R117 | R118 | R119 | R120
| R121 | R122 | R123 | R124 | R125 | R126 | R127 | R128
deriving (Eq, Ord, Show, Enum, Bounded, Ix)
-- | return registers
-- extra results from foreign calls can be stored here (first result is returned)
data StgRet = Ret1 | Ret2 | Ret3 | Ret4 | Ret5 | Ret6 | Ret7 | Ret8 | Ret9 | Ret10
deriving (Eq, Ord, Show, Enum, Bounded, Ix)
instance ToJExpr StgReg where
toJExpr = (registers!)
-- only the registers that have a single ident
registersI :: Array StgReg Ident
registersI = listArray (minBound, R32) (map (ri.(registers!)) $ enumFromTo R1 R32)
where
ri (ValExpr (JVar i)) = i
ri _ = error "registersI: not an ident"
registers :: Array StgReg JExpr
registers = listArray (minBound, maxBound) (map regN (enumFrom R1))
where
regN r
| fromEnum r < 32 = ValExpr . JVar . TxtI . T.pack . ("h$"++) . map toLower . show $ r
| otherwise = [je| h$regs[`fromEnum r-32`] |]
instance ToJExpr StgRet where
toJExpr r = ValExpr (JVar (rets!r))
rets :: Array StgRet Ident
rets = listArray (minBound, maxBound) (map retN (enumFrom Ret1))
where
retN = TxtI . T.pack . ("h$"++) . map toLower . show
regName :: StgReg -> String
regName = map toLower . show
regNum :: StgReg -> Int
regNum r = fromEnum r + 1
numReg :: Int -> StgReg
numReg r = toEnum (r - 1)
minReg :: Int
minReg = regNum minBound
maxReg :: Int
maxReg = regNum maxBound
data IdType = IdPlain | IdEntry | IdConEntry deriving (Enum, Eq, Ord, Show)
data IdKey = IdKey !Int !Int !IdType deriving (Eq, Ord)
newtype IdCache = IdCache (M.Map IdKey Ident)
data OtherSymb = OtherSymb !Module !Text
deriving (Ord, Eq, Show)
emptyIdCache :: IdCache
emptyIdCache = IdCache M.empty
data GenState = GenState
{ _gsSettings :: CgSettings -- ^ codegen settings, read-only
, _gsModule :: !Module -- ^ current module
, _gsDynFlags :: DynFlags -- ^ dynamic flags
, _gsId :: !Int -- ^ unique number for the id generator
, _gsIdents :: !IdCache -- ^ hash consing for identifiers from a Unique
, _gsUnfloated :: !(UniqFM StgExpr) -- ^ unfloated arguments
, _gsGroup :: GenGroupState -- ^ state for the current binding group
, _gsGlobal :: [JStat] -- ^ global (per module) statements (gets included when anything else from the module is used)
}
-- | the state relevant for the current binding group
data GenGroupState = GenGroupState
{ _ggsToplevelStats :: [JStat] -- ^ extra toplevel statements for the binding group
, _ggsClosureInfo :: [ClosureInfo] -- ^ closure metadata (info tables) for the binding group
, _ggsStatic :: [StaticInfo] -- ^ static (CAF) data in our binding group
, _ggsStack :: [StackSlot] -- ^ stack info for the current expression
, _ggsStackDepth :: Int -- ^ current stack depth
, _ggsExtraDeps :: Set OtherSymb -- ^ extra dependencies for the linkable unit that contains this group
}
instance Default GenGroupState where
def = GenGroupState [] [] [] [] 0 S.empty
type C = State GenState JStat
type G = State GenState
data StackSlot = SlotId !Id !Int
| SlotUnknown
deriving (Eq, Ord, Show)
makeLenses ''GenGroupState
makeLenses ''GenState
assertRtsStat :: C -> C
assertRtsStat stat = do
s <- use gsSettings
if csAssertRts s then stat else mempty
-- | emit a global (for the current module) toplevel statement
emitGlobal :: JStat -> G ()
emitGlobal s = gsGlobal %= (s:)
-- functions below modify the current binding group state
-- | start with a new binding group
resetGroup :: G ()
resetGroup = gsGroup .= def
-- | add a dependency on a particular symbol to the current group
addDependency :: OtherSymb -> G ()
addDependency symbol = gsGroup . ggsExtraDeps %= (S.insert symbol)
-- | emit a top-level statement for the current binding group
emitToplevel :: JStat -> G ()
emitToplevel s = gsGroup . ggsToplevelStats %= (s:)
-- | add closure info in our binding group. all heap objects must have closure info
emitClosureInfo :: ClosureInfo -> G ()
emitClosureInfo ci = gsGroup . ggsClosureInfo %= (ci:)
-- | emit static data for the binding group
emitStatic :: Text -> StaticVal -> Maybe Ident -> G ()
emitStatic ident val cc = gsGroup . ggsStatic %= (StaticInfo ident val cc :)
adjPushStack :: Int -> G ()
adjPushStack n = do
stackDepth += n
dropSlots n
dropSlots :: Int -> G ()
dropSlots n = gsGroup . ggsStack %= drop n
-- | add knowledge about the stack slots
addSlots :: [StackSlot] -> G ()
addSlots xs = gsGroup . ggsStack %= (xs++)
stackDepth :: Lens' GenState Int
stackDepth = gsGroup . ggsStackDepth
-- | run the action with no stack info
resetSlots :: G a -> G a
resetSlots m = do
s <- getSlots
d <- use stackDepth
setSlots []
a <- m
setSlots s
stackDepth .= d
return a
-- | run the action with current stack info, but don't let modifications propagate
isolateSlots :: G a -> G a
isolateSlots m = do
s <- getSlots
d <- use stackDepth
a <- m
setSlots s
stackDepth .= d
return a
-- | overwrite our stack knowledge
setSlots :: [StackSlot] -> G ()
setSlots xs = gsGroup . ggsStack .= xs
-- | retrieve our current stack knowledge
getSlots :: G [StackSlot]
getSlots = use (gsGroup . ggsStack)
-- | add `n` unknown slots to our stack knowledge
addUnknownSlots :: Int -> G ()
addUnknownSlots n = addSlots (replicate n SlotUnknown)
throwSimpleSrcErr :: DynFlags -> SrcSpan -> String -> G a
throwSimpleSrcErr df span msg = return $! Ex.throw (simpleSrcErr df span msg)
initState :: DynFlags -> Module -> UniqFM StgExpr -> GenState
initState df m unfloat =
GenState (dfCgSettings df) m df 1 emptyIdCache unfloat def []
runGen :: DynFlags -> Module -> UniqFM StgExpr -> G a -> a
runGen df m unfloat = flip evalState (initState df m unfloat)
instance Monoid C where
mappend = liftM2 (<>)
mempty = return mempty
data Special = Stack
| Sp
deriving (Show, Eq)
instance ToJExpr Special where
toJExpr Stack = [je| h$stack |]
toJExpr Sp = [je| h$sp |]
adjSp' :: Int -> JStat
adjSp' 0 = mempty
adjSp' e = [j| `Sp` = `Sp` + `e`; |]
adjSpN' :: Int -> JStat
adjSpN' 0 = mempty
adjSpN' e = [j| `Sp` = `Sp` - `e`; |]
adjSp :: Int -> C
adjSp 0 = return mempty
adjSp e = stackDepth += e >> return [j| `Sp` = `Sp` + `e`; |]
adjSpN :: Int -> C
adjSpN 0 = return mempty
adjSpN e = stackDepth -= e >> return [j| `Sp` = `Sp` - `e`; |]
pushN :: Array Int Ident
pushN = listArray (1,32) $ map (TxtI . T.pack . ("h$p"++) . show) [(1::Int)..32]
pushN' :: Array Int JExpr
pushN' = fmap (ValExpr . JVar) pushN
pushNN :: Array Integer Ident
pushNN = listArray (1,255) $ map (TxtI . T.pack . ("h$pp"++) . show) [(1::Int)..255]
pushNN' :: Array Integer JExpr
pushNN' = fmap (ValExpr . JVar) pushNN
pushOptimized' :: [(Id,Int)]
-> C
pushOptimized' xs = do
slots <- getSlots
pushOptimized =<< (sequence $ zipWith f xs (slots++repeat SlotUnknown))
where
f (i1,n1) (SlotId i2 n2) = (,i1==i2&&n1==n2) <$> genIdsN i1 n1
f (i1,n1) _ = (,False) <$> genIdsN i1 n1
{- | optimized push that reuses existing values on stack
automatically chooses an optimized partial push (h$ppN)
function when possible.
-}
pushOptimized :: [(JExpr,Bool)] -- ^ contents of the slots, True if same value is already there
-> C
pushOptimized [] = return mempty
pushOptimized xs = do
dropSlots l
stackDepth += length xs
go . csInlinePush <$> use gsSettings
where
go True = inlinePush
go _
| all snd xs = adjSp' l
| all (not.snd) xs && l <= 32 =
ApplStat (pushN' ! l) (map fst xs)
| l <= 8 && not (snd $ last xs) =
ApplStat (pushNN' ! sig) [ e | (e,False) <- xs ]
| otherwise = inlinePush
l = length xs
sig :: Integer
sig = L.foldl1' (.|.) $ zipWith (\(_e,b) i -> if not b then bit i else 0) xs [0..]
inlinePush = adjSp' l <> mconcat (zipWith pushSlot [1..] xs)
pushSlot i (e,False) = [j| `Stack`[`offset i`] = `e` |]
pushSlot _ _ = mempty
offset i | i == l = [je| `Sp` |]
| otherwise = [je| `Sp` - `l-i` |]
push :: [JExpr] -> C
push xs = do
dropSlots (length xs)
stackDepth += length xs
flip push' xs <$> use gsSettings
push' :: CgSettings -> [JExpr] -> JStat
push' _ [] = mempty
push' cs xs
| csInlinePush cs || l > 32 || l < 2 = adjSp' l <> mconcat items
| otherwise = ApplStat (toJExpr $ pushN ! l) xs
where
items = zipWith (\i e -> [j| `Stack`[`offset i`] = `e`; |]) [(1::Int)..] xs
offset i | i == l = [je| `Sp` |]
| otherwise = [je| `Sp` - `l-i` |]
l = length xs
popUnknown :: [JExpr] -> C
popUnknown xs = popSkipUnknown 0 xs
popSkipUnknown :: Int -> [JExpr] -> C
popSkipUnknown n xs = popSkip n (map (,SlotUnknown) xs)
pop :: [(JExpr,StackSlot)] -> C
pop = popSkip 0
-- | pop the expressions, but ignore the top n elements of the stack
popSkip :: Int -> [(JExpr,StackSlot)] -> C
popSkip 0 [] = mempty
popSkip n [] = addUnknownSlots n >> adjSpN n
popSkip n xs = do
addUnknownSlots n
addSlots (map snd xs)
a <- adjSpN (length xs + n)
return (loadSkip n (map fst xs) <> a)
-- | pop things, don't upstate stack knowledge
popSkip' :: Int -- ^ number of slots to skip
-> [JExpr] -- ^ assign stack slot values to these
-> JStat
popSkip' 0 [] = mempty
popSkip' n [] = adjSpN' n
popSkip' n tgt = loadSkip n tgt <> adjSpN' (length tgt + n)
-- | like popSkip, but without modifying the stack pointer
loadSkip :: Int -> [JExpr] -> JStat
loadSkip = loadSkipFrom (toJExpr Sp)
loadSkipFrom :: JExpr -> Int -> [JExpr] -> JStat
loadSkipFrom fr n xs = mconcat items
where
items = reverse $ zipWith (\i e -> [j| `e` = `Stack`[`offset (i+n)`]; |]) [(0::Int)..] (reverse xs)
offset 0 = [je| `fr` |]
offset n = [je| `fr` - `n` |]
-- declare and pop
popSkipI :: Int -> [(Ident,StackSlot)] -> C
popSkipI 0 [] = mempty
popSkipI n [] = adjSpN n
popSkipI n xs = do
addUnknownSlots n
addSlots (map snd xs)
a <- adjSpN (length xs + n)
return (loadSkipI n (map fst xs) <> a)
-- like popSkip, but without modifying sp
loadSkipI :: Int -> [Ident] -> JStat
loadSkipI = loadSkipIFrom (toJExpr Sp)
loadSkipIFrom :: JExpr -> Int -> [Ident] -> JStat
loadSkipIFrom fr n xs = mconcat items
where
items = reverse $ zipWith f [(0::Int)..] (reverse xs)
offset 0 = fr
offset n = [je| `fr` - `n` |]
f i e = [j| `decl e`;
`e` = `Stack`[`offset (i+n)`];
|]
popn :: Int -> C
popn n = addUnknownSlots n >> adjSpN n
-- below: c argument is closure entry, p argument is (heap) pointer to entry
closureType :: JExpr -> JExpr
closureType c = [je| `c`.f.t |]
isThunk :: JExpr -> JExpr
isThunk c = [je| `c`.f.t === `Thunk` |]
isThunk' :: JExpr -> JExpr
isThunk' f = [je| `f`.t === `Thunk` |]
isFun :: JExpr -> JExpr
isFun c = [je| `c`.f.t === `Fun` |]
isFun' :: JExpr -> JExpr
isFun' f = [je| `f`.t === `Fun` |]
isPap :: JExpr -> JExpr
isPap c = [je| `c`.f.t === `Pap` |]
isPap' :: JExpr -> JExpr
isPap' f = [je| `f`.t === `Pap` |]
isCon :: JExpr -> JExpr
isCon c = [je| `c`.f.t === `Con` |]
isCon' :: JExpr -> JExpr
isCon' f = [je| `f`.t === `Con` |]
conTag :: JExpr -> JExpr
conTag c = [je| `c`.f.a |]
conTag' :: JExpr -> JExpr
conTag' f = [je| `f`.a |]
entry :: JExpr -> JExpr
entry p = [je| `p`.f |]
-- number of arguments (arity & 0xff = arguments, arity >> 8 = number of registers)
funArity :: JExpr -> JExpr
funArity c = [je| `c`.f.a |]
-- function arity with raw reference to the entry
funArity' :: JExpr -> JExpr
funArity' f = [je| `f`.a |]
-- arity of a partial application
papArity :: JExpr -> JExpr
papArity cp = [je| `cp`.d2.d1 |]
funOrPapArity :: JExpr -- ^ heap object
-> Maybe JExpr -- ^ reference to entry, if you have one already (saves a c.f lookup twice)
-> JExpr -- ^ arity tag (tag >> 8 = registers, tag & 0xff = arguments)
funOrPapArity c Nothing =
[je| `isFun c` ? `funArity c` : `papArity c` |]
funOrPapArity c (Just f) =
[je| `isFun' f` ? `funArity' f` : `papArity c` |]
{-
Most stack frames have a static size, stored in f.size, but there
are two exceptions:
- dynamically sized stack frames (f.size === -1) have the size
stored in the stack slot below the header
- h$ap_gen is special
-}
stackFrameSize :: JExpr -- ^ assign frame size to this
-> JExpr -- ^ stack frame header function
-> JStat -- ^ size of the frame, including header
stackFrameSize tgt f =
[j| if(`f` === h$ap_gen) { // h$ap_gen is special
`tgt` = (`Stack`[`Sp`-1] >> 8) + 2;
} else {
var tag = `f`.size;
if(tag < 0) { // dynamic size
`tgt` = `Stack`[`Sp`-1];
} else {
`tgt` = (tag & 0xff) + 1;
}
}
|]
-- some utilities do do something with a range of regs
-- start or end possibly supplied as javascript expr
withRegs :: StgReg -> StgReg -> (StgReg -> JStat) -> JStat
withRegs start end f = mconcat $ map f [start..end]
withRegs' :: Int -> Int -> (StgReg -> JStat) -> JStat
withRegs' start end f = withRegs (numReg start) (numReg end) f
-- start from js expr, start is guaranteed to be at least min
-- from low to high (fallthrough!)
withRegsS :: JExpr -> StgReg -> Int -> Bool -> (StgReg -> JStat) -> JStat
withRegsS start min end fallthrough f =
SwitchStat start (map mkCase [regNum min..end]) mempty
where
brk | fallthrough = mempty
| otherwise = [j| break; |]
mkCase n = (toJExpr n, [j| `f (numReg n)`; `brk`; |])
-- end from js expr, from high to low
withRegsRE :: Int -> JExpr -> StgReg -> Bool -> (StgReg -> JStat) -> JStat
withRegsRE start end max fallthrough f =
SwitchStat end (reverse $ map mkCase [numReg start..max]) mempty
where
brk | fallthrough = mempty
| otherwise = [j| break; |]
mkCase n = (toJExpr (regNum n), [j| `f n`; `brk` |])
-- | the global linkable unit of a module exports this symbol, depend on it to include that unit
-- (used for cost centres)
moduleGlobalSymbol :: DynFlags -> Module -> Text
moduleGlobalSymbol dflags m
= "h$" <>
T.pack (zEncodeString $ showModule dflags m) <>
"_<global>"
jsIdIdent :: Id -> Maybe Int -> IdType -> G Ident
jsIdIdent i mi suffix = do
IdCache cache <- use gsIdents
let key = IdKey (getKey . getUnique $ i) (fromMaybe 0 mi) suffix
case M.lookup key cache of
Just ident -> return ident
Nothing -> do
ident <- jsIdIdent' i mi suffix
let cache' = key `seq` ident `seq` IdCache (M.insert key ident cache)
gsIdents .= cache'
cache' `seq` return ident
jsIdIdent' :: Id -> Maybe Int -> IdType -> G Ident
jsIdIdent' i mn suffix0 = do
dflags <- use gsDynFlags
(prefix, u) <- mkPrefixU dflags
i' <- (\x -> T.pack $ "h$"++prefix++x++mns++suffix++u) . zEncodeString <$> name
i' `seq` return (TxtI i')
where
suffix = idTypeSuffix suffix0
mns = maybe "" (('_':).show) mn
name = fmap ('.':) . showPpr' . localiseName . getName $ i
mkPrefixU :: DynFlags -> G (String, String)
mkPrefixU dflags
| isExportedId i, Just x <- (nameModule_maybe . getName) i = do
let xstr = showModule dflags x
return (zEncodeString xstr, "")
| otherwise = (,('_':) . encodeUnique . getKey . getUnique $ i) . ('$':)
. zEncodeString . showModule dflags <$> use gsModule
showModule :: DynFlags -> Module -> String
showModule dflags m = pkg ++ ":" ++ modName
where
modName = moduleNameString (moduleName m)
pkg = encodePackageKey dflags (modulePackageKey m)
encodePackageKey :: DynFlags -> PackageKey -> String
encodePackageKey dflags k
| isGhcjsPrimPackage dflags k = "ghcjs-prim"
| otherwise = packageKeyString k
where
n = getPackageName dflags k
{-
some packages are wired into GHCJS, but not GHC
make sure we don't version them in the output
since the RTS uses thins from them
-}
isGhcjsPrimPackage :: DynFlags -> PackageKey -> Bool
isGhcjsPrimPackage dflags pkgKey
= pn == "ghcjs-prim" ||
(null pn && pkgKey == thisPackage dflags &&
any (=="-DBOOTING_PACKAGE=ghcjs-prim") (opt_P dflags))
where
pn = getPackageName dflags pkgKey
ghcjsPrimPackage :: DynFlags -> PackageKey
ghcjsPrimPackage dflags =
case prims of
((_,k):_) -> k
_ -> error "Package `ghcjs-prim' is required to link executables"
where
prims = filter ((=="ghcjs-prim").fst)
(searchModule dflags (mkModuleName "GHCJS.Prim"))
{-
wiredInPackages :: [String]
wiredInPackages = [ "ghcjs-prim" ]
isWiredInPackage :: DynFlags -> PackageKey -> Bool
isWiredInPackage pkg = pkg `elem` wiredInPackages
-}
idTypeSuffix :: IdType -> String
idTypeSuffix IdPlain = ""
idTypeSuffix IdEntry = "_e"
idTypeSuffix IdConEntry = "_con_e"
jsVar :: String -> JExpr
jsVar v = ValExpr . JVar . TxtI . T.pack $ v
jsId :: Id -> G JExpr
jsId i
-- | i == trueDataConId = return $ toJExpr True
-- | i == falseDataConId = return $ toJExpr False
| otherwise = ValExpr . JVar <$> jsIdIdent i Nothing IdPlain
-- entry id
jsEnId :: Id -> G JExpr
jsEnId i = ValExpr . JVar <$> jsEnIdI i
jsEnIdI :: Id -> G Ident
jsEnIdI i = jsIdIdent i Nothing IdEntry
jsEntryId :: Id -> G JExpr
jsEntryId i = ValExpr . JVar <$> jsEntryIdI i
jsEntryIdI :: Id -> G Ident
jsEntryIdI i = jsIdIdent i Nothing IdEntry
-- datacon entry, different name than the wrapper
jsDcEntryId :: Id -> G JExpr
jsDcEntryId i = ValExpr . JVar <$> jsDcEntryIdI i
jsDcEntryIdI :: Id -> G Ident
jsDcEntryIdI i = jsIdIdent i Nothing IdConEntry
jsIdV :: Id -> G JVal
jsIdV i = JVar <$> jsIdIdent i Nothing IdPlain
jsIdI :: Id -> G Ident
jsIdI i = jsIdIdent i Nothing IdPlain
-- some types, Word64, Addr#, unboxed tuple have more than one javascript var
jsIdIN :: Id -> Int -> G Ident
jsIdIN i n = jsIdIdent i (Just n) IdPlain
jsIdN :: Id -> Int -> G JExpr
jsIdN i n = ValExpr . JVar <$> jsIdIdent i (Just n) IdPlain
-- | generate all js vars for the ids (can be multiple per var)
genIds :: Id -> G [JExpr]
genIds i
| s == 0 = return mempty
| s == 1 = (:[]) <$> jsId i
| otherwise = mapM (jsIdN i) [1..s]
where
s = typeSize (idType i)
genIdsN :: Id -> Int -> G JExpr
genIdsN i n = do
xs <- genIds i
return $ xs !! (n-1)
-- | get all idents for an id
genIdsI :: Id -> G [Ident]
genIdsI i
| s == 1 = (:[]) <$> jsIdI i
| otherwise = mapM (jsIdIN i) [1..s]
where
s = typeSize (idType i)
genIdsIN :: Id -> Int -> G Ident
genIdsIN i n = do
xs <- genIdsI i
return $ xs !! (n-1)
-- | declare all js vars for the id
declIds :: Id -> C
declIds i
| s == 0 = return mempty
| s == 1 = decl <$> jsIdI i
| otherwise = mconcat <$> mapM (\n -> decl <$> jsIdIN i n) [1..s]
where
s = typeSize (idType i)
|
forked-upstream-packages-for-ghcjs/ghcjs
|
ghcjs/src/Gen2/RtsTypes.hs
|
mit
| 23,100
| 1
| 19
| 6,126
| 7,536
| 4,074
| 3,462
| -1
| -1
|
-- Non-deterministic choice
module HS08_Variation5 where
import Prelude hiding (lookup)
----------------
-- List Monad
----------------
type L a = [a]
unitL :: a -> L a
unitL a = [a]
bindL :: L a -> (a -> L b) -> L b
m `bindL` k = [b | a <- m, b <- k a]
zeroL :: L a
zeroL = []
plusL :: L a -> L a -> L a
l `plusL` m = l ++ m
showL m = show [ showval a | a <- m]
----------------
-- Datatypes
----------------
type Name = String
data Term = Var Name
| Con Int
| Add Term Term
| Lam Name Term
| App Term Term
-- new for the ND monad
| Fail
| Amb Term Term
data Value = Wrong
| Num Int
| Fun (Value -> L Value)
type Environment = [(Name, Value)]
----------------
-- Interpreter
----------------
showval :: Value -> String
showval Wrong = "<wrong>"
showval (Num i) = show i
showval (Fun f) = "<function>"
interp :: Term -> Environment -> L Value
interp (Var x) e = lookup x e
interp (Con i) e = unitL (Num i)
interp (Add u v) e = interp u e `bindL` (\a ->
interp v e `bindL` (\b ->
add a b))
interp (Lam x v) e = unitL (Fun (\a -> interp v ((x,a):e)))
interp (App t u) e = interp t e `bindL` (\f ->
interp u e `bindL` (\a ->
apply f a))
-- new for the ND monad
interp Fail e = zeroL
interp (Amb u v) e = interp u e `plusL` interp v e
lookup :: Name -> Environment -> L Value
lookup x [] = unitL Wrong
lookup x ((y,b):e) = if x==y then unitL b else lookup x e
add :: Value -> Value -> L Value
add (Num i) (Num j) = unitL (Num (i+j))
add a b = unitL Wrong
apply :: Value -> Value -> L Value
apply (Fun k) a = k a
apply f a = unitL Wrong
----------------
-- Test
----------------
test :: Term -> String
test t = showL (interp t [])
termL = (App (Lam "x" (Add (Var "x") (Var "x")))
(Amb (Con 1) (Con 2)))
|
BP-HUG/presentations
|
2017_march/HS08_Variation5.hs
|
mit
| 2,054
| 7
| 13
| 645
| 913
| 476
| 437
| 53
| 2
|
module Main where
import qualified System.Directory as Dir
import qualified System.IO as IO
import qualified System.Win32 as Win
import qualified System.Environment as Env
import qualified System.Process as Proc
import qualified System.FilePath as Path
import System.FilePath ((</>))
import Control.Applicative
import Control.Monad
import Data.Char
import Hibernate
import Table
import qualified Data.Map as Map
import Control.Exception
{-
Check if installed
Yes
Load config
Check if this instance is the main one
Yes
Check if there are arguments
Yes
Hibernate/unhibernate folder
No
Ask to add/remove registry key
No
Load table data
Restore current hibernated folder
No
Ask is exe placed in desired location
Ask for hibernation target location
Create configuraion and table data
Add registry key
-}
main :: IO ()
main = do
appDir <- Dir.getAppUserDataDirectory "Hibernate001"
installed <- Dir.doesDirectoryExist appDir
if installed then run
else install
prompt :: String -> IO String
prompt text = do
putStrLn text
getLine
install :: IO ()
install = do
confirm <- prompt "Are you sure this the current location of this file is where you want it installed? (y/n)"
case map toLower confirm of
'y' : _ -> do
appDir <- Dir.getAppUserDataDirectory "Hibernate001"
Dir.createDirectoryIfMissing True appDir
hibernationFolder <- prompt "Please specify a path where hibernated folders will be placed"
thisPath <- Env.getExecutablePath
saveConfig (Config thisPath hibernationFolder)
saveTable (0, Map.empty)
addRegistryEntry
_ -> return ()
run :: IO ()
run = do
args <- Env.getArgs
if null args then do
addRemove <- map toLower
<$> prompt "Do you want to [a]dd or [r]emove the program from Explorer's context menu?"
case addRemove of
'a':_ -> addRegistryEntry
'r':_ -> removeRegistryEntry
_ -> do putStrLn "Unrecognized option. Closing on key press..."
void getChar
else do putStrLn "Running..."
handle (\e -> print (e :: IOException)) $ case args of
"hibernate" : dir -> hibernate $ unwords dir
"unhibernate" : dir -> unhibernate $ unwords dir
opts -> putStrLn "Unrecognized command line options" >> print opts
putStrLn "Done!"
void getChar
addRegistryEntry :: IO ()
addRegistryEntry = do
thisPath <- Env.getExecutablePath
let hibCmd = "\"\\\"" ++ thisPath ++ "\\\" hibernate %%1\""
unhibCmd = "\"\\\"" ++ thisPath ++ "\\\" unhibernate %%1\""
code = unlines
[ "REG ADD HKCR\\Folder\\shell\\Hibernate\\command /f /d " ++ hibCmd
, "REG ADD HKCR\\Folder\\shell\\Unhibernate\\command /f /d " ++ unhibCmd ]
runAsAdmin code
removeRegistryEntry :: IO ()
removeRegistryEntry = do
thisPath <- Env.getExecutablePath
let code = unlines
[ "REG DELETE HKCR\\Folder\\shell\\Hibernate /f"
, "REG DELETE HKCR\\Folder\\shell\\Unhibernate /f" ]
runAsAdmin code
runAsAdmin :: String -> IO ()
runAsAdmin code = do
writeFile "reg.bat" code
void $ Proc.runCommand "powershell \"saps -filepath reg.bat -verb runas -wait\"" >>= Proc.waitForProcess
Dir.removeFile "reg.bat"
|
LukaHorvat/Hibernate
|
src/Main.hs
|
mit
| 3,490
| 0
| 15
| 977
| 693
| 345
| 348
| 77
| 6
|
{-# LANGUAGE DeriveGeneric #-}
module Backhand.Channel where
import qualified STMContainers.Map as M
import GHC.Generics
import Control.Concurrent.Chan.Unagi.Bounded
import Control.Concurrent.STM
import Data.Aeson
import Data.Semigroup.Bitraversable
import Data.Text
import ListT
import Backhand.Message
import Backhand.Unique
-- * Types
type Unagi a = (InChan a, OutChan a)
-- ** Requesters
type Requesters c = M.Map UniqueRequester (InChan c)
newRequester :: IO (UniqueRequester, Unagi c)
newRequester = pure (,) <*> newRequesterId <*> newChan 10
-- ** Modules
type Modules c = M.Map Text (InChan c)
newModule :: Text -> IO (Text, Unagi c)
newModule t = pure (,) <*> pure t <*> newChan 10
-- ** Channel
-- | Our product type for channel communications. Requestors are your abstract
-- clients; you will most likely want those clients to be managed and act as the
-- middleman for your providers. Modules are your abstract services which can
-- be anything from a game, a chat server, a client to another server, etc.
type Channel clientMsg serverMsg = (Requesters serverMsg, Modules clientMsg)
-- | Helper function to help you get started.
newChannel :: IO (ChanUUID, Channel c s)
newChannel = bitraverse1 id bisequence1 (newChanUUID, (M.newIO, M.newIO))
-- ** ChannelMap
-- | The ChannelMap is the backbone of our routing type. This will be the
-- structure you interact with to start new connections, delete old channels by
-- their `ChanUUID`, and ultimately any action that has to do with creating
-- a new channel.
type ChannelMap clientMsg serverMsg = M.Map ChanUUID (Channel clientMsg serverMsg)
-- | Helper function to help you get started.
newChannelMap :: STM (ChannelMap c s)
newChannelMap = M.new
newChannelMapIO :: IO (ChannelMap c s)
newChannelMapIO = M.newIO
-- * Utility
-- | Interacting with `Channel`s and `ChannelMap`s are the reason this library
-- exists so we provide some very basic functions for interactions between them.
-- You will want to wrap these in your own logic; such as creating a new
-- chatroom you'll add that chatroom instance (in this case a `Channel`) to the
-- chat server (in this case the `ChannelMap`).
addChannel :: ChanUUID -> Channel c s -> ChannelMap c s -> STM ()
addChannel u (r, m) = M.insert (r, m) u
addChannel' :: ChanUUID -> Channel c s -> ChannelMap c s -> IO ()
addChannel' u ch chm = atomically $ addChannel u ch chm
addNewChannel :: ChannelMap c s -> IO ChanUUID
addNewChannel chm = do
(u, ch) <- newChannel
addChannel' u ch chm
pure u
delChannel :: ChanUUID -> ChannelMap c s -> STM ()
delChannel = M.delete
delChannel' :: ChanUUID -> ChannelMap c s -> IO ()
delChannel' cid chm = atomically $ delChannel cid chm
joinChannel :: UniqueRequester -> InChan s -> ChanUUID -> ChannelMap c s -> STM BackhandChannelStatus
joinChannel rid inChan uuid cmap = do
channel <- M.lookup uuid cmap
case channel of
Just (r, _) -> do
M.insert inChan rid r
pure ChannelJoinSuccess
Nothing -> pure NoChannelFound
joinChannel' :: UniqueRequester -> InChan s -> ChanUUID -> ChannelMap c s -> IO BackhandChannelStatus
joinChannel' rid inChan uuid cmap =
atomically $ joinChannel rid inChan uuid cmap
leaveChannel :: ChannelMap c s -> UniqueRequester -> ChanUUID -> IO ()
leaveChannel cmap rid chanUUID = atomically $ do
channel <- M.lookup chanUUID cmap
case channel of
Just (r, _) ->
M.delete rid r
Nothing ->
pure ()
sendMessage :: ChannelMap c s -> ConnectionData c -> IO BackhandMessageStatus
sendMessage cmap (ConnectionData chanUUID moduleUUID clientMessage) = do
modChan <- atomically $ do
channel <- M.lookup chanUUID cmap
case channel of
Just (_, m) ->
M.lookup moduleUUID m
Nothing ->
pure Nothing
case modChan of
Just chan -> do
writeChan chan clientMessage
pure SendSuccess
Nothing ->
pure SendFailure
findChannel :: ChannelMap c s -> ChanUUID -> IO (Maybe (ChanUUID, [Text]))
findChannel cmap uuid =
atomically $ do
channel <- M.lookup uuid cmap
case channel of
Just (_, moduleMap) -> do
modules <- fold (\ r (mText, _) -> pure (mText : r) ) [] $ M.stream moduleMap
pure $ Just (uuid, modules)
Nothing -> pure Nothing
-- | If channel exists by our `ChanUUID`
isChannelPresent :: ChannelMap c s -> ChanUUID -> IO Bool
isChannelPresent cmap chanUUID = do
channel <- atomically $ M.lookup chanUUID cmap
pure $ case channel of
Just _ -> True
Nothing -> False
broadcast :: Requesters s -> s -> IO ()
broadcast rmap reply = do
channels <- atomically $
fold (\ r (_, inChan) -> pure (inChan : r) ) [] (M.stream rmap)
mapM_ (`writeChan` reply) channels
broadcastOthers :: UniqueRequester -> Requesters s -> s -> IO ()
broadcastOthers requester rmap reply = do
channels <- atomically $
fold (\ r (requester', inChan) ->
if requester' /= requester
then pure (inChan : r)
else pure r
) [] (M.stream rmap)
mapM_ (`writeChan` reply) channels
data BackhandChannelStatus
= NoChannelFound
| ChannelJoinSuccess
deriving Generic
instance FromJSON BackhandChannelStatus
instance ToJSON BackhandChannelStatus
data BackhandMessageStatus
= SendFailure
| SendSuccess
deriving Generic
instance FromJSON BackhandMessageStatus
instance ToJSON BackhandMessageStatus
|
quietspace/Backhand
|
backhand/src/Backhand/Channel.hs
|
mit
| 5,384
| 0
| 20
| 1,114
| 1,529
| 779
| 750
| 115
| 3
|
module Main where
main = do
print "Hello, "
print "World!"
|
shigemk2/haskell_abc
|
Main.hs
|
mit
| 69
| 0
| 7
| 21
| 21
| 10
| 11
| 4
| 1
|
-- | pdfname: Name a PDF file using the information from the `pdfinfo`
-- command.
module Main where
import qualified Data.Text.IO as T
import Options.Applicative ( execParser )
import System.FilePath ( (</>) )
import System.IO
( hPrint
, stderr
)
import Text.PDF.Info
( pdfInfo
, PDFInfoError(ProcessError, ProcessFailure)
)
------------------------------------------------------------------------------
-- Local imports
import CreateFile
( createFile
, generateFileName
)
import Options
( options
, Options( optDryRun
, optInputFile
)
, outputDir
)
import Utilities ( die )
------------------------------------------------------------------------------
main ∷ IO ()
main = do
opts ← execParser options
let file ∷ FilePath
file = optInputFile opts
info ← pdfInfo file
case info of
Right i → do
newFile ← generateFileName i
if optDryRun opts
then putStrLn $ "The full path name will be " ++ outputDir </> newFile
else createFile file newFile
Left pdfinfoErr → do
case pdfinfoErr of
ProcessFailure err → T.hPutStr stderr err
ProcessError err → hPrint stderr err
_ → T.hPutStr stderr "TODO: Missing error message"
die "PDF file or its metadata information is damaged"
|
asr/pdfname
|
src/Main.hs
|
mit
| 1,354
| 0
| 16
| 337
| 286
| 155
| 131
| -1
| -1
|
{-# LANGUAGE TemplateHaskell #-}
module UnitTest.ResponseParse.UserProfileResponse where
import Data.Aeson (Value)
import Data.Yaml.TH (decodeFile)
import Test.Tasty as Tasty
import Web.Facebook.Messenger
import UnitTest.Internal
---------------------------
-- USER PROFILE RESPONSE --
---------------------------
userProfileResponseVal :: Value
userProfileResponseVal = $$(decodeFile "test/json/response/user_profile.json")
userProfileResponseTest :: TestTree
userProfileResponseTest = parseTest "User Profile Response" userProfileResponseVal
$ UserProfileResponse
{ uprId = "1286146702283499"
, uprFirstName = Just "John"
, uprLastName = Just "Smith"
, uprProfilePic = Just "https://lookaside.facebook.com/platform/profilepic/?psid=1286146702283499&width=1024&ext=1526314033&hash=AeW3QpAe7PtwX5fM"
, uprLocale = Just "en_GB"
, uprTimezone = Just 2
, uprGender = Just "male"
, uprIsPaymentEnabled = Just True
, uprLastAdReferral = Just "6045246247433"
, uprEmail = Nothing
}
|
Vlix/facebookmessenger
|
test/UnitTest/ResponseParse/UserProfileResponse.hs
|
mit
| 1,315
| 0
| 8
| 435
| 172
| 102
| 70
| -1
| -1
|
{-# LANGUAGE RankNTypes, ExistentialQuantification, GeneralizedNewtypeDeriving #-}
{-# OPTIONS_HADDOCK prune, not-home #-}
-- | Provides types and encoding/decoding code. Types should be identical to those provided
-- in the Discord API documentation.
module Network.Discord.Types
( module Network.Discord.Types
, module Network.Discord.Types.Prelude
, module Network.Discord.Types.Channel
, module Network.Discord.Types.Events
, module Network.Discord.Types.Gateway
, module Network.Discord.Types.Guild
) where
import Data.Proxy (Proxy)
import Control.Monad.State (StateT, MonadState, evalStateT, execStateT)
import Control.Concurrent.STM
import Control.Monad.IO.Class (MonadIO)
import Network.WebSockets (Connection)
import System.IO.Unsafe (unsafePerformIO)
import qualified Network.HTTP.Req as R (MonadHttp(..))
import Network.Discord.Types.Channel
import Network.Discord.Types.Events
import Network.Discord.Types.Gateway
import Network.Discord.Types.Guild
import Network.Discord.Types.Prelude
-- | Provides a list of possible states for the client gateway to be in.
data StateEnum = Create | Start | Running | InvalidReconnect | InvalidDead
-- | Stores details needed to manage the gateway and bot
data DiscordState = forall a . (Client a) => DiscordState
{ getState :: StateEnum -- ^ Current state of the gateway
, getClient :: a -- ^ Currently running bot client
, getWebSocket :: Connection -- ^ Stored WebSocket gateway
, getSequenceNum :: TMVar Integer -- ^ Heartbeat sequence number
, getRateLimits :: TVar [(Int, Int)] -- ^ List of rate-limited endpoints
}
-- | Convenience type alias for the monad most used throughout most Discord.hs operations
newtype DiscordM a = DiscordM (StateT DiscordState IO a)
deriving (MonadIO, MonadState DiscordState, Monad, Applicative, Functor)
-- | Allow HTTP requests to be made from the DiscordM monad
instance R.MonadHttp DiscordM where
handleHttpException e = error $ show e
-- | Unwrap and eval a 'DiscordM'
evalDiscordM :: DiscordM a -> DiscordState -> IO a
evalDiscordM (DiscordM inner) = evalStateT inner
-- | Unwrap and exec a 'DiscordM'
execDiscordM :: DiscordM a -> DiscordState -> IO DiscordState
execDiscordM (DiscordM inner) = execStateT inner
-- | The Client typeclass holds the majority of the user-customizable state,
-- including merging states resulting from async operations.
class Client c where
-- | Provides authorization token associated with the client
getAuth :: c -> Auth
-- | Function for resolving state differences due to async operations.
-- Developers are responsible for preventing race conditions.
-- Remember as `merge newState oldState`
merge :: c -- ^ Modified state
-> c -- ^ Initial state
-> c -- ^ Merged state
merge _ st = st -- By default, we simply discard the modified state (we don't
-- store state by default)
-- | Control access to state. In cases where state locks aren't needed, this
-- is most likely the best solution. This implementation most likely
-- needs an accompanying {-\# NOINLINE getTMClient \#-} pragma to ensure
-- that a single state is shared between events
getTMClient :: TVar c
getTMClient = unsafePerformIO $ newTVarIO undefined
{-# NOINLINE getTMClient #-}
-- | In some cases, state locks are needed to prevent race conditions or
-- TVars are an unwanted solution. In these cases, both getClient and
-- modifyClient should be implemented.
getSTMClient :: Proxy c -- ^ Type witness for the client
-> STM c
getSTMClient _ = readTVar getTMClient
-- | modifyClient is used by mergeClient to merge application states before
-- and after an event handler is run
{-# NOINLINE getSTMClient #-}
modifyClient :: (c -> c) -> STM ()
modifyClient f = modifyTVar getTMClient f
-- | Merges application states before and after an event handler
mergeClient :: c -> STM ()
mergeClient client = modifyClient $ merge client
|
jano017/Discord.hs
|
src/Network/Discord/Types.hs
|
mit
| 4,299
| 0
| 11
| 1,042
| 595
| 359
| 236
| 53
| 1
|
module Y2020.M07.D02.Exercise where
import Data.Graph
{--
Okay, recall that highly connected graph from earlier this week?
--}
data Node = A | B | C | D | E | F | G | H
deriving (Eq, Ord, Show)
data Arc = Arc Node Node Int
deriving (Eq, Ord, Show)
graphArcs :: [Arc]
graphArcs =
let arcs = zipWith id (zipWith Arc [A,A,B,B,C,D,D,D,E,F,G]
[B,D,C,E,E,E,F,G,H,G,H])
[5,3,2,4,6,7,4,3,5,4,1]
in arcs ++ map flipNodes arcs
where flipNodes (Arc a b c) = Arc b a c
graph :: [Arc] -> Graph
graph arcs = undefined
{--
So, today, we're going to be studying cycles in graphs, ... MOTORCYCLES! AHA!
... no, ... wait ...
With the function cycles, this function will return all cycles for node a,
BUT NOT! ... and this is important, BUT NOT! ... fall into an infinite loop
of cycles at the get go and give you nothing in return.
Ooh! Salty cycles need to be ... um ... desalinated?
How does one 'unsalt' something?
Problem! (edited from p83 of the Prolog p99 problem set):
Write a function cycles to find the closed paths (cycles) p starting at a given
node a in the graph g.
We are not considering lengths of arcs with today's problem. We'll look at
lengths another day when we compute minimal spanning tree.
--}
cycles :: Graph -> Node -> [[Arc]]
cycles gr a = undefined
|
geophf/1HaskellADay
|
exercises/HAD/Y2020/M07/D02/Exercise.hs
|
mit
| 1,351
| 0
| 12
| 324
| 311
| 183
| 128
| 17
| 1
|
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
module Course.Validation where
import qualified Prelude as P(String)
import Course.Core
-- class Validation<A> {
-- Validation(String error) {} // Error
-- Validation(A value) {} // Value
-- }
-- $setup
-- >>> import Test.QuickCheck
-- >>> import qualified Prelude as P(fmap, either)
-- >>> instance Arbitrary a => Arbitrary (Validation a) where arbitrary = P.fmap (P.either Error Value) arbitrary
data Validation a = Error Err | Value a
deriving (Eq, Show)
type Err = P.String
-- | Returns whether or not the given validation is an error.
--
-- >>> isError (Error "message")
-- True
--
-- >>> isError (Value 7)
-- False
--
-- prop> isError x /= isValue x
isError :: Validation a -> Bool
isError (Error _) = True
isError (Value _) = False
-- | Returns whether or not the given validation is a value.
--
-- >>> isValue (Error "message")
-- False
--
-- >>> isValue (Value 7)
-- True
--
-- prop> isValue x /= isError x
isValue :: Validation a -> Bool
isValue = not . isError
-- | Maps a function on a validation's value side.
--
-- >>> mapValidation (+10) (Error "message")
-- Error "message"
--
-- >>> mapValidation (+10) (Value 7)
-- Value 17
--
-- prop> mapValidation id x == x
mapValidation :: (a -> b) -> Validation a -> Validation b
mapValidation _ (Error s) = Error s
mapValidation f (Value a) = Value (f a)
-- | Binds a function on a validation's value side to a new validation.
--
-- >>> bindValidation (\n -> if even n then Value (n + 10) else Error "odd") (Error "message")
-- Error "message"
--
-- >>> bindValidation (\n -> if even n then Value (n + 10) else Error "odd") (Value 7)
-- Error "odd"
--
-- >>> bindValidation (\n -> if even n then Value (n + 10) else Error "odd") (Value 8)
-- Value 18
--
-- prop> bindValidation Value x == x
bindValidation :: (a -> Validation b) -> Validation a -> Validation b
bindValidation _ (Error s) = Error s
bindValidation f (Value a) = f a
-- | Returns a validation's value side or the given default if it is an error.
--
-- >>> valueOr (Error "message") 3
-- 3
--
-- >>> valueOr (Value 7) 3
-- 7
--
-- prop> isValue x || valueOr x n == n
valueOr :: Validation a -> a -> a
valueOr (Error _) a = a
valueOr (Value a) _ = a
-- | Returns a validation's error side or the given default if it is a value.
--
-- >>> errorOr (Error "message") "q"
-- "message"
--
-- >>> errorOr (Value 7) "q"
-- "q"
--
-- prop> isError x || errorOr x e == e
errorOr :: Validation a -> Err -> Err
errorOr (Error e) _ = e
errorOr (Value _) a = a
valueValidation :: a -> Validation a
valueValidation = Value
|
harrisi/on-being-better
|
list-expansion/Haskell/course/src/Course/Validation.hs
|
cc0-1.0
| 2,622
| 0
| 8
| 521
| 434
| 256
| 178
| 27
| 1
|
{- |
Module : $EmptyHeader$
Description : <optional short description entry>
Copyright : (c) <Authors or Affiliations>
License : GPLv2 or higher, see LICENSE.txt
Maintainer : <email>
Stability : unstable | experimental | provisional | stable | frozen
Portability : portable | non-portable (<reason>)
<optional description>
-}
{-# OPTIONS -fglasgow-exts #-}
module GenericSequent where
import ModalLogic
import CombLogic
import Data.List as List
--import Data.Map as Map
-- | Generate all possible clauses out of a list of atoms
allClauses :: [a] -> [Clause a]
allClauses x = case x of
h:t -> let addPositive c (Implies n p) = Implies n (c:p)
addNegative c (Implies n p) = Implies (c:n) p
in List.map (addPositive h) (allClauses t) ++
List.map (addNegative h) (allClauses t)
_ -> [Implies [] []]
-- | Extract the modal atoms from a formula
getMA :: Eq a => Boole a -> [Boole a]
getMA x = case x of
And phi psi -> (getMA phi) `List.union` (getMA psi)
Not phi -> getMA phi
At phi -> [At phi]
_ -> []
-- | Substitution of modal atoms within a "Boole" expression
subst :: Eq a => Boole a -> Clause (Boole a) -> Boole a
subst x s@(Implies neg pos) =
case x of
And phi psi -> And (subst phi s) (subst psi s)
Not phi -> Not (subst phi s)
T -> T
F -> F
_ -> if (elem x neg) then F
else if (elem x pos) then T
else error "GenericSequent.subst"
-- | Evaluation of an instantiated "Boole" expression
eval :: Boole a -> Bool
eval x = case x of
And phi psi -> (eval phi) && (eval psi)
Not phi -> not (eval phi)
T -> True
F -> False
_ -> error "GenericSequent.eval"
-- | DNF: disjunctive normal form of a Boole expression
dnf :: (Eq a) => Boole a -> [Clause (Boole a)]
dnf phi = List.filter (\x -> eval (subst phi x)) (allClauses (getMA phi))
-- | CNF: conjunctive normal form of a Boole expression
cnf :: (Eq a) => Boole a -> [Clause (Boole a)]
cnf phi = List.map (\(Implies x y) -> Implies y x) (dnf (Not phi))
-- | Generic Provability Function
provable :: (Eq a, Form a b c) => Boole a -> Bool
provable _ = True
{-
provable phi =
let unwrap (Subst x) = Map.elems x
in all (\c -> any (all provable) (List.map unwrap.snd (match c))) (cnf phi)
-}
-- | Generic Satisfiability Function
sat :: (Eq a, Form a b c) => Boole a -> Bool
sat phi = not $ provable $ neg phi
-- | Function for "normalizing" negation
neg :: Eq a => Boole a -> Boole a
neg phi = case phi of
Not psi -> psi
_ -> phi
|
nevrenato/Hets_Fork
|
GMP/GenericSequent.hs
|
gpl-2.0
| 2,803
| 0
| 14
| 900
| 852
| 430
| 422
| 47
| 7
|
-- grid is a game written in Haskell
-- Copyright (C) 2018 karamellpelle@hotmail.com
--
-- This file is part of grid.
--
-- grid is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- grid is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with grid. If not, see <http://www.gnu.org/licenses/>.
--
module Game.Memory.Do.Grid
(
doGridShow,
doGridPlay,
doGridFailure,
) where
import MyPrelude
import Game
import Game.Grid
import Game.Grid.Modify
import Game.Grid.Do
import Game.Grid.StepDT
import Game.Memory
doGridShow :: s -> GridWorld -> MemoryWorld -> MEnv' (s, GridWorld, MemoryWorld)
doGridShow =
defaultDo (controlGrid controlCamera)
(tickClockMemoryGet, tickClockMemorySet)
(defaultStepDT collisionShow)
(noBreakModify)
(noDefaultModify)
doGridPlay :: s -> GridWorld -> MemoryWorld -> MEnv' (s, GridWorld, MemoryWorld)
doGridPlay =
defaultDo (controlGrid controlCameraPathContinue)
(tickClockMemoryGet, tickClockMemorySet)
(defaultStepDT collisionPlay)
(noBreakModify)
(noDefaultModify)
doGridFailure :: s -> GridWorld -> MemoryWorld -> MEnv' (s, GridWorld, MemoryWorld)
doGridFailure =
doGridShow
--------------------------------------------------------------------------------
--
collisionShow :: Collision s MemoryWorld
collisionShow =
Collision
{
onPathNode = \path s grid mem ->
case memoryFood mem of
-- all food eaten. halt.
[] -> do
let path' = path { pathAlpha = 1.0 }
return (path', s, grid, worldPushEvent mem EventAllFoodEaten)
-- continue with next food as current segment
(f:fs) -> do
path' <- pathEatTurn path f
return (path', s, grid, mem { memoryFood = fs })
}
collisionPlay :: Collision s MemoryWorld
collisionPlay =
Collision
{
onPathNode = \path s grid mem -> if memoryIsFailure mem
-- stop when failure
then return (path, s, grid, mem)
else case memoryFood mem of
-- all food eaten
[] -> do
let path' = path { pathAlpha = 1.0 }
return (path', s, grid, worldPushEvent mem EventAllFoodEaten)
-- path eats a new Segment. but is it correct?
(f:fs) -> do
path' <- pathEatContinue path
let t0 = pathTurn path
t1 = pathTurn path'
if direction (turnDiff t0 t1) == direction f
-- correct turn
then let (path'', mem') = handleCorrect f fs path' mem
in return (path'', s, grid, mem')
-- wrong turn
else let (path'', mem') = handleWrong f fs path' mem
in return (path'', s, grid, mem')
}
where
handleCorrect f fs path mem =
(path, mem { memoryFood = fs })
handleWrong f fs path mem =
let path' = path { pathCurrent = segmentEatTurn (path0Last path) f }
mem' = mem
{
memoryFood = fs,
memoryIsFailure = True,
memoryFailureIx = pathSize path',
memoryFailureSegment = pathCurrent path,
memoryEvents = memoryEvents mem ++ [EventWrongTurn]
}
in (path', mem')
|
karamellpelle/grid
|
source/Game/Memory/Do/Grid.hs
|
gpl-3.0
| 4,274
| 0
| 19
| 1,636
| 797
| 446
| 351
| 69
| 4
|
{-# OPTIONS_GHC -fno-warn-orphans #-}
module Application
( makeApplication
, getApplicationDev
, makeFoundation
) where
import Import
import qualified Data.ByteString as S
import qualified Data.ByteString.Lazy as L
import Yesod.Default.Config (
AppConfig, ConfigSettings (..), DefaultEnv (..)
, appExtra, appEnv, configSettings, withYamlEnvironment
)
import qualified Yesod.Default.Config
import Yesod.Default.Main
import Yesod.Default.Handlers
import Control.Monad.Logger (runLoggingT)
import qualified Database.Persist
import Database.Persist.Sql (runMigration)
import Network.Wai.Middleware.Autohead (autohead)
import Network.Wai.Middleware.RequestLogger
import Network.HTTP.Conduit (newManager, def)
import System.Directory (doesFileExist)
import System.IO (stdout)
import System.Log.FastLogger (mkLogger)
import Web.ClientSession (randomKey)
import Settings
-- Import all relevant handler modules here.
-- Don't forget to add new modules to your cabal file!
import Account
import Handler.Browser
import Handler.Comment
import Handler.Download
import qualified Handler.Download.ViewsCache as VC
import Handler.History
import Handler.Upload
import Handler.Terms
import Handler.User
import Handler.View
import qualified JobsDaemon.Daemon as J
import qualified JobsDaemon.Restore as J
import qualified JobsDaemon.Util as J
-- This line actually creates our YesodDispatch instance. It is the second half
-- of the call to mkYesodData which occurs in Foundation.hs. Please see the
-- comments there for more details.
mkYesodDispatch "App" resourcesApp
-- This function allocates resources (such as a database connection pool),
-- performs initialization and creates a WAI application. This is also the
-- place to put your migrate statements to have automatic database
-- migrations handled by Yesod.
makeApplication :: AppConfig DefaultEnv Extra -> IO Application
makeApplication conf = do
foundation <- makeFoundation conf
-- Starts the background processes.
let nJobsThreads = extraJobsThreads $ appExtra conf
_ <- J.forkJobsDaemon nJobsThreads foundation
_ <- VC.forkViewsCacheDaemon foundation
-- Initialize the logging middleware
logWare <- mkRequestLogger def {
outputFormat = if development
then Detailed True
else if extraReverseProxy $ appExtra $ settings foundation
then Apache FromHeader
else Apache FromSocket
, destination = Logger $ appLogger foundation
}
(logWare . autohead) <$> toWaiAppPlain foundation
-- | Loads up any necessary settings, creates your foundation datatype, and
-- performs some initialization.
makeFoundation :: AppConfig DefaultEnv Extra -> IO App
makeFoundation conf = do
manager <- newManager def
s <- staticSite
account <- makeAccount
dbconf <- withYamlEnvironment "config/sqlite.yml" (appEnv conf)
Database.Persist.loadConfig >>=
applyEnv
p <- createPoolConfig (dbconf :: Settings.PersistConf)
logger <- mkLogger True stdout
key <- getEncryptionKey
-- Initialises the concurrent queues.
jQueue <- J.newQueue
vCache <- VC.newCache
let foundation = App conf s account p manager dbconf logger key jQueue
vCache
-- Performs database migrations using our application's logging settings.
let migrations = migrateAccount >> migrateAll
runLoggingT (runPool dbconf (runMigration migrations) p)
(messageLoggerSource foundation logger)
J.restoreJobQueue foundation
return foundation
-- | Try to read the key file or initialize it with a random key.
getEncryptionKey :: IO L.ByteString
getEncryptionKey = do
exists <- doesFileExist encryptKeyFile
if exists
then L.readFile encryptKeyFile
else do
(bs, _) <- randomKey
S.writeFile encryptKeyFile bs
return $ L.fromStrict bs
-- for yesod devel
getApplicationDev :: IO (Int, Application)
getApplicationDev =
defaultDevelApp loader makeApplication
where
loader = Yesod.Default.Config.loadConfig (configSettings Development) {
csParseExtra = parseExtra
}
|
RaphaelJ/getwebb.org
|
Application.hs
|
gpl-3.0
| 4,262
| 0
| 14
| 909
| 807
| 443
| 364
| -1
| -1
|
{- ============================================================================
| Copyright 2011 Matthew D. Steele <mdsteele@alum.mit.edu> |
| |
| This file is part of Fallback. |
| |
| Fallback is free software: you can redistribute it and/or modify it under |
| the terms of the GNU General Public License as published by the Free |
| Software Foundation, either version 3 of the License, or (at your option) |
| any later version. |
| |
| Fallback is distributed in the hope that it will be useful, but WITHOUT |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
| FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for |
| more details. |
| |
| You should have received a copy of the GNU General Public License along |
| with Fallback. If not, see <http://www.gnu.org/licenses/>. |
============================================================================ -}
-- | This module implements the Precise Permissive Field of View algorithm. It
-- is a Haskell port of a piece of Python code by Aaron MacDonald. The
-- original code was found at
-- <http://roguebasin.roguelikedevelopment.org/index.php?title=Permissive_Field_of_View_in_Python>.
--
-- The original file contained the below notice:
--
-- > Author: Aaron MacDonald
-- > Date: June 14, 2007
-- >
-- > Description: An implementation of the precise permissive field
-- > of view algorithm for use in tile-based games.
-- > Based on the algorithm presented at
-- > http://roguebasin.roguelikedevelopment.org/
-- > index.php?title=
-- > Precise_Permissive_Field_of_View.
-- >
-- > You are free to use or modify this code as long as this notice is
-- > included.
-- > This code is released without warranty.
--
-- Much thanks to Aaron for releasing his code.
module Fallback.State.FOV (fieldOfView, lineOfSight) where
import Control.Applicative ((<$>))
import Control.Monad (ap, foldM, liftM2, when)
import Control.Monad.Fix (mfix)
import Control.Monad.ST (ST, runST)
import qualified Data.Set as Set
import Data.STRef
import Fallback.Data.Point (IPoint, Point(..), Position, SqDist(..), pAdd)
import Fallback.Utility (flip3, whenM)
-------------------------------------------------------------------------------
-- | Compute the field of view of a viewer, adding the coordinates of all
-- visible tiles to the set of already visible tiles. The required arguments
-- are the width and height of the map, a function that determines whether a
-- tile at a given position blocks vision, the square of the maximum vision
-- radius, the position of the viewer on the map, and the set to add
-- coordinates to.
fieldOfView :: (Int, Int) {-^map size-}
-> (Position -> Bool) {-^isBlocked function-}
-> SqDist {-^radius squared-} -> Position {-^viewer position-}
-> Set.Set Position {-^already visible-} -> Set.Set Position
fieldOfView (width, height) isBlocked (SqDist radiusSquared) start visible =
let radius = floor $ sqrt (fromIntegral radiusSquared :: Double)
minX = min radius $ pointX start
maxX = min radius $ width - pointX start - 1
minY = min radius $ pointY start
maxY = min radius $ height - pointY start - 1
check = checkQuadrent isBlocked radiusSquared start
in runST $ check (-1) 1 minX maxY =<< check (-1) (-1) minX minY =<<
check 1 (-1) maxX minY =<< check 1 1 maxX maxY (Set.insert start visible)
-- | Determine whether two positions can see each other (assuming an unlimited
-- vision range). This is more efficient than calling 'fieldOfView' from one
-- position and checking if the other position is in the set; however, calling
-- 'fieldOfView' is more efficient than calling this function many times for
-- many positions.
lineOfSight :: (Position -> Bool) {-^isBlocked function-} -> Position
-> Position -> Bool
lineOfSight isBlocked p1@(Point x1 y1) p2@(Point x2 y2) =
if x1 == x2 then
if y1 == y2 then True
else not $ any isBlocked $ map (Point x1) $ subrange y1 y2
else
if y1 == y2 then not $ any isBlocked $ map (flip Point y1) $ subrange x1 x2
else runST $ do
let { dx = x2 - x1; dy = y2 - y1 }
visible <- checkQuadrent isBlocked (dx * dx + dy * dy) p1 (signum dx)
(signum dy) (abs dx) (abs dy) Set.empty
return (Set.member p2 visible)
where subrange a b = [(min a b + 1) .. (max a b - 1)]
checkQuadrent :: (Position -> Bool) -> Int -> Position -> Int -> Int
-> Int -> Int -> Set.Set Position -> ST s (Set.Set Position)
checkQuadrent isBlocked radSq start dX dY maxX maxY vis = do
viewList <- newViewList maxX maxY
-- Visit the tiles diagonally and going outwards, like so:
-- .
-- .
-- . .
-- 9 .
-- 5 8 .
-- 2 4 7
-- @ 1 3 6 . . .
flip3 foldM vis [1 .. maxX + maxY] $ \vis' i -> do
flip3 foldM vis' [max 0 (i - maxX) .. min i maxY] $ \visible y -> do
let x = i - y
if (x * x + y * y > radSq) then return visible else do
-- Look for a view that contains this tile.
mbView <- firstView viewList >>= findView (Point x y)
-- If no view contains this tile, we can't see it, and we move on.
flip (maybe (return visible)) mbView $ \view -> do
-- We can see the tile; determine its absolute coordinates.
let tile = start `pAdd` Point (x * dX) (y * dY)
-- If this tile is opaque, we need to alter the view.
when (isBlocked tile) $ do
shallowLine <- readSTRef (viewShallowLine view)
steepLine <- readSTRef (viewSteepLine view)
above <- shallowLine `abovePoint` Point (x + 1) y
below <- steepLine `belowPoint` Point x (y + 1)
if above then
if below then do
-- The current coordinate is intersected by both lines in the
-- current view. The view is completely blocked.
removeView view
else do
-- The current coordinate is intersected by the shallow line of
-- the current view. The shallow line needs to be raised.
addShallowBump (Point x (y + 1)) view
else
if below then do
-- The current coordinate is intersected by the steep line of
-- the current view. The steep line needs to be lowered.
addSteepBump (Point (x + 1) y) view
else do
-- The current coordinate is completely between the two lines
-- of the current view. Split the current view into two views
-- above and below the current coordinate.
view' <- duplicateView view
addSteepBump (Point (x + 1) y) view
addShallowBump (Point x (y + 1)) view'
-- Whether or not this tile was blocked, mark that we can see it.
return (Set.insert tile visible)
-- | Find a view that contains the given position.
findView :: IPoint -> Maybe (View s) -> ST s (Maybe (View s))
findView (Point x y) mbView = do
mbView' <- findAbove (Point (x + 1) y) mbView
flip (maybe (return Nothing)) mbView' $ \view -> do
-- The position is below this view's steep line, so check if it's also
-- above the view's shallow line.
shallow <- readSTRef (viewShallowLine view)
aoc <- shallow `abovePointOrColinear` (Point x (y + 1))
return $ if aoc then Nothing else Just view
-- | Find a view whose steep line is above the given position.
findAbove :: IPoint -> Maybe (View s) -> ST s (Maybe (View s))
findAbove _ Nothing = return Nothing
findAbove pos (Just view) = do
steep <- readSTRef (viewSteepLine view)
boc <- steep `belowPointOrColinear` pos
if not boc then return (Just view) else
-- The current coordinate is above the current view and is ignored. The
-- steeper fields may need it though.
nextView view >>= findAbove pos
-------------------------------------------------------------------------------
-- | A doubly-linked list of 'View' objects.
data ViewList s = ViewList
{ vlistFirst :: ViewLink s,
vlistLast :: ViewLink s }
-- | Get the first view in the given list (or 'Nothing' if the list is empty).
firstView :: ViewList s -> ST s (Maybe (View s))
firstView vlist = either (const Nothing) Just <$> readSTRef (vlistFirst vlist)
-- | Create a new 'ViewList' containing a single 'View' with the given maximum
-- x and y values.
newViewList :: Int -> Int -> ST s (ViewList s)
newViewList maxX maxY = mfix $ \vlist -> do
shallow <- newLine (Point 0 1) (Point (maxX + 1) 0)
steep <- newLine (Point 1 0) (Point 0 (maxY + 1))
view <- return View `ap` (newSTRef shallow) `ap` (newSTRef steep)
`ap` (newSTRef []) `ap` (newSTRef [])
`ap` (newSTRef $ Left vlist) `ap` (newSTRef $ Left vlist)
liftM2 ViewList (newSTRef $ Right view) (newSTRef $ Right view)
-------------------------------------------------------------------------------
-- | A link in a 'ViewList'.
type ViewLink s = STRef s (Either (ViewList s) (View s))
pointPrevAt :: ViewLink s -> Either (ViewList s) (View s) -> ST s ()
pointPrevAt vlink target =
(either vlistLast viewPrev <$> readSTRef vlink) >>= flip writeSTRef target
pointNextAt :: ViewLink s -> Either (ViewList s) (View s) -> ST s ()
pointNextAt vlink target =
(either vlistFirst viewNext <$> readSTRef vlink) >>= flip writeSTRef target
-------------------------------------------------------------------------------
data View s = View
{ viewShallowLine :: STRef s (Line s),
viewSteepLine :: STRef s (Line s),
viewShallowBumps :: STRef s [IPoint],
viewSteepBumps :: STRef s [IPoint],
viewPrev :: ViewLink s,
viewNext :: ViewLink s }
-- | Get the next view in the list after the given view, if any.
nextView :: View s -> ST s (Maybe (View s))
nextView view = either (const Nothing) Just <$> readSTRef (viewNext view)
-- | Create a deep copy of the given view, insert the copy into the list just
-- after the view, and return the copy.
duplicateView :: View s -> ST s (View s)
duplicateView view = do
shallow' <- readSTRef (viewShallowLine view) >>= cloneLine
steep' <- readSTRef (viewSteepLine view) >>= cloneLine
-- Create a new view, with prev pointing to the given view and next pointing
-- to the next view after the given view.
view' <- return View `ap` (newSTRef shallow') `ap` (newSTRef steep')
`ap` (cloneSTRef $ viewShallowBumps view)
`ap` (cloneSTRef $ viewSteepBumps view)
`ap` (newSTRef $ Right view)
`ap` (cloneSTRef $ viewNext view)
-- Set prev of the next view to point to the clone.
(viewNext view') `pointPrevAt` (Right view')
-- Set next of the given view to point to the clone.
writeSTRef (viewNext view) (Right view')
return view'
-- | Remove the view from the list.
removeView :: View s -> ST s ()
removeView view = do
-- Set next of the previous view to point at the next view.
(viewPrev view `pointNextAt`) =<< readSTRef (viewNext view)
-- Set prev of the next view to point at the previous view.
(viewNext view `pointPrevAt`) =<< readSTRef (viewPrev view)
addShallowBump :: IPoint -> View s -> ST s ()
addShallowBump pos view = do
shallowLine <- readSTRef (viewShallowLine view)
writeSTRef (lineEnd shallowLine) pos
modifySTRef (viewShallowBumps view) (pos :)
loopM (readSTRef $ viewSteepBumps view) $ \bump -> do
whenM (shallowLine `abovePoint` bump) $ do
writeSTRef (lineBegin shallowLine) bump
checkView view
addSteepBump :: IPoint -> View s -> ST s ()
addSteepBump pos view = do
steepLine <- readSTRef (viewSteepLine view)
writeSTRef (lineEnd steepLine) pos
modifySTRef (viewSteepBumps view) (pos :)
loopM (readSTRef $ viewShallowBumps view) $ \bump -> do
whenM (steepLine `belowPoint` bump) $ do
writeSTRef (lineBegin steepLine) bump
checkView view
-- | Remove the view from the list if the two lines are colinear and they pass
-- through either of the starting corners.
checkView :: View s -> ST s ()
checkView view = do
shallow <- readSTRef (viewShallowLine view)
steep <- readSTRef (viewSteepLine view)
whenM (linesColinear shallow steep `andM`
((shallow `colinearWithPoint` Point 0 1) `orM`
(shallow `colinearWithPoint` Point 1 0))) $ do
removeView view
-------------------------------------------------------------------------------
data Line s = Line
{ lineBegin :: STRef s IPoint,
lineEnd :: STRef s IPoint }
newLine :: IPoint -> IPoint -> ST s (Line s)
newLine begin end = liftM2 Line (newSTRef begin) (newSTRef end)
cloneLine :: Line s -> ST s (Line s)
cloneLine line =
liftM2 Line (cloneSTRef $ lineBegin line) (cloneSTRef $ lineEnd line)
compareToPoint :: (Int -> Int -> Bool) -> Line s -> IPoint -> ST s Bool
compareToPoint fn line (Point x y) = do
Point xb yb <- readSTRef (lineBegin line)
Point xe ye <- readSTRef (lineEnd line)
return $ fn ((xe - xb) * (ye - y)) ((ye - yb) * (xe - x))
belowPoint :: Line s -> IPoint -> ST s Bool
belowPoint = compareToPoint (<)
belowPointOrColinear :: Line s -> IPoint -> ST s Bool
belowPointOrColinear = compareToPoint (<=)
colinearWithPoint :: Line s -> IPoint -> ST s Bool
colinearWithPoint = compareToPoint (==)
abovePointOrColinear :: Line s -> IPoint -> ST s Bool
abovePointOrColinear = compareToPoint (>=)
abovePoint :: Line s -> IPoint -> ST s Bool
abovePoint = compareToPoint (>)
linesColinear :: Line s -> Line s -> ST s Bool
linesColinear line1 line2 = do
pb <- readSTRef (lineBegin line2)
pe <- readSTRef (lineEnd line2)
(line1 `colinearWithPoint` pb) `andM` (line1 `colinearWithPoint` pe)
-------------------------------------------------------------------------------
andM, orM :: (Monad m) => m Bool -> m Bool -> m Bool
andM m1 m2 = do { b1 <- m1; if b1 then m2 else return False }
orM m1 m2 = do { b1 <- m1; if b1 then return True else m2 }
loopM :: (Monad m) => m [a] -> (a -> m ()) -> m ()
loopM list fn = list >>= mapM_ fn
cloneSTRef :: STRef s a -> ST s (STRef s a)
cloneSTRef ref = readSTRef ref >>= newSTRef
-------------------------------------------------------------------------------
|
mdsteele/fallback
|
src/Fallback/State/FOV.hs
|
gpl-3.0
| 14,877
| 0
| 35
| 3,962
| 3,776
| 1,946
| 1,830
| 183
| 5
|
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeFamilies #-}
{-# OPTIONS_GHC -fno-warn-unused-imports #-}
-- Module : Network.AWS.EC2.AttachClassicLinkVpc
-- Copyright : (c) 2013-2014 Brendan Hay <brendan.g.hay@gmail.com>
-- License : This Source Code Form is subject to the terms of
-- the Mozilla Public License, v. 2.0.
-- A copy of the MPL can be found in the LICENSE file or
-- you can obtain it at http://mozilla.org/MPL/2.0/.
-- Maintainer : Brendan Hay <brendan.g.hay@gmail.com>
-- Stability : experimental
-- Portability : non-portable (GHC extensions)
--
-- Derived from AWS service descriptions, licensed under Apache 2.0.
-- | Links an EC2-Classic instance to a ClassicLink-enabled VPC through one or
-- more of the VPC's security groups. You cannot link an EC2-Classic instance to
-- more than one VPC at a time. You can only link an instance that's in the 'running' state. An instance is automatically unlinked from a VPC when it's stopped -
-- you can link it to the VPC again when you restart it.
--
-- After you've linked an instance, you cannot change the VPC security groups
-- that are associated with it. To change the security groups, you must first
-- unlink the instance, and then link it again.
--
-- Linking your instance to a VPC is sometimes referred to as /attaching/ your
-- instance.
--
-- <http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AttachClassicLinkVpc.html>
module Network.AWS.EC2.AttachClassicLinkVpc
(
-- * Request
AttachClassicLinkVpc
-- ** Request constructor
, attachClassicLinkVpc
-- ** Request lenses
, aclvDryRun
, aclvGroups
, aclvInstanceId
, aclvVpcId
-- * Response
, AttachClassicLinkVpcResponse
-- ** Response constructor
, attachClassicLinkVpcResponse
-- ** Response lenses
, aclvrReturn
) where
import Network.AWS.Prelude
import Network.AWS.Request.Query
import Network.AWS.EC2.Types
import qualified GHC.Exts
data AttachClassicLinkVpc = AttachClassicLinkVpc
{ _aclvDryRun :: Maybe Bool
, _aclvGroups :: List "groupId" Text
, _aclvInstanceId :: Text
, _aclvVpcId :: Text
} deriving (Eq, Ord, Read, Show)
-- | 'AttachClassicLinkVpc' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'aclvDryRun' @::@ 'Maybe' 'Bool'
--
-- * 'aclvGroups' @::@ ['Text']
--
-- * 'aclvInstanceId' @::@ 'Text'
--
-- * 'aclvVpcId' @::@ 'Text'
--
attachClassicLinkVpc :: Text -- ^ 'aclvInstanceId'
-> Text -- ^ 'aclvVpcId'
-> AttachClassicLinkVpc
attachClassicLinkVpc p1 p2 = AttachClassicLinkVpc
{ _aclvInstanceId = p1
, _aclvVpcId = p2
, _aclvDryRun = Nothing
, _aclvGroups = mempty
}
-- | Checks whether you have the required permissions for the action, without
-- actually making the request, and provides an error response. If you have the
-- required permissions, the error response is 'DryRunOperation'. Otherwise, it is 'UnauthorizedOperation'.
aclvDryRun :: Lens' AttachClassicLinkVpc (Maybe Bool)
aclvDryRun = lens _aclvDryRun (\s a -> s { _aclvDryRun = a })
-- | The ID of one or more of the VPC's security groups. You cannot specify
-- security groups from a different VPC.
aclvGroups :: Lens' AttachClassicLinkVpc [Text]
aclvGroups = lens _aclvGroups (\s a -> s { _aclvGroups = a }) . _List
-- | The ID of an EC2-Classic instance to link to the ClassicLink-enabled VPC.
aclvInstanceId :: Lens' AttachClassicLinkVpc Text
aclvInstanceId = lens _aclvInstanceId (\s a -> s { _aclvInstanceId = a })
-- | The ID of a ClassicLink-enabled VPC.
aclvVpcId :: Lens' AttachClassicLinkVpc Text
aclvVpcId = lens _aclvVpcId (\s a -> s { _aclvVpcId = a })
newtype AttachClassicLinkVpcResponse = AttachClassicLinkVpcResponse
{ _aclvrReturn :: Maybe Bool
} deriving (Eq, Ord, Read, Show)
-- | 'AttachClassicLinkVpcResponse' constructor.
--
-- The fields accessible through corresponding lenses are:
--
-- * 'aclvrReturn' @::@ 'Maybe' 'Bool'
--
attachClassicLinkVpcResponse :: AttachClassicLinkVpcResponse
attachClassicLinkVpcResponse = AttachClassicLinkVpcResponse
{ _aclvrReturn = Nothing
}
-- | Returns 'true' if the request succeeds; otherwise, it returns an error.
aclvrReturn :: Lens' AttachClassicLinkVpcResponse (Maybe Bool)
aclvrReturn = lens _aclvrReturn (\s a -> s { _aclvrReturn = a })
instance ToPath AttachClassicLinkVpc where
toPath = const "/"
instance ToQuery AttachClassicLinkVpc where
toQuery AttachClassicLinkVpc{..} = mconcat
[ "DryRun" =? _aclvDryRun
, "SecurityGroupId" `toQueryList` _aclvGroups
, "InstanceId" =? _aclvInstanceId
, "VpcId" =? _aclvVpcId
]
instance ToHeaders AttachClassicLinkVpc
instance AWSRequest AttachClassicLinkVpc where
type Sv AttachClassicLinkVpc = EC2
type Rs AttachClassicLinkVpc = AttachClassicLinkVpcResponse
request = post "AttachClassicLinkVpc"
response = xmlResponse
instance FromXML AttachClassicLinkVpcResponse where
parseXML x = AttachClassicLinkVpcResponse
<$> x .@? "return"
|
romanb/amazonka
|
amazonka-ec2/gen/Network/AWS/EC2/AttachClassicLinkVpc.hs
|
mpl-2.0
| 5,531
| 0
| 10
| 1,189
| 643
| 394
| 249
| 72
| 1
|
{-# LANGUAGE FlexibleInstances #-}
module Net.DigitalOcean.Regions (
Region(..)
, getRegions
-- ** Lens Accessors
, rgnName, rgnSlug, rgnSizes, rgnFeatures, rgnAvailable
) where
import qualified Data.Text as T
import qualified Data.HashMap.Strict as HM
import Data.Aeson(FromJSON(..), Value(..), (.:), fromJSON)
import Control.Applicative
import Control.Lens hiding (Action)
import Control.Monad.IO.Class (MonadIO)
import Control.Monad.Error.Class (MonadError, Error)
import Net.DigitalOcean.Request (get)
import Net.DigitalOcean.Config (Config)
-- | A Digital Ocean region
data Region = Region
{ _rgnName :: !T.Text
, _rgnSlug :: !T.Text
, _rgnSizes :: ![T.Text]
, _rgnFeatures :: ![T.Text]
, _rgnAvailable :: Maybe Bool
} deriving (Show, Eq)
makeLenses ''Region
instance FromJSON Region where
parseJSON (Object x) = Region <$>
x .: "name" <*>
x .: "slug" <*>
x .: "sizes" <*>
x .: "features" <*>
x .: "available"
parseJSON _ = fail "region must be object"
-- | Returns a list of all the visible Digital Ocean regions
--
-- <https://developers.digitalocean.com/#list-all-regions DO documentation>
getRegions :: (Error e, MonadError e m, MonadIO m) =>
Config -> m [Region]
getRegions = get "/v2/regions/" "regions"
|
bluepeppers/DigitalOcean
|
src/Net/DigitalOcean/Regions.hs
|
agpl-3.0
| 1,458
| 0
| 15
| 409
| 351
| 208
| 143
| -1
| -1
|
-- This file is part of purebred
-- Copyright (C) 2017-2021 Fraser Tweedale and Róman Joost
--
-- purebred is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
module Purebred.Types.Parser.ByteString
(
niceEndOfInput
, skipSpaces
) where
import Control.Applicative ((<|>))
import Data.Attoparsec.ByteString.Char8
( Parser, endOfInput, peekChar', skipMany1, space )
import qualified Data.Attoparsec.Internal.Types as AT
-- | Assert end of input has been reached, or fail with a message
-- that includes the problematic character and the offset.
niceEndOfInput :: Parser ()
niceEndOfInput = endOfInput <|> p
where
p = do
c <- peekChar'
off <- offset
fail $ "unexpected " <> show c <> " at offset " <> show off
-- | Get the current position of the parser
offset :: AT.Parser i Int
offset = AT.Parser $ \t pos more _lose suc -> suc t pos more (AT.fromPos pos)
-- | skip whitespace. fails on no whitespace
skipSpaces :: Parser ()
skipSpaces = skipMany1 space
|
purebred-mua/purebred
|
src/Purebred/Types/Parser/ByteString.hs
|
agpl-3.0
| 1,588
| 0
| 12
| 295
| 217
| 129
| 88
| 18
| 1
|
module AlecSequences.A270841 (a270841) where
a270841 :: Integral a => a -> a
a270841 1 = 5
a270841 n = 2 ^ (n - 2) + n + 1
|
peterokagey/haskellOEIS
|
src/AlecSequences/A270841.hs
|
apache-2.0
| 131
| 0
| 9
| 36
| 62
| 33
| 29
| 4
| 1
|
{-# OPTIONS -fglasgow-exts #-}
-----------------------------------------------------------------------------
{-| Module : QIODevice.hs
Copyright : (c) David Harley 2010
Project : qtHaskell
Version : 1.1.4
Modified : 2010-09-02 17:02:31
Warning : this file is machine generated - do not modify.
--}
-----------------------------------------------------------------------------
module Qtc.Core.QIODevice (
isOpen
,isTextModeEnabled
,openMode
,peek
,setTextModeEnabled
,Qwrite(..)
,qIODevice_delete
,qIODevice_deleteLater
)
where
import Qth.ClassTypes.Core
import Qtc.Enums.Base
import Qtc.Enums.Core.QIODevice
import Qtc.Classes.Base
import Qtc.Classes.Qccs
import Qtc.Classes.Core
import Qtc.ClassTypes.Core
import Qth.ClassTypes.Core
instance QuserMethod (QIODevice ()) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QIODevice_userMethod cobj_qobj (toCInt evid)
foreign import ccall "qtc_QIODevice_userMethod" qtc_QIODevice_userMethod :: Ptr (TQIODevice a) -> CInt -> IO ()
instance QuserMethod (QIODeviceSc a) (()) (IO ()) where
userMethod qobj evid ()
= withObjectPtr qobj $ \cobj_qobj ->
qtc_QIODevice_userMethod cobj_qobj (toCInt evid)
instance QuserMethod (QIODevice ()) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QIODevice_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
foreign import ccall "qtc_QIODevice_userMethodVariant" qtc_QIODevice_userMethodVariant :: Ptr (TQIODevice a) -> CInt -> Ptr (TQVariant ()) -> IO (Ptr (TQVariant ()))
instance QuserMethod (QIODeviceSc a) (QVariant ()) (IO (QVariant ())) where
userMethod qobj evid qvoj
= withObjectRefResult $
withObjectPtr qobj $ \cobj_qobj ->
withObjectPtr qvoj $ \cobj_qvoj ->
qtc_QIODevice_userMethodVariant cobj_qobj (toCInt evid) cobj_qvoj
instance QatEnd (QIODevice ()) (()) where
atEnd x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_atEnd_h cobj_x0
foreign import ccall "qtc_QIODevice_atEnd_h" qtc_QIODevice_atEnd_h :: Ptr (TQIODevice a) -> IO CBool
instance QatEnd (QIODeviceSc a) (()) where
atEnd x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_atEnd_h cobj_x0
instance QbytesAvailable (QIODevice ()) (()) where
bytesAvailable x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_bytesAvailable_h cobj_x0
foreign import ccall "qtc_QIODevice_bytesAvailable_h" qtc_QIODevice_bytesAvailable_h :: Ptr (TQIODevice a) -> IO CLLong
instance QbytesAvailable (QIODeviceSc a) (()) where
bytesAvailable x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_bytesAvailable_h cobj_x0
instance QbytesToWrite (QIODevice ()) (()) where
bytesToWrite x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_bytesToWrite_h cobj_x0
foreign import ccall "qtc_QIODevice_bytesToWrite_h" qtc_QIODevice_bytesToWrite_h :: Ptr (TQIODevice a) -> IO CLLong
instance QbytesToWrite (QIODeviceSc a) (()) where
bytesToWrite x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_bytesToWrite_h cobj_x0
instance QcanReadLine (QIODevice ()) (()) where
canReadLine x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_canReadLine_h cobj_x0
foreign import ccall "qtc_QIODevice_canReadLine_h" qtc_QIODevice_canReadLine_h :: Ptr (TQIODevice a) -> IO CBool
instance QcanReadLine (QIODeviceSc a) (()) where
canReadLine x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_canReadLine_h cobj_x0
instance Qclose (QIODevice ()) (()) (IO ()) where
close x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_close_h cobj_x0
foreign import ccall "qtc_QIODevice_close_h" qtc_QIODevice_close_h :: Ptr (TQIODevice a) -> IO ()
instance Qclose (QIODeviceSc a) (()) (IO ()) where
close x0 ()
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_close_h cobj_x0
instance QerrorString (QIODevice a) (()) where
errorString x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_errorString cobj_x0
foreign import ccall "qtc_QIODevice_errorString" qtc_QIODevice_errorString :: Ptr (TQIODevice a) -> IO (Ptr (TQString ()))
isOpen :: QIODevice a -> (()) -> IO (Bool)
isOpen x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_isOpen cobj_x0
foreign import ccall "qtc_QIODevice_isOpen" qtc_QIODevice_isOpen :: Ptr (TQIODevice a) -> IO CBool
instance QisReadable (QIODevice a) (()) where
isReadable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_isReadable cobj_x0
foreign import ccall "qtc_QIODevice_isReadable" qtc_QIODevice_isReadable :: Ptr (TQIODevice a) -> IO CBool
instance QisSequential (QIODevice ()) (()) where
isSequential x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_isSequential_h cobj_x0
foreign import ccall "qtc_QIODevice_isSequential_h" qtc_QIODevice_isSequential_h :: Ptr (TQIODevice a) -> IO CBool
instance QisSequential (QIODeviceSc a) (()) where
isSequential x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_isSequential_h cobj_x0
isTextModeEnabled :: QIODevice a -> (()) -> IO (Bool)
isTextModeEnabled x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_isTextModeEnabled cobj_x0
foreign import ccall "qtc_QIODevice_isTextModeEnabled" qtc_QIODevice_isTextModeEnabled :: Ptr (TQIODevice a) -> IO CBool
instance QisWritable (QIODevice a) (()) where
isWritable x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_isWritable cobj_x0
foreign import ccall "qtc_QIODevice_isWritable" qtc_QIODevice_isWritable :: Ptr (TQIODevice a) -> IO CBool
instance Qopen (QIODevice ()) ((OpenMode)) where
open x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_open_h cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QIODevice_open_h" qtc_QIODevice_open_h :: Ptr (TQIODevice a) -> CLong -> IO CBool
instance Qopen (QIODeviceSc a) ((OpenMode)) where
open x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_open_h cobj_x0 (toCLong $ qFlags_toInt x1)
openMode :: QIODevice a -> (()) -> IO (OpenMode)
openMode x0 ()
= withQFlagsResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_openMode cobj_x0
foreign import ccall "qtc_QIODevice_openMode" qtc_QIODevice_openMode :: Ptr (TQIODevice a) -> IO CLong
peek :: QIODevice a -> ((Int)) -> IO (String)
peek x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_peek cobj_x0 (toCLLong x1)
foreign import ccall "qtc_QIODevice_peek" qtc_QIODevice_peek :: Ptr (TQIODevice a) -> CLLong -> IO (Ptr (TQString ()))
instance Qpos (QIODevice ()) (()) (IO (Int)) where
pos x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_pos_h cobj_x0
foreign import ccall "qtc_QIODevice_pos_h" qtc_QIODevice_pos_h :: Ptr (TQIODevice a) -> IO CLLong
instance Qpos (QIODeviceSc a) (()) (IO (Int)) where
pos x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_pos_h cobj_x0
instance Qqread (QIODevice a) ((Int)) where
qread x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_read cobj_x0 (toCLLong x1)
foreign import ccall "qtc_QIODevice_read" qtc_QIODevice_read :: Ptr (TQIODevice a) -> CLLong -> IO (Ptr (TQString ()))
instance QreadAll (QIODevice a) (()) where
readAll x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_readAll cobj_x0
foreign import ccall "qtc_QIODevice_readAll" qtc_QIODevice_readAll :: Ptr (TQIODevice a) -> IO (Ptr (TQString ()))
instance QreadLine (QIODevice a) (()) where
readLine x0 ()
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_readLine cobj_x0
foreign import ccall "qtc_QIODevice_readLine" qtc_QIODevice_readLine :: Ptr (TQIODevice a) -> IO (Ptr (TQString ()))
instance QreadLine (QIODevice a) ((Int)) where
readLine x0 (x1)
= withStringResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_readLine1 cobj_x0 (toCLLong x1)
foreign import ccall "qtc_QIODevice_readLine1" qtc_QIODevice_readLine1 :: Ptr (TQIODevice a) -> CLLong -> IO (Ptr (TQString ()))
instance Qreset (QIODevice ()) (()) (IO (Bool)) where
reset x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_reset_h cobj_x0
foreign import ccall "qtc_QIODevice_reset_h" qtc_QIODevice_reset_h :: Ptr (TQIODevice a) -> IO CBool
instance Qreset (QIODeviceSc a) (()) (IO (Bool)) where
reset x0 ()
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_reset_h cobj_x0
instance Qseek (QIODevice ()) ((Int)) where
seek x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_seek_h cobj_x0 (toCLLong x1)
foreign import ccall "qtc_QIODevice_seek_h" qtc_QIODevice_seek_h :: Ptr (TQIODevice a) -> CLLong -> IO CBool
instance Qseek (QIODeviceSc a) ((Int)) where
seek x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_seek_h cobj_x0 (toCLLong x1)
instance QsetErrorString (QIODevice ()) ((String)) where
setErrorString x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_setErrorString cobj_x0 cstr_x1
foreign import ccall "qtc_QIODevice_setErrorString" qtc_QIODevice_setErrorString :: Ptr (TQIODevice a) -> CWString -> IO ()
instance QsetErrorString (QIODeviceSc a) ((String)) where
setErrorString x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_setErrorString cobj_x0 cstr_x1
instance QsetOpenMode (QIODevice ()) ((OpenMode)) where
setOpenMode x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_setOpenMode cobj_x0 (toCLong $ qFlags_toInt x1)
foreign import ccall "qtc_QIODevice_setOpenMode" qtc_QIODevice_setOpenMode :: Ptr (TQIODevice a) -> CLong -> IO ()
instance QsetOpenMode (QIODeviceSc a) ((OpenMode)) where
setOpenMode x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_setOpenMode cobj_x0 (toCLong $ qFlags_toInt x1)
setTextModeEnabled :: QIODevice a -> ((Bool)) -> IO ()
setTextModeEnabled x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_setTextModeEnabled cobj_x0 (toCBool x1)
foreign import ccall "qtc_QIODevice_setTextModeEnabled" qtc_QIODevice_setTextModeEnabled :: Ptr (TQIODevice a) -> CBool -> IO ()
instance Qqsize (QIODevice ()) (()) (IO (Int)) where
qsize x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_size_h cobj_x0
foreign import ccall "qtc_QIODevice_size_h" qtc_QIODevice_size_h :: Ptr (TQIODevice a) -> IO CLLong
instance Qqsize (QIODeviceSc a) (()) (IO (Int)) where
qsize x0 ()
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_size_h cobj_x0
instance QwaitForBytesWritten (QIODevice ()) ((Int)) where
waitForBytesWritten x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_waitForBytesWritten_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QIODevice_waitForBytesWritten_h" qtc_QIODevice_waitForBytesWritten_h :: Ptr (TQIODevice a) -> CInt -> IO CBool
instance QwaitForBytesWritten (QIODeviceSc a) ((Int)) where
waitForBytesWritten x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_waitForBytesWritten_h cobj_x0 (toCInt x1)
instance QwaitForReadyRead (QIODevice ()) ((Int)) where
waitForReadyRead x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_waitForReadyRead_h cobj_x0 (toCInt x1)
foreign import ccall "qtc_QIODevice_waitForReadyRead_h" qtc_QIODevice_waitForReadyRead_h :: Ptr (TQIODevice a) -> CInt -> IO CBool
instance QwaitForReadyRead (QIODeviceSc a) ((Int)) where
waitForReadyRead x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_waitForReadyRead_h cobj_x0 (toCInt x1)
class Qwrite x1 where
write :: QIODevice a -> x1 -> IO (Int)
instance Qwrite ((String)) where
write x0 (x1)
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_write cobj_x0 cstr_x1
foreign import ccall "qtc_QIODevice_write" qtc_QIODevice_write :: Ptr (TQIODevice a) -> CWString -> IO CLLong
instance Qwrite ((String, Int)) where
write x0 (x1, x2)
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_write1 cobj_x0 cstr_x1 (toCLLong x2)
foreign import ccall "qtc_QIODevice_write1" qtc_QIODevice_write1 :: Ptr (TQIODevice a) -> CWString -> CLLong -> IO CLLong
instance QwriteData (QIODevice ()) ((String, Int)) where
writeData x0 (x1, x2)
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_writeData_h cobj_x0 cstr_x1 (toCLLong x2)
foreign import ccall "qtc_QIODevice_writeData_h" qtc_QIODevice_writeData_h :: Ptr (TQIODevice a) -> CWString -> CLLong -> IO CLLong
instance QwriteData (QIODeviceSc a) ((String, Int)) where
writeData x0 (x1, x2)
= withLongLongResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_writeData_h cobj_x0 cstr_x1 (toCLLong x2)
qIODevice_delete :: QIODevice a -> IO ()
qIODevice_delete x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_delete cobj_x0
foreign import ccall "qtc_QIODevice_delete" qtc_QIODevice_delete :: Ptr (TQIODevice a) -> IO ()
qIODevice_deleteLater :: QIODevice a -> IO ()
qIODevice_deleteLater x0
= withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_deleteLater cobj_x0
foreign import ccall "qtc_QIODevice_deleteLater" qtc_QIODevice_deleteLater :: Ptr (TQIODevice a) -> IO ()
instance QchildEvent (QIODevice ()) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_childEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QIODevice_childEvent" qtc_QIODevice_childEvent :: Ptr (TQIODevice a) -> Ptr (TQChildEvent t1) -> IO ()
instance QchildEvent (QIODeviceSc a) ((QChildEvent t1)) where
childEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_childEvent cobj_x0 cobj_x1
instance QconnectNotify (QIODevice ()) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_connectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QIODevice_connectNotify" qtc_QIODevice_connectNotify :: Ptr (TQIODevice a) -> CWString -> IO ()
instance QconnectNotify (QIODeviceSc a) ((String)) where
connectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_connectNotify cobj_x0 cstr_x1
instance QcustomEvent (QIODevice ()) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_customEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QIODevice_customEvent" qtc_QIODevice_customEvent :: Ptr (TQIODevice a) -> Ptr (TQEvent t1) -> IO ()
instance QcustomEvent (QIODeviceSc a) ((QEvent t1)) where
customEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_customEvent cobj_x0 cobj_x1
instance QdisconnectNotify (QIODevice ()) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_disconnectNotify cobj_x0 cstr_x1
foreign import ccall "qtc_QIODevice_disconnectNotify" qtc_QIODevice_disconnectNotify :: Ptr (TQIODevice a) -> CWString -> IO ()
instance QdisconnectNotify (QIODeviceSc a) ((String)) where
disconnectNotify x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_disconnectNotify cobj_x0 cstr_x1
instance Qevent (QIODevice ()) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_event_h cobj_x0 cobj_x1
foreign import ccall "qtc_QIODevice_event_h" qtc_QIODevice_event_h :: Ptr (TQIODevice a) -> Ptr (TQEvent t1) -> IO CBool
instance Qevent (QIODeviceSc a) ((QEvent t1)) where
event x0 (x1)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_event_h cobj_x0 cobj_x1
instance QeventFilter (QIODevice ()) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QIODevice_eventFilter_h cobj_x0 cobj_x1 cobj_x2
foreign import ccall "qtc_QIODevice_eventFilter_h" qtc_QIODevice_eventFilter_h :: Ptr (TQIODevice a) -> Ptr (TQObject t1) -> Ptr (TQEvent t2) -> IO CBool
instance QeventFilter (QIODeviceSc a) ((QObject t1, QEvent t2)) where
eventFilter x0 (x1, x2)
= withBoolResult $
withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
withObjectPtr x2 $ \cobj_x2 ->
qtc_QIODevice_eventFilter_h cobj_x0 cobj_x1 cobj_x2
instance Qreceivers (QIODevice ()) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_receivers cobj_x0 cstr_x1
foreign import ccall "qtc_QIODevice_receivers" qtc_QIODevice_receivers :: Ptr (TQIODevice a) -> CWString -> IO CInt
instance Qreceivers (QIODeviceSc a) ((String)) where
receivers x0 (x1)
= withIntResult $
withObjectPtr x0 $ \cobj_x0 ->
withCWString x1 $ \cstr_x1 ->
qtc_QIODevice_receivers cobj_x0 cstr_x1
instance Qsender (QIODevice ()) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_sender cobj_x0
foreign import ccall "qtc_QIODevice_sender" qtc_QIODevice_sender :: Ptr (TQIODevice a) -> IO (Ptr (TQObject ()))
instance Qsender (QIODeviceSc a) (()) where
sender x0 ()
= withQObjectResult $
withObjectPtr x0 $ \cobj_x0 ->
qtc_QIODevice_sender cobj_x0
instance QtimerEvent (QIODevice ()) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_timerEvent cobj_x0 cobj_x1
foreign import ccall "qtc_QIODevice_timerEvent" qtc_QIODevice_timerEvent :: Ptr (TQIODevice a) -> Ptr (TQTimerEvent t1) -> IO ()
instance QtimerEvent (QIODeviceSc a) ((QTimerEvent t1)) where
timerEvent x0 (x1)
= withObjectPtr x0 $ \cobj_x0 ->
withObjectPtr x1 $ \cobj_x1 ->
qtc_QIODevice_timerEvent cobj_x0 cobj_x1
|
uduki/hsQt
|
Qtc/Core/QIODevice.hs
|
bsd-2-clause
| 18,716
| 0
| 14
| 3,196
| 6,075
| 3,085
| 2,990
| -1
| -1
|
--
-- Copyright (c) 2013, Carl Joachim Svenn
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
--
-- 1. Redistributions of source code must retain the above copyright notice, this
-- list of conditions and the following disclaimer.
-- 2. Redistributions in binary form must reproduce the above copyright notice,
-- this list of conditions and the following disclaimer in the documentation
-- and/or other materials provided with the distribution.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-- FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--
{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses #-}
{-# LANGUAGE MagicHash, UnboxedTuples #-}
module File.Binary.Reader
(
Reader,
readBinary,
readBinaryAt,
readBinary',
readBinaryAt',
rSatisfy,
rWord8s,
rOneOf,
rNoneOf,
rAnyWord8,
rWord8,
rNUL,
rNonNUL,
rSkipNULs,
rBool,
rInt32,
rUInt32,
rCString,
rOffset,
rAlign,
word8sAsWord32,
) where
import MyPrelude
import Text.Parsec
import Text.Parsec.Pos
import Text.Parsec.Error
import System.IO
import Data.Binary.Put
import Control.Monad.Identity
--import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as BS
import Data.Char
import Data.Word
import Data.Bits
import Control.Exception as C
-- this is tmp!
#define PLATFORM_LE
{-
import GHC.Prim
import GHC.Exts
import GHC.Types
import GHC.Int
import Data.Int
-}
--------------------------------------------------------------------------------
--
-- todo: * write custom parser library for binary files as 'parsec', using 'binary'
-- (and 'binary-strict'?). this should fix current problems. currently,
-- we hack on top of 'parsec'
-- * implement functions for zlib, in order to work with directories?
--
-- fixme * write custom parser library for Word8!
-- * satisfy and string from Text.Parsec.Char should not be used, since
-- they update SourcePos wrong
--------------------------------------------------------------------------------
-- Reader
-- | fixme: parameterize monad as m.
-- then readBinaryXXX working in MonadIO m?
type Reader =
ParsecT ByteStream () IO
newtype ByteStream =
ByteStream
{
unwrapByteString :: BS.ByteString
}
wrapByteString :: BS.ByteString -> ByteStream
wrapByteString bs =
ByteStream { unwrapByteString = bs }
packByteStream :: [Word8] -> ByteStream
packByteStream =
wrapByteString . BS.pack
unpackByteStream :: ByteStream -> [Word8]
unpackByteStream =
BS.unpack . unwrapByteString
instance (Monad m) => Stream ByteStream m Word8 where
uncons = return .
fmap (\(w, bs) -> (w, wrapByteString bs)) .
BS.uncons .
unwrapByteString
--------------------------------------------------------------------------------
-- read
readByteStream :: FilePath -> IO ByteStream
readByteStream path =
wrapByteString `fmap` BS.readFile path
readByteStreamAt :: FilePath -> UInt -> IO ByteStream
readByteStreamAt path off =
wrapByteString `fmap` do C.bracket (openBinaryFile path ReadMode) hClose $ \h -> do
size <- hFileSize h
hSeek h AbsoluteSeek (fI off)
BS.hGet h (fI size - fI off)
parsingAt ::
Reader a ->
SourceName ->
UInt ->
ByteStream ->
IO (Either String a)
parsingAt p name off s =
runPT p () name s
where
runPT p u name s = do
res <- runParsecT p (State s (newPos name 0 (fI off)) u)
r <- parserReply res
case r of
Ok x _ _ -> return (Right x)
Error err -> return (Left $ showParseError err)
where
parserReply res = case res of
Consumed r -> r
Empty r -> r
showParseError :: ParseError -> String
showParseError err =
showSrc err ++ showMsg err
where
showSrc err =
"\"" ++ (sourceName $ errorPos err) ++
"\" (offset " ++ show (sourceColumn $ errorPos err) ++ "): "
showMsg err =
showErrorMessages "or" "unknown parse error" "expecting"
"unexpected" "end of input" (errorMessages err)
-- | read binary file
readBinary :: Reader a -> FilePath -> IO (Either String a)
readBinary ra path =
C.catch (readByteStream path >>= parsingAt ra path 0) $ \e ->
return $ Left $ show (e :: IOException)
-- | read binary file, at offset in 8-bit bytes
readBinaryAt :: Reader a -> FilePath -> UInt -> IO (Either String a)
readBinaryAt ra path off =
C.catch (readByteStreamAt path off >>= parsingAt ra path off) $ \e ->
return $ Left $ show (e :: IOException)
-- | assuming success, else error
readBinary' :: Reader a -> FilePath -> IO a
readBinary' ra path = do
readByteStream path >>= parsingAt ra path 0 >>= \res -> case res of
Left msg -> error msg
Right a -> return a
-- | assuming success, else error
readBinaryAt' :: Reader a -> FilePath -> UInt -> IO a
readBinaryAt' ra path off =
readByteStreamAt path off >>= parsingAt ra path off >>= \res -> case res of
Left msg -> error msg
Right a -> return a
--------------------------------------------------------------------------------
--
rSatisfy :: (Word8 -> Bool) -> Reader Word8
rSatisfy f =
tokenPrim (\w -> showWord8 w)
(\pos w _ws -> incSourceColumn pos 1)
(\w -> if f w then Just w else Nothing)
rWord8s :: [Word8] -> Reader ()
rWord8s s =
tokens show (\pos string -> incSourceColumn pos (length string)) s >> return ()
rOffset :: Reader UInt
rOffset =
(fI . sourceColumn) `fmap` getPosition
rOneOf :: [Word8] -> Reader Word8
rOneOf cs = rSatisfy (\c -> elem c cs)
rNoneOf :: [Word8] -> Reader Word8
rNoneOf cs = rSatisfy (\c -> not (elem c cs))
rAnyWord8 :: Reader Word8
rAnyWord8 = rSatisfy (const True)
rWord8 :: Word8 -> Reader ()
rWord8 c =
(rSatisfy (==c) >> return ()) <?> showWord8 c
rNUL :: Reader ()
rNUL =
(rSatisfy (== 0x00) <?> "NUL") >> return ()
rNonNUL :: Reader Word8
rNonNUL =
rSatisfy (/= 0x00) <?> "non-NUL"
rSkipNULs :: Reader ()
rSkipNULs = do
many rNUL
return ()
-- | False == 0x01
-- True == 0x02
rBool :: Reader Bool
rBool =
(rSatisfy (\w -> w == 0x01 || w == 0x02) >>= \w -> case w of
0x01 -> return False
0x02 -> return True
_ -> error "rBool"
) <?> "Bool"
-- | reading a C-string
rCString :: Reader String
rCString = do
ws <- many rNonNUL
rNUL
return $ map (chr . fI) ws
-- | reading a value [-2^31, 2^31)
rInt32 :: Reader Int
rInt32 = do
w0 <- rAnyWord8
w1 <- rAnyWord8
w2 <- rAnyWord8
w3 <- rAnyWord8
case word8sAsWord32 w0 w1 w2 w3 of
w32 -> convert w32
where
{-
convert (W32# w32#) =
(I# (unsafeCoerce# w32#))
-}
convert w32 =
if testBit w32 31
then return $ negate $ fI $ complement w32 + 1
else return $ fI w32
-- | reading a value [0, 2^32)
rUInt32 :: Reader UInt
rUInt32 = do
w0 <- rAnyWord8
w1 <- rAnyWord8
w2 <- rAnyWord8
w3 <- rAnyWord8
return $ fI $ word8sAsWord32 w0 w1 w2 w3
rAlign :: UInt -> Reader ()
rAlign n =
rOffset >>= \off -> do
replicateM_ (fI $ (n - off `mod` n) `mod` n) rAnyWord8
return ()
--------------------------------------------------------------------------------
--
-- | little endian -> platform endian
word8sAsWord32 :: Word8 -> Word8 -> Word8 -> Word8 -> Word32
word8sAsWord32 w0 w1 w2 w3 =
#ifdef PLATFORM_LE
(shiftL (fI w0) 0) .|.
(shiftL (fI w1) 8) .|.
(shiftL (fI w2) 16) .|.
(shiftL (fI w3) 24)
#else
(shiftL (fI w3) 0) .|.
(shiftL (fI w2) 8) .|.
(shiftL (fI w1) 16) .|.
(shiftL (fI w0) 24)
#endif
showWord8 :: Word8 -> String
showWord8 =
show . chr . fI
|
karamellpelle/MEnv
|
source/File/Binary/Reader.hs
|
bsd-2-clause
| 8,999
| 0
| 16
| 2,479
| 2,091
| 1,095
| 996
| -1
| -1
|
module Test.Observer (observer, observerName, printNum, x) where
import GOOL.Drasil (
ProgramSym, FileSym(..), PermanenceSym(..), BodySym(..), TypeSym(..),
StatementSym(..), VariableSym(..), ValueSym(..), ScopeSym(..),
MethodSym(..), initializer, StateVarSym(..), ClassSym(..), ModuleSym(..), FS,
CS, MS, VS)
import Prelude hiding (return,print,log,exp,sin,cos,tan)
observerName, observerDesc, printNum :: String
observerName = "Observer"
observerDesc = "This is an arbitrary class acting as an Observer"
printNum = "printNum"
observer :: (ProgramSym repr) => FS (repr (RenderFile repr))
observer = fileDoc (buildModule observerName [] [] [docClass observerDesc
helperClass])
x :: (VariableSym repr) => VS (repr (Variable repr))
x = var "x" int
selfX :: (VariableSym repr) => VS (repr (Variable repr))
selfX = objVarSelf x
helperClass :: (ClassSym repr) => CS (repr (Class repr))
helperClass = buildClass observerName Nothing [stateVar public dynamic x]
[observerConstructor, printNumMethod, getMethod x, setMethod x]
observerConstructor :: (MethodSym repr) => MS (repr (Method repr))
observerConstructor = initializer [] [(x, litInt 5)]
printNumMethod :: (MethodSym repr) => MS (repr (Method repr))
printNumMethod = method printNum public dynamic void [] $
oneLiner $ printLn $ valueOf selfX
|
JacquesCarette/literate-scientific-software
|
code/drasil-gool/Test/Observer.hs
|
bsd-2-clause
| 1,317
| 0
| 10
| 188
| 503
| 289
| 214
| 26
| 1
|
#!/usr/bin/env runhaskell
-- Cf. <http://www.mail-archive.com/haskell-cafe@haskell.org/msg59984.html>
-- <http://www.haskell.org/pipermail/haskell-cafe/2008-December/051785.html>
{-# OPTIONS_GHC -Wall -fwarn-tabs -fno-warn-missing-signatures #-}
module Main (main) where
import Distribution.Simple
import Distribution.Simple.LocalBuildInfo (withPrograms)
import Distribution.Simple.Program (userSpecifyArgs)
----------------------------------------------------------------
-- | Define __HADDOCK__ when building documentation.
main :: IO ()
main = defaultMainWithHooks
$ simpleUserHooks `modify_haddockHook` \oldHH pkg lbi hooks flags -> do
-- Call the old haddockHook with a modified LocalBuildInfo
(\lbi' -> oldHH pkg lbi' hooks flags)
$ lbi `modify_withPrograms` \oldWP ->
userSpecifyArgs "haddock" ["--optghc=-D__HADDOCK__"] oldWP
modify_haddockHook hooks f = hooks { haddockHook = f (haddockHook hooks) }
modify_withPrograms lbi f = lbi { withPrograms = f (withPrograms lbi) }
----------------------------------------------------------------
----------------------------------------------------------- fin.
|
bitemyapp/stm-chans
|
Setup.hs
|
bsd-3-clause
| 1,189
| 0
| 13
| 180
| 182
| 105
| 77
| 13
| 1
|
module Json.Internal.Encode
(
-- * ByteString builder
encodeToBuilder,
encodeToBuilderWith,
-- * ByteString
encodeToByteString,
encodeToByteStringWith,
-- * Text builder
encodeToTextBuilder,
encodeToTextBuilderWith,
-- * Text
encodeToText,
encodeToTextWith,
)
where
import Json.Internal.Encode.ByteString
import Json.Internal.Encode.Text
|
aelve/json-x
|
lib/Json/Internal/Encode.hs
|
bsd-3-clause
| 364
| 0
| 4
| 57
| 52
| 37
| 15
| 12
| 0
|
module Tubes.Model (
module Tubes.Model.Action,
module Tubes.Model.Tube,
module Tubes.Model.Universe,
) where
import Tubes.Model.Action
import Tubes.Model.Tube
import Tubes.Model.Universe
|
fizruk/tubes
|
src/Tubes/Model.hs
|
bsd-3-clause
| 195
| 0
| 5
| 24
| 48
| 33
| 15
| 7
| 0
|
-- Copyright (c) 2016-present, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree.
{-# LANGUAGE GADTs #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE NoRebindableSyntax #-}
module Duckling.Ordinal.RU.Rules
( rules
) where
import Data.HashMap.Strict (HashMap)
import Data.String
import Prelude
import qualified Data.HashMap.Strict as HashMap
import qualified Data.Text as Text
import Duckling.Dimensions.Types
import Duckling.Numeral.Helpers (parseInt)
import Duckling.Ordinal.Helpers
import Duckling.Regex.Types
import Duckling.Types
ordinalsFirstthMap :: HashMap Text.Text Int
ordinalsFirstthMap = HashMap.fromList
[ ( "перв", 1 )
, ( "втор", 2 )
, ( "трет", 3 )
, ( "четверт", 4 )
, ( "пят", 5 )
, ( "шест", 6 )
, ( "седьм", 7 )
, ( "восьм", 8 )
, ( "девят", 9 )
, ( "десят", 10 )
, ( "одиннадцат", 11 )
, ( "двенадцат", 12 )
, ( "тринадцат", 13 )
, ( "четырнадцат", 14 )
, ( "пятнадцат", 15 )
, ( "шестнадцат", 16 )
, ( "семнадцат", 17 )
, ( "восемнадцат", 18 )
, ( "девятнадцат", 19 )
, ( "двадцат", 20 )
]
cardinalsMap :: HashMap Text.Text Int
cardinalsMap = HashMap.fromList
[ ( "двадцать", 20 )
, ( "тридцать", 30 )
, ( "сорок", 40 )
, ( "пятьдесят", 50 )
, ( "шестьдесят", 60 )
, ( "семьдесят", 70 )
, ( "восемьдесят", 80 )
, ( "девяносто", 90 )
]
ruleOrdinalsFirstth :: Rule
ruleOrdinalsFirstth = Rule
{ name = "ordinals (first..19th)"
, pattern =
[ regex "(перв|втор|трет|четверт|пят|шест|седьм|восьм|девят|десят|одиннадцат|двенадцат|тринадцат|четырнадцат|пятнадцат|шестнадцат|семнадцат|восемнадцат|девятнадцат|двадцат)(ье(го|й)?|ого|ый|ой|ий|ая|ое|ья)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) ->
ordinal <$> HashMap.lookup (Text.toLower match) ordinalsFirstthMap
_ -> Nothing
}
ruleOrdinal :: Rule
ruleOrdinal = Rule
{ name = "ordinal 21..99"
, pattern =
[ regex "(двадцать|тридцать|сорок|пятьдесят|шестьдесят|семьдесят|восемьдесят|девяносто)"
, regex "(перв|втор|трет|четверт|пят|шест|седьм|восьм|девят)(ье(го|й)?|ого|ый|ой|ий|ая|ое|ья)"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (m1:_)):
Token RegexMatch (GroupMatch (m2:_)):
_) -> do
dozen <- HashMap.lookup (Text.toLower m1) cardinalsMap
unit <- HashMap.lookup (Text.toLower m2) ordinalsFirstthMap
Just . ordinal $ dozen + unit
_ -> Nothing
}
ruleOrdinalDigits :: Rule
ruleOrdinalDigits = Rule
{ name = "ordinal (digits)"
, pattern =
[ regex "0*(\\d+)-?((ы|о|и|а|e|ь)?(ее|й|я|е|го))"
]
, prod = \tokens -> case tokens of
(Token RegexMatch (GroupMatch (match:_)):_) -> ordinal <$> parseInt match
_ -> Nothing
}
rules :: [Rule]
rules =
[ ruleOrdinal
, ruleOrdinalDigits
, ruleOrdinalsFirstth
]
|
facebookincubator/duckling
|
Duckling/Ordinal/RU/Rules.hs
|
bsd-3-clause
| 3,484
| 0
| 18
| 614
| 768
| 459
| 309
| 83
| 2
|
{-# LANGUAGE OverloadedStrings #-}
module Dalvik.ClassHierarchy (
-- * Class Hierarchy Analysis
CHA,
classHierarchyAnalysis,
classHierarchyParent
) where
import Control.Monad ( foldM, liftM )
import Control.Monad.Catch as E
import qualified Data.ByteString.Char8 as BS
import Data.Map
import qualified Data.Map as M
import Dalvik.ClassName
import Dalvik.Types
-- | The result of a class hierarchy analysis
data CHA = CHA (Map BS.ByteString BS.ByteString)
deriving (Eq, Ord, Show)
-- | Extract the class hierarchy from a Dex file. This hierarchy only
-- includes the types referenced in the Dex file.
classHierarchyAnalysis :: (E.MonadThrow m) => DexFile -> m CHA
classHierarchyAnalysis dex =
liftM CHA $ foldM addClassParent M.empty $ M.toList (dexClasses dex)
where
addClassParent m (tyId, klass) = do
cname <- getTypeName dex tyId
case cname == "Ljava/lang/Object;" of
True -> return m
False -> do
superName <- getTypeName dex (classSuperId klass)
return $ M.insert cname superName m
-- | Look up the parent of a class. Only Object has no parent.
--
-- The input is a 'NameLike': either a ByteString or a ClassName
-- (which is easily convertible to ByteString).
classHierarchyParent :: (NameLike a) => CHA -> a -> Maybe BS.ByteString
classHierarchyParent (CHA cha) cname = M.lookup (toName cname) cha
class NameLike a where
toName :: a -> BS.ByteString
instance NameLike BS.ByteString where
toName = id
instance NameLike ClassName where
toName = renderClassName
|
travitch/dalvik
|
src/Dalvik/ClassHierarchy.hs
|
bsd-3-clause
| 1,556
| 0
| 17
| 311
| 369
| 199
| 170
| 32
| 2
|
module Monto.Types where
import Data.Text (Text)
type VersionID = Int
type ProductID = Int
type Source = Text
type Language = Text
type Product = Text
type Port = Int
type ServiceID = Text
|
wpmp/monto-broker
|
src/Monto/Types.hs
|
bsd-3-clause
| 225
| 0
| 5
| 70
| 58
| 38
| 20
| 9
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.