2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
5 \section[TcType]{Types used in the typechecker}
7 This module provides the Type interface for front-end parts of the
10 * treat "source types" as opaque:
11 newtypes, and predicates are meaningful.
12 * look through usage types
14 The "tc" prefix is for "TypeChecker", because the type checker
15 is the principal client.
19 --------------------------------
21 TcType, TcSigmaType, TcRhoType, TcTauType, TcPredType, TcThetaType,
22 TcTyVar, TcTyVarSet, TcKind, TcCoVar,
24 --------------------------------
26 UserTypeCtxt(..), pprUserTypeCtxt,
27 TcTyVarDetails(..), pprTcTyVarDetails,
28 MetaDetails(Flexi, Indirect), MetaInfo(..),
29 SkolemInfo(..), pprSkolTvBinding, pprSkolInfo,
30 isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isMetaTyVarTy,
31 isSigTyVar, isOverlappableTyVar, isTyConableTyVar,
33 isFlexi, isIndirect, isUnkSkol, isRuntimeUnkSkol,
35 --------------------------------
39 --------------------------------
41 -- These are important because they do not look through newtypes
43 tcSplitForAllTys, tcSplitPhiTy, tcSplitPredFunTy_maybe,
44 tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcSplitFunTysN,
45 tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
46 tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, repSplitAppTy_maybe,
47 tcInstHeadTyNotSynonym, tcInstHeadTyAppAllTyVars,
48 tcGetTyVar_maybe, tcGetTyVar,
49 tcSplitSigmaTy, tcDeepSplitSigmaTy_maybe,
51 ---------------------------------
53 -- Again, newtypes are opaque
54 tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred, tcEqTypeX,
56 isSigmaTy, isOverloadedTy, isRigidTy,
57 isDoubleTy, isFloatTy, isIntTy, isWordTy, isStringTy,
58 isIntegerTy, isBoolTy, isUnitTy, isCharTy,
59 isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy,
62 ---------------------------------
63 -- Misc type manipulators
65 tyClsNamesOfType, tyClsNamesOfDFunHead,
68 ---------------------------------
70 getClassPredTys_maybe, getClassPredTys,
71 isClassPred, isTyVarClassPred, isEqPred,
72 mkClassPred, mkIPPred, tcSplitPredTy_maybe,
74 isPredTy, isDictTy, isDictLikeTy,
75 tcSplitDFunTy, tcSplitDFunHead, predTyUnique,
77 isRefineableTy, isRefineablePred,
79 -- * Tidying type related things up for printing
81 tidyOpenType, tidyOpenTypes,
82 tidyTyVarBndr, tidyFreeTyVars,
83 tidyOpenTyVar, tidyOpenTyVars,
84 tidyTopType, tidyPred,
85 tidyKind, tidySkolemTyVar,
87 ---------------------------------
88 -- Foreign import and export
89 isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
90 isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
91 isFFIExportResultTy, -- :: Type -> Bool
92 isFFIExternalTy, -- :: Type -> Bool
93 isFFIDynArgumentTy, -- :: Type -> Bool
94 isFFIDynResultTy, -- :: Type -> Bool
95 isFFIPrimArgumentTy, -- :: DynFlags -> Type -> Bool
96 isFFIPrimResultTy, -- :: DynFlags -> Type -> Bool
97 isFFILabelTy, -- :: Type -> Bool
98 isFFIDotnetTy, -- :: DynFlags -> Type -> Bool
99 isFFIDotnetObjTy, -- :: Type -> Bool
100 isFFITy, -- :: Type -> Bool
101 isFunPtrTy, -- :: Type -> Bool
102 tcSplitIOType_maybe, -- :: Type -> Maybe Type
104 --------------------------------
105 -- Rexported from Coercion
108 --------------------------------
109 -- Rexported from Type
110 Kind, -- Stuff to do with kinds is insensitive to pre/post Tc
111 unliftedTypeKind, liftedTypeKind, argTypeKind,
112 openTypeKind, mkArrowKind, mkArrowKinds,
113 isLiftedTypeKind, isUnliftedTypeKind, isSubOpenTypeKind,
114 isSubArgTypeKind, isSubKind, splitKindFunTys, defaultKind,
115 kindVarRef, mkKindVar,
117 Type, PredType(..), ThetaType,
118 mkForAllTy, mkForAllTys,
119 mkFunTy, mkFunTys, zipFunTys,
120 mkTyConApp, mkAppTy, mkAppTys, applyTy, applyTys,
121 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
123 -- Type substitutions
124 TvSubst(..), -- Representation visible to a few friends
125 TvSubstEnv, emptyTvSubst, substEqSpec,
126 mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst,
127 mkTopTvSubst, notElemTvSubst, unionTvSubst,
128 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope, lookupTyVar,
129 extendTvSubst, extendTvSubstList, isInScope, mkTvSubst, zipTyEnv,
130 substTy, substTys, substTyWith, substTheta, substTyVar, substTyVars, substTyVarBndr,
132 isUnLiftedType, -- Source types are always lifted
133 isUnboxedTupleType, -- Ditto
136 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
137 tcTyVarsOfType, tcTyVarsOfTypes, tcTyVarsOfPred, exactTyVarsOfType,
140 pprKind, pprParendKind,
141 pprType, pprParendType, pprTypeApp, pprTyThingCategory,
142 pprPred, pprTheta, pprThetaArrow, pprClassPred
146 #include "HsVersions.h"
158 import HsExpr( HsMatchContext )
174 import Data.List( mapAccumL )
178 %************************************************************************
182 %************************************************************************
184 The type checker divides the generic Type world into the
185 following more structured beasts:
187 sigma ::= forall tyvars. phi
188 -- A sigma type is a qualified type
190 -- Note that even if 'tyvars' is empty, theta
191 -- may not be: e.g. (?x::Int) => Int
193 -- Note that 'sigma' is in prenex form:
194 -- all the foralls are at the front.
195 -- A 'phi' type has no foralls to the right of
203 -- A 'tau' type has no quantification anywhere
204 -- Note that the args of a type constructor must be taus
206 | tycon tau_1 .. tau_n
210 -- In all cases, a (saturated) type synonym application is legal,
211 -- provided it expands to the required form.
214 type TcTyVar = TyVar -- Used only during type inference
215 type TcCoVar = CoVar -- Used only during type inference; mutable
216 type TcType = Type -- A TcType can have mutable type variables
217 -- Invariant on ForAllTy in TcTypes:
219 -- a cannot occur inside a MutTyVar in T; that is,
220 -- T is "flattened" before quantifying over a
222 -- These types do not have boxy type variables in them
223 type TcPredType = PredType
224 type TcThetaType = ThetaType
225 type TcSigmaType = TcType
226 type TcRhoType = TcType
227 type TcTauType = TcType
229 type TcTyVarSet = TyVarSet
233 %************************************************************************
235 \subsection{TyVarDetails}
237 %************************************************************************
239 TyVarDetails gives extra info about type variables, used during type
240 checking. It's attached to mutable type variables only.
241 It's knot-tied back to Var.lhs. There is no reason in principle
242 why Var.lhs shouldn't actually have the definition, but it "belongs" here.
245 Note [Signature skolems]
246 ~~~~~~~~~~~~~~~~~~~~~~~~
251 (x,y,z) = ([y,z], z, head x)
253 Here, x and y have type sigs, which go into the environment. We used to
254 instantiate their types with skolem constants, and push those types into
255 the RHS, so we'd typecheck the RHS with type
257 where a*, b* are skolem constants, and c is an ordinary meta type varible.
259 The trouble is that the occurrences of z in the RHS force a* and b* to
260 be the *same*, so we can't make them into skolem constants that don't unify
261 with each other. Alas.
263 One solution would be insist that in the above defn the programmer uses
264 the same type variable in both type signatures. But that takes explanation.
266 The alternative (currently implemented) is to have a special kind of skolem
267 constant, SigTv, which can unify with other SigTvs. These are *not* treated
268 as righd for the purposes of GADTs. And they are used *only* for pattern
269 bindings and mutually recursive function bindings. See the function
270 TcBinds.tcInstSig, and its use_skols parameter.
274 -- A TyVarDetails is inside a TyVar
276 = SkolemTv SkolemInfo -- A skolem constant
279 -- The "skolem" obtained by flattening during
280 -- constraint simplification
282 -- In comments we will use the notation alpha[flat = ty]
283 -- to represent a flattening skolem variable alpha
284 -- identified with type ty.
286 | MetaTv MetaInfo (IORef MetaDetails)
289 = Flexi -- Flexi type variables unify to become Indirects
293 = TauTv -- This MetaTv is an ordinary unification variable
294 -- A TauTv is always filled in with a tau-type, which
295 -- never contains any ForAlls
297 | SigTv Name -- A variant of TauTv, except that it should not be
298 -- unified with a type, only with a type variable
299 -- SigTvs are only distinguished to improve error messages
300 -- see Note [Signature skolems]
301 -- The MetaDetails, if filled in, will
302 -- always be another SigTv or a SkolemTv
303 -- The Name is the name of the function from whose
304 -- type signature we got this skolem
306 | TcsTv -- A MetaTv allocated by the constraint solver
307 -- Its particular property is that it is always "touchable"
308 -- Nevertheless, the constraint solver has to try to guess
309 -- what type to instantiate it to
311 ----------------------------------
312 -- SkolemInfo describes a site where
313 -- a) type variables are skolemised
314 -- b) an implication constraint is generated
316 = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
317 -- a programmer-supplied type signature
318 -- Location of the binding site is on the TyVar
320 -- The rest are for non-scoped skolems
321 | ClsSkol Class -- Bound at a class decl
322 | InstSkol -- Bound at an instance decl
323 | FamInstSkol -- Bound at a family instance decl
324 | PatSkol -- An existential type variable bound by a pattern for
325 DataCon -- a data constructor with an existential type.
326 (HsMatchContext Name)
327 -- e.g. data T = forall a. Eq a => MkT a
329 -- The pattern MkT x will allocate an existential type
332 | ArrowSkol -- An arrow form (see TcArrows)
334 | IPSkol [IPName Name] -- Binding site of an implicit parameter
336 | RuleSkol RuleName -- The LHS of a RULE
337 | GenSkol TcType -- Bound when doing a subsumption check for ty
339 | RuntimeUnkSkol -- a type variable used to represent an unknown
340 -- runtime type (used in the GHCi debugger)
342 | UnkSkol -- Unhelpful info (until I improve it)
344 -------------------------------------
345 -- UserTypeCtxt describes the places where a
346 -- programmer-written type signature can occur
347 -- Like SkolemInfo, no location info
349 = FunSigCtxt Name -- Function type signature
350 -- Also used for types in SPECIALISE pragmas
351 | ExprSigCtxt -- Expression type signature
352 | ConArgCtxt Name -- Data constructor argument
353 | TySynCtxt Name -- RHS of a type synonym decl
354 | GenPatCtxt -- Pattern in generic decl
355 -- f{| a+b |} (Inl x) = ...
356 | LamPatSigCtxt -- Type sig in lambda pattern
358 | BindPatSigCtxt -- Type sig in pattern binding pattern
360 | ResSigCtxt -- Result type sig
362 | ForSigCtxt Name -- Foreign inport or export signature
363 | DefaultDeclCtxt -- Types in a default declaration
364 | SpecInstCtxt -- SPECIALISE instance pragma
365 | ThBrackCtxt -- Template Haskell type brackets [t| ... |]
367 -- Notes re TySynCtxt
368 -- We allow type synonyms that aren't types; e.g. type List = []
370 -- If the RHS mentions tyvars that aren't in scope, we'll
371 -- quantify over them:
372 -- e.g. type T = a->a
373 -- will become type T = forall a. a->a
375 -- With gla-exts that's right, but for H98 we should complain.
377 ---------------------------------
380 mkKindName :: Unique -> Name
381 mkKindName unique = mkSystemName unique kind_var_occ
383 kindVarRef :: KindVar -> IORef MetaDetails
385 ASSERT ( isTcTyVar tc )
386 case tcTyVarDetails tc of
387 MetaTv TauTv ref -> ref
388 _ -> pprPanic "kindVarRef" (ppr tc)
390 mkKindVar :: Unique -> IORef MetaDetails -> KindVar
392 = mkTcTyVar (mkKindName u)
393 tySuperKind -- not sure this is right,
394 -- do we need kind vars for
398 kind_var_occ :: OccName -- Just one for all KindVars
399 -- They may be jiggled by tidying
400 kind_var_occ = mkOccName tvName "k"
403 %************************************************************************
407 %************************************************************************
410 pprTcTyVarDetails :: TcTyVarDetails -> SDoc
412 pprTcTyVarDetails (SkolemTv _) = ptext (sLit "sk")
413 pprTcTyVarDetails (FlatSkol {}) = ptext (sLit "fsk")
414 pprTcTyVarDetails (MetaTv TauTv _) = ptext (sLit "tau")
415 pprTcTyVarDetails (MetaTv TcsTv _) = ptext (sLit "tcs")
416 pprTcTyVarDetails (MetaTv (SigTv _) _) = ptext (sLit "sig")
418 pprUserTypeCtxt :: UserTypeCtxt -> SDoc
419 pprUserTypeCtxt (FunSigCtxt n) = ptext (sLit "the type signature for") <+> quotes (ppr n)
420 pprUserTypeCtxt ExprSigCtxt = ptext (sLit "an expression type signature")
421 pprUserTypeCtxt (ConArgCtxt c) = ptext (sLit "the type of the constructor") <+> quotes (ppr c)
422 pprUserTypeCtxt (TySynCtxt c) = ptext (sLit "the RHS of the type synonym") <+> quotes (ppr c)
423 pprUserTypeCtxt GenPatCtxt = ptext (sLit "the type pattern of a generic definition")
424 pprUserTypeCtxt ThBrackCtxt = ptext (sLit "a Template Haskell quotation [t|...|]")
425 pprUserTypeCtxt LamPatSigCtxt = ptext (sLit "a pattern type signature")
426 pprUserTypeCtxt BindPatSigCtxt = ptext (sLit "a pattern type signature")
427 pprUserTypeCtxt ResSigCtxt = ptext (sLit "a result type signature")
428 pprUserTypeCtxt (ForSigCtxt n) = ptext (sLit "the foreign declaration for") <+> quotes (ppr n)
429 pprUserTypeCtxt DefaultDeclCtxt = ptext (sLit "a type in a `default' declaration")
430 pprUserTypeCtxt SpecInstCtxt = ptext (sLit "a SPECIALISE instance pragma")
432 pprSkolTvBinding :: TcTyVar -> SDoc
433 -- Print info about the binding of a skolem tyvar,
434 -- or nothing if we don't have anything useful to say
436 = ASSERT ( isTcTyVar tv )
437 quotes (ppr tv) <+> ppr_details (tcTyVarDetails tv)
439 ppr_details (SkolemTv info) = ppr_skol info
440 ppr_details (FlatSkol {}) = ptext (sLit "is a flattening type variable")
441 ppr_details (MetaTv (SigTv n) _) = ptext (sLit "is bound by the type signature for")
443 ppr_details (MetaTv _ _) = ptext (sLit "is a meta type variable")
445 ppr_skol UnkSkol = ptext (sLit "is an unknown type variable") -- Unhelpful
446 ppr_skol RuntimeUnkSkol = ptext (sLit "is an unknown runtime type")
447 ppr_skol info = sep [ptext (sLit "is a rigid type variable bound by"),
448 sep [pprSkolInfo info,
449 nest 2 (ptext (sLit "at") <+> ppr (getSrcLoc tv))]]
451 instance Outputable SkolemInfo where
454 pprSkolInfo :: SkolemInfo -> SDoc
455 -- Complete the sentence "is a rigid type variable bound by..."
456 pprSkolInfo (SigSkol ctxt) = pprUserTypeCtxt ctxt
457 pprSkolInfo (IPSkol ips) = ptext (sLit "the implicit-parameter bindings for")
458 <+> pprWithCommas ppr ips
459 pprSkolInfo (ClsSkol cls) = ptext (sLit "the class declaration for") <+> quotes (ppr cls)
460 pprSkolInfo InstSkol = ptext (sLit "the instance declaration")
461 pprSkolInfo FamInstSkol = ptext (sLit "the family instance declaration")
462 pprSkolInfo (RuleSkol name) = ptext (sLit "the RULE") <+> doubleQuotes (ftext name)
463 pprSkolInfo ArrowSkol = ptext (sLit "the arrow form")
464 pprSkolInfo (PatSkol dc _) = sep [ ptext (sLit "a pattern with constructor")
465 , ppr dc <+> dcolon <+> ppr (dataConUserType dc) ]
466 pprSkolInfo (GenSkol ty) = sep [ ptext (sLit "the polymorphic type")
470 -- For type variables the others are dealt with by pprSkolTvBinding.
471 -- For Insts, these cases should not happen
472 pprSkolInfo UnkSkol = WARN( True, text "pprSkolInfo: UnkSkol" ) ptext (sLit "UnkSkol")
473 pprSkolInfo RuntimeUnkSkol = WARN( True, text "pprSkolInfo: RuntimeUnkSkol" ) ptext (sLit "RuntimeUnkSkol")
475 instance Outputable MetaDetails where
476 ppr Flexi = ptext (sLit "Flexi")
477 ppr (Indirect ty) = ptext (sLit "Indirect") <+> ppr ty
481 %************************************************************************
483 \subsection{TidyType}
485 %************************************************************************
488 -- | This tidies up a type for printing in an error message, or in
489 -- an interface file.
491 -- It doesn't change the uniques at all, just the print names.
492 tidyTyVarBndr :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
493 tidyTyVarBndr env@(tidy_env, subst) tyvar
494 = case tidyOccName tidy_env (getOccName name) of
495 (tidy', occ') -> ((tidy', subst'), tyvar'')
497 subst' = extendVarEnv subst tyvar tyvar''
498 tyvar' = setTyVarName tyvar name'
499 name' = tidyNameOcc name occ'
500 -- Don't forget to tidy the kind for coercions!
501 tyvar'' | isCoVar tyvar = setTyVarKind tyvar' kind'
503 kind' = tidyType env (tyVarKind tyvar)
505 name = tyVarName tyvar
508 tidyFreeTyVars :: TidyEnv -> TyVarSet -> TidyEnv
509 -- ^ Add the free 'TyVar's to the env in tidy form,
510 -- so that we can tidy the type they are free in
511 tidyFreeTyVars env tyvars = fst (tidyOpenTyVars env (varSetElems tyvars))
514 tidyOpenTyVars :: TidyEnv -> [TyVar] -> (TidyEnv, [TyVar])
515 tidyOpenTyVars env tyvars = mapAccumL tidyOpenTyVar env tyvars
518 tidyOpenTyVar :: TidyEnv -> TyVar -> (TidyEnv, TyVar)
519 -- ^ Treat a new 'TyVar' as a binder, and give it a fresh tidy name
520 -- using the environment if one has not already been allocated. See
521 -- also 'tidyTyVarBndr'
522 tidyOpenTyVar env@(_, subst) tyvar
523 = case lookupVarEnv subst tyvar of
524 Just tyvar' -> (env, tyvar') -- Already substituted
525 Nothing -> tidyTyVarBndr env tyvar -- Treat it as a binder
528 tidyType :: TidyEnv -> Type -> Type
529 tidyType env@(_, subst) ty
532 go (TyVarTy tv) = case lookupVarEnv subst tv of
534 Just tv' -> expand tv'
535 go (TyConApp tycon tys) = let args = map go tys
536 in args `seqList` TyConApp tycon args
537 go (PredTy sty) = PredTy (tidyPred env sty)
538 go (AppTy fun arg) = (AppTy $! (go fun)) $! (go arg)
539 go (FunTy fun arg) = (FunTy $! (go fun)) $! (go arg)
540 go (ForAllTy tv ty) = ForAllTy tvp $! (tidyType envp ty)
542 (envp, tvp) = tidyTyVarBndr env tv
544 -- Expand FlatSkols, the skolems introduced by flattening process
545 -- We don't want to show them in type error messages
546 expand tv | isTcTyVar tv
547 , FlatSkol ty <- tcTyVarDetails tv
553 tidyTypes :: TidyEnv -> [Type] -> [Type]
554 tidyTypes env tys = map (tidyType env) tys
557 tidyPred :: TidyEnv -> PredType -> PredType
558 tidyPred env (IParam n ty) = IParam n (tidyType env ty)
559 tidyPred env (ClassP clas tys) = ClassP clas (tidyTypes env tys)
560 tidyPred env (EqPred ty1 ty2) = EqPred (tidyType env ty1) (tidyType env ty2)
563 -- | Grabs the free type variables, tidies them
564 -- and then uses 'tidyType' to work over the type itself
565 tidyOpenType :: TidyEnv -> Type -> (TidyEnv, Type)
567 = (env', tidyType env' ty)
569 env' = tidyFreeTyVars env (tyVarsOfType ty)
572 tidyOpenTypes :: TidyEnv -> [Type] -> (TidyEnv, [Type])
573 tidyOpenTypes env tys = mapAccumL tidyOpenType env tys
576 -- | Calls 'tidyType' on a top-level type (i.e. with an empty tidying environment)
577 tidyTopType :: Type -> Type
578 tidyTopType ty = tidyType emptyTidyEnv ty
581 tidySkolemTyVar :: TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
582 -- Tidy the type inside a GenSkol, preparatory to printing it
583 tidySkolemTyVar env tv
584 = ASSERT( isTcTyVar tv && (isSkolemTyVar tv || isSigTyVar tv ) )
585 (env1, mkTcTyVar (tyVarName tv) (tyVarKind tv) info1)
587 (env1, info1) = case tcTyVarDetails tv of
588 SkolemTv info -> (env1, SkolemTv info')
590 (env1, info') = tidy_skol_info env info
593 tidy_skol_info env (GenSkol ty) = (env1, GenSkol ty1)
595 (env1, ty1) = tidyOpenType env ty
596 tidy_skol_info env info = (env, info)
599 tidyKind :: TidyEnv -> Kind -> (TidyEnv, Kind)
600 tidyKind env k = tidyOpenType env k
604 %************************************************************************
608 %************************************************************************
611 isImmutableTyVar :: TyVar -> Bool
614 | isTcTyVar tv = isSkolemTyVar tv
617 isTyConableTyVar, isSkolemTyVar, isOverlappableTyVar,
618 isMetaTyVar :: TcTyVar -> Bool
621 -- True of a meta-type variable that can be filled in
622 -- with a type constructor application; in particular,
624 = ASSERT( isTcTyVar tv)
625 case tcTyVarDetails tv of
626 MetaTv (SigTv _) _ -> False
630 = ASSERT2( isTcTyVar tv, ppr tv )
631 case tcTyVarDetails tv of
636 -- isOverlappableTyVar has a unique purpose.
637 -- See Note [Binding when looking up instances] in InstEnv.
638 isOverlappableTyVar tv
639 = ASSERT( isTcTyVar tv )
640 case tcTyVarDetails tv of
641 SkolemTv (PatSkol {}) -> True
642 SkolemTv (InstSkol {}) -> True
646 = ASSERT2( isTcTyVar tv, ppr tv )
647 case tcTyVarDetails tv of
651 isMetaTyVarTy :: TcType -> Bool
652 isMetaTyVarTy (TyVarTy tv) = isMetaTyVar tv
653 isMetaTyVarTy _ = False
655 isSigTyVar :: Var -> Bool
657 = ASSERT( isTcTyVar tv )
658 case tcTyVarDetails tv of
659 MetaTv (SigTv _) _ -> True
662 metaTvRef :: TyVar -> IORef MetaDetails
664 = ASSERT2( isTcTyVar tv, ppr tv )
665 case tcTyVarDetails tv of
667 _ -> pprPanic "metaTvRef" (ppr tv)
669 isFlexi, isIndirect :: MetaDetails -> Bool
673 isIndirect (Indirect _) = True
676 isRuntimeUnkSkol :: TyVar -> Bool
677 -- Called only in TcErrors; see Note [Runtime skolems] there
678 isRuntimeUnkSkol x | isTcTyVar x
679 , SkolemTv RuntimeUnkSkol <- tcTyVarDetails x
683 isUnkSkol :: TyVar -> Bool
684 isUnkSkol x | isTcTyVar x
685 , SkolemTv UnkSkol <- tcTyVarDetails x = True
690 %************************************************************************
692 \subsection{Tau, sigma and rho}
694 %************************************************************************
697 mkSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
698 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
700 mkPhiTy :: [PredType] -> Type -> Type
701 mkPhiTy theta ty = foldr (\p r -> mkFunTy (mkPredTy p) r) ty theta
704 @isTauTy@ tests for nested for-alls. It should not be called on a boxy type.
707 isTauTy :: Type -> Bool
708 isTauTy ty | Just ty' <- tcView ty = isTauTy ty'
709 isTauTy (TyVarTy _) = True
710 isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
711 isTauTy (AppTy a b) = isTauTy a && isTauTy b
712 isTauTy (FunTy a b) = isTauTy a && isTauTy b
713 isTauTy (PredTy _) = True -- Don't look through source types
717 isTauTyCon :: TyCon -> Bool
718 -- Returns False for type synonyms whose expansion is a polytype
720 | isClosedSynTyCon tc = isTauTy (snd (synTyConDefn tc))
724 isRigidTy :: TcType -> Bool
725 -- A type is rigid if it has no meta type variables in it
726 isRigidTy ty = all isImmutableTyVar (varSetElems (tcTyVarsOfType ty))
728 isRefineableTy :: TcType -> (Bool,Bool)
729 -- A type should have type refinements applied to it if it has
730 -- free type variables, and they are all rigid
731 isRefineableTy ty = (null tc_tvs, all isImmutableTyVar tc_tvs)
733 tc_tvs = varSetElems (tcTyVarsOfType ty)
735 isRefineablePred :: TcPredType -> Bool
736 isRefineablePred pred = not (null tc_tvs) && all isImmutableTyVar tc_tvs
738 tc_tvs = varSetElems (tcTyVarsOfPred pred)
741 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
742 -- construct a dictionary function name
743 getDFunTyKey ty | Just ty' <- tcView ty = getDFunTyKey ty'
744 getDFunTyKey (TyVarTy tv) = getOccName tv
745 getDFunTyKey (TyConApp tc _) = getOccName tc
746 getDFunTyKey (AppTy fun _) = getDFunTyKey fun
747 getDFunTyKey (FunTy _ _) = getOccName funTyCon
748 getDFunTyKey (ForAllTy _ t) = getDFunTyKey t
749 getDFunTyKey ty = pprPanic "getDFunTyKey" (pprType ty)
750 -- PredTy shouldn't happen
754 %************************************************************************
756 \subsection{Expanding and splitting}
758 %************************************************************************
760 These tcSplit functions are like their non-Tc analogues, but
761 a) they do not look through newtypes
762 b) they do not look through PredTys
764 However, they are non-monadic and do not follow through mutable type
765 variables. It's up to you to make sure this doesn't matter.
768 tcSplitForAllTys :: Type -> ([TyVar], Type)
769 tcSplitForAllTys ty = split ty ty []
771 split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
772 split _ (ForAllTy tv ty) tvs
773 | not (isCoVar tv) = split ty ty (tv:tvs)
774 split orig_ty _ tvs = (reverse tvs, orig_ty)
776 tcIsForAllTy :: Type -> Bool
777 tcIsForAllTy ty | Just ty' <- tcView ty = tcIsForAllTy ty'
778 tcIsForAllTy (ForAllTy tv _) = not (isCoVar tv)
779 tcIsForAllTy _ = False
781 tcSplitPredFunTy_maybe :: Type -> Maybe (PredType, Type)
782 -- Split off the first predicate argument from a type
783 tcSplitPredFunTy_maybe ty | Just ty' <- tcView ty = tcSplitPredFunTy_maybe ty'
784 tcSplitPredFunTy_maybe (ForAllTy tv ty)
785 | isCoVar tv = Just (coVarPred tv, ty)
786 tcSplitPredFunTy_maybe (FunTy arg res)
787 | Just p <- tcSplitPredTy_maybe arg = Just (p, res)
788 tcSplitPredFunTy_maybe _
791 tcSplitPhiTy :: Type -> (ThetaType, Type)
796 = case tcSplitPredFunTy_maybe ty of
797 Just (pred, ty) -> split ty (pred:ts)
798 Nothing -> (reverse ts, ty)
800 tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
801 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
802 (tvs, rho) -> case tcSplitPhiTy rho of
803 (theta, tau) -> (tvs, theta, tau)
805 -----------------------
806 tcDeepSplitSigmaTy_maybe
807 :: TcSigmaType -> Maybe ([TcType], [TyVar], ThetaType, TcSigmaType)
808 -- Looks for a *non-trivial* quantified type, under zero or more function arrows
809 -- By "non-trivial" we mean either tyvars or constraints are non-empty
811 tcDeepSplitSigmaTy_maybe ty
812 | Just (arg_ty, res_ty) <- tcSplitFunTy_maybe ty
813 , Just (arg_tys, tvs, theta, rho) <- tcDeepSplitSigmaTy_maybe res_ty
814 = Just (arg_ty:arg_tys, tvs, theta, rho)
816 | (tvs, theta, rho) <- tcSplitSigmaTy ty
817 , not (null tvs && null theta)
818 = Just ([], tvs, theta, rho)
820 | otherwise = Nothing
822 -----------------------
823 tcTyConAppTyCon :: Type -> TyCon
824 tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of
826 Nothing -> pprPanic "tcTyConAppTyCon" (pprType ty)
828 tcTyConAppArgs :: Type -> [Type]
829 tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
830 Just (_, args) -> args
831 Nothing -> pprPanic "tcTyConAppArgs" (pprType ty)
833 tcSplitTyConApp :: Type -> (TyCon, [Type])
834 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
836 Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
838 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
839 tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
840 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
841 tcSplitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
842 -- Newtypes are opaque, so they may be split
843 -- However, predicates are not treated
844 -- as tycon applications by the type checker
845 tcSplitTyConApp_maybe _ = Nothing
847 -----------------------
848 tcSplitFunTys :: Type -> ([Type], Type)
849 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
851 Just (arg,res) -> (arg:args, res')
853 (args,res') = tcSplitFunTys res
855 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
856 tcSplitFunTy_maybe ty | Just ty' <- tcView ty = tcSplitFunTy_maybe ty'
857 tcSplitFunTy_maybe (FunTy arg res) | not (isPredTy arg) = Just (arg, res)
858 tcSplitFunTy_maybe _ = Nothing
859 -- Note the (not (isPredTy arg)) guard
860 -- Consider (?x::Int) => Bool
861 -- We don't want to treat this as a function type!
862 -- A concrete example is test tc230:
863 -- f :: () -> (?p :: ()) => () -> ()
869 -> Arity -- N: Number of desired args
870 -> ([TcSigmaType], -- Arg types (N or fewer)
871 TcSigmaType) -- The rest of the type
873 tcSplitFunTysN ty n_args
876 | Just (arg,res) <- tcSplitFunTy_maybe ty
877 = case tcSplitFunTysN res (n_args - 1) of
878 (args, res) -> (arg:args, res)
882 tcSplitFunTy :: Type -> (Type, Type)
883 tcSplitFunTy ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
885 tcFunArgTy :: Type -> Type
886 tcFunArgTy ty = fst (tcSplitFunTy ty)
888 tcFunResultTy :: Type -> Type
889 tcFunResultTy ty = snd (tcSplitFunTy ty)
891 -----------------------
892 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
893 tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty'
894 tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty
896 tcSplitAppTy :: Type -> (Type, Type)
897 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
899 Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
901 tcSplitAppTys :: Type -> (Type, [Type])
905 go ty args = case tcSplitAppTy_maybe ty of
906 Just (ty', arg) -> go ty' (arg:args)
909 -----------------------
910 tcGetTyVar_maybe :: Type -> Maybe TyVar
911 tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty'
912 tcGetTyVar_maybe (TyVarTy tv) = Just tv
913 tcGetTyVar_maybe _ = Nothing
915 tcGetTyVar :: String -> Type -> TyVar
916 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
918 tcIsTyVarTy :: Type -> Bool
919 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
921 -----------------------
922 tcSplitDFunTy :: Type -> ([TyVar], Int, Class, [Type])
923 -- Split the type of a dictionary function
924 -- We don't use tcSplitSigmaTy, because a DFun may (with NDP)
925 -- have non-Pred arguments, such as
926 -- df :: forall m. (forall b. Eq b => Eq (m b)) -> C m
928 = case tcSplitForAllTys ty of { (tvs, rho) ->
929 case split_dfun_args 0 rho of { (n_theta, tau) ->
930 case tcSplitDFunHead tau of { (clas, tys) ->
931 (tvs, n_theta, clas, tys) }}}
933 -- Count the context of the dfun. This can be a mix of
934 -- coercion and class constraints; or (in the general NDP case)
935 -- some other function argument
936 split_dfun_args n ty | Just ty' <- tcView ty = split_dfun_args n ty'
937 split_dfun_args n (ForAllTy tv ty) = ASSERT( isCoVar tv ) split_dfun_args (n+1) ty
938 split_dfun_args n (FunTy _ ty) = split_dfun_args (n+1) ty
939 split_dfun_args n ty = (n, ty)
941 tcSplitDFunHead :: Type -> (Class, [Type])
943 = case tcSplitPredTy_maybe tau of
944 Just (ClassP clas tys) -> (clas, tys)
945 _ -> pprPanic "tcSplitDFunHead" (ppr tau)
947 tcInstHeadTyNotSynonym :: Type -> Bool
948 -- Used in Haskell-98 mode, for the argument types of an instance head
949 -- These must not be type synonyms, but everywhere else type synonyms
950 -- are transparent, so we need a special function here
951 tcInstHeadTyNotSynonym ty
953 TyConApp tc _ -> not (isSynTyCon tc)
956 tcInstHeadTyAppAllTyVars :: Type -> Bool
957 -- Used in Haskell-98 mode, for the argument types of an instance head
958 -- These must be a constructor applied to type variable arguments
959 tcInstHeadTyAppAllTyVars ty
960 | Just ty' <- tcView ty -- Look through synonyms
961 = tcInstHeadTyAppAllTyVars ty'
964 TyConApp _ tys -> ok tys
965 FunTy arg res -> ok [arg, res]
968 -- Check that all the types are type variables,
969 -- and that each is distinct
970 ok tys = equalLength tvs tys && hasNoDups tvs
972 tvs = mapCatMaybes get_tv tys
974 get_tv (TyVarTy tv) = Just tv -- through synonyms
980 %************************************************************************
982 \subsection{Predicate types}
984 %************************************************************************
987 evVarPred :: EvVar -> PredType
989 = case tcSplitPredTy_maybe (varType var) of
991 Nothing -> pprPanic "evVarPred" (ppr var <+> ppr (varType var))
993 tcSplitPredTy_maybe :: Type -> Maybe PredType
994 -- Returns Just for predicates only
995 tcSplitPredTy_maybe ty | Just ty' <- tcView ty = tcSplitPredTy_maybe ty'
996 tcSplitPredTy_maybe (PredTy p) = Just p
997 tcSplitPredTy_maybe _ = Nothing
999 predTyUnique :: PredType -> Unique
1000 predTyUnique (IParam n _) = getUnique (ipNameName n)
1001 predTyUnique (ClassP clas _) = getUnique clas
1002 predTyUnique (EqPred a b) = pprPanic "predTyUnique" (ppr (EqPred a b))
1006 --------------------- Dictionary types ---------------------------------
1009 mkClassPred :: Class -> [Type] -> PredType
1010 mkClassPred clas tys = ClassP clas tys
1012 isClassPred :: PredType -> Bool
1013 isClassPred (ClassP _ _) = True
1014 isClassPred _ = False
1016 isTyVarClassPred :: PredType -> Bool
1017 isTyVarClassPred (ClassP _ tys) = all tcIsTyVarTy tys
1018 isTyVarClassPred _ = False
1020 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
1021 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
1022 getClassPredTys_maybe _ = Nothing
1024 getClassPredTys :: PredType -> (Class, [Type])
1025 getClassPredTys (ClassP clas tys) = (clas, tys)
1026 getClassPredTys _ = panic "getClassPredTys"
1028 mkDictTy :: Class -> [Type] -> Type
1029 mkDictTy clas tys = mkPredTy (ClassP clas tys)
1031 isDictLikeTy :: Type -> Bool
1032 -- Note [Dictionary-like types]
1033 isDictLikeTy ty | Just ty' <- tcView ty = isDictTy ty'
1034 isDictLikeTy (PredTy p) = isClassPred p
1035 isDictLikeTy (TyConApp tc tys)
1036 | isTupleTyCon tc = all isDictLikeTy tys
1037 isDictLikeTy _ = False
1040 Note [Dictionary-like types]
1041 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1042 Being "dictionary-like" means either a dictionary type or a tuple thereof.
1043 In GHC 6.10 we build implication constraints which construct such tuples,
1044 and if we land up with a binding
1045 t :: (C [a], Eq [a])
1047 then we want to treat t as cheap under "-fdicts-cheap" for example.
1048 (Implication constraints are normally inlined, but sadly not if the
1049 occurrence is itself inside an INLINE function! Until we revise the
1050 handling of implication constraints, that is.) This turned out to
1051 be important in getting good arities in DPH code. Example:
1054 class D a where { foo :: a -> a }
1055 instance C a => D (Maybe a) where { foo x = x }
1057 bar :: (C a, C b) => a -> b -> (Maybe a, Maybe b)
1059 bar x y = (foo (Just x), foo (Just y))
1061 Then 'bar' should jolly well have arity 4 (two dicts, two args), but
1062 we ended up with something like
1063 bar = __inline_me__ (\d1,d2. let t :: (D (Maybe a), D (Maybe b)) = ...
1066 This is all a bit ad-hoc; eg it relies on knowing that implication
1067 constraints build tuples.
1069 --------------------- Implicit parameters ---------------------------------
1072 mkIPPred :: IPName Name -> Type -> PredType
1073 mkIPPred ip ty = IParam ip ty
1075 isIPPred :: PredType -> Bool
1076 isIPPred (IParam _ _) = True
1080 --------------------- Equality predicates ---------------------------------
1082 substEqSpec :: TvSubst -> [(TyVar,Type)] -> [(TcType,TcType)]
1083 substEqSpec subst eq_spec = [ (substTyVar subst tv, substTy subst ty)
1084 | (tv,ty) <- eq_spec]
1088 %************************************************************************
1090 \subsection{Predicates}
1092 %************************************************************************
1094 isSigmaTy returns true of any qualified type. It doesn't *necessarily* have
1096 f :: (?x::Int) => Int -> Int
1099 isSigmaTy :: Type -> Bool
1100 isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty'
1101 isSigmaTy (ForAllTy _ _) = True
1102 isSigmaTy (FunTy a _) = isPredTy a
1105 isOverloadedTy :: Type -> Bool
1106 -- Yes for a type of a function that might require evidence-passing
1107 -- Used only by bindLocalMethods
1108 -- NB: be sure to check for type with an equality predicate; hence isCoVar
1109 isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty'
1110 isOverloadedTy (ForAllTy tv ty) = isCoVar tv || isOverloadedTy ty
1111 isOverloadedTy (FunTy a _) = isPredTy a
1112 isOverloadedTy _ = False
1114 isPredTy :: Type -> Bool -- Belongs in TcType because it does
1115 -- not look through newtypes, or predtypes (of course)
1116 isPredTy ty | Just ty' <- tcView ty = isPredTy ty'
1117 isPredTy (PredTy _) = True
1122 isFloatTy, isDoubleTy, isIntegerTy, isIntTy, isWordTy, isBoolTy,
1123 isUnitTy, isCharTy :: Type -> Bool
1124 isFloatTy = is_tc floatTyConKey
1125 isDoubleTy = is_tc doubleTyConKey
1126 isIntegerTy = is_tc integerTyConKey
1127 isIntTy = is_tc intTyConKey
1128 isWordTy = is_tc wordTyConKey
1129 isBoolTy = is_tc boolTyConKey
1130 isUnitTy = is_tc unitTyConKey
1131 isCharTy = is_tc charTyConKey
1133 isStringTy :: Type -> Bool
1135 = case tcSplitTyConApp_maybe ty of
1136 Just (tc, [arg_ty]) -> tc == listTyCon && isCharTy arg_ty
1139 is_tc :: Unique -> Type -> Bool
1140 -- Newtypes are opaque to this
1141 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
1142 Just (tc, _) -> uniq == getUnique tc
1147 -- NB: Currently used in places where we have already expanded type synonyms;
1148 -- hence no 'coreView'. This could, however, be changed without breaking
1150 isSynFamilyTyConApp :: TcTauType -> Bool
1151 isSynFamilyTyConApp (TyConApp tc tys) = isSynFamilyTyCon tc &&
1152 length tys == tyConArity tc
1153 isSynFamilyTyConApp _other = False
1157 %************************************************************************
1161 %************************************************************************
1164 deNoteType :: Type -> Type
1165 -- Remove all *outermost* type synonyms and other notes
1166 deNoteType ty | Just ty' <- tcView ty = deNoteType ty'
1171 tcTyVarsOfType :: Type -> TcTyVarSet
1172 -- Just the *TcTyVars* free in the type
1173 -- (Types.tyVarsOfTypes finds all free TyVars)
1174 tcTyVarsOfType (TyVarTy tv) = if isTcTyVar tv then unitVarSet tv
1176 tcTyVarsOfType (TyConApp _ tys) = tcTyVarsOfTypes tys
1177 tcTyVarsOfType (PredTy sty) = tcTyVarsOfPred sty
1178 tcTyVarsOfType (FunTy arg res) = tcTyVarsOfType arg `unionVarSet` tcTyVarsOfType res
1179 tcTyVarsOfType (AppTy fun arg) = tcTyVarsOfType fun `unionVarSet` tcTyVarsOfType arg
1180 tcTyVarsOfType (ForAllTy tyvar ty) = (tcTyVarsOfType ty `delVarSet` tyvar)
1181 `unionVarSet` tcTyVarsOfTyVar tyvar
1182 -- We do sometimes quantify over skolem TcTyVars
1184 tcTyVarsOfTyVar :: TcTyVar -> TyVarSet
1185 tcTyVarsOfTyVar tv | isCoVar tv = tcTyVarsOfType (tyVarKind tv)
1186 | otherwise = emptyVarSet
1188 tcTyVarsOfTypes :: [Type] -> TyVarSet
1189 tcTyVarsOfTypes tys = foldr (unionVarSet.tcTyVarsOfType) emptyVarSet tys
1191 tcTyVarsOfPred :: PredType -> TyVarSet
1192 tcTyVarsOfPred (IParam _ ty) = tcTyVarsOfType ty
1193 tcTyVarsOfPred (ClassP _ tys) = tcTyVarsOfTypes tys
1194 tcTyVarsOfPred (EqPred ty1 ty2) = tcTyVarsOfType ty1 `unionVarSet` tcTyVarsOfType ty2
1197 Note [Silly type synonym]
1198 ~~~~~~~~~~~~~~~~~~~~~~~~~
1201 What are the free tyvars of (T x)? Empty, of course!
1202 Here's the example that Ralf Laemmel showed me:
1203 foo :: (forall a. C u a -> C u a) -> u
1204 mappend :: Monoid u => u -> u -> u
1206 bar :: Monoid u => u
1207 bar = foo (\t -> t `mappend` t)
1208 We have to generalise at the arg to f, and we don't
1209 want to capture the constraint (Monad (C u a)) because
1210 it appears to mention a. Pretty silly, but it was useful to him.
1212 exactTyVarsOfType is used by the type checker to figure out exactly
1213 which type variables are mentioned in a type. It's also used in the
1214 smart-app checking code --- see TcExpr.tcIdApp
1216 On the other hand, consider a *top-level* definition
1217 f = (\x -> x) :: T a -> T a
1218 If we don't abstract over 'a' it'll get fixed to GHC.Prim.Any, and then
1219 if we have an application like (f "x") we get a confusing error message
1220 involving Any. So the conclusion is this: when generalising
1221 - at top level use tyVarsOfType
1222 - in nested bindings use exactTyVarsOfType
1223 See Trac #1813 for example.
1226 exactTyVarsOfType :: TcType -> TyVarSet
1227 -- Find the free type variables (of any kind)
1228 -- but *expand* type synonyms. See Note [Silly type synonym] above.
1229 exactTyVarsOfType ty
1232 go ty | Just ty' <- tcView ty = go ty' -- This is the key line
1233 go (TyVarTy tv) = unitVarSet tv
1234 go (TyConApp _ tys) = exactTyVarsOfTypes tys
1235 go (PredTy ty) = go_pred ty
1236 go (FunTy arg res) = go arg `unionVarSet` go res
1237 go (AppTy fun arg) = go fun `unionVarSet` go arg
1238 go (ForAllTy tyvar ty) = delVarSet (go ty) tyvar
1239 `unionVarSet` go_tv tyvar
1241 go_pred (IParam _ ty) = go ty
1242 go_pred (ClassP _ tys) = exactTyVarsOfTypes tys
1243 go_pred (EqPred ty1 ty2) = go ty1 `unionVarSet` go ty2
1245 go_tv tyvar | isCoVar tyvar = go (tyVarKind tyvar)
1246 | otherwise = emptyVarSet
1248 exactTyVarsOfTypes :: [TcType] -> TyVarSet
1249 exactTyVarsOfTypes tys = foldr (unionVarSet . exactTyVarsOfType) emptyVarSet tys
1252 Find the free tycons and classes of a type. This is used in the front
1253 end of the compiler.
1256 tyClsNamesOfType :: Type -> NameSet
1257 tyClsNamesOfType (TyVarTy _) = emptyNameSet
1258 tyClsNamesOfType (TyConApp tycon tys) = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
1259 tyClsNamesOfType (PredTy (IParam _ ty)) = tyClsNamesOfType ty
1260 tyClsNamesOfType (PredTy (ClassP cl tys)) = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
1261 tyClsNamesOfType (PredTy (EqPred ty1 ty2)) = tyClsNamesOfType ty1 `unionNameSets` tyClsNamesOfType ty2
1262 tyClsNamesOfType (FunTy arg res) = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
1263 tyClsNamesOfType (AppTy fun arg) = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
1264 tyClsNamesOfType (ForAllTy _ ty) = tyClsNamesOfType ty
1266 tyClsNamesOfTypes :: [Type] -> NameSet
1267 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
1269 tyClsNamesOfDFunHead :: Type -> NameSet
1270 -- Find the free type constructors and classes
1271 -- of the head of the dfun instance type
1272 -- The 'dfun_head_type' is because of
1273 -- instance Foo a => Baz T where ...
1274 -- The decl is an orphan if Baz and T are both not locally defined,
1275 -- even if Foo *is* locally defined
1276 tyClsNamesOfDFunHead dfun_ty
1277 = case tcSplitSigmaTy dfun_ty of
1278 (_, _, head_ty) -> tyClsNamesOfType head_ty
1282 %************************************************************************
1284 \subsection[TysWiredIn-ext-type]{External types}
1286 %************************************************************************
1288 The compiler's foreign function interface supports the passing of a
1289 restricted set of types as arguments and results (the restricting factor
1293 tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type, CoercionI)
1294 -- (isIOType t) returns Just (IO,t',co)
1295 -- if co : t ~ IO t'
1296 -- returns Nothing otherwise
1297 tcSplitIOType_maybe ty
1298 = case tcSplitTyConApp_maybe ty of
1299 -- This split absolutely has to be a tcSplit, because we must
1300 -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
1302 Just (io_tycon, [io_res_ty])
1303 | io_tycon `hasKey` ioTyConKey
1304 -> Just (io_tycon, io_res_ty, IdCo ty)
1307 | not (isRecursiveTyCon tc)
1308 , Just (ty, co1) <- instNewTyCon_maybe tc tys
1309 -- Newtypes that require a coercion are ok
1310 -> case tcSplitIOType_maybe ty of
1312 Just (tc, ty', co2) -> Just (tc, ty', co1 `mkTransCoI` co2)
1316 isFFITy :: Type -> Bool
1317 -- True for any TyCon that can possibly be an arg or result of an FFI call
1318 isFFITy ty = checkRepTyCon legalFFITyCon ty
1320 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
1321 -- Checks for valid argument type for a 'foreign import'
1322 isFFIArgumentTy dflags safety ty
1323 = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
1325 isFFIExternalTy :: Type -> Bool
1326 -- Types that are allowed as arguments of a 'foreign export'
1327 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
1329 isFFIImportResultTy :: DynFlags -> Type -> Bool
1330 isFFIImportResultTy dflags ty
1331 = checkRepTyCon (legalFIResultTyCon dflags) ty
1333 isFFIExportResultTy :: Type -> Bool
1334 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
1336 isFFIDynArgumentTy :: Type -> Bool
1337 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
1338 -- or a newtype of either.
1339 isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1341 isFFIDynResultTy :: Type -> Bool
1342 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
1343 -- or a newtype of either.
1344 isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1346 isFFILabelTy :: Type -> Bool
1347 -- The type of a foreign label must be Ptr, FunPtr, Addr,
1348 -- or a newtype of either.
1349 isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1351 isFFIPrimArgumentTy :: DynFlags -> Type -> Bool
1352 -- Checks for valid argument type for a 'foreign import prim'
1353 -- Currently they must all be simple unlifted types.
1354 isFFIPrimArgumentTy dflags ty
1355 = checkRepTyCon (legalFIPrimArgTyCon dflags) ty
1357 isFFIPrimResultTy :: DynFlags -> Type -> Bool
1358 -- Checks for valid result type for a 'foreign import prim'
1359 -- Currently it must be an unlifted type, including unboxed tuples.
1360 isFFIPrimResultTy dflags ty
1361 = checkRepTyCon (legalFIPrimResultTyCon dflags) ty
1363 isFFIDotnetTy :: DynFlags -> Type -> Bool
1364 isFFIDotnetTy dflags ty
1365 = checkRepTyCon (\ tc -> (legalFIResultTyCon dflags tc ||
1366 isFFIDotnetObjTy ty || isStringTy ty)) ty
1367 -- NB: isStringTy used to look through newtypes, but
1368 -- it no longer does so. May need to adjust isFFIDotNetTy
1369 -- if we do want to look through newtypes.
1371 isFFIDotnetObjTy :: Type -> Bool
1373 = checkRepTyCon check_tc t_ty
1375 (_, t_ty) = tcSplitForAllTys ty
1376 check_tc tc = getName tc == objectTyConName
1378 isFunPtrTy :: Type -> Bool
1379 isFunPtrTy = checkRepTyConKey [funPtrTyConKey]
1381 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
1382 -- Look through newtypes, but *not* foralls
1383 -- Should work even for recursive newtypes
1384 -- eg Manuel had: newtype T = MkT (Ptr T)
1385 checkRepTyCon check_tc ty
1389 | Just (tc,tys) <- splitTyConApp_maybe ty
1390 = case carefullySplitNewType_maybe rec_nts tc tys of
1391 Just (rec_nts', ty') -> go rec_nts' ty'
1392 Nothing -> check_tc tc
1396 checkRepTyConKey :: [Unique] -> Type -> Bool
1397 -- Like checkRepTyCon, but just looks at the TyCon key
1398 checkRepTyConKey keys
1399 = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
1402 ----------------------------------------------
1403 These chaps do the work; they are not exported
1404 ----------------------------------------------
1407 legalFEArgTyCon :: TyCon -> Bool
1409 -- It's illegal to make foreign exports that take unboxed
1410 -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
1411 = boxedMarshalableTyCon tc
1413 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
1414 legalFIResultTyCon dflags tc
1415 | tc == unitTyCon = True
1416 | otherwise = marshalableTyCon dflags tc
1418 legalFEResultTyCon :: TyCon -> Bool
1419 legalFEResultTyCon tc
1420 | tc == unitTyCon = True
1421 | otherwise = boxedMarshalableTyCon tc
1423 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
1424 -- Checks validity of types going from Haskell -> external world
1425 legalOutgoingTyCon dflags _ tc
1426 = marshalableTyCon dflags tc
1428 legalFFITyCon :: TyCon -> Bool
1429 -- True for any TyCon that can possibly be an arg or result of an FFI call
1431 = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon
1433 marshalableTyCon :: DynFlags -> TyCon -> Bool
1434 marshalableTyCon dflags tc
1435 = (xopt Opt_UnliftedFFITypes dflags
1436 && isUnLiftedTyCon tc
1437 && not (isUnboxedTupleTyCon tc)
1438 && case tyConPrimRep tc of -- Note [Marshalling VoidRep]
1441 || boxedMarshalableTyCon tc
1443 boxedMarshalableTyCon :: TyCon -> Bool
1444 boxedMarshalableTyCon tc
1445 = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
1446 , int32TyConKey, int64TyConKey
1447 , wordTyConKey, word8TyConKey, word16TyConKey
1448 , word32TyConKey, word64TyConKey
1449 , floatTyConKey, doubleTyConKey
1450 , ptrTyConKey, funPtrTyConKey
1456 legalFIPrimArgTyCon :: DynFlags -> TyCon -> Bool
1457 -- Check args of 'foreign import prim', only allow simple unlifted types.
1458 -- Strictly speaking it is unnecessary to ban unboxed tuples here since
1459 -- currently they're of the wrong kind to use in function args anyway.
1460 legalFIPrimArgTyCon dflags tc
1461 = xopt Opt_UnliftedFFITypes dflags
1462 && isUnLiftedTyCon tc
1463 && not (isUnboxedTupleTyCon tc)
1465 legalFIPrimResultTyCon :: DynFlags -> TyCon -> Bool
1466 -- Check result type of 'foreign import prim'. Allow simple unlifted
1467 -- types and also unboxed tuple result types '... -> (# , , #)'
1468 legalFIPrimResultTyCon dflags tc
1469 = xopt Opt_UnliftedFFITypes dflags
1470 && isUnLiftedTyCon tc
1471 && (isUnboxedTupleTyCon tc
1472 || case tyConPrimRep tc of -- Note [Marshalling VoidRep]
1477 Note [Marshalling VoidRep]
1478 ~~~~~~~~~~~~~~~~~~~~~~~~~~
1479 We don't treat State# (whose PrimRep is VoidRep) as marshalable.
1480 In turn that means you can't write
1481 foreign import foo :: Int -> State# RealWorld
1483 Reason: the back end falls over with panic "primRepHint:VoidRep";
1484 and there is no compelling reason to permit it