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,
24 BoxyTyVar, BoxySigmaType, BoxyRhoType, BoxyThetaType, BoxyType,
26 --------------------------------
28 UserTypeCtxt(..), pprUserTypeCtxt,
29 TcTyVarDetails(..), BoxInfo(..), pprTcTyVarDetails,
30 MetaDetails(Flexi, Indirect), SkolemInfo(..), pprSkolTvBinding, pprSkolInfo,
31 isImmutableTyVar, isSkolemTyVar, isMetaTyVar, isBoxyTyVar, isSigTyVar, isExistentialTyVar,
35 --------------------------------
39 --------------------------------
41 -- These are important because they do not look through newtypes
43 tcSplitForAllTys, tcSplitPhiTy,
44 tcSplitFunTy_maybe, tcSplitFunTys, tcFunArgTy, tcFunResultTy, tcSplitFunTysN,
45 tcSplitTyConApp, tcSplitTyConApp_maybe, tcTyConAppTyCon, tcTyConAppArgs,
46 tcSplitAppTy_maybe, tcSplitAppTy, tcSplitAppTys, repSplitAppTy_maybe,
47 tcValidInstHeadTy, tcGetTyVar_maybe, tcGetTyVar,
48 tcSplitSigmaTy, tcMultiSplitSigmaTy,
50 ---------------------------------
52 -- Again, newtypes are opaque
53 tcEqType, tcEqTypes, tcEqPred, tcCmpType, tcCmpTypes, tcCmpPred, tcEqTypeX,
55 isSigmaTy, isOverloadedTy, isRigidTy, isBoxyTy,
56 isDoubleTy, isFloatTy, isIntTy, isStringTy,
57 isIntegerTy, isBoolTy, isUnitTy,
58 isTauTy, isTauTyCon, tcIsTyVarTy, tcIsForAllTy,
60 ---------------------------------
61 -- Misc type manipulators
62 deNoteType, classesOfTheta,
63 tyClsNamesOfType, tyClsNamesOfDFunHead,
66 ---------------------------------
68 getClassPredTys_maybe, getClassPredTys,
69 isClassPred, isTyVarClassPred, isEqPred,
70 mkDictTy, tcSplitPredTy_maybe,
71 isPredTy, isDictTy, tcSplitDFunTy, tcSplitDFunHead, predTyUnique,
72 mkClassPred, isInheritablePred, isIPPred,
73 dataConsStupidTheta, isRefineableTy,
75 ---------------------------------
76 -- Foreign import and export
77 isFFIArgumentTy, -- :: DynFlags -> Safety -> Type -> Bool
78 isFFIImportResultTy, -- :: DynFlags -> Type -> Bool
79 isFFIExportResultTy, -- :: Type -> Bool
80 isFFIExternalTy, -- :: Type -> Bool
81 isFFIDynArgumentTy, -- :: Type -> Bool
82 isFFIDynResultTy, -- :: Type -> Bool
83 isFFILabelTy, -- :: Type -> Bool
84 isFFIDotnetTy, -- :: DynFlags -> Type -> Bool
85 isFFIDotnetObjTy, -- :: Type -> Bool
86 isFFITy, -- :: Type -> Bool
87 tcSplitIOType_maybe, -- :: Type -> Maybe Type
88 toDNType, -- :: Type -> DNType
90 --------------------------------
91 -- Rexported from Type
92 Kind, -- Stuff to do with kinds is insensitive to pre/post Tc
93 unliftedTypeKind, liftedTypeKind, argTypeKind,
94 openTypeKind, mkArrowKind, mkArrowKinds,
95 isLiftedTypeKind, isUnliftedTypeKind, isSubOpenTypeKind,
96 isSubArgTypeKind, isSubKind, defaultKind,
97 kindVarRef, mkKindVar,
99 Type, PredType(..), ThetaType,
100 mkForAllTy, mkForAllTys,
101 mkFunTy, mkFunTys, zipFunTys,
102 mkTyConApp, mkAppTy, mkAppTys, applyTy, applyTys,
103 mkTyVarTy, mkTyVarTys, mkTyConTy, mkPredTy, mkPredTys,
105 -- Type substitutions
106 TvSubst(..), -- Representation visible to a few friends
107 TvSubstEnv, emptyTvSubst, substEqSpec,
108 mkOpenTvSubst, zipOpenTvSubst, zipTopTvSubst, mkTopTvSubst, notElemTvSubst,
109 getTvSubstEnv, setTvSubstEnv, getTvInScope, extendTvInScope, lookupTyVar,
110 extendTvSubst, extendTvSubstList, isInScope, mkTvSubst, zipTyEnv,
111 substTy, substTys, substTyWith, substTheta, substTyVar, substTyVarBndr,
113 isUnLiftedType, -- Source types are always lifted
114 isUnboxedTupleType, -- Ditto
117 tidyTopType, tidyType, tidyPred, tidyTypes, tidyFreeTyVars, tidyOpenType, tidyOpenTypes,
118 tidyTyVarBndr, tidyOpenTyVar, tidyOpenTyVars, tidySkolemTyVar,
121 tyVarsOfType, tyVarsOfTypes, tyVarsOfPred, tyVarsOfTheta,
122 tcTyVarsOfType, tcTyVarsOfTypes, exactTyVarsOfType, exactTyVarsOfTypes,
124 pprKind, pprParendKind,
125 pprType, pprParendType, pprTyThingCategory,
126 pprPred, pprTheta, pprThetaArrow, pprClassPred
130 #include "HsVersions.h"
163 %************************************************************************
167 %************************************************************************
169 The type checker divides the generic Type world into the
170 following more structured beasts:
172 sigma ::= forall tyvars. phi
173 -- A sigma type is a qualified type
175 -- Note that even if 'tyvars' is empty, theta
176 -- may not be: e.g. (?x::Int) => Int
178 -- Note that 'sigma' is in prenex form:
179 -- all the foralls are at the front.
180 -- A 'phi' type has no foralls to the right of
188 -- A 'tau' type has no quantification anywhere
189 -- Note that the args of a type constructor must be taus
191 | tycon tau_1 .. tau_n
195 -- In all cases, a (saturated) type synonym application is legal,
196 -- provided it expands to the required form.
199 type TcTyVar = TyVar -- Used only during type inference
200 type TcType = Type -- A TcType can have mutable type variables
201 -- Invariant on ForAllTy in TcTypes:
203 -- a cannot occur inside a MutTyVar in T; that is,
204 -- T is "flattened" before quantifying over a
206 -- These types do not have boxy type variables in them
207 type TcPredType = PredType
208 type TcThetaType = ThetaType
209 type TcSigmaType = TcType
210 type TcRhoType = TcType
211 type TcTauType = TcType
213 type TcTyVarSet = TyVarSet
215 -- These types may have boxy type variables in them
216 type BoxyTyVar = TcTyVar
217 type BoxyRhoType = TcType
218 type BoxyThetaType = TcThetaType
219 type BoxySigmaType = TcType
220 type BoxyType = TcType
224 %************************************************************************
226 \subsection{TyVarDetails}
228 %************************************************************************
230 TyVarDetails gives extra info about type variables, used during type
231 checking. It's attached to mutable type variables only.
232 It's knot-tied back to Var.lhs. There is no reason in principle
233 why Var.lhs shouldn't actually have the definition, but it "belongs" here.
236 Note [Signature skolems]
237 ~~~~~~~~~~~~~~~~~~~~~~~~
242 (x,y,z) = ([y,z], z, head x)
244 Here, x and y have type sigs, which go into the environment. We used to
245 instantiate their types with skolem constants, and push those types into
246 the RHS, so we'd typecheck the RHS with type
248 where a*, b* are skolem constants, and c is an ordinary meta type varible.
250 The trouble is that the occurrences of z in the RHS force a* and b* to
251 be the *same*, so we can't make them into skolem constants that don't unify
252 with each other. Alas.
254 One solution would be insist that in the above defn the programmer uses
255 the same type variable in both type signatures. But that takes explanation.
257 The alternative (currently implemented) is to have a special kind of skolem
258 constant, SigTv, which can unify with other SigTvs. These are *not* treated
259 as righd for the purposes of GADTs. And they are used *only* for pattern
260 bindings and mutually recursive function bindings. See the function
261 TcBinds.tcInstSig, and its use_skols parameter.
265 -- A TyVarDetails is inside a TyVar
267 = SkolemTv SkolemInfo -- A skolem constant
269 | MetaTv BoxInfo (IORef MetaDetails)
272 = BoxTv -- The contents is a (non-boxy) sigma-type
273 -- That is, this MetaTv is a "box"
275 | TauTv -- The contents is a (non-boxy) tau-type
276 -- That is, this MetaTv is an ordinary unification variable
278 | SigTv SkolemInfo -- A variant of TauTv, except that it should not be
279 -- unified with a type, only with a type variable
280 -- SigTvs are only distinguished to improve error messages
281 -- see Note [Signature skolems]
282 -- The MetaDetails, if filled in, will
283 -- always be another SigTv or a SkolemTv
286 -- A TauTv is always filled in with a tau-type, which
287 -- never contains any BoxTvs, nor any ForAlls
289 -- However, a BoxTv can contain a type that contains further BoxTvs
290 -- Notably, when typechecking an explicit list, say [e1,e2], with
291 -- expected type being a box b1, we fill in b1 with (List b2), where
292 -- b2 is another (currently empty) box.
295 = Flexi -- Flexi type variables unify to become
298 | Indirect TcType -- INVARIANT:
299 -- For a BoxTv, this type must be non-boxy
300 -- For a TauTv, this type must be a tau-type
302 -- Generally speaking, SkolemInfo should not contain location info
303 -- that is contained in the Name of the tyvar with this SkolemInfo
305 = SigSkol UserTypeCtxt -- A skolem that is created by instantiating
306 -- a programmer-supplied type signature
307 -- Location of the binding site is on the TyVar
309 -- The rest are for non-scoped skolems
310 | ClsSkol Class -- Bound at a class decl
311 | InstSkol -- Bound at an instance decl
312 | FamInstSkol -- Bound at a family instance decl
313 | PatSkol DataCon -- An existential type variable bound by a pattern for
314 -- a data constructor with an existential type. E.g.
315 -- data T = forall a. Eq a => MkT a
317 -- The pattern MkT x will allocate an existential type
319 | ArrowSkol -- An arrow form (see TcArrows)
321 | RuleSkol RuleName -- The LHS of a RULE
322 | GenSkol [TcTyVar] -- Bound when doing a subsumption check for
323 TcType -- (forall tvs. ty)
325 | UnkSkol -- Unhelpful info (until I improve it)
327 -------------------------------------
328 -- UserTypeCtxt describes the places where a
329 -- programmer-written type signature can occur
330 -- Like SkolemInfo, no location info
332 = FunSigCtxt Name -- Function type signature
333 -- Also used for types in SPECIALISE pragmas
334 | ExprSigCtxt -- Expression type signature
335 | ConArgCtxt Name -- Data constructor argument
336 | TySynCtxt Name -- RHS of a type synonym decl
337 | GenPatCtxt -- Pattern in generic decl
338 -- f{| a+b |} (Inl x) = ...
339 | LamPatSigCtxt -- Type sig in lambda pattern
341 | BindPatSigCtxt -- Type sig in pattern binding pattern
343 | ResSigCtxt -- Result type sig
345 | ForSigCtxt Name -- Foreign inport or export signature
346 | DefaultDeclCtxt -- Types in a default declaration
347 | SpecInstCtxt -- SPECIALISE instance pragma
349 -- Notes re TySynCtxt
350 -- We allow type synonyms that aren't types; e.g. type List = []
352 -- If the RHS mentions tyvars that aren't in scope, we'll
353 -- quantify over them:
354 -- e.g. type T = a->a
355 -- will become type T = forall a. a->a
357 -- With gla-exts that's right, but for H98 we should complain.
359 ---------------------------------
362 mkKindName :: Unique -> Name
363 mkKindName unique = mkSystemName unique kind_var_occ
365 kindVarRef :: KindVar -> IORef MetaDetails
367 ASSERT ( isTcTyVar tc )
368 case tcTyVarDetails tc of
369 MetaTv TauTv ref -> ref
370 other -> pprPanic "kindVarRef" (ppr tc)
372 mkKindVar :: Unique -> IORef MetaDetails -> KindVar
374 = mkTcTyVar (mkKindName u)
375 tySuperKind -- not sure this is right,
376 -- do we need kind vars for
380 kind_var_occ :: OccName -- Just one for all KindVars
381 -- They may be jiggled by tidying
382 kind_var_occ = mkOccName tvName "k"
386 %************************************************************************
390 %************************************************************************
393 pprTcTyVarDetails :: TcTyVarDetails -> SDoc
395 pprTcTyVarDetails (SkolemTv _) = ptext SLIT("sk")
396 pprTcTyVarDetails (MetaTv BoxTv _) = ptext SLIT("box")
397 pprTcTyVarDetails (MetaTv TauTv _) = ptext SLIT("tau")
398 pprTcTyVarDetails (MetaTv (SigTv _) _) = ptext SLIT("sig")
400 pprUserTypeCtxt :: UserTypeCtxt -> SDoc
401 pprUserTypeCtxt (FunSigCtxt n) = ptext SLIT("the type signature for") <+> quotes (ppr n)
402 pprUserTypeCtxt ExprSigCtxt = ptext SLIT("an expression type signature")
403 pprUserTypeCtxt (ConArgCtxt c) = ptext SLIT("the type of the constructor") <+> quotes (ppr c)
404 pprUserTypeCtxt (TySynCtxt c) = ptext SLIT("the RHS of the type synonym") <+> quotes (ppr c)
405 pprUserTypeCtxt GenPatCtxt = ptext SLIT("the type pattern of a generic definition")
406 pprUserTypeCtxt LamPatSigCtxt = ptext SLIT("a pattern type signature")
407 pprUserTypeCtxt BindPatSigCtxt = ptext SLIT("a pattern type signature")
408 pprUserTypeCtxt ResSigCtxt = ptext SLIT("a result type signature")
409 pprUserTypeCtxt (ForSigCtxt n) = ptext SLIT("the foreign declaration for") <+> quotes (ppr n)
410 pprUserTypeCtxt DefaultDeclCtxt = ptext SLIT("a type in a `default' declaration")
411 pprUserTypeCtxt SpecInstCtxt = ptext SLIT("a SPECIALISE instance pragma")
414 --------------------------------
415 tidySkolemTyVar :: TidyEnv -> TcTyVar -> (TidyEnv, TcTyVar)
416 -- Tidy the type inside a GenSkol, preparatory to printing it
417 tidySkolemTyVar env tv
418 = ASSERT( isSkolemTyVar tv || isSigTyVar tv )
419 (env1, mkTcTyVar (tyVarName tv) (tyVarKind tv) info1)
421 (env1, info1) = case tcTyVarDetails tv of
422 SkolemTv info -> (env1, SkolemTv info')
424 (env1, info') = tidy_skol_info env info
425 MetaTv (SigTv info) box -> (env1, MetaTv (SigTv info') box)
427 (env1, info') = tidy_skol_info env info
430 tidy_skol_info env (GenSkol tvs ty) = (env2, GenSkol tvs1 ty1)
432 (env1, tvs1) = tidyOpenTyVars env tvs
433 (env2, ty1) = tidyOpenType env1 ty
434 tidy_skol_info env info = (env, info)
436 pprSkolTvBinding :: TcTyVar -> SDoc
437 -- Print info about the binding of a skolem tyvar,
438 -- or nothing if we don't have anything useful to say
440 = ASSERT ( isTcTyVar tv )
441 ppr_details (tcTyVarDetails tv)
443 ppr_details (MetaTv TauTv _) = quotes (ppr tv) <+> ptext SLIT("is a meta type variable")
444 ppr_details (MetaTv BoxTv _) = quotes (ppr tv) <+> ptext SLIT("is a boxy type variable")
445 ppr_details (MetaTv (SigTv info) _) = ppr_skol info
446 ppr_details (SkolemTv info) = ppr_skol info
448 ppr_skol UnkSkol = empty -- Unhelpful; omit
449 ppr_skol info = quotes (ppr tv) <+> ptext SLIT("is bound by")
450 <+> sep [pprSkolInfo info, nest 2 (ptext SLIT("at") <+> ppr (getSrcLoc tv))]
452 pprSkolInfo :: SkolemInfo -> SDoc
453 pprSkolInfo (SigSkol ctxt) = pprUserTypeCtxt ctxt
454 pprSkolInfo (ClsSkol cls) = ptext SLIT("the class declaration for") <+> quotes (ppr cls)
455 pprSkolInfo InstSkol = ptext SLIT("the instance declaration")
456 pprSkolInfo FamInstSkol = ptext SLIT("the family instance declaration")
457 pprSkolInfo (RuleSkol name) = ptext SLIT("the RULE") <+> doubleQuotes (ftext name)
458 pprSkolInfo ArrowSkol = ptext SLIT("the arrow form")
459 pprSkolInfo (PatSkol dc) = sep [ptext SLIT("the constructor") <+> quotes (ppr dc)]
460 pprSkolInfo (GenSkol tvs ty) = sep [ptext SLIT("the polymorphic type"),
461 nest 2 (quotes (ppr (mkForAllTys tvs ty)))]
464 -- For type variables the others are dealt with by pprSkolTvBinding.
465 -- For Insts, these cases should not happen
466 pprSkolInfo UnkSkol = panic "UnkSkol"
468 instance Outputable MetaDetails where
469 ppr Flexi = ptext SLIT("Flexi")
470 ppr (Indirect ty) = ptext SLIT("Indirect") <+> ppr ty
474 %************************************************************************
478 %************************************************************************
481 isImmutableTyVar, isSkolemTyVar, isExistentialTyVar, isBoxyTyVar, isMetaTyVar :: TyVar -> Bool
483 | isTcTyVar tv = isSkolemTyVar tv
487 = ASSERT( isTcTyVar tv )
488 case tcTyVarDetails tv of
492 isExistentialTyVar tv -- Existential type variable, bound by a pattern
493 = ASSERT( isTcTyVar tv )
494 case tcTyVarDetails tv of
495 SkolemTv (PatSkol {}) -> True
499 = ASSERT2( isTcTyVar tv, ppr tv )
500 case tcTyVarDetails tv of
505 = ASSERT( isTcTyVar tv )
506 case tcTyVarDetails tv of
507 MetaTv BoxTv _ -> True
511 = ASSERT( isTcTyVar tv )
512 case tcTyVarDetails tv of
513 MetaTv (SigTv _) _ -> True
516 metaTvRef :: TyVar -> IORef MetaDetails
518 = ASSERT( isTcTyVar tv )
519 case tcTyVarDetails tv of
521 other -> pprPanic "metaTvRef" (ppr tv)
523 isFlexi, isIndirect :: MetaDetails -> Bool
525 isFlexi other = False
527 isIndirect (Indirect _) = True
528 isIndirect other = False
532 %************************************************************************
534 \subsection{Tau, sigma and rho}
536 %************************************************************************
539 mkSigmaTy :: [TyVar] -> [PredType] -> Type -> Type
540 mkSigmaTy tyvars theta tau = mkForAllTys tyvars (mkPhiTy theta tau)
542 mkPhiTy :: [PredType] -> Type -> Type
543 mkPhiTy theta ty = foldr (\p r -> FunTy (mkPredTy p) r) ty theta
546 @isTauTy@ tests for nested for-alls. It should not be called on a boxy type.
549 isTauTy :: Type -> Bool
550 isTauTy ty | Just ty' <- tcView ty = isTauTy ty'
551 isTauTy (TyVarTy tv) = ASSERT( not (isTcTyVar tv && isBoxyTyVar tv) )
553 isTauTy (TyConApp tc tys) = all isTauTy tys && isTauTyCon tc
554 isTauTy (AppTy a b) = isTauTy a && isTauTy b
555 isTauTy (FunTy a b) = isTauTy a && isTauTy b
556 isTauTy (PredTy p) = True -- Don't look through source types
557 isTauTy other = False
560 isTauTyCon :: TyCon -> Bool
561 -- Returns False for type synonyms whose expansion is a polytype
563 | isSynTyCon tc && not (isOpenTyCon tc) = isTauTy (snd (synTyConDefn tc))
567 isBoxyTy :: TcType -> Bool
568 isBoxyTy ty = any isBoxyTyVar (varSetElems (tcTyVarsOfType ty))
570 isRigidTy :: TcType -> Bool
571 -- A type is rigid if it has no meta type variables in it
572 isRigidTy ty = all isSkolemTyVar (varSetElems (tcTyVarsOfType ty))
574 isRefineableTy :: TcType -> Bool
575 -- A type should have type refinements applied to it if it has
576 -- free type variables, and they are all rigid
577 isRefineableTy ty = not (null tc_tvs) && all isSkolemTyVar tc_tvs
579 tc_tvs = varSetElems (tcTyVarsOfType ty)
582 getDFunTyKey :: Type -> OccName -- Get some string from a type, to be used to
583 -- construct a dictionary function name
584 getDFunTyKey ty | Just ty' <- tcView ty = getDFunTyKey ty'
585 getDFunTyKey (TyVarTy tv) = getOccName tv
586 getDFunTyKey (TyConApp tc _) = getOccName tc
587 getDFunTyKey (AppTy fun _) = getDFunTyKey fun
588 getDFunTyKey (FunTy arg _) = getOccName funTyCon
589 getDFunTyKey (ForAllTy _ t) = getDFunTyKey t
590 getDFunTyKey ty = pprPanic "getDFunTyKey" (pprType ty)
591 -- PredTy shouldn't happen
595 %************************************************************************
597 \subsection{Expanding and splitting}
599 %************************************************************************
601 These tcSplit functions are like their non-Tc analogues, but
602 a) they do not look through newtypes
603 b) they do not look through PredTys
604 c) [future] they ignore usage-type annotations
606 However, they are non-monadic and do not follow through mutable type
607 variables. It's up to you to make sure this doesn't matter.
610 tcSplitForAllTys :: Type -> ([TyVar], Type)
611 tcSplitForAllTys ty = split ty ty []
613 split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
614 split orig_ty (ForAllTy tv ty) tvs
615 | not (isCoVar tv) = split ty ty (tv:tvs)
616 split orig_ty t tvs = (reverse tvs, orig_ty)
618 tcIsForAllTy ty | Just ty' <- tcView ty = tcIsForAllTy ty'
619 tcIsForAllTy (ForAllTy tv ty) = not (isCoVar tv)
620 tcIsForAllTy t = False
622 tcSplitPhiTy :: Type -> (ThetaType, Type)
623 tcSplitPhiTy ty = split ty ty []
625 split orig_ty ty tvs | Just ty' <- tcView ty = split orig_ty ty' tvs
627 split orig_ty (ForAllTy tv ty) ts
628 | isCoVar tv = split ty ty (eq_pred:ts)
630 PredTy eq_pred = tyVarKind tv
631 split orig_ty (FunTy arg res) ts
632 | Just p <- tcSplitPredTy_maybe arg = split res res (p:ts)
633 split orig_ty ty ts = (reverse ts, orig_ty)
635 tcSplitSigmaTy :: Type -> ([TyVar], ThetaType, Type)
636 tcSplitSigmaTy ty = case tcSplitForAllTys ty of
637 (tvs, rho) -> case tcSplitPhiTy rho of
638 (theta, tau) -> (tvs, theta, tau)
640 -----------------------
643 -> ( [([TyVar], ThetaType)], -- forall as.C => forall bs.D
644 TcSigmaType) -- The rest of the type
646 -- We need a loop here because we are now prepared to entertain
648 -- f:: forall a. Eq a => forall b. Baz b => tau
649 -- We want to instantiate this to
650 -- f2::tau {f2 = f1 b (Baz b), f1 = f a (Eq a)}
652 tcMultiSplitSigmaTy sigma
653 = case (tcSplitSigmaTy sigma) of
654 ([],[],ty) -> ([], sigma)
655 (tvs, theta, ty) -> case tcMultiSplitSigmaTy ty of
656 (pairs, rest) -> ((tvs,theta):pairs, rest)
658 -----------------------
659 tcTyConAppTyCon :: Type -> TyCon
660 tcTyConAppTyCon ty = case tcSplitTyConApp_maybe ty of
662 Nothing -> pprPanic "tcTyConAppTyCon" (pprType ty)
664 tcTyConAppArgs :: Type -> [Type]
665 tcTyConAppArgs ty = case tcSplitTyConApp_maybe ty of
666 Just (_, args) -> args
667 Nothing -> pprPanic "tcTyConAppArgs" (pprType ty)
669 tcSplitTyConApp :: Type -> (TyCon, [Type])
670 tcSplitTyConApp ty = case tcSplitTyConApp_maybe ty of
672 Nothing -> pprPanic "tcSplitTyConApp" (pprType ty)
674 tcSplitTyConApp_maybe :: Type -> Maybe (TyCon, [Type])
675 tcSplitTyConApp_maybe ty | Just ty' <- tcView ty = tcSplitTyConApp_maybe ty'
676 tcSplitTyConApp_maybe (TyConApp tc tys) = Just (tc, tys)
677 tcSplitTyConApp_maybe (FunTy arg res) = Just (funTyCon, [arg,res])
678 -- Newtypes are opaque, so they may be split
679 -- However, predicates are not treated
680 -- as tycon applications by the type checker
681 tcSplitTyConApp_maybe other = Nothing
683 -----------------------
684 tcSplitFunTys :: Type -> ([Type], Type)
685 tcSplitFunTys ty = case tcSplitFunTy_maybe ty of
687 Just (arg,res) -> (arg:args, res')
689 (args,res') = tcSplitFunTys res
691 tcSplitFunTy_maybe :: Type -> Maybe (Type, Type)
692 tcSplitFunTy_maybe ty | Just ty' <- tcView ty = tcSplitFunTy_maybe ty'
693 tcSplitFunTy_maybe (FunTy arg res) = Just (arg, res)
694 tcSplitFunTy_maybe other = Nothing
698 -> Arity -- N: Number of desired args
699 -> ([TcSigmaType], -- Arg types (N or fewer)
700 TcSigmaType) -- The rest of the type
702 tcSplitFunTysN ty n_args
705 | Just (arg,res) <- tcSplitFunTy_maybe ty
706 = case tcSplitFunTysN res (n_args - 1) of
707 (args, res) -> (arg:args, res)
711 tcSplitFunTy ty = expectJust "tcSplitFunTy" (tcSplitFunTy_maybe ty)
712 tcFunArgTy ty = fst (tcSplitFunTy ty)
713 tcFunResultTy ty = snd (tcSplitFunTy ty)
715 -----------------------
716 tcSplitAppTy_maybe :: Type -> Maybe (Type, Type)
717 tcSplitAppTy_maybe ty | Just ty' <- tcView ty = tcSplitAppTy_maybe ty'
718 tcSplitAppTy_maybe ty = repSplitAppTy_maybe ty
720 tcSplitAppTy :: Type -> (Type, Type)
721 tcSplitAppTy ty = case tcSplitAppTy_maybe ty of
723 Nothing -> pprPanic "tcSplitAppTy" (pprType ty)
725 tcSplitAppTys :: Type -> (Type, [Type])
729 go ty args = case tcSplitAppTy_maybe ty of
730 Just (ty', arg) -> go ty' (arg:args)
733 -----------------------
734 tcGetTyVar_maybe :: Type -> Maybe TyVar
735 tcGetTyVar_maybe ty | Just ty' <- tcView ty = tcGetTyVar_maybe ty'
736 tcGetTyVar_maybe (TyVarTy tv) = Just tv
737 tcGetTyVar_maybe other = Nothing
739 tcGetTyVar :: String -> Type -> TyVar
740 tcGetTyVar msg ty = expectJust msg (tcGetTyVar_maybe ty)
742 tcIsTyVarTy :: Type -> Bool
743 tcIsTyVarTy ty = maybeToBool (tcGetTyVar_maybe ty)
745 -----------------------
746 tcSplitDFunTy :: Type -> ([TyVar], [PredType], Class, [Type])
747 -- Split the type of a dictionary function
749 = case tcSplitSigmaTy ty of { (tvs, theta, tau) ->
750 case tcSplitDFunHead tau of { (clas, tys) ->
751 (tvs, theta, clas, tys) }}
753 tcSplitDFunHead :: Type -> (Class, [Type])
755 = case tcSplitPredTy_maybe tau of
756 Just (ClassP clas tys) -> (clas, tys)
757 other -> panic "tcSplitDFunHead"
759 tcValidInstHeadTy :: Type -> Bool
760 -- Used in Haskell-98 mode, for the argument types of an instance head
761 -- These must not be type synonyms, but everywhere else type synonyms
762 -- are transparent, so we need a special function here
765 NoteTy _ ty -> tcValidInstHeadTy ty
766 TyConApp tc tys -> not (isSynTyCon tc) && ok tys
767 FunTy arg res -> ok [arg, res]
770 -- Check that all the types are type variables,
771 -- and that each is distinct
772 ok tys = equalLength tvs tys && hasNoDups tvs
774 tvs = mapCatMaybes get_tv tys
776 get_tv (NoteTy _ ty) = get_tv ty -- Again, do not look
777 get_tv (TyVarTy tv) = Just tv -- through synonyms
778 get_tv other = Nothing
783 %************************************************************************
785 \subsection{Predicate types}
787 %************************************************************************
790 tcSplitPredTy_maybe :: Type -> Maybe PredType
791 -- Returns Just for predicates only
792 tcSplitPredTy_maybe ty | Just ty' <- tcView ty = tcSplitPredTy_maybe ty'
793 tcSplitPredTy_maybe (PredTy p) = Just p
794 tcSplitPredTy_maybe other = Nothing
796 predTyUnique :: PredType -> Unique
797 predTyUnique (IParam n _) = getUnique (ipNameName n)
798 predTyUnique (ClassP clas tys) = getUnique clas
802 --------------------- Dictionary types ---------------------------------
805 mkClassPred clas tys = ClassP clas tys
807 isClassPred :: PredType -> Bool
808 isClassPred (ClassP clas tys) = True
809 isClassPred other = False
811 isTyVarClassPred (ClassP clas tys) = all tcIsTyVarTy tys
812 isTyVarClassPred other = False
814 getClassPredTys_maybe :: PredType -> Maybe (Class, [Type])
815 getClassPredTys_maybe (ClassP clas tys) = Just (clas, tys)
816 getClassPredTys_maybe _ = Nothing
818 getClassPredTys :: PredType -> (Class, [Type])
819 getClassPredTys (ClassP clas tys) = (clas, tys)
820 getClassPredTys other = panic "getClassPredTys"
822 mkDictTy :: Class -> [Type] -> Type
823 mkDictTy clas tys = mkPredTy (ClassP clas tys)
825 isDictTy :: Type -> Bool
826 isDictTy ty | Just ty' <- tcView ty = isDictTy ty'
827 isDictTy (PredTy p) = isClassPred p
828 isDictTy other = False
831 --------------------- Implicit parameters ---------------------------------
834 isIPPred :: PredType -> Bool
835 isIPPred (IParam _ _) = True
836 isIPPred other = False
838 isInheritablePred :: PredType -> Bool
839 -- Can be inherited by a context. For example, consider
840 -- f x = let g y = (?v, y+x)
841 -- in (g 3 with ?v = 8,
843 -- The point is that g's type must be quantifed over ?v:
844 -- g :: (?v :: a) => a -> a
845 -- but it doesn't need to be quantified over the Num a dictionary
846 -- which can be free in g's rhs, and shared by both calls to g
847 isInheritablePred (ClassP _ _) = True
848 isInheritablePred other = False
851 --------------------- Equality predicates ---------------------------------
853 substEqSpec :: TvSubst -> [(TyVar,Type)] -> [(TcType,TcType)]
854 substEqSpec subst eq_spec = [ (substTyVar subst tv, substTy subst ty)
855 | (tv,ty) <- eq_spec]
858 --------------------- The stupid theta (sigh) ---------------------------------
861 dataConsStupidTheta :: [DataCon] -> ThetaType
862 -- Union the stupid thetas from all the specified constructors (non-empty)
863 -- All the constructors should have the same result type, modulo alpha conversion
864 -- The resulting ThetaType uses type variables from the *first* constructor in the list
866 -- It's here because it's used in MkId.mkRecordSelId, and in TcExpr
867 dataConsStupidTheta (con1:cons)
868 = nubBy tcEqPred all_preds
870 all_preds = dataConStupidTheta con1 ++ other_stupids
871 res_tys1 = dataConResTys con1
872 tvs1 = tyVarsOfTypes res_tys1
873 other_stupids = [ substPred subst pred
875 , let Just subst = tcMatchTys tvs1 res_tys1 (dataConResTys con)
876 , pred <- dataConStupidTheta con ]
877 dataConsStupidTheta [] = panic "dataConsStupidTheta"
881 %************************************************************************
883 \subsection{Predicates}
885 %************************************************************************
887 isSigmaTy returns true of any qualified type. It doesn't *necessarily* have
889 f :: (?x::Int) => Int -> Int
892 isSigmaTy :: Type -> Bool
893 isSigmaTy ty | Just ty' <- tcView ty = isSigmaTy ty'
894 isSigmaTy (ForAllTy tyvar ty) = True
895 isSigmaTy (FunTy a b) = isPredTy a
898 isOverloadedTy :: Type -> Bool
899 isOverloadedTy ty | Just ty' <- tcView ty = isOverloadedTy ty'
900 isOverloadedTy (ForAllTy tyvar ty) = isOverloadedTy ty
901 isOverloadedTy (FunTy a b) = isPredTy a
902 isOverloadedTy _ = False
904 isPredTy :: Type -> Bool -- Belongs in TcType because it does
905 -- not look through newtypes, or predtypes (of course)
906 isPredTy ty | Just ty' <- tcView ty = isPredTy ty'
907 isPredTy (PredTy sty) = True
912 isFloatTy = is_tc floatTyConKey
913 isDoubleTy = is_tc doubleTyConKey
914 isIntegerTy = is_tc integerTyConKey
915 isIntTy = is_tc intTyConKey
916 isBoolTy = is_tc boolTyConKey
917 isUnitTy = is_tc unitTyConKey
919 is_tc :: Unique -> Type -> Bool
920 -- Newtypes are opaque to this
921 is_tc uniq ty = case tcSplitTyConApp_maybe ty of
922 Just (tc, _) -> uniq == getUnique tc
927 %************************************************************************
931 %************************************************************************
934 deNoteType :: Type -> Type
935 -- Remove all *outermost* type synonyms and other notes
936 deNoteType ty | Just ty' <- tcView ty = deNoteType ty'
941 tcTyVarsOfType :: Type -> TcTyVarSet
942 -- Just the *TcTyVars* free in the type
943 -- (Types.tyVarsOfTypes finds all free TyVars)
944 tcTyVarsOfType (TyVarTy tv) = if isTcTyVar tv then unitVarSet tv
946 tcTyVarsOfType (TyConApp tycon tys) = tcTyVarsOfTypes tys
947 tcTyVarsOfType (NoteTy _ ty) = tcTyVarsOfType ty
948 tcTyVarsOfType (PredTy sty) = tcTyVarsOfPred sty
949 tcTyVarsOfType (FunTy arg res) = tcTyVarsOfType arg `unionVarSet` tcTyVarsOfType res
950 tcTyVarsOfType (AppTy fun arg) = tcTyVarsOfType fun `unionVarSet` tcTyVarsOfType arg
951 tcTyVarsOfType (ForAllTy tyvar ty) = (tcTyVarsOfType ty `delVarSet` tyvar)
952 `unionVarSet` tcTyVarsOfTyVar tyvar
953 -- We do sometimes quantify over skolem TcTyVars
955 tcTyVarsOfTyVar :: TcTyVar -> TyVarSet
956 tcTyVarsOfTyVar tv | isCoVar tv = tcTyVarsOfType (tyVarKind tv)
957 | otherwise = emptyVarSet
959 tcTyVarsOfTypes :: [Type] -> TyVarSet
960 tcTyVarsOfTypes tys = foldr (unionVarSet.tcTyVarsOfType) emptyVarSet tys
962 tcTyVarsOfPred :: PredType -> TyVarSet
963 tcTyVarsOfPred (IParam _ ty) = tcTyVarsOfType ty
964 tcTyVarsOfPred (ClassP _ tys) = tcTyVarsOfTypes tys
965 tcTyVarsOfPred (EqPred ty1 ty2) = tcTyVarsOfType ty1 `unionVarSet` tcTyVarsOfType ty2
968 Note [Silly type synonym]
969 ~~~~~~~~~~~~~~~~~~~~~~~~~
972 What are the free tyvars of (T x)? Empty, of course!
973 Here's the example that Ralf Laemmel showed me:
974 foo :: (forall a. C u a -> C u a) -> u
975 mappend :: Monoid u => u -> u -> u
978 bar = foo (\t -> t `mappend` t)
979 We have to generalise at the arg to f, and we don't
980 want to capture the constraint (Monad (C u a)) because
981 it appears to mention a. Pretty silly, but it was useful to him.
983 exactTyVarsOfType is used by the type checker to figure out exactly
984 which type variables are mentioned in a type. It's also used in the
985 smart-app checking code --- see TcExpr.tcIdApp
988 exactTyVarsOfType :: TcType -> TyVarSet
989 -- Find the free type variables (of any kind)
990 -- but *expand* type synonyms. See Note [Silly type synonym] above.
994 go ty | Just ty' <- tcView ty = go ty' -- This is the key line
995 go (TyVarTy tv) = unitVarSet tv
996 go (TyConApp tycon tys) = exactTyVarsOfTypes tys
997 go (PredTy ty) = go_pred ty
998 go (FunTy arg res) = go arg `unionVarSet` go res
999 go (AppTy fun arg) = go fun `unionVarSet` go arg
1000 go (ForAllTy tyvar ty) = delVarSet (go ty) tyvar
1001 `unionVarSet` go_tv tyvar
1003 go_pred (IParam _ ty) = go ty
1004 go_pred (ClassP _ tys) = exactTyVarsOfTypes tys
1005 go_pred (EqPred ty1 ty2) = go ty1 `unionVarSet` go ty2
1007 go_tv tyvar | isCoVar tyvar = go (tyVarKind tyvar)
1008 | otherwise = emptyVarSet
1010 exactTyVarsOfTypes :: [TcType] -> TyVarSet
1011 exactTyVarsOfTypes tys = foldr (unionVarSet . exactTyVarsOfType) emptyVarSet tys
1014 Find the free tycons and classes of a type. This is used in the front
1015 end of the compiler.
1018 tyClsNamesOfType :: Type -> NameSet
1019 tyClsNamesOfType (TyVarTy tv) = emptyNameSet
1020 tyClsNamesOfType (TyConApp tycon tys) = unitNameSet (getName tycon) `unionNameSets` tyClsNamesOfTypes tys
1021 tyClsNamesOfType (NoteTy _ ty2) = tyClsNamesOfType ty2
1022 tyClsNamesOfType (PredTy (IParam n ty)) = tyClsNamesOfType ty
1023 tyClsNamesOfType (PredTy (ClassP cl tys)) = unitNameSet (getName cl) `unionNameSets` tyClsNamesOfTypes tys
1024 tyClsNamesOfType (PredTy (EqPred ty1 ty2)) = tyClsNamesOfType ty1 `unionNameSets` tyClsNamesOfType ty2
1025 tyClsNamesOfType (FunTy arg res) = tyClsNamesOfType arg `unionNameSets` tyClsNamesOfType res
1026 tyClsNamesOfType (AppTy fun arg) = tyClsNamesOfType fun `unionNameSets` tyClsNamesOfType arg
1027 tyClsNamesOfType (ForAllTy tyvar ty) = tyClsNamesOfType ty
1029 tyClsNamesOfTypes tys = foldr (unionNameSets . tyClsNamesOfType) emptyNameSet tys
1031 tyClsNamesOfDFunHead :: Type -> NameSet
1032 -- Find the free type constructors and classes
1033 -- of the head of the dfun instance type
1034 -- The 'dfun_head_type' is because of
1035 -- instance Foo a => Baz T where ...
1036 -- The decl is an orphan if Baz and T are both not locally defined,
1037 -- even if Foo *is* locally defined
1038 tyClsNamesOfDFunHead dfun_ty
1039 = case tcSplitSigmaTy dfun_ty of
1040 (tvs,_,head_ty) -> tyClsNamesOfType head_ty
1042 classesOfTheta :: ThetaType -> [Class]
1043 -- Looks just for ClassP things; maybe it should check
1044 classesOfTheta preds = [ c | ClassP c _ <- preds ]
1048 %************************************************************************
1050 \subsection[TysWiredIn-ext-type]{External types}
1052 %************************************************************************
1054 The compiler's foreign function interface supports the passing of a
1055 restricted set of types as arguments and results (the restricting factor
1059 tcSplitIOType_maybe :: Type -> Maybe (TyCon, Type)
1060 -- (isIOType t) returns (Just (IO,t')) if t is of the form (IO t'), or
1061 -- some newtype wrapping thereof
1062 -- returns Nothing otherwise
1063 tcSplitIOType_maybe ty
1064 | Just (io_tycon, [io_res_ty]) <- tcSplitTyConApp_maybe ty,
1065 -- This split absolutely has to be a tcSplit, because we must
1066 -- see the IO type; and it's a newtype which is transparent to splitTyConApp.
1067 io_tycon `hasKey` ioTyConKey
1068 = Just (io_tycon, io_res_ty)
1070 | Just ty' <- coreView ty -- Look through non-recursive newtypes
1071 = tcSplitIOType_maybe ty'
1076 isFFITy :: Type -> Bool
1077 -- True for any TyCon that can possibly be an arg or result of an FFI call
1078 isFFITy ty = checkRepTyCon legalFFITyCon ty
1080 isFFIArgumentTy :: DynFlags -> Safety -> Type -> Bool
1081 -- Checks for valid argument type for a 'foreign import'
1082 isFFIArgumentTy dflags safety ty
1083 = checkRepTyCon (legalOutgoingTyCon dflags safety) ty
1085 isFFIExternalTy :: Type -> Bool
1086 -- Types that are allowed as arguments of a 'foreign export'
1087 isFFIExternalTy ty = checkRepTyCon legalFEArgTyCon ty
1089 isFFIImportResultTy :: DynFlags -> Type -> Bool
1090 isFFIImportResultTy dflags ty
1091 = checkRepTyCon (legalFIResultTyCon dflags) ty
1093 isFFIExportResultTy :: Type -> Bool
1094 isFFIExportResultTy ty = checkRepTyCon legalFEResultTyCon ty
1096 isFFIDynArgumentTy :: Type -> Bool
1097 -- The argument type of a foreign import dynamic must be Ptr, FunPtr, Addr,
1098 -- or a newtype of either.
1099 isFFIDynArgumentTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1101 isFFIDynResultTy :: Type -> Bool
1102 -- The result type of a foreign export dynamic must be Ptr, FunPtr, Addr,
1103 -- or a newtype of either.
1104 isFFIDynResultTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1106 isFFILabelTy :: Type -> Bool
1107 -- The type of a foreign label must be Ptr, FunPtr, Addr,
1108 -- or a newtype of either.
1109 isFFILabelTy = checkRepTyConKey [ptrTyConKey, funPtrTyConKey]
1111 isFFIDotnetTy :: DynFlags -> Type -> Bool
1112 isFFIDotnetTy dflags ty
1113 = checkRepTyCon (\ tc -> (legalFIResultTyCon dflags tc ||
1114 isFFIDotnetObjTy ty || isStringTy ty)) ty
1116 -- Support String as an argument or result from a .NET FFI call.
1118 case tcSplitTyConApp_maybe (repType ty) of
1120 | tc == listTyCon ->
1121 case tcSplitTyConApp_maybe (repType arg_ty) of
1122 Just (cc,[]) -> cc == charTyCon
1126 -- Support String as an argument or result from a .NET FFI call.
1127 isFFIDotnetObjTy ty =
1129 (_, t_ty) = tcSplitForAllTys ty
1131 case tcSplitTyConApp_maybe (repType t_ty) of
1132 Just (tc, [arg_ty]) | getName tc == objectTyConName -> True
1135 toDNType :: Type -> DNType
1137 | isStringTy ty = DNString
1138 | isFFIDotnetObjTy ty = DNObject
1139 | Just (tc,argTys) <- tcSplitTyConApp_maybe ty
1140 = case lookup (getUnique tc) dn_assoc of
1143 | tc `hasKey` ioTyConKey -> toDNType (head argTys)
1144 | otherwise -> pprPanic ("toDNType: unsupported .NET type")
1145 (pprType ty <+> parens (hcat (map pprType argTys)) <+> ppr tc)
1146 | otherwise = panic "toDNType" -- Is this right?
1148 dn_assoc :: [ (Unique, DNType) ]
1149 dn_assoc = [ (unitTyConKey, DNUnit)
1150 , (intTyConKey, DNInt)
1151 , (int8TyConKey, DNInt8)
1152 , (int16TyConKey, DNInt16)
1153 , (int32TyConKey, DNInt32)
1154 , (int64TyConKey, DNInt64)
1155 , (wordTyConKey, DNInt)
1156 , (word8TyConKey, DNWord8)
1157 , (word16TyConKey, DNWord16)
1158 , (word32TyConKey, DNWord32)
1159 , (word64TyConKey, DNWord64)
1160 , (floatTyConKey, DNFloat)
1161 , (doubleTyConKey, DNDouble)
1162 , (ptrTyConKey, DNPtr)
1163 , (funPtrTyConKey, DNPtr)
1164 , (charTyConKey, DNChar)
1165 , (boolTyConKey, DNBool)
1168 checkRepTyCon :: (TyCon -> Bool) -> Type -> Bool
1169 -- Look through newtypes
1170 -- Non-recursive ones are transparent to splitTyConApp,
1171 -- but recursive ones aren't. Manuel had:
1172 -- newtype T = MkT (Ptr T)
1173 -- and wanted it to work...
1174 checkRepTyCon check_tc ty
1175 | Just (tc,_) <- splitTyConApp_maybe (repType ty) = check_tc tc
1178 checkRepTyConKey :: [Unique] -> Type -> Bool
1179 -- Like checkRepTyCon, but just looks at the TyCon key
1180 checkRepTyConKey keys
1181 = checkRepTyCon (\tc -> tyConUnique tc `elem` keys)
1184 ----------------------------------------------
1185 These chaps do the work; they are not exported
1186 ----------------------------------------------
1189 legalFEArgTyCon :: TyCon -> Bool
1191 -- It's illegal to make foreign exports that take unboxed
1192 -- arguments. The RTS API currently can't invoke such things. --SDM 7/2000
1193 = boxedMarshalableTyCon tc
1195 legalFIResultTyCon :: DynFlags -> TyCon -> Bool
1196 legalFIResultTyCon dflags tc
1197 | tc == unitTyCon = True
1198 | otherwise = marshalableTyCon dflags tc
1200 legalFEResultTyCon :: TyCon -> Bool
1201 legalFEResultTyCon tc
1202 | tc == unitTyCon = True
1203 | otherwise = boxedMarshalableTyCon tc
1205 legalOutgoingTyCon :: DynFlags -> Safety -> TyCon -> Bool
1206 -- Checks validity of types going from Haskell -> external world
1207 legalOutgoingTyCon dflags safety tc
1208 = marshalableTyCon dflags tc
1210 legalFFITyCon :: TyCon -> Bool
1211 -- True for any TyCon that can possibly be an arg or result of an FFI call
1213 = isUnLiftedTyCon tc || boxedMarshalableTyCon tc || tc == unitTyCon
1215 marshalableTyCon dflags tc
1216 = (dopt Opt_GlasgowExts dflags && isUnLiftedTyCon tc)
1217 || boxedMarshalableTyCon tc
1219 boxedMarshalableTyCon tc
1220 = getUnique tc `elem` [ intTyConKey, int8TyConKey, int16TyConKey
1221 , int32TyConKey, int64TyConKey
1222 , wordTyConKey, word8TyConKey, word16TyConKey
1223 , word32TyConKey, word64TyConKey
1224 , floatTyConKey, doubleTyConKey
1225 , ptrTyConKey, funPtrTyConKey